repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/pass_state.rs
crates/egui/src/pass_state.rs
use ahash::HashMap; use crate::{Align, Id, IdMap, LayerId, Rangef, Rect, Vec2, WidgetRects, id::IdSet, style}; #[cfg(debug_assertions)] use crate::{Align2, Color32, FontId, NumExt as _, Painter, pos2}; /// Reset at the start of each frame. #[derive(Clone, Debug, Default)] pub struct TooltipPassState { /// If a tooltip has been shown this frame, where was it? /// This is used to prevent multiple tooltips to cover each other. pub widget_tooltips: IdMap<PerWidgetTooltipState>, } impl TooltipPassState { pub fn clear(&mut self) { let Self { widget_tooltips } = self; widget_tooltips.clear(); } } #[derive(Clone, Copy, Debug)] pub struct PerWidgetTooltipState { /// Bounding rectangle for all widget and all previous tooltips. pub bounding_rect: Rect, /// How many tooltips have been shown for this widget this frame? pub tooltip_count: usize, } #[derive(Clone, Debug, Default)] pub struct PerLayerState { /// Is there any open popup (menus, combo-boxes, etc)? /// /// Does NOT include tooltips. pub open_popups: IdSet, /// Which widget is showing a tooltip (if any)? /// /// Only one widget per layer may show a tooltip. /// But if a tooltip contains a tooltip, you can show a tooltip on top of a tooltip. pub widget_with_tooltip: Option<Id>, } #[derive(Clone, Debug)] pub struct ScrollTarget { // The range that the scroll area should scroll to. pub range: Rangef, /// How should we align the rect within the visible area? /// If `align` is [`Align::TOP`] it means "put the top of the rect at the top of the scroll area", etc. /// If `align` is `None`, it'll scroll enough to bring the UI into view. pub align: Option<Align>, /// How should the scroll be animated? pub animation: style::ScrollAnimation, } impl ScrollTarget { pub fn new(range: Rangef, align: Option<Align>, animation: style::ScrollAnimation) -> Self { Self { range, align, animation, } } } #[derive(Clone)] pub struct AccessKitPassState { pub nodes: IdMap<accesskit::Node>, pub parent_map: IdMap<Id>, } #[cfg(debug_assertions)] #[derive(Clone)] pub struct DebugRect { pub rect: Rect, pub callstack: String, pub is_clicking: bool, } #[cfg(debug_assertions)] impl DebugRect { pub fn paint(self, painter: &Painter) { let Self { rect, callstack, is_clicking, } = self; let ctx = painter.ctx(); // Paint rectangle around widget: { // Print width and height: let text_color = if ctx.global_style().visuals.dark_mode { Color32::WHITE } else { Color32::BLACK }; painter.debug_text( rect.left_center() + 2.0 * Vec2::LEFT, Align2::RIGHT_CENTER, text_color, format!("H: {:.1}", rect.height()), ); painter.debug_text( rect.center_top(), Align2::CENTER_BOTTOM, text_color, format!("W: {:.1}", rect.width()), ); // Paint rect: let rect_fg_color = if is_clicking { Color32::WHITE } else { Color32::LIGHT_BLUE }; let rect_bg_color = Color32::BLUE.gamma_multiply(0.5); painter.rect( rect, 0.0, rect_bg_color, (1.0, rect_fg_color), crate::StrokeKind::Outside, ); } if !callstack.is_empty() { let font_id = FontId::monospace(12.0); let text = format!("{callstack}\n\n(click to copy)"); let text_color = Color32::WHITE; let galley = painter.layout_no_wrap(text, font_id, text_color); // Position the text either under or above: let content_rect = ctx.content_rect(); let y = if galley.size().y <= rect.top() { // Above rect.top() - galley.size().y - 16.0 } else { // Below rect.bottom() }; let y = y .at_most(content_rect.bottom() - galley.size().y) .at_least(0.0); let x = rect .left() .at_most(content_rect.right() - galley.size().x) .at_least(0.0); let text_pos = pos2(x, y); let text_bg_color = Color32::from_black_alpha(180); let text_rect_stroke_color = if is_clicking { Color32::WHITE } else { text_bg_color }; let text_rect = Rect::from_min_size(text_pos, galley.size()); painter.rect( text_rect, 0.0, text_bg_color, (1.0, text_rect_stroke_color), crate::StrokeKind::Middle, ); painter.galley(text_pos, galley, text_color); if is_clicking { ctx.copy_text(callstack); } } } } /// State that is collected during a pass, then saved for the next pass, /// and then cleared. /// /// (NOTE: we usually run only one pass per frame). /// /// One per viewport. #[derive(Clone)] pub struct PassState { /// All [`Id`]s that were used this pass. pub used_ids: IdMap<Rect>, /// All widgets produced this pass. pub widgets: WidgetRects, /// Per-layer state. /// /// Not all layers registers themselves there though. pub layers: HashMap<LayerId, PerLayerState>, pub tooltips: TooltipPassState, /// Starts off as the `screen_rect`, shrinks as panels are added. /// The [`crate::CentralPanel`] does not change this. pub available_rect: Rect, /// Starts off as the `screen_rect`, shrinks as panels are added. /// The [`crate::CentralPanel`] retracts from this. pub unused_rect: Rect, /// How much space is used by panels. pub used_by_panels: Rect, /// The current scroll area should scroll to this range (horizontal, vertical). pub scroll_target: [Option<ScrollTarget>; 2], /// The current scroll area should scroll by this much. /// /// The delta dictates how the _content_ should move. /// /// A positive X-value indicates the content is being moved right, /// as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, /// as when swiping down on a touch-screen or track-pad with natural scrolling. pub scroll_delta: (Vec2, style::ScrollAnimation), pub accesskit_state: Option<AccessKitPassState>, /// Highlight these widgets the next pass. pub highlight_next_pass: IdSet, #[cfg(debug_assertions)] pub debug_rect: Option<DebugRect>, } impl Default for PassState { fn default() -> Self { Self { used_ids: Default::default(), widgets: Default::default(), layers: Default::default(), tooltips: Default::default(), available_rect: Rect::NAN, unused_rect: Rect::NAN, used_by_panels: Rect::NAN, scroll_target: [None, None], scroll_delta: (Vec2::default(), style::ScrollAnimation::none()), accesskit_state: None, highlight_next_pass: Default::default(), #[cfg(debug_assertions)] debug_rect: None, } } } impl PassState { pub(crate) fn begin_pass(&mut self, content_rect: Rect) { profiling::function_scope!(); let Self { used_ids, widgets, tooltips, layers, available_rect, unused_rect, used_by_panels, scroll_target, scroll_delta, accesskit_state, highlight_next_pass, #[cfg(debug_assertions)] debug_rect, } = self; used_ids.clear(); widgets.clear(); tooltips.clear(); layers.clear(); *available_rect = content_rect; *unused_rect = content_rect; *used_by_panels = Rect::NOTHING; *scroll_target = [None, None]; *scroll_delta = Default::default(); #[cfg(debug_assertions)] { *debug_rect = None; } *accesskit_state = None; highlight_next_pass.clear(); } /// How much space is still available after panels has been added. pub(crate) fn available_rect(&self) -> Rect { debug_assert!( self.available_rect.is_finite(), "Called `available_rect()` before `Context::run()`" ); self.available_rect } /// Shrink `available_rect`. pub(crate) fn allocate_left_panel(&mut self, panel_rect: Rect) { debug_assert!( panel_rect.min.distance(self.available_rect.min) < 0.1, "Mismatching left panel. You must not create a panel from within another panel." ); self.available_rect.min.x = panel_rect.max.x; self.unused_rect.min.x = panel_rect.max.x; self.used_by_panels |= panel_rect; } /// Shrink `available_rect`. pub(crate) fn allocate_right_panel(&mut self, panel_rect: Rect) { debug_assert!( panel_rect.max.distance(self.available_rect.max) < 0.1, "Mismatching right panel. You must not create a panel from within another panel." ); self.available_rect.max.x = panel_rect.min.x; self.unused_rect.max.x = panel_rect.min.x; self.used_by_panels |= panel_rect; } /// Shrink `available_rect`. pub(crate) fn allocate_top_panel(&mut self, panel_rect: Rect) { debug_assert!( panel_rect.min.distance(self.available_rect.min) < 0.1, "Mismatching top panel. You must not create a panel from within another panel." ); self.available_rect.min.y = panel_rect.max.y; self.unused_rect.min.y = panel_rect.max.y; self.used_by_panels |= panel_rect; } /// Shrink `available_rect`. pub(crate) fn allocate_bottom_panel(&mut self, panel_rect: Rect) { debug_assert!( panel_rect.max.distance(self.available_rect.max) < 0.1, "Mismatching bottom panel. You must not create a panel from within another panel." ); self.available_rect.max.y = panel_rect.min.y; self.unused_rect.max.y = panel_rect.min.y; self.used_by_panels |= panel_rect; } pub(crate) fn allocate_central_panel(&mut self, panel_rect: Rect) { // Note: we do not shrink `available_rect`, because // we allow windows to cover the CentralPanel. self.unused_rect = Rect::NOTHING; // Nothing left unused after this self.used_by_panels |= panel_rect; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/menu.rs
crates/egui/src/menu.rs
#![expect(deprecated)] //! Deprecated menu API - Use [`crate::containers::menu`] instead. //! //! Usage: //! ``` //! fn show_menu(ui: &mut egui::Ui) { //! use egui::{menu, Button}; //! //! menu::bar(ui, |ui| { //! ui.menu_button("File", |ui| { //! if ui.button("Open").clicked() { //! // … //! } //! }); //! }); //! } //! ``` use super::{ Align, Context, Id, InnerResponse, PointerState, Pos2, Rect, Response, Sense, TextStyle, Ui, Vec2, style::WidgetVisuals, }; use crate::{ Align2, Area, Color32, Frame, Key, LayerId, Layout, NumExt as _, Order, Stroke, Style, TextWrapMode, UiKind, WidgetText, epaint, vec2, widgets::{Button, ImageButton}, }; use epaint::mutex::RwLock; use std::sync::Arc; /// What is saved between frames. #[derive(Clone, Default)] pub struct BarState { open_menu: MenuRootManager, } impl BarState { pub fn load(ctx: &Context, bar_id: Id) -> Self { ctx.data_mut(|d| d.get_temp::<Self>(bar_id).unwrap_or_default()) } pub fn store(self, ctx: &Context, bar_id: Id) { ctx.data_mut(|d| d.insert_temp(bar_id, self)); } /// Show a menu at pointer if primary-clicked response. /// /// Should be called from [`Context`] on a [`Response`] pub fn bar_menu<R>( &mut self, button: &Response, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { MenuRoot::stationary_click_interaction(button, &mut self.open_menu); self.open_menu.show(button, add_contents) } pub(crate) fn has_root(&self) -> bool { self.open_menu.inner.is_some() } } impl std::ops::Deref for BarState { type Target = MenuRootManager; fn deref(&self) -> &Self::Target { &self.open_menu } } impl std::ops::DerefMut for BarState { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.open_menu } } fn set_menu_style(style: &mut Style) { if style.compact_menu_style { style.spacing.button_padding = vec2(2.0, 0.0); style.visuals.widgets.active.bg_stroke = Stroke::NONE; style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; style.visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; } } /// The menu bar goes well in a [`crate::Panel::top`], /// but can also be placed in a [`crate::Window`]. /// In the latter case you may want to wrap it in [`Frame`]. #[deprecated = "Use `egui::MenuBar::new().ui(` instead"] pub fn bar<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { ui.horizontal(|ui| { set_menu_style(ui.style_mut()); // Take full width and fixed height: let height = ui.spacing().interact_size.y; ui.set_min_size(vec2(ui.available_width(), height)); add_contents(ui) }) } /// Construct a top level menu in a menu bar. This would be e.g. "File", "Edit" etc. /// /// Responds to primary clicks. /// /// Returns `None` if the menu is not open. pub fn menu_button<R>( ui: &mut Ui, title: impl Into<WidgetText>, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { stationary_menu_impl(ui, title, Box::new(add_contents)) } /// Construct a top level menu with a custom button in a menu bar. /// /// Responds to primary clicks. /// /// Returns `None` if the menu is not open. pub fn menu_custom_button<R>( ui: &mut Ui, button: Button<'_>, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { stationary_menu_button_impl(ui, button, Box::new(add_contents)) } /// Construct a top level menu with an image in a menu bar. This would be e.g. "File", "Edit" etc. /// /// Responds to primary clicks. /// /// Returns `None` if the menu is not open. #[deprecated = "Use `menu_custom_button` instead"] pub fn menu_image_button<R>( ui: &mut Ui, image_button: ImageButton<'_>, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { stationary_menu_button_impl( ui, Button::image(image_button.image), Box::new(add_contents), ) } /// Construct a nested sub menu in another menu. /// /// Opens on hover. /// /// Returns `None` if the menu is not open. pub fn submenu_button<R>( ui: &mut Ui, parent_state: Arc<RwLock<MenuState>>, title: impl Into<WidgetText>, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { SubMenu::new(parent_state, title).show(ui, add_contents) } /// wrapper for the contents of every menu. fn menu_popup<'c, R>( ctx: &Context, parent_layer: LayerId, menu_state_arc: &Arc<RwLock<MenuState>>, menu_id: Id, add_contents: impl FnOnce(&mut Ui) -> R + 'c, ) -> InnerResponse<R> { let pos = { let mut menu_state = menu_state_arc.write(); menu_state.entry_count = 0; menu_state.rect.min }; let area_id = menu_id.with("__menu"); ctx.pass_state_mut(|fs| { fs.layers .entry(parent_layer) .or_default() .open_popups .insert(area_id) }); let area = Area::new(area_id) .kind(UiKind::Menu) .order(Order::Foreground) .fixed_pos(pos) .default_width(ctx.global_style().spacing.menu_width) .sense(Sense::hover()); let mut sizing_pass = false; let area_response = area.show(ctx, |ui| { sizing_pass = ui.is_sizing_pass(); set_menu_style(ui.style_mut()); Frame::menu(ui.style()) .show(ui, |ui| { ui.set_menu_state(Some(Arc::clone(menu_state_arc))); ui.with_layout(Layout::top_down_justified(Align::LEFT), add_contents) .inner }) .inner }); let area_rect = area_response.response.rect; menu_state_arc.write().rect = if sizing_pass { // During the sizing pass we didn't know the size yet, // so we might have just constrained the position unnecessarily. // Therefore keep the original=desired position until the next frame. Rect::from_min_size(pos, area_rect.size()) } else { // We knew the size, and this is where it ended up (potentially constrained to screen). // Remember it for the future: area_rect }; area_response } /// Build a top level menu with a button. /// /// Responds to primary clicks. fn stationary_menu_impl<'c, R>( ui: &mut Ui, title: impl Into<WidgetText>, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<Option<R>> { let title = title.into(); let bar_id = ui.id(); let menu_id = bar_id.with(title.text()); let mut bar_state = BarState::load(ui.ctx(), bar_id); let mut button = Button::new(title); if bar_state.open_menu.is_menu_open(menu_id) { button = button.fill(ui.visuals().widgets.open.weak_bg_fill); button = button.stroke(ui.visuals().widgets.open.bg_stroke); } let button_response = ui.add(button); let inner = bar_state.bar_menu(&button_response, add_contents); bar_state.store(ui.ctx(), bar_id); InnerResponse::new(inner.map(|r| r.inner), button_response) } /// Build a top level menu with an image button. /// /// Responds to primary clicks. fn stationary_menu_button_impl<'c, R>( ui: &mut Ui, button: Button<'_>, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<Option<R>> { let bar_id = ui.id(); let mut bar_state = BarState::load(ui.ctx(), bar_id); let button_response = ui.add(button); let inner = bar_state.bar_menu(&button_response, add_contents); bar_state.store(ui.ctx(), bar_id); InnerResponse::new(inner.map(|r| r.inner), button_response) } pub(crate) const CONTEXT_MENU_ID_STR: &str = "__egui::context_menu"; /// Response to secondary clicks (right-clicks) by showing the given menu. pub fn context_menu( response: &Response, add_contents: impl FnOnce(&mut Ui), ) -> Option<InnerResponse<()>> { let menu_id = Id::new(CONTEXT_MENU_ID_STR); let mut bar_state = BarState::load(&response.ctx, menu_id); MenuRoot::context_click_interaction(response, &mut bar_state); let inner_response = bar_state.show(response, add_contents); bar_state.store(&response.ctx, menu_id); inner_response } /// Returns `true` if the context menu is opened for this widget. pub fn context_menu_opened(response: &Response) -> bool { let menu_id = Id::new(CONTEXT_MENU_ID_STR); let bar_state = BarState::load(&response.ctx, menu_id); bar_state.is_menu_open(response.id) } /// Stores the state for the context menu. #[derive(Clone, Default)] pub struct MenuRootManager { inner: Option<MenuRoot>, } impl MenuRootManager { /// Show a menu at pointer if right-clicked response. /// /// Should be called from [`Context`] on a [`Response`] pub fn show<R>( &mut self, button: &Response, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { if let Some(root) = self.inner.as_mut() { let (menu_response, inner_response) = root.show(button, add_contents); if menu_response.is_close() { self.inner = None; } inner_response } else { None } } fn is_menu_open(&self, id: Id) -> bool { self.inner.as_ref().map(|m| m.id) == Some(id) } } impl std::ops::Deref for MenuRootManager { type Target = Option<MenuRoot>; fn deref(&self) -> &Self::Target { &self.inner } } impl std::ops::DerefMut for MenuRootManager { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } /// Menu root associated with an Id from a Response #[derive(Clone)] pub struct MenuRoot { pub menu_state: Arc<RwLock<MenuState>>, pub id: Id, } impl MenuRoot { pub fn new(position: Pos2, id: Id) -> Self { Self { menu_state: Arc::new(RwLock::new(MenuState::new(position))), id, } } pub fn show<R>( &self, button: &Response, add_contents: impl FnOnce(&mut Ui) -> R, ) -> (MenuResponse, Option<InnerResponse<R>>) { if self.id == button.id { let inner_response = menu_popup( &button.ctx, button.layer_id, &self.menu_state, self.id, add_contents, ); let menu_state = self.menu_state.read(); let escape_pressed = button.ctx.input(|i| i.key_pressed(Key::Escape)); if menu_state.response.is_close() || escape_pressed || inner_response.response.should_close() { return (MenuResponse::Close, Some(inner_response)); } } (MenuResponse::Stay, None) } /// Interaction with a stationary menu, i.e. fixed in another Ui. /// /// Responds to primary clicks. fn stationary_interaction(button: &Response, root: &mut MenuRootManager) -> MenuResponse { let id = button.id; if (button.clicked() && root.is_menu_open(id)) || button.ctx.input(|i| i.key_pressed(Key::Escape)) { // menu open and button clicked or esc pressed return MenuResponse::Close; } else if (button.clicked() && !root.is_menu_open(id)) || (button.hovered() && root.is_some()) { // menu not open and button clicked // or button hovered while other menu is open let mut pos = button.rect.left_bottom(); let menu_frame = Frame::menu(&button.ctx.global_style()); pos.x -= menu_frame.total_margin().left; // Make fist button in menu align with the parent button pos.y += button.ctx.global_style().spacing.menu_spacing; if let Some(root) = root.inner.as_mut() { let menu_rect = root.menu_state.read().rect; let content_rect = button.ctx.input(|i| i.content_rect()); if pos.y + menu_rect.height() > content_rect.max.y { pos.y = content_rect.max.y - menu_rect.height() - button.rect.height(); } if pos.x + menu_rect.width() > content_rect.max.x { pos.x = content_rect.max.x - menu_rect.width(); } } if let Some(to_global) = button.ctx.layer_transform_to_global(button.layer_id) { pos = to_global * pos; } return MenuResponse::Create(pos, id); } else if button .ctx .input(|i| i.pointer.any_pressed() && i.pointer.primary_down()) && let Some(pos) = button.ctx.input(|i| i.pointer.interact_pos()) && let Some(root) = root.inner.as_mut() && root.id == id { // pressed somewhere while this menu is open let in_menu = root.menu_state.read().area_contains(pos); if !in_menu { return MenuResponse::Close; } } MenuResponse::Stay } /// Interaction with a context menu (secondary click). pub fn context_interaction(response: &Response, root: &mut Option<Self>) -> MenuResponse { let response = response.interact(Sense::click()); let hovered = response.hovered(); let secondary_clicked = response.secondary_clicked(); response.ctx.input(|input| { let pointer = &input.pointer; if let Some(pos) = pointer.interact_pos() { let (in_old_menu, destroy) = if let Some(root) = root { let in_old_menu = root.menu_state.read().area_contains(pos); let destroy = !in_old_menu && pointer.any_pressed() && root.id == response.id; (in_old_menu, destroy) } else { (false, false) }; if !in_old_menu { if hovered && secondary_clicked { return MenuResponse::Create(pos, response.id); } else if destroy || hovered && pointer.primary_down() { return MenuResponse::Close; } } } MenuResponse::Stay }) } pub fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) { match menu_response { MenuResponse::Create(pos, id) => { root.inner = Some(Self::new(pos, id)); } MenuResponse::Close => root.inner = None, MenuResponse::Stay => {} } } /// Respond to secondary (right) clicks. pub fn context_click_interaction(response: &Response, root: &mut MenuRootManager) { let menu_response = Self::context_interaction(response, root); Self::handle_menu_response(root, menu_response); } // Responds to primary clicks. pub fn stationary_click_interaction(button: &Response, root: &mut MenuRootManager) { let menu_response = Self::stationary_interaction(button, root); Self::handle_menu_response(root, menu_response); } } #[derive(Copy, Clone, PartialEq, Eq)] pub enum MenuResponse { Close, Stay, Create(Pos2, Id), } impl MenuResponse { pub fn is_close(&self) -> bool { *self == Self::Close } } pub struct SubMenuButton { text: WidgetText, icon: WidgetText, index: usize, } impl SubMenuButton { /// The `icon` can be an emoji (e.g. `⏵` right arrow), shown right of the label fn new(text: impl Into<WidgetText>, icon: impl Into<WidgetText>, index: usize) -> Self { Self { text: text.into(), icon: icon.into(), index, } } fn visuals<'a>( ui: &'a Ui, response: &Response, menu_state: &MenuState, sub_id: Id, ) -> &'a WidgetVisuals { if menu_state.is_open(sub_id) && !response.hovered() { &ui.style().visuals.widgets.open } else { ui.style().interact(response) } } #[inline] pub fn icon(mut self, icon: impl Into<WidgetText>) -> Self { self.icon = icon.into(); self } pub(crate) fn show(self, ui: &mut Ui, menu_state: &MenuState, sub_id: Id) -> Response { let Self { text, icon, .. } = self; let text_style = TextStyle::Button; let sense = Sense::click(); let text_icon_gap = ui.spacing().item_spacing.x; let button_padding = ui.spacing().button_padding; let total_extra = button_padding + button_padding; let text_available_width = ui.available_width() - total_extra.x; let text_galley = text.into_galley( ui, Some(TextWrapMode::Wrap), text_available_width, text_style.clone(), ); let icon_available_width = text_available_width - text_galley.size().x; let icon_galley = icon.into_galley( ui, Some(TextWrapMode::Wrap), icon_available_width, text_style, ); let text_and_icon_size = Vec2::new( text_galley.size().x + text_icon_gap + icon_galley.size().x, text_galley.size().y.max(icon_galley.size().y), ); let mut desired_size = text_and_icon_size + 2.0 * button_padding; desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y); let (rect, response) = ui.allocate_at_least(desired_size, sense); response.widget_info(|| { crate::WidgetInfo::labeled( crate::WidgetType::Button, ui.is_enabled(), text_galley.text(), ) }); if ui.is_rect_visible(rect) { let visuals = Self::visuals(ui, &response, menu_state, sub_id); let text_pos = Align2::LEFT_CENTER .align_size_within_rect(text_galley.size(), rect.shrink2(button_padding)) .min; let icon_pos = Align2::RIGHT_CENTER .align_size_within_rect(icon_galley.size(), rect.shrink2(button_padding)) .min; if ui.visuals().button_frame { ui.painter().rect_filled( rect.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, ); } let text_color = visuals.text_color(); ui.painter().galley(text_pos, text_galley, text_color); ui.painter().galley(icon_pos, icon_galley, text_color); } response } } pub struct SubMenu { button: SubMenuButton, parent_state: Arc<RwLock<MenuState>>, } impl SubMenu { fn new(parent_state: Arc<RwLock<MenuState>>, text: impl Into<WidgetText>) -> Self { let index = parent_state.write().next_entry_index(); Self { button: SubMenuButton::new(text, "⏵", index), parent_state, } } pub fn show<R>( self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { let sub_id = ui.id().with(self.button.index); let response = self.button.show(ui, &self.parent_state.read(), sub_id); self.parent_state .write() .submenu_button_interaction(ui, sub_id, &response); let inner = self.parent_state .write() .show_submenu(ui.ctx(), ui.layer_id(), sub_id, add_contents); InnerResponse::new(inner, response) } } /// Components of menu state, public for advanced usage. /// /// Usually you don't need to use it directly. pub struct MenuState { /// The opened sub-menu and its [`Id`] sub_menu: Option<(Id, Arc<RwLock<Self>>)>, /// Bounding box of this menu (without the sub-menu), /// including the frame and everything. pub rect: Rect, /// Used to check if any menu in the tree wants to close pub response: MenuResponse, /// Used to hash different [`Id`]s for sub-menus entry_count: usize, } impl MenuState { pub fn new(position: Pos2) -> Self { Self { rect: Rect::from_min_size(position, Vec2::ZERO), sub_menu: None, response: MenuResponse::Stay, entry_count: 0, } } /// Close menu hierarchy. pub fn close(&mut self) { self.response = MenuResponse::Close; } fn show_submenu<R>( &mut self, ctx: &Context, parent_layer: LayerId, id: Id, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { let (sub_response, response) = self.submenu(id).map(|sub| { let inner_response = menu_popup(ctx, parent_layer, sub, id, add_contents); if inner_response.response.should_close() { sub.write().close(); } (sub.read().response, inner_response.inner) })?; self.cascade_close_response(sub_response); Some(response) } /// Check if position is in the menu hierarchy's area. pub fn area_contains(&self, pos: Pos2) -> bool { self.rect.contains(pos) || self .sub_menu .as_ref() .is_some_and(|(_, sub)| sub.read().area_contains(pos)) } fn next_entry_index(&mut self) -> usize { self.entry_count += 1; self.entry_count - 1 } /// Sense button interaction opening and closing submenu. fn submenu_button_interaction(&mut self, ui: &Ui, sub_id: Id, button: &Response) { let pointer = ui.input(|i| i.pointer.clone()); let open = self.is_open(sub_id); if self.moving_towards_current_submenu(&pointer) { // We don't close the submenu if the pointer is on its way to hover it. // ensure to repaint once even when pointer is not moving ui.request_repaint(); } else if !open && button.hovered() { // TODO(emilk): open menu to the left if there isn't enough space to the right let mut pos = button.rect.right_top(); pos.x = self.rect.right() + ui.spacing().menu_spacing; pos.y -= Frame::menu(ui.style()).total_margin().top; // align the first button in the submenu with the parent button self.open_submenu(sub_id, pos); } else if open && ui.response().contains_pointer() && !button.hovered() && !self.hovering_current_submenu(&pointer) { // We are hovering something else in the menu, so close the submenu. self.close_submenu(); } } /// Check if pointer is moving towards current submenu. fn moving_towards_current_submenu(&self, pointer: &PointerState) -> bool { if pointer.is_still() { return false; } if let Some(sub_menu) = self.current_submenu() && let Some(pos) = pointer.hover_pos() { let rect = sub_menu.read().rect; return rect.intersects_ray(pos, pointer.direction().normalized()); } false } /// Check if pointer is hovering current submenu. fn hovering_current_submenu(&self, pointer: &PointerState) -> bool { if let Some(sub_menu) = self.current_submenu() && let Some(pos) = pointer.hover_pos() { return sub_menu.read().area_contains(pos); } false } /// Cascade close response to menu root. fn cascade_close_response(&mut self, response: MenuResponse) { if response.is_close() { self.response = response; } } fn is_open(&self, id: Id) -> bool { self.sub_id() == Some(id) } fn sub_id(&self) -> Option<Id> { self.sub_menu.as_ref().map(|(id, _)| *id) } fn current_submenu(&self) -> Option<&Arc<RwLock<Self>>> { self.sub_menu.as_ref().map(|(_, sub)| sub) } fn submenu(&self, id: Id) -> Option<&Arc<RwLock<Self>>> { let (k, sub) = self.sub_menu.as_ref()?; if id == *k { Some(sub) } else { None } } /// Open submenu at position, if not already open. fn open_submenu(&mut self, id: Id, pos: Pos2) { if !self.is_open(id) { self.sub_menu = Some((id, Arc::new(RwLock::new(Self::new(pos))))); } } fn close_submenu(&mut self) { self.sub_menu = None; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/interaction.rs
crates/egui/src/interaction.rs
//! How mouse and touch interzcts with widgets. use crate::{Id, InputState, Key, WidgetRects, hit_test, id, input_state, memory}; use self::{hit_test::WidgetHits, id::IdSet, input_state::PointerEvent, memory::InteractionState}; /// Calculated at the start of each frame /// based on: /// * Widget rects from precious frame /// * Mouse/touch input /// * Current [`InteractionState`]. #[derive(Clone, Default)] pub struct InteractionSnapshot { /// The widget that got clicked this frame. pub clicked: Option<Id>, /// This widget was long-pressed on a touch screen, /// so trigger a secondary click on it (context menu). pub long_touched: Option<Id>, /// Drag started on this widget this frame. /// /// This will also be found in `dragged` this frame. pub drag_started: Option<Id>, /// This widget is being dragged this frame. /// /// Set the same frame a drag starts, /// but unset the frame a drag ends. /// /// NOTE: this may not have a corresponding [`crate::WidgetRect`], /// if this for instance is a drag-and-drop widget which /// isn't painted whilst being dragged pub dragged: Option<Id>, /// This widget was let go this frame, /// after having been dragged. /// /// The widget will not be found in [`Self::dragged`] this frame. pub drag_stopped: Option<Id>, /// A small set of widgets (usually 0-1) that the pointer is hovering over. /// /// Show these widgets as highlighted, if they are interactive. /// /// While dragging or clicking something, nothing else is hovered. /// /// Use [`Self::contains_pointer`] to find a drop-zone for drag-and-drop. pub hovered: IdSet, /// All widgets that contain the pointer this frame, /// regardless if the user is currently clicking or dragging. /// /// This is usually a larger set than [`Self::hovered`], /// and can be used for e.g. drag-and-drop zones. pub contains_pointer: IdSet, } impl InteractionSnapshot { pub fn ui(&self, ui: &mut crate::Ui) { let Self { clicked, long_touched, drag_started, dragged, drag_stopped, hovered, contains_pointer, } = self; fn id_ui<'a>(ui: &mut crate::Ui, widgets: impl IntoIterator<Item = &'a Id>) { for id in widgets { ui.label(id.short_debug_format()); } } crate::Grid::new("interaction").show(ui, |ui| { ui.label("clicked"); id_ui(ui, clicked); ui.end_row(); ui.label("long_touched"); id_ui(ui, long_touched); ui.end_row(); ui.label("drag_started"); id_ui(ui, drag_started); ui.end_row(); ui.label("dragged"); id_ui(ui, dragged); ui.end_row(); ui.label("drag_stopped"); id_ui(ui, drag_stopped); ui.end_row(); ui.label("hovered"); id_ui(ui, hovered); ui.end_row(); ui.label("contains_pointer"); id_ui(ui, contains_pointer); ui.end_row(); }); } } pub(crate) fn interact( prev_snapshot: &InteractionSnapshot, widgets: &WidgetRects, hits: &WidgetHits, input: &InputState, interaction: &mut InteractionState, ) -> InteractionSnapshot { profiling::function_scope!(); if let Some(id) = interaction.potential_click_id && !widgets.contains(id) { // The widget we were interested in clicking is gone. interaction.potential_click_id = None; } if let Some(id) = interaction.potential_drag_id && !widgets.contains(id) { // The widget we were interested in dragging is gone. // This is fine! This could be drag-and-drop, // and the widget being dragged is now "in the air" and thus // not registered in the new frame. } let mut clicked = None; let mut dragged = prev_snapshot.dragged; let mut long_touched = None; if input.key_pressed(Key::Escape) { // Abort dragging on escape dragged = None; interaction.potential_drag_id = None; } if input.is_long_touch() { // We implement "press-and-hold for context menu" on touch screens here if let Some(widget) = interaction .potential_click_id .and_then(|id| widgets.get(id)) { dragged = None; clicked = Some(widget.id); long_touched = Some(widget.id); interaction.potential_click_id = None; interaction.potential_drag_id = None; } } // Note: in the current code a press-release in the same frame is NOT considered a drag. for pointer_event in &input.pointer.pointer_events { match pointer_event { PointerEvent::Moved(_) => {} PointerEvent::Pressed { .. } => { // Maybe new click? if interaction.potential_click_id.is_none() { interaction.potential_click_id = hits.click.map(|w| w.id); } // Maybe new drag? if interaction.potential_drag_id.is_none() { interaction.potential_drag_id = hits.drag.map(|w| w.id); } } PointerEvent::Released { click, button: _ } => { if click.is_some() && !input.pointer.is_decidedly_dragging() && let Some(widget) = interaction .potential_click_id .and_then(|id| widgets.get(id)) { clicked = Some(widget.id); } interaction.potential_drag_id = None; interaction.potential_click_id = None; dragged = None; } } } if dragged.is_none() { // Check if we started dragging something new: if let Some(widget) = interaction.potential_drag_id.and_then(|id| widgets.get(id)) && widget.enabled { let is_dragged = if widget.sense.senses_click() && widget.sense.senses_drag() { // This widget is sensitive to both clicks and drags. // When the mouse first is pressed, it could be either, // so we postpone the decision until we know. input.pointer.is_decidedly_dragging() } else { // This widget is just sensitive to drags, so we can mark it as dragged right away: widget.sense.senses_drag() }; if is_dragged { dragged = Some(widget.id); } } } if !input.pointer.could_any_button_be_click() { interaction.potential_click_id = None; } if !input.pointer.any_down() || input.pointer.latest_pos().is_none() { interaction.potential_click_id = None; interaction.potential_drag_id = None; } // ------------------------------------------------------------------------ let drag_changed = dragged != prev_snapshot.dragged; let drag_stopped = drag_changed.then_some(prev_snapshot.dragged).flatten(); let drag_started = drag_changed.then_some(dragged).flatten(); // if let Some(drag_started) = drag_started { // eprintln!( // "Started dragging {} {:?}", // drag_started.id.short_debug_format(), // drag_started.rect // ); // } let contains_pointer: IdSet = hits .contains_pointer .iter() .chain(&hits.click) .chain(&hits.drag) .map(|w| w.id) .collect(); let hovered = if clicked.is_some() || dragged.is_some() || long_touched.is_some() { // If currently clicking or dragging, only that and nothing else is hovered. clicked .iter() .chain(&dragged) .chain(&long_touched) .copied() .collect() } else { // We may be hovering an interactive widget or two. // We must also consider the case where non-interactive widgets // are _on top_ of an interactive widget. // For instance: a label in a draggable window. // In that case we want to hover _both_ widgets, // otherwise we won't see tooltips for the label. // // So: we want to hover _all_ widgets above the interactive widget (if any), // but none below it (an interactive widget stops the hover search). // // To know when to stop we need to first know the order of the widgets, // which luckily we already have in `hits.close`. let order = |id| hits.close.iter().position(|w| w.id == id); let click_order = hits.click.and_then(|w| order(w.id)).unwrap_or(0); let drag_order = hits.drag.and_then(|w| order(w.id)).unwrap_or(0); let top_interactive_order = click_order.max(drag_order); let mut hovered: IdSet = hits.click.iter().chain(&hits.drag).map(|w| w.id).collect(); for w in &hits.contains_pointer { let is_interactive = w.sense.senses_click() || w.sense.senses_drag(); if is_interactive { // The only interactive widgets we mark as hovered are the ones // in `hits.click` and `hits.drag`! } else { let is_on_top_of_the_interactive_widget = top_interactive_order <= order(w.id).unwrap_or(0); if is_on_top_of_the_interactive_widget { hovered.insert(w.id); } } } hovered }; InteractionSnapshot { clicked, long_touched, drag_started, dragged, drag_stopped, hovered, contains_pointer, } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/grid.rs
crates/egui/src/grid.rs
use std::sync::Arc; use emath::GuiRounding as _; use crate::{ Align2, Color32, Context, Id, InnerResponse, NumExt as _, Painter, Rect, Region, Style, Ui, UiBuilder, Vec2, vec2, }; #[cfg(debug_assertions)] use crate::Stroke; #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct State { col_widths: Vec<f32>, row_heights: Vec<f32>, } impl State { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_temp(id)) } pub fn store(self, ctx: &Context, id: Id) { // We don't persist Grids, because // A) there are potentially a lot of them, using up a lot of space (and therefore serialization time) // B) if the code changes, the grid _should_ change, and not remember old sizes ctx.data_mut(|d| d.insert_temp(id, self)); } fn set_min_col_width(&mut self, col: usize, width: f32) { self.col_widths .resize(self.col_widths.len().max(col + 1), 0.0); self.col_widths[col] = self.col_widths[col].max(width); } fn set_min_row_height(&mut self, row: usize, height: f32) { self.row_heights .resize(self.row_heights.len().max(row + 1), 0.0); self.row_heights[row] = self.row_heights[row].max(height); } fn col_width(&self, col: usize) -> Option<f32> { self.col_widths.get(col).copied() } fn row_height(&self, row: usize) -> Option<f32> { self.row_heights.get(row).copied() } fn full_width(&self, x_spacing: f32) -> f32 { self.col_widths.iter().sum::<f32>() + (self.col_widths.len().at_least(1) - 1) as f32 * x_spacing } } // ---------------------------------------------------------------------------- // type alias for boxed function to determine row color during grid generation type ColorPickerFn = Box<dyn Send + Sync + Fn(usize, &Style) -> Option<Color32>>; pub(crate) struct GridLayout { ctx: Context, style: std::sync::Arc<Style>, id: Id, /// First frame (no previous know state). is_first_frame: bool, /// State previous frame (if any). /// This can be used to predict future sizes of cells. prev_state: State, /// State accumulated during the current frame. curr_state: State, initial_available: Rect, // Options: num_columns: Option<usize>, spacing: Vec2, min_cell_size: Vec2, max_cell_size: Vec2, color_picker: Option<ColorPickerFn>, // Cursor: col: usize, row: usize, } impl GridLayout { pub(crate) fn new(ui: &Ui, id: Id, prev_state: Option<State>) -> Self { let is_first_frame = prev_state.is_none(); let prev_state = prev_state.unwrap_or_default(); // TODO(emilk): respect current layout let initial_available = ui.placer().max_rect().intersect(ui.cursor()); debug_assert!( initial_available.min.x.is_finite(), "Grid not yet available for right-to-left layouts" ); ui.ctx().check_for_id_clash(id, initial_available, "Grid"); Self { ctx: ui.ctx().clone(), style: Arc::clone(ui.style()), id, is_first_frame, prev_state, curr_state: State::default(), initial_available, num_columns: None, spacing: ui.spacing().item_spacing, min_cell_size: ui.spacing().interact_size, max_cell_size: Vec2::INFINITY, color_picker: None, col: 0, row: 0, } } } impl GridLayout { fn prev_col_width(&self, col: usize) -> f32 { self.prev_state .col_width(col) .unwrap_or(self.min_cell_size.x) } fn prev_row_height(&self, row: usize) -> f32 { self.prev_state .row_height(row) .unwrap_or(self.min_cell_size.y) } pub(crate) fn wrap_text(&self) -> bool { self.max_cell_size.x.is_finite() } pub(crate) fn available_rect(&self, region: &Region) -> Rect { let is_last_column = Some(self.col + 1) == self.num_columns; let width = if is_last_column { // The first frame we don't really know the widths of the previous columns, // so returning a big available width here can cause trouble. if self.is_first_frame { self.curr_state .col_width(self.col) .unwrap_or(self.min_cell_size.x) } else { (self.initial_available.right() - region.cursor.left()) .at_most(self.max_cell_size.x) } } else if self.max_cell_size.x.is_finite() { // TODO(emilk): should probably heed `prev_state` here too self.max_cell_size.x } else { // If we want to allow width-filling widgets like [`Separator`] in one of the first cells // then we need to make sure they don't spill out of the first cell: self.prev_state .col_width(self.col) .or_else(|| self.curr_state.col_width(self.col)) .unwrap_or(self.min_cell_size.x) }; // If something above was wider, we can be wider: let width = width.max(self.curr_state.col_width(self.col).unwrap_or(0.0)); let available = region.max_rect.intersect(region.cursor); let height = region.max_rect.max.y - available.top(); let height = height .at_least(self.min_cell_size.y) .at_most(self.max_cell_size.y); Rect::from_min_size(available.min, vec2(width, height)) } pub(crate) fn next_cell(&self, cursor: Rect, child_size: Vec2) -> Rect { let width = self.prev_state.col_width(self.col).unwrap_or(0.0); let height = self.prev_row_height(self.row); let size = child_size.max(vec2(width, height)); Rect::from_min_size(cursor.min, size).round_ui() } #[expect(clippy::unused_self)] pub(crate) fn align_size_within_rect(&self, size: Vec2, frame: Rect) -> Rect { // TODO(emilk): allow this alignment to be customized Align2::LEFT_CENTER .align_size_within_rect(size, frame) .round_ui() } pub(crate) fn justify_and_align(&self, frame: Rect, size: Vec2) -> Rect { self.align_size_within_rect(size, frame) } pub(crate) fn advance(&mut self, cursor: &mut Rect, _frame_rect: Rect, widget_rect: Rect) { #[cfg(debug_assertions)] { let debug_expand_width = self.style.debug.show_expand_width; let debug_expand_height = self.style.debug.show_expand_height; if debug_expand_width || debug_expand_height { let rect = widget_rect; let too_wide = rect.width() > self.prev_col_width(self.col); let too_high = rect.height() > self.prev_row_height(self.row); if (debug_expand_width && too_wide) || (debug_expand_height && too_high) { let painter = self.ctx.debug_painter(); painter.rect_stroke( rect, 0.0, (1.0, Color32::LIGHT_BLUE), crate::StrokeKind::Inside, ); let stroke = Stroke::new(2.5, Color32::from_rgb(200, 0, 0)); let paint_line_seg = |a, b| painter.line_segment([a, b], stroke); if debug_expand_width && too_wide { paint_line_seg(rect.left_top(), rect.left_bottom()); paint_line_seg(rect.left_center(), rect.right_center()); paint_line_seg(rect.right_top(), rect.right_bottom()); } } } } self.curr_state .set_min_col_width(self.col, widget_rect.width().max(self.min_cell_size.x)); self.curr_state .set_min_row_height(self.row, widget_rect.height().max(self.min_cell_size.y)); cursor.min.x += self.prev_col_width(self.col) + self.spacing.x; self.col += 1; } fn paint_row(&self, cursor: &Rect, painter: &Painter) { // handle row color painting based on color-picker function let Some(color_picker) = self.color_picker.as_ref() else { return; }; let Some(row_color) = color_picker(self.row, &self.style) else { return; }; let Some(height) = self.prev_state.row_height(self.row) else { return; }; // Paint background for coming row: let size = Vec2::new(self.prev_state.full_width(self.spacing.x), height); let rect = Rect::from_min_size(cursor.min, size); let rect = rect.expand2(0.5 * self.spacing.y * Vec2::Y); let rect = rect.expand2(2.0 * Vec2::X); // HACK: just looks better with some spacing on the sides painter.rect_filled(rect, 2.0, row_color); } pub(crate) fn end_row(&mut self, cursor: &mut Rect, painter: &Painter) { cursor.min.x = self.initial_available.min.x; cursor.min.y += self.spacing.y; cursor.min.y += self .curr_state .row_height(self.row) .unwrap_or(self.min_cell_size.y); self.col = 0; self.row += 1; self.paint_row(cursor, painter); } pub(crate) fn save(&self) { // We need to always save state on the first frame, otherwise request_discard // would be called repeatedly (see #5132) if self.curr_state != self.prev_state || self.is_first_frame { self.curr_state.clone().store(&self.ctx, self.id); self.ctx.request_repaint(); } } } // ---------------------------------------------------------------------------- /// A simple grid layout. /// /// The cells are always laid out left to right, top-down. /// The contents of each cell will be aligned to the left and center. /// /// If you want to add multiple widgets to a cell you need to group them with /// [`Ui::horizontal`], [`Ui::vertical`] etc. /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::Grid::new("some_unique_id").show(ui, |ui| { /// ui.label("First row, first column"); /// ui.label("First row, second column"); /// ui.end_row(); /// /// ui.label("Second row, first column"); /// ui.label("Second row, second column"); /// ui.label("Second row, third column"); /// ui.end_row(); /// /// ui.horizontal(|ui| { ui.label("Same"); ui.label("cell"); }); /// ui.label("Third row, second column"); /// ui.end_row(); /// }); /// # }); /// ``` #[must_use = "You should call .show()"] pub struct Grid { id_salt: Id, num_columns: Option<usize>, min_col_width: Option<f32>, min_row_height: Option<f32>, max_cell_size: Vec2, spacing: Option<Vec2>, start_row: usize, color_picker: Option<ColorPickerFn>, } impl Grid { /// Create a new [`Grid`] with a locally unique identifier. pub fn new(id_salt: impl std::hash::Hash) -> Self { Self { id_salt: Id::new(id_salt), num_columns: None, min_col_width: None, min_row_height: None, max_cell_size: Vec2::INFINITY, spacing: None, start_row: 0, color_picker: None, } } /// Setting this will allow for dynamic coloring of rows of the grid object #[inline] pub fn with_row_color<F>(mut self, color_picker: F) -> Self where F: Send + Sync + Fn(usize, &Style) -> Option<Color32> + 'static, { self.color_picker = Some(Box::new(color_picker)); self } /// Setting this will allow the last column to expand to take up the rest of the space of the parent [`Ui`]. #[inline] pub fn num_columns(mut self, num_columns: usize) -> Self { self.num_columns = Some(num_columns); self } /// If `true`, add a subtle background color to every other row. /// /// This can make a table easier to read. /// Default is whatever is in [`crate::Visuals::striped`]. pub fn striped(self, striped: bool) -> Self { if striped { self.with_row_color(striped_row_color) } else { // Explicitly set the row color to nothing. // Needed so that when the style.visuals.striped value is checked later on, // it is clear that the user does not want stripes on this specific Grid. self.with_row_color(|_row: usize, _style: &Style| None) } } /// Set minimum width of each column. /// Default: [`crate::style::Spacing::interact_size`]`.x`. #[inline] pub fn min_col_width(mut self, min_col_width: f32) -> Self { self.min_col_width = Some(min_col_width); self } /// Set minimum height of each row. /// Default: [`crate::style::Spacing::interact_size`]`.y`. #[inline] pub fn min_row_height(mut self, min_row_height: f32) -> Self { self.min_row_height = Some(min_row_height); self } /// Set soft maximum width (wrapping width) of each column. #[inline] pub fn max_col_width(mut self, max_col_width: f32) -> Self { self.max_cell_size.x = max_col_width; self } /// Set spacing between columns/rows. /// Default: [`crate::style::Spacing::item_spacing`]. #[inline] pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self { self.spacing = Some(spacing.into()); self } /// Change which row number the grid starts on. /// This can be useful when you have a large [`crate::Grid`] inside of [`crate::ScrollArea::show_rows`]. #[inline] pub fn start_row(mut self, start_row: usize) -> Self { self.start_row = start_row; self } } impl Grid { pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { self.show_dyn(ui, Box::new(add_contents)) } fn show_dyn<'c, R>( self, ui: &mut Ui, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<R> { let Self { id_salt, num_columns, min_col_width, min_row_height, max_cell_size, spacing, start_row, mut color_picker, } = self; let min_col_width = min_col_width.unwrap_or_else(|| ui.spacing().interact_size.x); let min_row_height = min_row_height.unwrap_or_else(|| ui.spacing().interact_size.y); let spacing = spacing.unwrap_or_else(|| ui.spacing().item_spacing); if color_picker.is_none() && ui.visuals().striped { color_picker = Some(Box::new(striped_row_color)); } let id = ui.make_persistent_id(id_salt); let prev_state = State::load(ui.ctx(), id); // Each grid cell is aligned LEFT_CENTER. // If somebody wants to wrap more things inside a cell, // then we should pick a default layout that matches that alignment, // which we do here: let max_rect = ui.cursor().intersect(ui.max_rect()); let mut ui_builder = UiBuilder::new().max_rect(max_rect); if prev_state.is_none() { // The initial frame will be glitchy, because we don't know the sizes of things to come. if ui.is_visible() { // Try to cover up the glitchy initial frame: ui.request_discard("new Grid"); } // Hide the ui this frame, and make things as narrow as possible: ui_builder = ui_builder.sizing_pass().invisible(); } ui.scope_builder(ui_builder, |ui| { ui.horizontal(|ui| { let is_color = color_picker.is_some(); let grid = GridLayout { num_columns, color_picker, min_cell_size: vec2(min_col_width, min_row_height), max_cell_size, spacing, row: start_row, ..GridLayout::new(ui, id, prev_state) }; // paint first incoming row if is_color { let cursor = ui.cursor(); let painter = ui.painter(); grid.paint_row(&cursor, painter); } ui.set_grid(grid); let r = add_contents(ui); ui.save_grid(); r }) .inner }) } } fn striped_row_color(row: usize, style: &Style) -> Option<Color32> { if row % 2 == 1 { return Some(style.visuals.faint_bg_color); } None }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/drag_and_drop.rs
crates/egui/src/drag_and_drop.rs
use std::{any::Any, sync::Arc}; use crate::{Context, CursorIcon, Plugin, Ui}; /// Plugin for tracking drag-and-drop payload. /// /// This plugin stores the current drag-and-drop payload internally and handles /// automatic cleanup when the drag operation ends (via Escape key or mouse release). /// /// This is a low-level API. For a higher-level API, see: /// - [`crate::Ui::dnd_drag_source`] /// - [`crate::Ui::dnd_drop_zone`] /// - [`crate::Response::dnd_set_drag_payload`] /// - [`crate::Response::dnd_hover_payload`] /// - [`crate::Response::dnd_release_payload`] /// /// This is a built-in plugin in egui, automatically registered during [`Context`] creation. /// /// See [this example](https://github.com/emilk/egui/blob/main/crates/egui_demo_lib/src/demo/drag_and_drop.rs). #[doc(alias = "drag and drop")] #[derive(Clone, Default)] pub struct DragAndDrop { /// The current drag-and-drop payload, if any. Automatically cleared when drag ends. payload: Option<Arc<dyn Any + Send + Sync>>, } impl Plugin for DragAndDrop { fn debug_name(&self) -> &'static str { "DragAndDrop" } /// Interrupt drag-and-drop if the user presses the escape key. /// /// This needs to happen at frame start so we can properly capture the escape key. fn on_begin_pass(&mut self, ui: &mut Ui) { let has_any_payload = self.payload.is_some(); if has_any_payload { let abort_dnd_due_to_escape_key = ui.input_mut(|i| i.consume_key(crate::Modifiers::NONE, crate::Key::Escape)); if abort_dnd_due_to_escape_key { self.payload = None; } } } /// Interrupt drag-and-drop if the user releases the mouse button. /// /// This is a catch-all safety net in case user code doesn't capture the drag payload itself. /// This must happen at end-of-frame such that we don't shadow the mouse release event from user /// code. fn on_end_pass(&mut self, ui: &mut Ui) { let has_any_payload = self.payload.is_some(); if has_any_payload { let abort_dnd_due_to_mouse_release = ui.input_mut(|i| i.pointer.any_released()); if abort_dnd_due_to_mouse_release { self.payload = None; } else { // We set the cursor icon only if its default, as the user code might have // explicitly set it already. ui.output_mut(|o| { if o.cursor_icon == CursorIcon::Default { o.cursor_icon = CursorIcon::Grabbing; } }); } } } } impl DragAndDrop { /// Set a drag-and-drop payload. /// /// This can be read by [`Self::payload`] until the pointer is released. pub fn set_payload<Payload>(ctx: &Context, payload: Payload) where Payload: Any + Send + Sync, { ctx.plugin::<Self>().lock().payload = Some(Arc::new(payload)); } /// Clears the payload, setting it to `None`. pub fn clear_payload(ctx: &Context) { ctx.plugin::<Self>().lock().payload = None; } /// Retrieve the payload, if any. /// /// Returns `None` if there is no payload, or if it is not of the requested type. /// /// Returns `Some` both during a drag and on the frame the pointer is released /// (if there is a payload). pub fn payload<Payload>(ctx: &Context) -> Option<Arc<Payload>> where Payload: Any + Send + Sync, { Arc::clone(ctx.plugin::<Self>().lock().payload.as_ref()?) .downcast() .ok() } /// Retrieve and clear the payload, if any. /// /// Returns `None` if there is no payload, or if it is not of the requested type. /// /// Returns `Some` both during a drag and on the frame the pointer is released /// (if there is a payload). pub fn take_payload<Payload>(ctx: &Context) -> Option<Arc<Payload>> where Payload: Any + Send + Sync, { ctx.plugin::<Self>().lock().payload.take()?.downcast().ok() } /// Are we carrying a payload of the given type? /// /// Returns `true` both during a drag and on the frame the pointer is released /// (if there is a payload). pub fn has_payload_of_type<Payload>(ctx: &Context) -> bool where Payload: Any + Send + Sync, { Self::payload::<Payload>(ctx).is_some() } /// Are we carrying a payload? /// /// Returns `true` both during a drag and on the frame the pointer is released /// (if there is a payload). pub fn has_any_payload(ctx: &Context) -> bool { ctx.plugin::<Self>().lock().payload.is_some() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widget_rect.rs
crates/egui/src/widget_rect.rs
use ahash::HashMap; use crate::{Id, IdMap, LayerId, Rect, Sense, WidgetInfo}; /// Used to store each widget's [Id], [Rect] and [Sense] each frame. /// /// Used to check which widget gets input when a user clicks somewhere. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WidgetRect { /// The globally unique widget id. /// /// For interactive widgets, this better be globally unique. /// If not there will be weird bugs, /// and also big red warning test on the screen in debug builds /// (see [`crate::Options::warn_on_id_clash`]). /// /// You can ensure globally unique ids using [`crate::Ui::push_id`]. pub id: Id, /// What layer the widget is on. pub layer_id: LayerId, /// The full widget rectangle, in local layer coordinates. pub rect: Rect, /// Where the widget is, in local layer coordinates. /// /// This is after clipping with the parent ui clip rect. pub interact_rect: Rect, /// How the widget responds to interaction. /// /// Note: if [`Self::enabled`] is `false`, then /// the widget _effectively_ doesn't sense anything, /// but can still have the same `Sense`. /// This is because the sense informs the styling of the widget, /// but we don't want to change the style when a widget is disabled /// (that is handled by the `Painter` directly). pub sense: Sense, /// Is the widget enabled? pub enabled: bool, } impl WidgetRect { pub fn transform(self, transform: emath::TSTransform) -> Self { let Self { id, layer_id, rect, interact_rect, sense, enabled, } = self; Self { id, layer_id, rect: transform * rect, interact_rect: transform * interact_rect, sense, enabled, } } } /// How to handle multiple calls to [`crate::Response::interact`] and [`crate::Ui::interact_opt`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InteractOptions { /// If we call interact on the same widget multiple times, /// should we move it to the top on subsequent calls? pub move_to_top: bool, } #[expect(clippy::derivable_impls)] // Nice to be explicit impl Default for InteractOptions { fn default() -> Self { Self { move_to_top: false } } } /// Stores the [`WidgetRect`]s of all widgets generated during a single egui update/frame. /// /// All [`crate::Ui`]s have a [`WidgetRect`]. It is created in [`crate::Ui::new`] with [`Rect::NOTHING`] /// and updated with the correct [`Rect`] when the [`crate::Ui`] is dropped. #[derive(Default, Clone)] pub struct WidgetRects { /// All widgets, in painting order. by_layer: HashMap<LayerId, Vec<WidgetRect>>, /// All widgets, by id, and their order in their respective layer by_id: IdMap<(usize, WidgetRect)>, /// Info about some widgets. /// /// Only filled in if the widget is interacted with, /// or if this is a debug build. infos: IdMap<WidgetInfo>, } impl PartialEq for WidgetRects { fn eq(&self, other: &Self) -> bool { self.by_layer == other.by_layer } } impl WidgetRects { /// All known layers with widgets. pub fn layer_ids(&self) -> impl ExactSizeIterator<Item = LayerId> + '_ { self.by_layer.keys().copied() } pub fn layers(&self) -> impl Iterator<Item = (&LayerId, &[WidgetRect])> + '_ { self.by_layer .iter() .map(|(layer_id, rects)| (layer_id, &rects[..])) } #[inline] pub fn get(&self, id: Id) -> Option<&WidgetRect> { self.by_id.get(&id).map(|(_, w)| w) } /// In which layer, and in which order in that layer? pub fn order(&self, id: Id) -> Option<(LayerId, usize)> { self.by_id.get(&id).map(|(idx, w)| (w.layer_id, *idx)) } #[inline] pub fn contains(&self, id: Id) -> bool { self.by_id.contains_key(&id) } /// All widgets in this layer, sorted back-to-front. #[inline] pub fn get_layer(&self, layer_id: LayerId) -> impl Iterator<Item = &WidgetRect> + '_ { self.by_layer.get(&layer_id).into_iter().flatten() } /// Clear the contents while retaining allocated memory. pub fn clear(&mut self) { let Self { by_layer, by_id, infos, } = self; #[expect(clippy::iter_over_hash_type)] for rects in by_layer.values_mut() { rects.clear(); } by_id.clear(); infos.clear(); } /// Insert the given widget rect in the given layer. pub fn insert(&mut self, layer_id: LayerId, widget_rect: WidgetRect, options: InteractOptions) { let Self { by_layer, by_id, infos: _, } = self; let InteractOptions { move_to_top } = options; let layer_widgets = by_layer.entry(layer_id).or_default(); match by_id.entry(widget_rect.id) { std::collections::hash_map::Entry::Vacant(entry) => { // A new widget let idx_in_layer = layer_widgets.len(); entry.insert((idx_in_layer, widget_rect)); layer_widgets.push(widget_rect); } std::collections::hash_map::Entry::Occupied(mut entry) => { // This is a known widget, but we might need to update it! // e.g. calling `response.interact(…)` to add more interaction. let (idx_in_layer, existing) = entry.get_mut(); // Update it: existing.rect = widget_rect.rect; // last wins existing.interact_rect = widget_rect.interact_rect; // last wins existing.sense |= widget_rect.sense; existing.enabled |= widget_rect.enabled; if existing.layer_id == widget_rect.layer_id { if move_to_top { layer_widgets.remove(*idx_in_layer); *idx_in_layer = layer_widgets.len(); layer_widgets.push(*existing); } else { layer_widgets[*idx_in_layer] = *existing; } } else if cfg!(debug_assertions) { panic!( "DEBUG ASSERT: Widget {:?} changed layer_id during the frame from {:?} to {:?}", widget_rect.id, existing.layer_id, widget_rect.layer_id ); } } } } pub fn set_info(&mut self, id: Id, info: WidgetInfo) { self.infos.insert(id, info); } pub fn info(&self, id: Id) -> Option<&WidgetInfo> { self.infos.get(&id) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/layout.rs
crates/egui/src/layout.rs
use emath::GuiRounding as _; use crate::{ Align, emath::{Align2, NumExt as _, Pos2, Rect, Vec2, pos2, vec2}, }; const INFINITY: f32 = f32::INFINITY; // ---------------------------------------------------------------------------- /// This describes the bounds and existing contents of an [`Ui`][`crate::Ui`]. /// It is what is used and updated by [`Layout`] when adding new widgets. #[derive(Clone, Copy, Debug)] pub(crate) struct Region { /// This is the minimal size of the [`Ui`](crate::Ui). /// When adding new widgets, this will generally expand. /// /// Always finite. /// /// The bounding box of all child widgets, but not necessarily a tight bounding box /// since [`Ui`](crate::Ui) can start with a non-zero `min_rect` size. pub min_rect: Rect, /// The maximum size of this [`Ui`](crate::Ui). This is a *soft max* /// meaning new widgets will *try* not to expand beyond it, /// but if they have to, they will. /// /// Text will wrap at `max_rect.right()`. /// Some widgets (like separator lines) will try to fill the full `max_rect` width of the ui. /// /// `max_rect` will always be at least the size of `min_rect`. /// /// If the `max_rect` size is zero, it is a signal that child widgets should be as small as possible. /// If the `max_rect` size is infinite, it is a signal that child widgets should take up as much room as they want. pub max_rect: Rect, /// Where the next widget will be put. /// /// One side of this will always be infinite: the direction in which new widgets will be added. /// The opposing side is what is incremented. /// The crossing sides are initialized to `max_rect`. /// /// So one can think of `cursor` as a constraint on the available region. /// /// If something has already been added, this will point to `style.spacing.item_spacing` beyond the latest child. /// The cursor can thus be `style.spacing.item_spacing` pixels outside of the `min_rect`. pub(crate) cursor: Rect, } impl Region { /// Expand the `min_rect` and `max_rect` of this ui to include a child at the given rect. pub fn expand_to_include_rect(&mut self, rect: Rect) { self.min_rect |= rect; self.max_rect |= rect; } /// Ensure we are big enough to contain the given X-coordinate. /// This is sometimes useful to expand a ui to stretch to a certain place. pub fn expand_to_include_x(&mut self, x: f32) { self.min_rect.extend_with_x(x); self.max_rect.extend_with_x(x); self.cursor.extend_with_x(x); } /// Ensure we are big enough to contain the given Y-coordinate. /// This is sometimes useful to expand a ui to stretch to a certain place. pub fn expand_to_include_y(&mut self, y: f32) { self.min_rect.extend_with_y(y); self.max_rect.extend_with_y(y); self.cursor.extend_with_y(y); } pub fn sanity_check(&self) { debug_assert!( !self.min_rect.any_nan(), "min rect has Nan: {:?}", self.min_rect ); debug_assert!( !self.max_rect.any_nan(), "max rect has Nan: {:?}", self.max_rect ); debug_assert!(!self.cursor.any_nan(), "cursor has Nan: {:?}", self.cursor); } } // ---------------------------------------------------------------------------- /// Layout direction, one of [`LeftToRight`](Direction::LeftToRight), [`RightToLeft`](Direction::RightToLeft), [`TopDown`](Direction::TopDown), [`BottomUp`](Direction::BottomUp). #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Direction { LeftToRight, RightToLeft, TopDown, BottomUp, } impl Direction { #[inline(always)] pub fn is_horizontal(self) -> bool { match self { Self::LeftToRight | Self::RightToLeft => true, Self::TopDown | Self::BottomUp => false, } } #[inline(always)] pub fn is_vertical(self) -> bool { match self { Self::LeftToRight | Self::RightToLeft => false, Self::TopDown | Self::BottomUp => true, } } } // ---------------------------------------------------------------------------- /// The layout of a [`Ui`][`crate::Ui`], e.g. "vertical & centered". /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { /// ui.label("world!"); /// ui.label("Hello"); /// }); /// # }); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] // #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Layout { /// Main axis direction pub main_dir: Direction, /// If true, wrap around when reading the end of the main direction. /// For instance, for `main_dir == Direction::LeftToRight` this will /// wrap to a new row when we reach the right side of the `max_rect`. pub main_wrap: bool, /// How to align things on the main axis. pub main_align: Align, /// Justify the main axis? pub main_justify: bool, /// How to align things on the cross axis. /// For vertical layouts: put things to left, center or right? /// For horizontal layouts: put things to top, center or bottom? pub cross_align: Align, /// Justify the cross axis? /// For vertical layouts justify mean all widgets get maximum width. /// For horizontal layouts justify mean all widgets get maximum height. pub cross_justify: bool, } impl Default for Layout { fn default() -> Self { // TODO(emilk): Get from `Style` instead. Self::top_down(Align::LEFT) // This is a very euro-centric default. } } /// ## Constructors impl Layout { /// Place elements horizontally, left to right. /// /// The `valign` parameter controls how to align elements vertically. #[inline(always)] pub fn left_to_right(valign: Align) -> Self { Self { main_dir: Direction::LeftToRight, main_wrap: false, main_align: Align::Center, // looks best to e.g. center text within a button main_justify: false, cross_align: valign, cross_justify: false, } } /// Place elements horizontally, right to left. /// /// The `valign` parameter controls how to align elements vertically. #[inline(always)] pub fn right_to_left(valign: Align) -> Self { Self { main_dir: Direction::RightToLeft, main_wrap: false, main_align: Align::Center, // looks best to e.g. center text within a button main_justify: false, cross_align: valign, cross_justify: false, } } /// Place elements vertically, top to bottom. /// /// Use the provided horizontal alignment. #[inline(always)] pub fn top_down(halign: Align) -> Self { Self { main_dir: Direction::TopDown, main_wrap: false, main_align: Align::Center, // looks best to e.g. center text within a button main_justify: false, cross_align: halign, cross_justify: false, } } /// Top-down layout justified so that buttons etc fill the full available width. #[inline(always)] pub fn top_down_justified(halign: Align) -> Self { Self::top_down(halign).with_cross_justify(true) } /// Place elements vertically, bottom up. /// /// Use the provided horizontal alignment. #[inline(always)] pub fn bottom_up(halign: Align) -> Self { Self { main_dir: Direction::BottomUp, main_wrap: false, main_align: Align::Center, // looks best to e.g. center text within a button main_justify: false, cross_align: halign, cross_justify: false, } } #[inline(always)] pub fn from_main_dir_and_cross_align(main_dir: Direction, cross_align: Align) -> Self { Self { main_dir, main_wrap: false, main_align: Align::Center, // looks best to e.g. center text within a button main_justify: false, cross_align, cross_justify: false, } } /// For when you want to add a single widget to a layout, and that widget /// should use up all available space. /// /// Only one widget may be added to the inner `Ui`! #[inline(always)] pub fn centered_and_justified(main_dir: Direction) -> Self { Self { main_dir, main_wrap: false, main_align: Align::Center, main_justify: true, cross_align: Align::Center, cross_justify: true, } } /// Wrap widgets when we overflow the main axis? /// /// For instance, for left-to-right layouts, setting this to `true` will /// put widgets on a new row if we would overflow the right side of [`crate::Ui::max_rect`]. #[inline(always)] pub fn with_main_wrap(self, main_wrap: bool) -> Self { Self { main_wrap, ..self } } /// The alignment to use on the main axis. #[inline(always)] pub fn with_main_align(self, main_align: Align) -> Self { Self { main_align, ..self } } /// The alignment to use on the cross axis. /// /// The "cross" axis is the one orthogonal to the main axis. /// For instance: in left-to-right layout, the main axis is horizontal and the cross axis is vertical. #[inline(always)] pub fn with_cross_align(self, cross_align: Align) -> Self { Self { cross_align, ..self } } /// Justify widgets on the main axis? /// /// Justify here means "take up all available space". #[inline(always)] pub fn with_main_justify(self, main_justify: bool) -> Self { Self { main_justify, ..self } } /// Justify widgets along the cross axis? /// /// Justify here means "take up all available space". /// /// The "cross" axis is the one orthogonal to the main axis. /// For instance: in left-to-right layout, the main axis is horizontal and the cross axis is vertical. #[inline(always)] pub fn with_cross_justify(self, cross_justify: bool) -> Self { Self { cross_justify, ..self } } } /// ## Inspectors impl Layout { #[inline(always)] pub fn main_dir(&self) -> Direction { self.main_dir } #[inline(always)] pub fn main_wrap(&self) -> bool { self.main_wrap } #[inline(always)] pub fn cross_align(&self) -> Align { self.cross_align } #[inline(always)] pub fn cross_justify(&self) -> bool { self.cross_justify } #[inline(always)] pub fn is_horizontal(&self) -> bool { self.main_dir().is_horizontal() } #[inline(always)] pub fn is_vertical(&self) -> bool { self.main_dir().is_vertical() } pub fn prefer_right_to_left(&self) -> bool { self.main_dir == Direction::RightToLeft || self.main_dir.is_vertical() && self.cross_align == Align::Max } /// e.g. for adjusting the placement of something. /// * in horizontal layout: left or right? /// * in vertical layout: same as [`Self::horizontal_align`]. pub fn horizontal_placement(&self) -> Align { match self.main_dir { Direction::LeftToRight => Align::LEFT, Direction::RightToLeft => Align::RIGHT, Direction::TopDown | Direction::BottomUp => self.cross_align, } } /// e.g. for when aligning text within a button. pub fn horizontal_align(&self) -> Align { if self.is_horizontal() { self.main_align } else { self.cross_align } } /// e.g. for when aligning text within a button. pub fn vertical_align(&self) -> Align { if self.is_vertical() { self.main_align } else { self.cross_align } } /// e.g. for when aligning text within a button. fn align2(&self) -> Align2 { Align2([self.horizontal_align(), self.vertical_align()]) } pub fn horizontal_justify(&self) -> bool { if self.is_horizontal() { self.main_justify } else { self.cross_justify } } pub fn vertical_justify(&self) -> bool { if self.is_vertical() { self.main_justify } else { self.cross_justify } } } /// ## Doing layout impl Layout { pub fn align_size_within_rect(&self, size: Vec2, outer: Rect) -> Rect { debug_assert!(size.x >= 0.0 && size.y >= 0.0, "Negative size: {size:?}"); debug_assert!(!outer.is_negative(), "Negative outer: {outer:?}"); self.align2().align_size_within_rect(size, outer).round_ui() } fn initial_cursor(&self, max_rect: Rect) -> Rect { let mut cursor = max_rect; match self.main_dir { Direction::LeftToRight => { cursor.max.x = INFINITY; } Direction::RightToLeft => { cursor.min.x = -INFINITY; } Direction::TopDown => { cursor.max.y = INFINITY; } Direction::BottomUp => { cursor.min.y = -INFINITY; } } cursor } pub(crate) fn region_from_max_rect(&self, max_rect: Rect) -> Region { debug_assert!(!max_rect.any_nan(), "max_rect is not NaN: {max_rect:?}"); let mut region = Region { min_rect: Rect::NOTHING, // temporary max_rect, cursor: self.initial_cursor(max_rect), }; let seed = self.next_widget_position(&region); region.min_rect = Rect::from_center_size(seed, Vec2::ZERO); region } pub(crate) fn available_rect_before_wrap(&self, region: &Region) -> Rect { self.available_from_cursor_max_rect(region.cursor, region.max_rect) } /// Amount of space available for a widget. /// For wrapping layouts, this is the maximum (after wrap). pub(crate) fn available_size(&self, r: &Region) -> Vec2 { if self.main_wrap { if self.main_dir.is_horizontal() { vec2(r.max_rect.width(), r.cursor.height()) } else { vec2(r.cursor.width(), r.max_rect.height()) } } else { self.available_from_cursor_max_rect(r.cursor, r.max_rect) .size() } } /// Given the cursor in the region, how much space is available /// for the next widget? fn available_from_cursor_max_rect(&self, cursor: Rect, max_rect: Rect) -> Rect { debug_assert!(!cursor.any_nan(), "cursor is NaN: {cursor:?}"); debug_assert!(!max_rect.any_nan(), "max_rect is NaN: {max_rect:?}"); // NOTE: in normal top-down layout the cursor has moved below the current max_rect, // but the available shouldn't be negative. // ALSO: with wrapping layouts, cursor jumps to new row before expanding max_rect. let mut avail = max_rect; match self.main_dir { Direction::LeftToRight => { avail.min.x = cursor.min.x; avail.max.x = avail.max.x.max(cursor.min.x); avail.max.x = avail.max.x.max(avail.min.x); avail.max.y = avail.max.y.max(avail.min.y); } Direction::RightToLeft => { avail.max.x = cursor.max.x; avail.min.x = avail.min.x.min(cursor.max.x); avail.min.x = avail.min.x.min(avail.max.x); avail.max.y = avail.max.y.max(avail.min.y); } Direction::TopDown => { avail.min.y = cursor.min.y; avail.max.y = avail.max.y.max(cursor.min.y); avail.max.x = avail.max.x.max(avail.min.x); avail.max.y = avail.max.y.max(avail.min.y); } Direction::BottomUp => { avail.max.y = cursor.max.y; avail.min.y = avail.min.y.min(cursor.max.y); avail.max.x = avail.max.x.max(avail.min.x); avail.min.y = avail.min.y.min(avail.max.y); } } // We can use the cursor to restrict the available region. // For instance, we use this to restrict the available space of a parent Ui // after adding a panel to it. // We also use it for wrapping layouts. avail = avail.intersect(cursor); // Make sure it isn't negative: if avail.max.x < avail.min.x { let x = 0.5 * (avail.min.x + avail.max.x); avail.min.x = x; avail.max.x = x; } if avail.max.y < avail.min.y { let y = 0.5 * (avail.min.y + avail.max.y); avail.min.y = y; avail.max.y = y; } debug_assert!(!avail.any_nan(), "avail is NaN: {avail:?}"); avail } /// Returns where to put the next widget that is of the given size. /// The returned `frame_rect` [`Rect`] will always be justified along the cross axis. /// This is what you then pass to `advance_after_rects`. /// Use `justify_and_align` to get the inner `widget_rect`. pub(crate) fn next_frame(&self, region: &Region, child_size: Vec2, spacing: Vec2) -> Rect { region.sanity_check(); debug_assert!( child_size.x >= 0.0 && child_size.y >= 0.0, "Negative size: {child_size:?}" ); if self.main_wrap { let available_size = self.available_rect_before_wrap(region).size(); let Region { mut cursor, mut max_rect, min_rect, } = *region; match self.main_dir { Direction::LeftToRight => { if available_size.x < child_size.x && max_rect.left() < cursor.left() { // New row let new_row_height = cursor.height().max(child_size.y); // let new_top = cursor.bottom() + spacing.y; let new_top = min_rect.bottom() + spacing.y; // tighter packing cursor = Rect::from_min_max( pos2(max_rect.left(), new_top), pos2(INFINITY, new_top + new_row_height), ); max_rect.max.y = max_rect.max.y.max(cursor.max.y); } } Direction::RightToLeft => { if available_size.x < child_size.x && cursor.right() < max_rect.right() { // New row let new_row_height = cursor.height().max(child_size.y); // let new_top = cursor.bottom() + spacing.y; let new_top = min_rect.bottom() + spacing.y; // tighter packing cursor = Rect::from_min_max( pos2(-INFINITY, new_top), pos2(max_rect.right(), new_top + new_row_height), ); max_rect.max.y = max_rect.max.y.max(cursor.max.y); } } Direction::TopDown => { if available_size.y < child_size.y && max_rect.top() < cursor.top() { // New column let new_col_width = cursor.width().max(child_size.x); cursor = Rect::from_min_max( pos2(cursor.right() + spacing.x, max_rect.top()), pos2(cursor.right() + spacing.x + new_col_width, INFINITY), ); max_rect.max.x = max_rect.max.x.max(cursor.max.x); } } Direction::BottomUp => { if available_size.y < child_size.y && cursor.bottom() < max_rect.bottom() { // New column let new_col_width = cursor.width().max(child_size.x); cursor = Rect::from_min_max( pos2(cursor.right() + spacing.x, -INFINITY), pos2( cursor.right() + spacing.x + new_col_width, max_rect.bottom(), ), ); max_rect.max.x = max_rect.max.x.max(cursor.max.x); } } } // Use the new cursor: let region = Region { min_rect, max_rect, cursor, }; self.next_frame_ignore_wrap(&region, child_size) } else { self.next_frame_ignore_wrap(region, child_size) } } fn next_frame_ignore_wrap(&self, region: &Region, child_size: Vec2) -> Rect { region.sanity_check(); debug_assert!( child_size.x >= 0.0 && child_size.y >= 0.0, "Negative size: {child_size:?}" ); let available_rect = self.available_rect_before_wrap(region); let mut frame_size = child_size; if (self.is_vertical() && self.horizontal_align() == Align::Center) || self.horizontal_justify() { frame_size.x = frame_size.x.max(available_rect.width()); // fill full width } if (self.is_horizontal() && self.vertical_align() == Align::Center) || self.vertical_justify() { frame_size.y = frame_size.y.max(available_rect.height()); // fill full height } let align2 = match self.main_dir { Direction::LeftToRight => Align2([Align::LEFT, self.vertical_align()]), Direction::RightToLeft => Align2([Align::RIGHT, self.vertical_align()]), Direction::TopDown => Align2([self.horizontal_align(), Align::TOP]), Direction::BottomUp => Align2([self.horizontal_align(), Align::BOTTOM]), }; let mut frame_rect = align2.align_size_within_rect(frame_size, available_rect); if self.is_horizontal() && frame_rect.top() < region.cursor.top() { // for horizontal layouts we always want to expand down, // or we will overlap the row above. // This is a bit hacky. Maybe we should do it for vertical layouts too. frame_rect = frame_rect.translate(Vec2::Y * (region.cursor.top() - frame_rect.top())); } debug_assert!(!frame_rect.any_nan(), "frame_rect is NaN: {frame_rect:?}"); debug_assert!(!frame_rect.is_negative(), "frame_rect is negative"); frame_rect.round_ui() } /// Apply justify (fill width/height) and/or alignment after calling `next_space`. pub(crate) fn justify_and_align(&self, frame: Rect, mut child_size: Vec2) -> Rect { debug_assert!( child_size.x >= 0.0 && child_size.y >= 0.0, "Negative size: {child_size:?}" ); debug_assert!(!frame.is_negative(), "frame is negative"); if self.horizontal_justify() { child_size.x = child_size.x.at_least(frame.width()); // fill full width } if self.vertical_justify() { child_size.y = child_size.y.at_least(frame.height()); // fill full height } self.align_size_within_rect(child_size, frame) } pub(crate) fn next_widget_space_ignore_wrap_justify( &self, region: &Region, size: Vec2, ) -> Rect { let frame = self.next_frame_ignore_wrap(region, size); let rect = self.align_size_within_rect(size, frame); debug_assert!(!rect.any_nan(), "rect is NaN: {rect:?}"); debug_assert!(!rect.is_negative(), "rect is negative: {rect:?}"); rect } /// Where would the next tiny widget be centered? pub(crate) fn next_widget_position(&self, region: &Region) -> Pos2 { self.next_widget_space_ignore_wrap_justify(region, Vec2::ZERO) .center() } /// Advance the cursor by this many points, and allocate in region. pub(crate) fn advance_cursor(&self, region: &mut Region, amount: f32) { match self.main_dir { Direction::LeftToRight => { region.cursor.min.x += amount; region.expand_to_include_x(region.cursor.min.x); } Direction::RightToLeft => { region.cursor.max.x -= amount; region.expand_to_include_x(region.cursor.max.x); } Direction::TopDown => { region.cursor.min.y += amount; region.expand_to_include_y(region.cursor.min.y); } Direction::BottomUp => { region.cursor.max.y -= amount; region.expand_to_include_y(region.cursor.max.y); } } } /// Advance cursor after a widget was added to a specific rectangle. /// /// * `frame_rect`: the frame inside which a widget was e.g. centered /// * `widget_rect`: the actual rect used by the widget pub(crate) fn advance_after_rects( &self, cursor: &mut Rect, frame_rect: Rect, widget_rect: Rect, item_spacing: Vec2, ) { debug_assert!(!cursor.any_nan(), "cursor is NaN: {cursor:?}"); if self.main_wrap { if cursor.intersects(frame_rect.shrink(1.0)) { // make row/column larger if necessary *cursor |= frame_rect; } else { // this is a new row or column. We temporarily use NAN for what will be filled in later. match self.main_dir { Direction::LeftToRight => { *cursor = Rect::from_min_max( pos2(f32::NAN, frame_rect.min.y), pos2(INFINITY, frame_rect.max.y), ); } Direction::RightToLeft => { *cursor = Rect::from_min_max( pos2(-INFINITY, frame_rect.min.y), pos2(f32::NAN, frame_rect.max.y), ); } Direction::TopDown => { *cursor = Rect::from_min_max( pos2(frame_rect.min.x, f32::NAN), pos2(frame_rect.max.x, INFINITY), ); } Direction::BottomUp => { *cursor = Rect::from_min_max( pos2(frame_rect.min.x, -INFINITY), pos2(frame_rect.max.x, f32::NAN), ); } } } } else { // Make sure we also expand where we consider adding things (the cursor): if self.is_horizontal() { cursor.min.y = cursor.min.y.min(frame_rect.min.y); cursor.max.y = cursor.max.y.max(frame_rect.max.y); } else { cursor.min.x = cursor.min.x.min(frame_rect.min.x); cursor.max.x = cursor.max.x.max(frame_rect.max.x); } } match self.main_dir { Direction::LeftToRight => { cursor.min.x = widget_rect.max.x + item_spacing.x; } Direction::RightToLeft => { cursor.max.x = widget_rect.min.x - item_spacing.x; } Direction::TopDown => { cursor.min.y = widget_rect.max.y + item_spacing.y; } Direction::BottomUp => { cursor.max.y = widget_rect.min.y - item_spacing.y; } } } /// Move to the next row in a wrapping layout. /// Otherwise does nothing. pub(crate) fn end_row(&self, region: &mut Region, spacing: Vec2) { if self.main_wrap { match self.main_dir { Direction::LeftToRight => { let new_top = region.cursor.bottom() + spacing.y; region.cursor = Rect::from_min_max( pos2(region.max_rect.left(), new_top), pos2(INFINITY, new_top + region.cursor.height()), ); } Direction::RightToLeft => { let new_top = region.cursor.bottom() + spacing.y; region.cursor = Rect::from_min_max( pos2(-INFINITY, new_top), pos2(region.max_rect.right(), new_top + region.cursor.height()), ); } Direction::TopDown | Direction::BottomUp => {} } } } /// Set row height in horizontal wrapping layout. pub(crate) fn set_row_height(&self, region: &mut Region, height: f32) { if self.main_wrap && self.is_horizontal() { region.cursor.max.y = region.cursor.min.y + height; } } } // ---------------------------------------------------------------------------- /// ## Debug stuff impl Layout { /// Shows where the next widget is going to be placed #[cfg(debug_assertions)] pub(crate) fn paint_text_at_cursor( &self, painter: &crate::Painter, region: &Region, stroke: epaint::Stroke, text: impl ToString, ) { let cursor = region.cursor; let next_pos = self.next_widget_position(region); let l = 64.0; let align = match self.main_dir { Direction::LeftToRight => { painter.line_segment([cursor.left_top(), cursor.left_bottom()], stroke); painter.arrow(next_pos, vec2(l, 0.0), stroke); Align2([Align::LEFT, self.vertical_align()]) } Direction::RightToLeft => { painter.line_segment([cursor.right_top(), cursor.right_bottom()], stroke); painter.arrow(next_pos, vec2(-l, 0.0), stroke); Align2([Align::RIGHT, self.vertical_align()]) } Direction::TopDown => { painter.line_segment([cursor.left_top(), cursor.right_top()], stroke); painter.arrow(next_pos, vec2(0.0, l), stroke); Align2([self.horizontal_align(), Align::TOP]) } Direction::BottomUp => { painter.line_segment([cursor.left_bottom(), cursor.right_bottom()], stroke); painter.arrow(next_pos, vec2(0.0, -l), stroke); Align2([self.horizontal_align(), Align::BOTTOM]) } }; painter.debug_text(next_pos, align, stroke.color, text); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/style.rs
crates/egui/src/style.rs
//! egui theme (spacing, colors, etc). use emath::Align; use epaint::{AlphaFromCoverage, CornerRadius, Shadow, Stroke, TextOptions, text::FontTweak}; use std::{collections::BTreeMap, ops::RangeInclusive, sync::Arc}; use crate::{ ComboBox, CursorIcon, FontFamily, FontId, Grid, Margin, Response, RichText, TextWrapMode, WidgetText, ecolor::Color32, emath::{Rangef, Rect, Vec2, pos2, vec2}, reset_button_with, }; /// How to format numbers in e.g. a [`crate::DragValue`]. #[derive(Clone)] pub struct NumberFormatter( Arc<dyn 'static + Sync + Send + Fn(f64, RangeInclusive<usize>) -> String>, ); impl NumberFormatter { /// The first argument is the number to be formatted. /// The second argument is the range of the number of decimals to show. /// /// See [`Self::format`] for the meaning of the `decimals` argument. #[inline] pub fn new( formatter: impl 'static + Sync + Send + Fn(f64, RangeInclusive<usize>) -> String, ) -> Self { Self(Arc::new(formatter)) } /// Format the given number with the given number of decimals. /// /// Decimals are counted after the decimal point. /// /// The minimum number of decimals is usually automatically calculated /// from the sensitivity of the [`crate::DragValue`] and will usually be respected (e.g. include trailing zeroes), /// but if the given value requires more decimals to represent accurately, /// more decimals will be shown, up to the given max. #[inline] pub fn format(&self, value: f64, decimals: RangeInclusive<usize>) -> String { (self.0)(value, decimals) } } impl std::fmt::Debug for NumberFormatter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("NumberFormatter") } } impl PartialEq for NumberFormatter { #[inline] fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } // ---------------------------------------------------------------------------- /// Alias for a [`FontId`] (font of a certain size). /// /// The font is found via look-up in [`Style::text_styles`]. /// You can use [`TextStyle::resolve`] to do this lookup. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextStyle { /// Used when small text is needed. Small, /// Normal labels. Easily readable, doesn't take up too much space. Body, /// Same size as [`Self::Body`], but used when monospace is important (for code snippets, aligning numbers, etc). Monospace, /// Buttons. Maybe slightly bigger than [`Self::Body`]. /// /// Signifies that he item can be interacted with. Button, /// Heading. Probably larger than [`Self::Body`]. Heading, /// A user-chosen style, found in [`Style::text_styles`]. /// ``` /// egui::TextStyle::Name("footing".into()); /// ```` Name(std::sync::Arc<str>), } impl std::fmt::Display for TextStyle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Small => "Small".fmt(f), Self::Body => "Body".fmt(f), Self::Monospace => "Monospace".fmt(f), Self::Button => "Button".fmt(f), Self::Heading => "Heading".fmt(f), Self::Name(name) => (*name).fmt(f), } } } impl TextStyle { /// Look up this [`TextStyle`] in [`Style::text_styles`]. pub fn resolve(&self, style: &Style) -> FontId { style.text_styles.get(self).cloned().unwrap_or_else(|| { panic!( "Failed to find {:?} in Style::text_styles. Available styles:\n{:#?}", self, style.text_styles() ) }) } } // ---------------------------------------------------------------------------- /// A way to select [`FontId`], either by picking one directly or by using a [`TextStyle`]. #[derive(Debug, Clone)] pub enum FontSelection { /// Default text style - will use [`TextStyle::Body`], unless /// [`Style::override_font_id`] or [`Style::override_text_style`] is set. Default, /// Directly select size and font family FontId(FontId), /// Use a [`TextStyle`] to look up the [`FontId`] in [`Style::text_styles`]. Style(TextStyle), } impl Default for FontSelection { #[inline] fn default() -> Self { Self::Default } } impl FontSelection { /// Resolve to a [`FontId`]. /// /// On [`Self::Default`] and no override in the style, this will /// resolve to [`TextStyle::Body`]. pub fn resolve(self, style: &Style) -> FontId { self.resolve_with_fallback(style, TextStyle::Body.into()) } /// Resolve with a final fallback. /// /// Fallback is resolved on [`Self::Default`] and no override in the style. pub fn resolve_with_fallback(self, style: &Style, fallback: Self) -> FontId { match self { Self::Default => { if let Some(override_font_id) = &style.override_font_id { override_font_id.clone() } else if let Some(text_style) = &style.override_text_style { text_style.resolve(style) } else { fallback.resolve(style) } } Self::FontId(font_id) => font_id, Self::Style(text_style) => text_style.resolve(style), } } } impl From<FontId> for FontSelection { #[inline(always)] fn from(font_id: FontId) -> Self { Self::FontId(font_id) } } impl From<TextStyle> for FontSelection { #[inline(always)] fn from(text_style: TextStyle) -> Self { Self::Style(text_style) } } // ---------------------------------------------------------------------------- /// Utility to modify a [`Style`] in some way. /// Constructed via [`StyleModifier::from`] from a `Fn(&mut Style)` or a [`Style`]. #[derive(Clone, Default)] pub struct StyleModifier(Option<Arc<dyn Fn(&mut Style) + Send + Sync>>); impl std::fmt::Debug for StyleModifier { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("StyleModifier") } } impl<T> From<T> for StyleModifier where T: Fn(&mut Style) + Send + Sync + 'static, { fn from(f: T) -> Self { Self(Some(Arc::new(f))) } } impl From<Style> for StyleModifier { fn from(style: Style) -> Self { Self(Some(Arc::new(move |s| *s = style.clone()))) } } impl StyleModifier { /// Create a new [`StyleModifier`] from a function. pub fn new(f: impl Fn(&mut Style) + Send + Sync + 'static) -> Self { Self::from(f) } /// Apply the modification to the given [`Style`]. /// Usually used with [`Ui::style_mut`]. pub fn apply(&self, style: &mut Style) { if let Some(f) = &self.0 { f(style); } } } // ---------------------------------------------------------------------------- /// Specifies the look and feel of egui. /// /// You can change the visuals of a [`Ui`] with [`Ui::style_mut`] /// and of everything with [`crate::Context::set_style_of`]. /// To choose between dark and light style, use [`crate::Context::set_theme`]. /// /// If you want to change fonts, use [`crate::Context::set_fonts`] instead. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Style { /// If set this will change the default [`TextStyle`] for all widgets. /// /// On most widgets you can also set an explicit text style, /// which will take precedence over this. pub override_text_style: Option<TextStyle>, /// If set this will change the font family and size for all widgets. /// /// On most widgets you can also set an explicit text style, /// which will take precedence over this. pub override_font_id: Option<FontId>, /// How to vertically align text. /// /// Set to `None` to use align that depends on the current layout. pub override_text_valign: Option<Align>, /// The [`FontFamily`] and size you want to use for a specific [`TextStyle`]. /// /// The most convenient way to look something up in this is to use [`TextStyle::resolve`]. /// /// If you would like to overwrite app `text_styles` /// /// ``` /// # let mut ctx = egui::Context::default(); /// use egui::FontFamily::Proportional; /// use egui::FontId; /// use egui::TextStyle::*; /// use std::collections::BTreeMap; /// /// // Redefine text_styles /// let text_styles: BTreeMap<_, _> = [ /// (Heading, FontId::new(30.0, Proportional)), /// (Name("Heading2".into()), FontId::new(25.0, Proportional)), /// (Name("Context".into()), FontId::new(23.0, Proportional)), /// (Body, FontId::new(18.0, Proportional)), /// (Monospace, FontId::new(14.0, Proportional)), /// (Button, FontId::new(14.0, Proportional)), /// (Small, FontId::new(10.0, Proportional)), /// ].into(); /// /// // Mutate global styles with new text styles /// ctx.all_styles_mut(move |style| style.text_styles = text_styles.clone()); /// ``` pub text_styles: BTreeMap<TextStyle, FontId>, /// The style to use for [`DragValue`] text. pub drag_value_text_style: TextStyle, /// How to format numbers as strings, e.g. in a [`crate::DragValue`]. /// /// You can override this to e.g. add thousands separators. #[cfg_attr(feature = "serde", serde(skip))] pub number_formatter: NumberFormatter, /// If set, labels, buttons, etc. will use this to determine whether to wrap the text at the /// right edge of the [`Ui`] they are in. By default, this is `None`. /// /// **Note**: this API is deprecated, use `wrap_mode` instead. /// /// * `None`: use `wrap_mode` instead /// * `Some(true)`: wrap mode defaults to [`crate::TextWrapMode::Wrap`] /// * `Some(false)`: wrap mode defaults to [`crate::TextWrapMode::Extend`] #[deprecated = "Use wrap_mode instead"] pub wrap: Option<bool>, /// If set, labels, buttons, etc. will use this to determine whether to wrap or truncate the /// text at the right edge of the [`Ui`] they are in, or to extend it. By default, this is /// `None`. /// /// * `None`: follow layout (with may wrap) /// * `Some(mode)`: use the specified mode as default pub wrap_mode: Option<crate::TextWrapMode>, /// Sizes and distances between widgets pub spacing: Spacing, /// How and when interaction happens. pub interaction: Interaction, /// Colors etc. pub visuals: Visuals, /// How many seconds a typical animation should last. pub animation_time: f32, /// Options to help debug why egui behaves strangely. /// /// Only available in debug builds. #[cfg(debug_assertions)] pub debug: DebugOptions, /// Show tooltips explaining [`DragValue`]:s etc when hovered. /// /// This only affects a few egui widgets. pub explanation_tooltips: bool, /// Show the URL of hyperlinks in a tooltip when hovered. pub url_in_tooltip: bool, /// If true and scrolling is enabled for only one direction, allow horizontal scrolling without pressing shift pub always_scroll_the_only_direction: bool, /// The animation that should be used when scrolling a [`crate::ScrollArea`] using e.g. [`Ui::scroll_to_rect`]. pub scroll_animation: ScrollAnimation, /// Use a more compact style for menus. pub compact_menu_style: bool, } #[test] fn style_impl_send_sync() { fn assert_send_sync<T: Send + Sync>() {} assert_send_sync::<Style>(); } impl Style { // TODO(emilk): rename style.interact() to maybe… `style.interactive` ? /// Use this style for interactive things. /// Note that you must already have a response, /// i.e. you must allocate space and interact BEFORE painting the widget! pub fn interact(&self, response: &Response) -> &WidgetVisuals { self.visuals.widgets.style(response) } pub fn interact_selectable(&self, response: &Response, selected: bool) -> WidgetVisuals { let mut visuals = *self.visuals.widgets.style(response); if selected { visuals.weak_bg_fill = self.visuals.selection.bg_fill; visuals.bg_fill = self.visuals.selection.bg_fill; // visuals.bg_stroke = self.visuals.selection.stroke; visuals.fg_stroke = self.visuals.selection.stroke; } visuals } /// Style to use for non-interactive widgets. pub fn noninteractive(&self) -> &WidgetVisuals { &self.visuals.widgets.noninteractive } /// All known text styles. pub fn text_styles(&self) -> Vec<TextStyle> { self.text_styles.keys().cloned().collect() } } /// Controls the sizes and distances between widgets. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Spacing { /// Horizontal and vertical spacing between widgets. /// /// To add extra space between widgets, use [`Ui::add_space`]. /// /// `item_spacing` is inserted _after_ adding a widget, so to increase the spacing between /// widgets `A` and `B` you need to change `item_spacing` before adding `A`. pub item_spacing: Vec2, /// Horizontal and vertical margins within a window frame. pub window_margin: Margin, /// Button size is text size plus this on each side pub button_padding: Vec2, /// Horizontal and vertical margins within a menu frame. pub menu_margin: Margin, /// Indent collapsing regions etc by this much. pub indent: f32, /// Minimum size of a [`DragValue`], color picker button, and other small widgets. /// `interact_size.y` is the default height of button, slider, etc. /// Anything clickable should be (at least) this size. pub interact_size: Vec2, // TODO(emilk): rename min_interact_size ? /// Default width of a [`Slider`]. pub slider_width: f32, /// Default rail height of a [`Slider`]. pub slider_rail_height: f32, /// Default (minimum) width of a [`ComboBox`]. pub combo_width: f32, /// Default width of a [`crate::TextEdit`]. pub text_edit_width: f32, /// Checkboxes, radio button and collapsing headers have an icon at the start. /// This is the width/height of the outer part of this icon (e.g. the BOX of the checkbox). pub icon_width: f32, /// Checkboxes, radio button and collapsing headers have an icon at the start. /// This is the width/height of the inner part of this icon (e.g. the check of the checkbox). pub icon_width_inner: f32, /// Checkboxes, radio button and collapsing headers have an icon at the start. /// This is the spacing between the icon and the text pub icon_spacing: f32, /// The size used for the [`Ui::max_rect`] the first frame. /// /// Text will wrap at this width, and images that expand to fill the available space /// will expand to this size. /// /// If the contents are smaller than this size, the area will shrink to fit the contents. /// If the contents overflow, the area will grow. pub default_area_size: Vec2, /// Width of a tooltip (`on_hover_ui`, `on_hover_text` etc). pub tooltip_width: f32, /// The default wrapping width of a menu. /// /// Items longer than this will wrap to a new line. pub menu_width: f32, /// Horizontal distance between a menu and a submenu. pub menu_spacing: f32, /// End indented regions with a horizontal line pub indent_ends_with_horizontal_line: bool, /// Height of a combo-box before showing scroll bars. pub combo_height: f32, /// Controls the spacing of a [`crate::ScrollArea`]. pub scroll: ScrollStyle, } impl Spacing { /// Returns small icon rectangle and big icon rectangle pub fn icon_rectangles(&self, rect: Rect) -> (Rect, Rect) { let icon_width = self.icon_width; let big_icon_rect = Rect::from_center_size( pos2(rect.left() + icon_width / 2.0, rect.center().y), vec2(icon_width, icon_width), ); let small_icon_rect = Rect::from_center_size(big_icon_rect.center(), Vec2::splat(self.icon_width_inner)); (small_icon_rect, big_icon_rect) } } // ---------------------------------------------------------------------------- /// Controls the spacing and visuals of a [`crate::ScrollArea`]. /// /// There are three presets to chose from: /// * [`Self::solid`] /// * [`Self::thin`] /// * [`Self::floating`] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct ScrollStyle { /// If `true`, scroll bars float above the content, partially covering it. /// /// If `false`, the scroll bars allocate space, shrinking the area /// available to the contents. /// /// This also changes the colors of the scroll-handle to make /// it more promiment. pub floating: bool, /// Extra margin added around the contents of a [`crate::ScrollArea`]. /// /// The scroll bars will be either on top of this margin, or outside of it, /// depending on the value of [`Self::floating`]. pub content_margin: Margin, /// The width of the scroll bars at it largest. pub bar_width: f32, /// Make sure the scroll handle is at least this big pub handle_min_length: f32, /// Margin between contents and scroll bar. pub bar_inner_margin: f32, /// Margin between scroll bar and the outer container (e.g. right of a vertical scroll bar). /// Only makes sense for non-floating scroll bars. pub bar_outer_margin: f32, /// The thin width of floating scroll bars that the user is NOT hovering. /// /// When the user hovers the scroll bars they expand to [`Self::bar_width`]. pub floating_width: f32, /// How much space is allocated for a floating scroll bar? /// /// Normally this is zero, but you could set this to something small /// like 4.0 and set [`Self::dormant_handle_opacity`] and /// [`Self::dormant_background_opacity`] to e.g. 0.5 /// so as to always show a thin scroll bar. pub floating_allocated_width: f32, /// If true, use colors with more contrast. Good for floating scroll bars. pub foreground_color: bool, /// The opaqueness of the background when the user is neither scrolling /// nor hovering the scroll area. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub dormant_background_opacity: f32, /// The opaqueness of the background when the user is hovering /// the scroll area, but not the scroll bar. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub active_background_opacity: f32, /// The opaqueness of the background when the user is hovering /// over the scroll bars. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub interact_background_opacity: f32, /// The opaqueness of the handle when the user is neither scrolling /// nor hovering the scroll area. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub dormant_handle_opacity: f32, /// The opaqueness of the handle when the user is hovering /// the scroll area, but not the scroll bar. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub active_handle_opacity: f32, /// The opaqueness of the handle when the user is hovering /// over the scroll bars. /// /// This is only for floating scroll bars. /// Solid scroll bars are always opaque. pub interact_handle_opacity: f32, } impl Default for ScrollStyle { fn default() -> Self { Self::floating() } } impl ScrollStyle { /// Solid scroll bars that always use up space pub fn solid() -> Self { Self { floating: false, content_margin: Margin::ZERO, bar_width: 6.0, handle_min_length: 12.0, bar_inner_margin: 4.0, bar_outer_margin: 0.0, floating_width: 2.0, floating_allocated_width: 0.0, foreground_color: false, dormant_background_opacity: 0.0, active_background_opacity: 0.4, interact_background_opacity: 0.7, dormant_handle_opacity: 0.0, active_handle_opacity: 0.6, interact_handle_opacity: 1.0, } } /// Thin scroll bars that expand on hover pub fn thin() -> Self { Self { floating: true, bar_width: 10.0, floating_allocated_width: 6.0, foreground_color: false, dormant_background_opacity: 1.0, dormant_handle_opacity: 1.0, active_background_opacity: 1.0, active_handle_opacity: 1.0, // Be translucent when expanded so we can see the content interact_background_opacity: 0.6, interact_handle_opacity: 0.6, ..Self::solid() } } /// No scroll bars until you hover the scroll area, /// at which time they appear faintly, and then expand /// when you hover the scroll bars. pub fn floating() -> Self { Self { floating: true, bar_width: 10.0, foreground_color: true, floating_allocated_width: 0.0, dormant_background_opacity: 0.0, dormant_handle_opacity: 0.0, ..Self::solid() } } /// Width of a solid vertical scrollbar, or height of a horizontal scroll bar, when it is at its widest. pub fn allocated_width(&self) -> f32 { if self.floating { self.floating_allocated_width } else { self.bar_inner_margin + self.bar_width + self.bar_outer_margin } } pub fn ui(&mut self, ui: &mut Ui) { ui.horizontal(|ui| { ui.label("Presets:"); ui.selectable_value(self, Self::solid(), "Solid"); ui.selectable_value(self, Self::thin(), "Thin"); ui.selectable_value(self, Self::floating(), "Floating"); }); ui.collapsing("Details", |ui| { self.details_ui(ui); }); } pub fn details_ui(&mut self, ui: &mut Ui) { let Self { floating, content_margin, bar_width, handle_min_length, bar_inner_margin, bar_outer_margin, floating_width, floating_allocated_width, foreground_color, dormant_background_opacity, active_background_opacity, interact_background_opacity, dormant_handle_opacity, active_handle_opacity, interact_handle_opacity, } = self; ui.horizontal(|ui| { ui.label("Type:"); ui.selectable_value(floating, false, "Solid"); ui.selectable_value(floating, true, "Floating"); }); ui.horizontal(|ui| { ui.label("Content margin:"); content_margin.ui(ui); }); ui.horizontal(|ui| { ui.add(DragValue::new(bar_width).range(0.0..=32.0)); ui.label("Full bar width"); }); if *floating { ui.horizontal(|ui| { ui.add(DragValue::new(floating_width).range(0.0..=32.0)); ui.label("Thin bar width"); }); ui.horizontal(|ui| { ui.add(DragValue::new(floating_allocated_width).range(0.0..=32.0)); ui.label("Allocated width"); }); } ui.horizontal(|ui| { ui.add(DragValue::new(handle_min_length).range(0.0..=32.0)); ui.label("Minimum handle length"); }); ui.horizontal(|ui| { ui.add(DragValue::new(bar_outer_margin).range(0.0..=32.0)); ui.label("Outer margin"); }); ui.horizontal(|ui| { ui.label("Color:"); ui.selectable_value(foreground_color, false, "Background"); ui.selectable_value(foreground_color, true, "Foreground"); }); if *floating { crate::Grid::new("opacity").show(ui, |ui| { fn opacity_ui(ui: &mut Ui, opacity: &mut f32) { ui.add(DragValue::new(opacity).speed(0.01).range(0.0..=1.0)); } ui.label("Opacity"); ui.label("Dormant"); ui.label("Active"); ui.label("Interacting"); ui.end_row(); ui.label("Background:"); opacity_ui(ui, dormant_background_opacity); opacity_ui(ui, active_background_opacity); opacity_ui(ui, interact_background_opacity); ui.end_row(); ui.label("Handle:"); opacity_ui(ui, dormant_handle_opacity); opacity_ui(ui, active_handle_opacity); opacity_ui(ui, interact_handle_opacity); ui.end_row(); }); } else { ui.horizontal(|ui| { ui.add(DragValue::new(bar_inner_margin).range(0.0..=32.0)); ui.label("Inner margin"); }); } } } // ---------------------------------------------------------------------------- /// Scroll animation configuration, used when programmatically scrolling somewhere (e.g. with `[crate::Ui::scroll_to_cursor]`). /// /// The animation duration is calculated based on the distance to be scrolled via `[ScrollAnimation::points_per_second]` /// and can be clamped to a min / max duration via `[ScrollAnimation::duration]`. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct ScrollAnimation { /// With what speed should we scroll? (Default: 1000.0) pub points_per_second: f32, /// The min / max scroll duration. pub duration: Rangef, } impl Default for ScrollAnimation { fn default() -> Self { Self { points_per_second: 1000.0, duration: Rangef::new(0.1, 0.3), } } } impl ScrollAnimation { /// New scroll animation pub fn new(points_per_second: f32, duration: Rangef) -> Self { Self { points_per_second, duration, } } /// No animation, scroll instantly. pub fn none() -> Self { Self { points_per_second: f32::INFINITY, duration: Rangef::new(0.0, 0.0), } } /// Scroll with a fixed duration, regardless of distance. pub fn duration(t: f32) -> Self { Self { points_per_second: f32::INFINITY, duration: Rangef::new(t, t), } } pub fn ui(&mut self, ui: &mut crate::Ui) { crate::Grid::new("scroll_animation").show(ui, |ui| { ui.label("Scroll animation:"); ui.add( DragValue::new(&mut self.points_per_second) .speed(100.0) .range(0.0..=5000.0), ); ui.label("points/second"); ui.end_row(); ui.label("Min duration:"); ui.add( DragValue::new(&mut self.duration.min) .speed(0.01) .range(0.0..=self.duration.max), ); ui.label("seconds"); ui.end_row(); ui.label("Max duration:"); ui.add( DragValue::new(&mut self.duration.max) .speed(0.01) .range(0.0..=1.0), ); ui.label("seconds"); ui.end_row(); }); } } // ---------------------------------------------------------------------------- /// How and when interaction happens. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Interaction { /// How close a widget must be to the mouse to have a chance to register as a click or drag. /// /// If this is larger than zero, it gets easier to hit widgets, /// which is important for e.g. touch screens. pub interact_radius: f32, /// Radius of the interactive area of the side of a window during drag-to-resize. pub resize_grab_radius_side: f32, /// Radius of the interactive area of the corner of a window during drag-to-resize. pub resize_grab_radius_corner: f32, /// If `false`, tooltips will show up anytime you hover anything, even if mouse is still moving pub show_tooltips_only_when_still: bool, /// Delay in seconds before showing tooltips after the mouse stops moving pub tooltip_delay: f32, /// If you have waited for a tooltip and then hover some other widget within /// this many seconds, then show the new tooltip right away, /// skipping [`Self::tooltip_delay`]. /// /// This lets the user quickly move over some dead space to hover the next thing. pub tooltip_grace_time: f32, /// Can you select the text on a [`crate::Label`] by default? pub selectable_labels: bool, /// Can the user select text that span multiple labels? /// /// The default is `true`, but text selection can be slightly glitchy, /// so you may want to disable it. pub multi_widget_text_select: bool, } /// Look and feel of the text cursor. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TextCursorStyle { /// The color and width of the text cursor pub stroke: Stroke, /// Show where the text cursor would be if you clicked? pub preview: bool, /// Should the cursor blink? pub blink: bool, /// When blinking, this is how long the cursor is visible. pub on_duration: f32, /// When blinking, this is how long the cursor is invisible. pub off_duration: f32, } impl Default for TextCursorStyle { fn default() -> Self { Self { stroke: Stroke::new(2.0, Color32::from_rgb(192, 222, 255)), // Dark mode preview: false, blink: true, on_duration: 0.5, off_duration: 0.5, } } } /// Controls the visual style (colors etc) of egui. /// /// You can change the visuals of a [`Ui`] with [`Ui::visuals_mut`] /// and of everything with [`crate::Context::set_visuals_of`]. /// /// If you want to change fonts, use [`crate::Context::set_fonts`] instead. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Visuals { /// If true, the visuals are overall dark with light text. /// If false, the visuals are overall light with dark text. /// /// NOTE: setting this does very little by itself, /// this is more to provide a convenient summary of the rest of the settings. pub dark_mode: bool, /// Controls how we render text. /// /// The [`TextOptions::max_texture_side`] is ignored and overruled by /// [`crate::RawInput::max_texture_side`]. pub text_options: TextOptions, /// Override default text color for all text. /// /// This is great for setting the color of text for any widget. /// /// If `text_color` is `None` (default), then the text color will be the same as the /// foreground stroke color (`WidgetVisuals::fg_stroke`) /// and will depend on whether or not the widget is being interacted with. /// /// In the future we may instead modulate /// the `text_color` based on whether or not it is interacted with /// so that `visuals.text_color` is always used, /// but its alpha may be different based on whether or not /// it is disabled, non-interactive, hovered etc. pub override_text_color: Option<Color32>, /// How strong "weak" text is. /// /// Ignored if [`Self::weak_text_color`] is set.
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/ui.rs
crates/egui/src/ui.rs
#![warn(missing_docs)] // Let's keep `Ui` well-documented. #![expect(clippy::use_self)] use std::{any::Any, hash::Hash, ops::Deref, sync::Arc}; use emath::GuiRounding as _; use epaint::mutex::RwLock; use crate::containers::menu; use crate::{containers::*, ecolor::*, layout::*, placer::Placer, widgets::*, *}; // ---------------------------------------------------------------------------- /// This is what you use to place widgets. /// /// Represents a region of the screen with a type of layout (horizontal or vertical). /// /// ``` /// # egui::__run_test_ui(|ui| { /// ui.add(egui::Label::new("Hello World!")); /// ui.label("A shorter and more convenient way to add a label."); /// ui.horizontal(|ui| { /// ui.label("Add widgets"); /// if ui.button("on the same row!").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` pub struct Ui { /// Generated based on id of parent ui together with an optional id salt. /// /// This should be stable from one frame to next /// so it can be used as a source for storing state /// (e.g. window position, or if a collapsing header is open). /// /// However, it is not necessarily globally unique. /// For instance, sibling `Ui`s share the same [`Self::id`] /// unless they where explicitly given different id salts using /// [`UiBuilder::id_salt`]. id: Id, /// This is a globally unique ID of this `Ui`, /// based on where in the hierarchy of widgets this Ui is in. /// /// This means it is not _stable_, as it can change if new widgets /// are added or removed prior to this one. /// It should therefore only be used for transient interactions (clicks etc), /// not for storing state over time. unique_id: Id, /// This is used to create a unique interact ID for some widgets. /// /// This value is based on where in the hierarchy of widgets this Ui is in, /// and the value is increment with each added child widget. /// This works as an Id source only as long as new widgets aren't added or removed. /// They are therefore only good for Id:s that have no state. next_auto_id_salt: u64, /// Specifies paint layer, clip rectangle and a reference to [`Context`]. painter: Painter, /// The [`Style`] (visuals, spacing, etc) of this ui. /// Commonly many [`Ui`]s share the same [`Style`]. /// The [`Ui`] implements copy-on-write for this. style: Arc<Style>, /// Handles the [`Ui`] size and the placement of new widgets. placer: Placer, /// If false we are unresponsive to input, /// and all widgets will assume a gray style. enabled: bool, /// Set to true in special cases where we do one frame /// where we size up the contents of the Ui, without actually showing it. sizing_pass: bool, /// Indicates whether this Ui belongs to a Menu. #[expect(deprecated)] menu_state: Option<Arc<RwLock<crate::menu::MenuState>>>, /// The [`UiStack`] for this [`Ui`]. stack: Arc<UiStack>, /// The sense for the ui background. sense: Sense, /// Whether [`Ui::remember_min_rect`] should be called when the [`Ui`] is dropped. /// This is an optimization, so we don't call [`Ui::remember_min_rect`] multiple times at the /// end of a [`Ui::scope`]. min_rect_already_remembered: bool, } /// Allow using [`Ui`] like a [`Context`]. impl Deref for Ui { type Target = Context; #[inline] fn deref(&self) -> &Self::Target { self.ctx() } } impl Ui { // ------------------------------------------------------------------------ // Creation: /// Create a new top-level [`Ui`]. /// /// Normally you would not use this directly, but instead use /// [`crate::Panel`], [`crate::CentralPanel`], [`crate::Window`] or [`crate::Area`]. pub fn new(ctx: Context, id: Id, ui_builder: UiBuilder) -> Self { let UiBuilder { id_salt, global_scope: _, ui_stack_info, layer_id, max_rect, layout, disabled, invisible, sizing_pass, style, sense, accessibility_parent, } = ui_builder; let layer_id = layer_id.unwrap_or_else(LayerId::background); debug_assert!( id_salt.is_none(), "Top-level Ui:s should not have an id_salt" ); let max_rect = max_rect.unwrap_or_else(|| ctx.content_rect()); let clip_rect = max_rect; let layout = layout.unwrap_or_default(); let disabled = disabled || invisible; let style = style.unwrap_or_else(|| ctx.global_style()); let sense = sense.unwrap_or_else(Sense::hover); let placer = Placer::new(max_rect, layout); let ui_stack = UiStack { id, layout_direction: layout.main_dir, info: ui_stack_info, parent: None, min_rect: placer.min_rect(), max_rect: placer.max_rect(), }; let mut ui = Ui { id, unique_id: id, next_auto_id_salt: id.with("auto").value(), painter: Painter::new(ctx, layer_id, clip_rect), style, placer, enabled: true, sizing_pass, menu_state: None, stack: Arc::new(ui_stack), sense, min_rect_already_remembered: false, }; if let Some(accessibility_parent) = accessibility_parent { ui.ctx() .register_accesskit_parent(ui.unique_id, accessibility_parent); } // Register in the widget stack early, to ensure we are behind all widgets we contain: let start_rect = Rect::NOTHING; // This will be overwritten when `remember_min_rect` is called ui.ctx().create_widget( WidgetRect { id: ui.unique_id, layer_id: ui.layer_id(), rect: start_rect, interact_rect: start_rect, sense, enabled: ui.enabled, }, true, Default::default(), ); if disabled { ui.disable(); } if invisible { ui.set_invisible(); } ui.ctx().accesskit_node_builder(ui.unique_id, |node| { node.set_role(accesskit::Role::GenericContainer); }); ui } /// Create a new [`Ui`] at a specific region. /// /// Note: calling this function twice from the same [`Ui`] will create a conflict of id. Use /// [`Self::scope`] if needed. /// /// When in doubt, use `None` for the `UiStackInfo` argument. #[deprecated = "Use ui.new_child() instead"] pub fn child_ui( &mut self, max_rect: Rect, layout: Layout, ui_stack_info: Option<UiStackInfo>, ) -> Self { self.new_child( UiBuilder::new() .max_rect(max_rect) .layout(layout) .ui_stack_info(ui_stack_info.unwrap_or_default()), ) } /// Create a new [`Ui`] at a specific region with a specific id. /// /// When in doubt, use `None` for the `UiStackInfo` argument. #[deprecated = "Use ui.new_child() instead"] pub fn child_ui_with_id_source( &mut self, max_rect: Rect, layout: Layout, id_salt: impl Hash, ui_stack_info: Option<UiStackInfo>, ) -> Self { self.new_child( UiBuilder::new() .id_salt(id_salt) .max_rect(max_rect) .layout(layout) .ui_stack_info(ui_stack_info.unwrap_or_default()), ) } /// Create a child `Ui` with the properties of the given builder. /// /// This is a very low-level function. /// Usually you are better off using [`Self::scope_builder`]. /// /// Note that calling this does not allocate any space in the parent `Ui`, /// so after adding widgets to the child `Ui` you probably want to allocate /// the [`Ui::min_rect`] of the child in the parent `Ui` using e.g. /// [`Ui::advance_cursor_after_rect`]. pub fn new_child(&mut self, ui_builder: UiBuilder) -> Self { let UiBuilder { id_salt, global_scope, ui_stack_info, layer_id, max_rect, layout, disabled, invisible, sizing_pass, style, sense, accessibility_parent, } = ui_builder; let mut painter = self.painter.clone(); let id_salt = id_salt.unwrap_or_else(|| Id::from("child")); let max_rect = max_rect.unwrap_or_else(|| self.available_rect_before_wrap()); let mut layout = layout.unwrap_or_else(|| *self.layout()); let enabled = self.enabled && !disabled && !invisible; if let Some(layer_id) = layer_id { painter.set_layer_id(layer_id); } if invisible { painter.set_invisible(); } let sizing_pass = self.sizing_pass || sizing_pass; let style = style.unwrap_or_else(|| Arc::clone(&self.style)); let sense = sense.unwrap_or_else(Sense::hover); if sizing_pass { // During the sizing pass we want widgets to use up as little space as possible, // so that we measure the only the space we _need_. layout.cross_justify = false; if layout.cross_align == Align::Center { layout.cross_align = Align::Min; } } debug_assert!(!max_rect.any_nan(), "max_rect is NaN: {max_rect:?}"); let (stable_id, unique_id) = if global_scope { (id_salt, id_salt) } else { let stable_id = self.id.with(id_salt); let unique_id = stable_id.with(self.next_auto_id_salt); (stable_id, unique_id) }; let next_auto_id_salt = unique_id.value().wrapping_add(1); self.next_auto_id_salt = self.next_auto_id_salt.wrapping_add(1); let placer = Placer::new(max_rect, layout); let ui_stack = UiStack { id: unique_id, layout_direction: layout.main_dir, info: ui_stack_info, parent: Some(Arc::clone(&self.stack)), min_rect: placer.min_rect(), max_rect: placer.max_rect(), }; let mut child_ui = Ui { id: stable_id, unique_id, next_auto_id_salt, painter, style, placer, enabled, sizing_pass, menu_state: self.menu_state.clone(), stack: Arc::new(ui_stack), sense, min_rect_already_remembered: false, }; if disabled { child_ui.disable(); } child_ui.ctx().register_accesskit_parent( child_ui.unique_id, accessibility_parent.unwrap_or(self.unique_id), ); // Register in the widget stack early, to ensure we are behind all widgets we contain: let start_rect = Rect::NOTHING; // This will be overwritten when `remember_min_rect` is called child_ui.ctx().create_widget( WidgetRect { id: child_ui.unique_id, layer_id: child_ui.layer_id(), rect: start_rect, interact_rect: start_rect, sense, enabled: child_ui.enabled, }, true, Default::default(), ); child_ui .ctx() .accesskit_node_builder(child_ui.unique_id, |node| { node.set_role(accesskit::Role::GenericContainer); }); child_ui } // ------------------------------------------------- /// Set to true in special cases where we do one frame /// where we size up the contents of the Ui, without actually showing it. /// /// This will also turn the Ui invisible. /// Should be called right after [`Self::new`], if at all. #[inline] #[deprecated = "Use UiBuilder.sizing_pass().invisible()"] pub fn set_sizing_pass(&mut self) { self.sizing_pass = true; self.set_invisible(); } /// Set to true in special cases where we do one frame /// where we size up the contents of the Ui, without actually showing it. #[inline] pub fn is_sizing_pass(&self) -> bool { self.sizing_pass } // ------------------------------------------------- /// Generated based on id of parent ui together with an optional id salt. /// /// This should be stable from one frame to next /// so it can be used as a source for storing state /// (e.g. window position, or if a collapsing header is open). /// /// However, it is not necessarily globally unique. /// For instance, sibling `Ui`s share the same [`Self::id`] /// unless they were explicitly given different id salts using /// [`UiBuilder::id_salt`]. #[inline] pub fn id(&self) -> Id { self.id } /// This is a globally unique ID of this `Ui`, /// based on where in the hierarchy of widgets this Ui is in. /// /// This means it is not _stable_, as it can change if new widgets /// are added or removed prior to this one. /// It should therefore only be used for transient interactions (clicks etc), /// not for storing state over time. #[inline] pub fn unique_id(&self) -> Id { self.unique_id } /// Style options for this [`Ui`] and its children. /// /// Note that this may be a different [`Style`] than that of [`Context::style`]. #[inline] pub fn style(&self) -> &Arc<Style> { &self.style } /// Mutably borrow internal [`Style`]. /// Changes apply to this [`Ui`] and its subsequent children. /// /// To set the style of all [`Ui`]s, use [`Context::set_style_of`]. /// /// Example: /// ``` /// # egui::__run_test_ui(|ui| { /// ui.style_mut().override_text_style = Some(egui::TextStyle::Heading); /// # }); /// ``` pub fn style_mut(&mut self) -> &mut Style { Arc::make_mut(&mut self.style) // clone-on-write } /// Changes apply to this [`Ui`] and its subsequent children. /// /// To set the style of all [`Ui`]s, use [`Context::set_style_of`]. pub fn set_style(&mut self, style: impl Into<Arc<Style>>) { self.style = style.into(); } /// Reset to the default style set in [`Context`]. pub fn reset_style(&mut self) { self.style = self.ctx().global_style(); } /// The current spacing options for this [`Ui`]. /// Short for `ui.style().spacing`. #[inline] pub fn spacing(&self) -> &crate::style::Spacing { &self.style.spacing } /// Mutably borrow internal [`Spacing`]. /// Changes apply to this [`Ui`] and its subsequent children. /// /// Example: /// ``` /// # egui::__run_test_ui(|ui| { /// ui.spacing_mut().item_spacing = egui::vec2(10.0, 2.0); /// # }); /// ``` pub fn spacing_mut(&mut self) -> &mut crate::style::Spacing { &mut self.style_mut().spacing } /// The current visuals settings of this [`Ui`]. /// Short for `ui.style().visuals`. #[inline] pub fn visuals(&self) -> &crate::Visuals { &self.style.visuals } /// Mutably borrow internal `visuals`. /// Changes apply to this [`Ui`] and its subsequent children. /// /// To set the visuals of all [`Ui`]s, use [`Context::set_visuals_of`]. /// /// Example: /// ``` /// # egui::__run_test_ui(|ui| { /// ui.visuals_mut().override_text_color = Some(egui::Color32::RED); /// # }); /// ``` pub fn visuals_mut(&mut self) -> &mut crate::Visuals { &mut self.style_mut().visuals } /// Get a reference to this [`Ui`]'s [`UiStack`]. #[inline] pub fn stack(&self) -> &Arc<UiStack> { &self.stack } /// Get a reference to the parent [`Context`]. #[inline] pub fn ctx(&self) -> &Context { self.painter.ctx() } /// Use this to paint stuff within this [`Ui`]. #[inline] pub fn painter(&self) -> &Painter { &self.painter } /// Number of physical pixels for each logical UI point. #[inline] pub fn pixels_per_point(&self) -> f32 { self.painter.pixels_per_point() } /// If `false`, the [`Ui`] does not allow any interaction and /// the widgets in it will draw with a gray look. #[inline] pub fn is_enabled(&self) -> bool { self.enabled } /// Calling `disable()` will cause the [`Ui`] to deny all future interaction /// and all the widgets will draw with a gray look. /// /// Usually it is more convenient to use [`Self::add_enabled_ui`] or [`Self::add_enabled`]. /// /// Note that once disabled, there is no way to re-enable the [`Ui`]. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut enabled = true; /// ui.group(|ui| { /// ui.checkbox(&mut enabled, "Enable subsection"); /// if !enabled { /// ui.disable(); /// } /// if ui.button("Button that is not always clickable").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` pub fn disable(&mut self) { self.enabled = false; if self.is_visible() { self.painter .multiply_opacity(self.visuals().disabled_alpha()); } } /// Calling `set_enabled(false)` will cause the [`Ui`] to deny all future interaction /// and all the widgets will draw with a gray look. /// /// Usually it is more convenient to use [`Self::add_enabled_ui`] or [`Self::add_enabled`]. /// /// Calling `set_enabled(true)` has no effect - it will NOT re-enable the [`Ui`] once disabled. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut enabled = true; /// ui.group(|ui| { /// ui.checkbox(&mut enabled, "Enable subsection"); /// ui.set_enabled(enabled); /// if ui.button("Button that is not always clickable").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` #[deprecated = "Use disable(), add_enabled_ui(), or add_enabled() instead"] pub fn set_enabled(&mut self, enabled: bool) { if !enabled { self.disable(); } } /// If `false`, any widgets added to the [`Ui`] will be invisible and non-interactive. /// /// This is `false` if any parent had [`UiBuilder::invisible`] /// or if [`Context::will_discard`]. #[inline] pub fn is_visible(&self) -> bool { self.painter.is_visible() } /// Calling `set_invisible()` will cause all further widgets to be invisible, /// yet still allocate space. /// /// The widgets will not be interactive (`set_invisible()` implies `disable()`). /// /// Once invisible, there is no way to make the [`Ui`] visible again. /// /// Usually it is more convenient to use [`Self::add_visible_ui`] or [`Self::add_visible`]. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut visible = true; /// ui.group(|ui| { /// ui.checkbox(&mut visible, "Show subsection"); /// if !visible { /// ui.set_invisible(); /// } /// if ui.button("Button that is not always shown").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` pub fn set_invisible(&mut self) { self.painter.set_invisible(); self.disable(); } /// Calling `set_visible(false)` will cause all further widgets to be invisible, /// yet still allocate space. /// /// The widgets will not be interactive (`set_visible(false)` implies `set_enabled(false)`). /// /// Calling `set_visible(true)` has no effect. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut visible = true; /// ui.group(|ui| { /// ui.checkbox(&mut visible, "Show subsection"); /// ui.set_visible(visible); /// if ui.button("Button that is not always shown").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` #[deprecated = "Use set_invisible(), add_visible_ui(), or add_visible() instead"] pub fn set_visible(&mut self, visible: bool) { if !visible { self.painter.set_invisible(); self.disable(); } } /// Make the widget in this [`Ui`] semi-transparent. /// /// `opacity` must be between 0.0 and 1.0, where 0.0 means fully transparent (i.e., invisible) /// and 1.0 means fully opaque. /// /// ### Example /// ``` /// # egui::__run_test_ui(|ui| { /// ui.group(|ui| { /// ui.set_opacity(0.5); /// if ui.button("Half-transparent button").clicked() { /// /* … */ /// } /// }); /// # }); /// ``` /// /// See also: [`Self::opacity`] and [`Self::multiply_opacity`]. pub fn set_opacity(&mut self, opacity: f32) { self.painter.set_opacity(opacity); } /// Like [`Self::set_opacity`], but multiplies the given value with the current opacity. /// /// See also: [`Self::set_opacity`] and [`Self::opacity`]. pub fn multiply_opacity(&mut self, opacity: f32) { self.painter.multiply_opacity(opacity); } /// Read the current opacity of the underlying painter. /// /// See also: [`Self::set_opacity`] and [`Self::multiply_opacity`]. #[inline] pub fn opacity(&self) -> f32 { self.painter.opacity() } /// Read the [`Layout`]. #[inline] pub fn layout(&self) -> &Layout { self.placer.layout() } /// Which wrap mode should the text use in this [`Ui`]? /// /// This is determined first by [`Style::wrap_mode`], and then by the layout of this [`Ui`]. pub fn wrap_mode(&self) -> TextWrapMode { #[expect(deprecated)] if let Some(wrap_mode) = self.style.wrap_mode { wrap_mode } // `wrap` handling for backward compatibility else if let Some(wrap) = self.style.wrap { if wrap { TextWrapMode::Wrap } else { TextWrapMode::Extend } } else if let Some(grid) = self.placer.grid() { if grid.wrap_text() { TextWrapMode::Wrap } else { TextWrapMode::Extend } } else { let layout = self.layout(); if layout.is_vertical() || layout.is_horizontal() && layout.main_wrap() { TextWrapMode::Wrap } else { TextWrapMode::Extend } } } /// Should text wrap in this [`Ui`]? /// /// This is determined first by [`Style::wrap_mode`], and then by the layout of this [`Ui`]. #[deprecated = "Use `wrap_mode` instead"] pub fn wrap_text(&self) -> bool { self.wrap_mode() == TextWrapMode::Wrap } /// How to vertically align text #[inline] pub fn text_valign(&self) -> Align { self.style() .override_text_valign .unwrap_or_else(|| self.layout().vertical_align()) } /// Create a painter for a sub-region of this Ui. /// /// The clip-rect of the returned [`Painter`] will be the intersection /// of the given rectangle and the `clip_rect()` of this [`Ui`]. pub fn painter_at(&self, rect: Rect) -> Painter { self.painter().with_clip_rect(rect) } /// Use this to paint stuff within this [`Ui`]. #[inline] pub fn layer_id(&self) -> LayerId { self.painter().layer_id() } /// The height of text of this text style. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. pub fn text_style_height(&self, style: &TextStyle) -> f32 { self.fonts_mut(|f| f.row_height(&style.resolve(self.style()))) } /// Screen-space rectangle for clipping what we paint in this ui. /// This is used, for instance, to avoid painting outside a window that is smaller than its contents. #[inline] pub fn clip_rect(&self) -> Rect { self.painter.clip_rect() } /// Constrain the rectangle in which we can paint. /// /// Short for `ui.set_clip_rect(ui.clip_rect().intersect(new_clip_rect))`. /// /// See also: [`Self::clip_rect`] and [`Self::set_clip_rect`]. #[inline] pub fn shrink_clip_rect(&mut self, new_clip_rect: Rect) { self.painter.shrink_clip_rect(new_clip_rect); } /// Screen-space rectangle for clipping what we paint in this ui. /// This is used, for instance, to avoid painting outside a window that is smaller than its contents. /// /// Warning: growing the clip rect might cause unexpected results! /// When in doubt, use [`Self::shrink_clip_rect`] instead. pub fn set_clip_rect(&mut self, clip_rect: Rect) { self.painter.set_clip_rect(clip_rect); } /// Can be used for culling: if `false`, then no part of `rect` will be visible on screen. /// /// This is false if the whole `Ui` is invisible (see [`UiBuilder::invisible`]) /// or if [`Context::will_discard`] is true. pub fn is_rect_visible(&self, rect: Rect) -> bool { self.is_visible() && rect.intersects(self.clip_rect()) } } // ------------------------------------------------------------------------ /// # Sizes etc impl Ui { /// Where and how large the [`Ui`] is already. /// All widgets that have been added to this [`Ui`] fits within this rectangle. /// /// No matter what, the final Ui will be at least this large. /// /// This will grow as new widgets are added, but never shrink. pub fn min_rect(&self) -> Rect { self.placer.min_rect() } /// Size of content; same as `min_rect().size()` pub fn min_size(&self) -> Vec2 { self.min_rect().size() } /// New widgets will *try* to fit within this rectangle. /// /// Text labels will wrap to fit within `max_rect`. /// Separator lines will span the `max_rect`. /// /// If a new widget doesn't fit within the `max_rect` then the /// [`Ui`] will make room for it by expanding both `min_rect` and `max_rect`. pub fn max_rect(&self) -> Rect { self.placer.max_rect() } /// Used for animation, kind of hacky pub(crate) fn force_set_min_rect(&mut self, min_rect: Rect) { self.placer.force_set_min_rect(min_rect); } // ------------------------------------------------------------------------ /// Set the maximum size of the ui. /// You won't be able to shrink it below the current minimum size. pub fn set_max_size(&mut self, size: Vec2) { self.set_max_width(size.x); self.set_max_height(size.y); } /// Set the maximum width of the ui. /// You won't be able to shrink it below the current minimum size. pub fn set_max_width(&mut self, width: f32) { self.placer.set_max_width(width); } /// Set the maximum height of the ui. /// You won't be able to shrink it below the current minimum size. pub fn set_max_height(&mut self, height: f32) { self.placer.set_max_height(height); } // ------------------------------------------------------------------------ /// Set the minimum size of the ui. /// This can't shrink the ui, only make it larger. pub fn set_min_size(&mut self, size: Vec2) { self.set_min_width(size.x); self.set_min_height(size.y); } /// Set the minimum width of the ui. /// This can't shrink the ui, only make it larger. pub fn set_min_width(&mut self, width: f32) { debug_assert!( 0.0 <= width, "Negative width makes no sense, but got: {width}" ); self.placer.set_min_width(width); } /// Set the minimum height of the ui. /// This can't shrink the ui, only make it larger. pub fn set_min_height(&mut self, height: f32) { debug_assert!( 0.0 <= height, "Negative height makes no sense, but got: {height}" ); self.placer.set_min_height(height); } /// Makes the ui always fill up the available space. /// /// This can be useful to call inside a panel with `resizable == true` /// to make sure the resized space is used. pub fn take_available_space(&mut self) { self.set_min_size(self.available_size()); } /// Makes the ui always fill up the available space in the x axis. /// /// This can be useful to call inside a side panel with /// `resizable == true` to make sure the resized space is used. pub fn take_available_width(&mut self) { self.set_min_width(self.available_width()); } /// Makes the ui always fill up the available space in the y axis. /// /// This can be useful to call inside a top bottom panel with /// `resizable == true` to make sure the resized space is used. pub fn take_available_height(&mut self) { self.set_min_height(self.available_height()); } // ------------------------------------------------------------------------ /// Helper: shrinks the max width to the current width, /// so further widgets will try not to be wider than previous widgets. /// Useful for normal vertical layouts. pub fn shrink_width_to_current(&mut self) { self.set_max_width(self.min_rect().width()); } /// Helper: shrinks the max height to the current height, /// so further widgets will try not to be taller than previous widgets. pub fn shrink_height_to_current(&mut self) { self.set_max_height(self.min_rect().height()); } /// Expand the `min_rect` and `max_rect` of this ui to include a child at the given rect. pub fn expand_to_include_rect(&mut self, rect: Rect) { self.placer.expand_to_include_rect(rect); } /// `ui.set_width_range(min..=max);` is equivalent to `ui.set_min_width(min); ui.set_max_width(max);`. pub fn set_width_range(&mut self, width: impl Into<Rangef>) { let width = width.into(); self.set_min_width(width.min); self.set_max_width(width.max); } /// `ui.set_height_range(min..=max);` is equivalent to `ui.set_min_height(min); ui.set_max_height(max);`. pub fn set_height_range(&mut self, height: impl Into<Rangef>) { let height = height.into(); self.set_min_height(height.min); self.set_max_height(height.max); } /// Set both the minimum and maximum width. pub fn set_width(&mut self, width: f32) { self.set_min_width(width); self.set_max_width(width); } /// Set both the minimum and maximum height. pub fn set_height(&mut self, height: f32) { self.set_min_height(height); self.set_max_height(height); } /// Ensure we are big enough to contain the given x-coordinate. /// This is sometimes useful to expand a ui to stretch to a certain place. pub fn expand_to_include_x(&mut self, x: f32) { self.placer.expand_to_include_x(x); } /// Ensure we are big enough to contain the given y-coordinate. /// This is sometimes useful to expand a ui to stretch to a certain place. pub fn expand_to_include_y(&mut self, y: f32) { self.placer.expand_to_include_y(y); } // ------------------------------------------------------------------------ // Layout related measures: /// The available space at the moment, given the current cursor. /// /// This how much more space we can take up without overflowing our parent. /// Shrinks as widgets allocate space and the cursor moves. /// A small size should be interpreted as "as little as possible". /// An infinite size should be interpreted as "as much as you want". pub fn available_size(&self) -> Vec2 { self.placer.available_size() } /// The available width at the moment, given the current cursor. /// /// See [`Self::available_size`] for more information. pub fn available_width(&self) -> f32 { self.available_size().x } /// The available height at the moment, given the current cursor. /// /// See [`Self::available_size`] for more information. pub fn available_height(&self) -> f32 { self.available_size().y
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/load.rs
crates/egui/src/load.rs
//! # Image loading //! //! If you just want to display some images, [`egui_extras`](https://crates.io/crates/egui_extras/) //! will get you up and running quickly with its reasonable default implementations of the traits described below. //! //! 1. Add [`egui_extras`](https://crates.io/crates/egui_extras/) as a dependency with the `all_loaders` feature. //! 2. Add a call to [`egui_extras::install_image_loaders`](https://docs.rs/egui_extras/latest/egui_extras/fn.install_image_loaders.html) //! in your app's setup code. //! 3. Use [`Ui::image`][`crate::ui::Ui::image`] with some [`ImageSource`][`crate::ImageSource`]. //! //! ## Loading process //! //! There are three kinds of loaders: //! - [`BytesLoader`]: load the raw bytes of an image //! - [`ImageLoader`]: decode the bytes into an array of colors //! - [`TextureLoader`]: ask the backend to put an image onto the GPU //! //! The different kinds of loaders represent different layers in the loading process: //! //! ```text,ignore //! ui.image("file://image.png") //! └► Context::try_load_texture //! └► TextureLoader::load //! └► Context::try_load_image //! └► ImageLoader::load //! └► Context::try_load_bytes //! └► BytesLoader::load //! ``` //! //! As each layer attempts to load the URI, it first asks the layer below it //! for the data it needs to do its job. But this is not a strict requirement, //! an implementation could instead generate the data it needs! //! //! Loader trait implementations may be registered on a context with: //! - [`Context::add_bytes_loader`] //! - [`Context::add_image_loader`] //! - [`Context::add_texture_loader`] //! //! There may be multiple loaders of the same kind registered at the same time. //! The `try_load` methods on [`Context`] will attempt to call each loader one by one, //! until one of them returns something other than [`LoadError::NotSupported`]. //! //! The loaders are stored in the context. This means they may hold state across frames, //! which they can (and _should_) use to cache the results of the operations they perform. //! //! For example, a [`BytesLoader`] that loads file URIs (`file://image.png`) //! would cache each file read. A [`TextureLoader`] would cache each combination //! of `(URI, TextureOptions)`, and so on. //! //! Each URI will be passed through the loaders as a plain `&str`. //! The loaders are free to derive as much meaning from the URI as they wish to. //! For example, a loader may determine that it doesn't support loading a specific URI //! if the protocol does not match what it expects. mod bytes_loader; mod texture_loader; use std::{ borrow::Cow, fmt::{Debug, Display}, ops::Deref, sync::Arc, }; use ahash::HashMap; use emath::{Float as _, OrderedFloat}; use epaint::{ColorImage, TextureHandle, TextureId, Vec2, mutex::Mutex, textures::TextureOptions}; use crate::Context; pub use self::{bytes_loader::DefaultBytesLoader, texture_loader::DefaultTextureLoader}; /// Represents a failed attempt at loading an image. #[derive(Clone, Debug)] pub enum LoadError { /// Programmer error: There are no image loaders installed. NoImageLoaders, /// A specific loader does not support this scheme or protocol. NotSupported, /// A specific loader does not support the format of the image. FormatNotSupported { detected_format: Option<String> }, /// Programmer error: Failed to find the bytes for this image because /// there was no [`BytesLoader`] supporting the scheme. NoMatchingBytesLoader, /// Programmer error: Failed to parse the bytes as an image because /// there was no [`ImageLoader`] supporting the format. NoMatchingImageLoader { detected_format: Option<String> }, /// Programmer error: no matching [`TextureLoader`]. /// Because of the [`DefaultTextureLoader`], this error should never happen. NoMatchingTextureLoader, /// Runtime error: Loading was attempted, but failed (e.g. "File not found"). Loading(String), } impl LoadError { /// Returns the (approximate) size of the error message in bytes. pub fn byte_size(&self) -> usize { match self { Self::FormatNotSupported { detected_format } | Self::NoMatchingImageLoader { detected_format } => { detected_format.as_ref().map_or(0, |s| s.len()) } Self::Loading(message) => message.len(), _ => std::mem::size_of::<Self>(), } } } impl Display for LoadError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NoImageLoaders => f.write_str( "No image loaders are installed. If you're trying to load some images \ for the first time, follow the steps outlined in https://docs.rs/egui/latest/egui/load/index.html"), Self::NoMatchingBytesLoader => f.write_str("No matching BytesLoader. Either you need to call Context::include_bytes, or install some more bytes loaders, e.g. using egui_extras."), Self::NoMatchingImageLoader { detected_format: None } => f.write_str("No matching ImageLoader. Either no ImageLoader is installed or the image is corrupted / has an unsupported format."), Self::NoMatchingImageLoader { detected_format: Some(detected_format) } => write!(f, "No matching ImageLoader for format: {detected_format:?}. Make sure you enabled the necessary features on the image crate."), Self::NoMatchingTextureLoader => f.write_str("No matching TextureLoader. Did you remove the default one?"), Self::NotSupported => f.write_str("Image scheme or URI not supported by this loader"), Self::FormatNotSupported { detected_format } => write!(f, "Image format not supported by this loader: {detected_format:?}"), Self::Loading(message) => f.write_str(message), } } } impl std::error::Error for LoadError {} pub type Result<T, E = LoadError> = std::result::Result<T, E>; /// Given as a hint for image loading requests. /// /// Used mostly for rendering SVG:s to a good size. /// The [`SizeHint`] determines at what resolution the image should be rasterized. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum SizeHint { /// Scale original size by some factor, keeping the original aspect ratio. /// /// The original size of the image is usually its texel resolution, /// but for an SVG it's the point size of the SVG. /// /// For instance, setting `Scale(2.0)` will rasterize SVG:s to twice their original size, /// which is useful for high-DPI displays. Scale(OrderedFloat<f32>), /// Scale to exactly this pixel width, keeping the original aspect ratio. Width(u32), /// Scale to exactly this pixel height, keeping the original aspect ratio. Height(u32), /// Scale to this pixel size. Size { width: u32, height: u32, /// If true, the image will be as large as possible /// while still fitting within the given width/height. maintain_aspect_ratio: bool, }, } impl SizeHint { /// Multiply size hint by a factor. pub fn scale_by(self, factor: f32) -> Self { match self { Self::Scale(scale) => Self::Scale(OrderedFloat(factor * scale.0)), Self::Width(width) => Self::Width((factor * width as f32).round() as _), Self::Height(height) => Self::Height((factor * height as f32).round() as _), Self::Size { width, height, maintain_aspect_ratio, } => Self::Size { width: (factor * width as f32).round() as _, height: (factor * height as f32).round() as _, maintain_aspect_ratio, }, } } } impl Default for SizeHint { #[inline] fn default() -> Self { Self::Scale(1.0.ord()) } } /// Represents a byte buffer. /// /// This is essentially `Cow<'static, [u8]>` but with the `Owned` variant being an `Arc`. #[derive(Clone)] pub enum Bytes { Static(&'static [u8]), Shared(Arc<[u8]>), } impl Debug for Bytes { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Static(arg0) => f.debug_tuple("Static").field(&arg0.len()).finish(), Self::Shared(arg0) => f.debug_tuple("Shared").field(&arg0.len()).finish(), } } } impl From<&'static [u8]> for Bytes { #[inline] fn from(value: &'static [u8]) -> Self { Self::Static(value) } } impl<const N: usize> From<&'static [u8; N]> for Bytes { #[inline] fn from(value: &'static [u8; N]) -> Self { Self::Static(value) } } impl From<Arc<[u8]>> for Bytes { #[inline] fn from(value: Arc<[u8]>) -> Self { Self::Shared(value) } } impl From<Vec<u8>> for Bytes { #[inline] fn from(value: Vec<u8>) -> Self { Self::Shared(value.into()) } } impl AsRef<[u8]> for Bytes { #[inline] fn as_ref(&self) -> &[u8] { match self { Self::Static(bytes) => bytes, Self::Shared(bytes) => bytes, } } } impl Deref for Bytes { type Target = [u8]; #[inline] fn deref(&self) -> &Self::Target { self.as_ref() } } /// Represents bytes which are currently being loaded. /// /// This is similar to [`std::task::Poll`], but the `Pending` variant /// contains an optional `size`, which may be used during layout to /// pre-allocate space the image. #[derive(Clone)] pub enum BytesPoll { /// Bytes are being loaded. Pending { /// Point size of the image. /// /// Set if known (e.g. from a HTTP header, or by parsing the image file header). size: Option<Vec2>, }, /// Bytes are loaded. Ready { /// Point size of the image. /// /// Set if known (e.g. from a HTTP header, or by parsing the image file header). size: Option<Vec2>, /// File contents, e.g. the contents of a `.png`. bytes: Bytes, /// Mime type of the content, e.g. `image/png`. /// /// Set if known (e.g. from `Content-Type` HTTP header). mime: Option<String>, }, } /// Used to get a unique ID when implementing one of the loader traits: [`BytesLoader::id`], [`ImageLoader::id`], and [`TextureLoader::id`]. /// /// This just expands to `module_path!()` concatenated with the given type name. #[macro_export] macro_rules! generate_loader_id { ($ty:ident) => { concat!(module_path!(), "::", stringify!($ty)) }; } pub use crate::generate_loader_id; pub type BytesLoadResult = Result<BytesPoll>; /// Represents a loader capable of loading raw unstructured bytes from somewhere, /// e.g. from disk or network. /// /// It should also provide any subsequent loaders a hint for what the bytes may /// represent using [`BytesPoll::Ready::mime`], if it can be inferred. /// /// Implementations are expected to cache at least each `URI`. pub trait BytesLoader { /// Unique ID of this loader. /// /// To reduce the chance of collisions, use [`generate_loader_id`] for this. fn id(&self) -> &str; /// Try loading the bytes from the given uri. /// /// Implementations should call `ctx.request_repaint` to wake up the ui /// once the data is ready. /// /// The implementation should cache any result, so that calling this /// is immediate-mode safe. /// /// # Errors /// This may fail with: /// - [`LoadError::NotSupported`] if the loader does not support loading `uri`. /// - [`LoadError::Loading`] if the loading process failed. fn load(&self, ctx: &Context, uri: &str) -> BytesLoadResult; /// Forget the given `uri`. /// /// If `uri` is cached, it should be evicted from cache, /// so that it may be fully reloaded. fn forget(&self, uri: &str); /// Forget all URIs ever given to this loader. /// /// If the loader caches any URIs, the entire cache should be cleared, /// so that all of them may be fully reloaded. fn forget_all(&self); /// Implementations may use this to perform work at the end of a frame, /// such as evicting unused entries from a cache. fn end_pass(&self, pass_index: u64) { let _ = pass_index; } /// If the loader caches any data, this should return the size of that cache. fn byte_size(&self) -> usize; /// Returns `true` if some data is currently being loaded. fn has_pending(&self) -> bool { false } } /// Represents an image which is currently being loaded. /// /// This is similar to [`std::task::Poll`], but the `Pending` variant /// contains an optional `size`, which may be used during layout to /// pre-allocate space the image. #[derive(Clone)] pub enum ImagePoll { /// Image is loading. Pending { /// Point size of the image. /// /// Set if known (e.g. from a HTTP header, or by parsing the image file header). size: Option<Vec2>, }, /// Image is loaded. Ready { image: Arc<ColorImage> }, } pub type ImageLoadResult = Result<ImagePoll>; /// An `ImageLoader` decodes raw bytes into a [`ColorImage`]. /// /// Implementations are expected to cache at least each `URI`. pub trait ImageLoader: std::any::Any { /// Unique ID of this loader. /// /// To reduce the chance of collisions, include `module_path!()` as part of this ID. /// /// For example: `concat!(module_path!(), "::MyLoader")` /// for `my_crate::my_loader::MyLoader`. fn id(&self) -> &str; /// Try loading the image from the given uri. /// /// Implementations should call `ctx.request_repaint` to wake up the ui /// once the image is ready. /// /// The implementation should cache any result, so that calling this /// is immediate-mode safe. /// /// # Errors /// This may fail with: /// - [`LoadError::NotSupported`] if the loader does not support loading `uri`. /// - [`LoadError::Loading`] if the loading process failed. fn load(&self, ctx: &Context, uri: &str, size_hint: SizeHint) -> ImageLoadResult; /// Forget the given `uri`. /// /// If `uri` is cached, it should be evicted from cache, /// so that it may be fully reloaded. fn forget(&self, uri: &str); /// Forget all URIs ever given to this loader. /// /// If the loader caches any URIs, the entire cache should be cleared, /// so that all of them may be fully reloaded. fn forget_all(&self); /// Implementations may use this to perform work at the end of a pass, /// such as evicting unused entries from a cache. fn end_pass(&self, pass_index: u64) { let _ = pass_index; } /// If the loader caches any data, this should return the size of that cache. fn byte_size(&self) -> usize; /// Returns `true` if some image is currently being loaded. /// /// NOTE: You probably also want to check [`BytesLoader::has_pending`]. fn has_pending(&self) -> bool { false } } /// A texture with a known size. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SizedTexture { pub id: TextureId, /// Point size of the original SVG, or the size of the image in texels. pub size: Vec2, } impl SizedTexture { /// Create a [`SizedTexture`] from a texture `id` with a specific `size`. pub fn new(id: impl Into<TextureId>, size: impl Into<Vec2>) -> Self { Self { id: id.into(), size: size.into(), } } /// Fetch the [id][`SizedTexture::id`] and [size][`SizedTexture::size`] from a [`TextureHandle`]. pub fn from_handle(handle: &TextureHandle) -> Self { let size = handle.size(); Self { id: handle.id(), size: Vec2::new(size[0] as f32, size[1] as f32), } } } impl From<(TextureId, Vec2)> for SizedTexture { #[inline] fn from((id, size): (TextureId, Vec2)) -> Self { Self { id, size } } } impl<'a> From<&'a TextureHandle> for SizedTexture { #[inline] fn from(handle: &'a TextureHandle) -> Self { Self::from_handle(handle) } } /// Represents a texture is currently being loaded. /// /// This is similar to [`std::task::Poll`], but the `Pending` variant /// contains an optional `size`, which may be used during layout to /// pre-allocate space the image. #[derive(Clone, Copy)] pub enum TexturePoll { /// Texture is loading. Pending { /// Point size of the image. /// /// Set if known (e.g. from a HTTP header, or by parsing the image file header). size: Option<Vec2>, }, /// Texture is loaded. Ready { texture: SizedTexture }, } impl TexturePoll { /// Point size of the original SVG, or the size of the image in texels. #[inline] pub fn size(&self) -> Option<Vec2> { match self { Self::Pending { size } => *size, Self::Ready { texture } => Some(texture.size), } } #[inline] pub fn texture_id(&self) -> Option<TextureId> { match self { Self::Pending { .. } => None, Self::Ready { texture } => Some(texture.id), } } #[inline] pub fn is_pending(&self) -> bool { matches!(self, Self::Pending { .. }) } #[inline] pub fn is_ready(&self) -> bool { matches!(self, Self::Ready { .. }) } } pub type TextureLoadResult = Result<TexturePoll>; /// A `TextureLoader` uploads a [`ColorImage`] to the GPU, returning a [`SizedTexture`]. /// /// `egui` comes with an implementation that uses [`Context::load_texture`], /// which just asks the egui backend to upload the image to the GPU. /// /// You can implement this trait if you do your own uploading of images to the GPU. /// For instance, you can use this to refer to textures in a game engine that egui /// doesn't otherwise know about. /// /// Implementations are expected to cache each combination of `(URI, TextureOptions)`. pub trait TextureLoader { /// Unique ID of this loader. /// /// To reduce the chance of collisions, include `module_path!()` as part of this ID. /// /// For example: `concat!(module_path!(), "::MyLoader")` /// for `my_crate::my_loader::MyLoader`. fn id(&self) -> &str; /// Try loading the texture from the given uri. /// /// Implementations should call `ctx.request_repaint` to wake up the ui /// once the texture is ready. /// /// The implementation should cache any result, so that calling this /// is immediate-mode safe. /// /// # Errors /// This may fail with: /// - [`LoadError::NotSupported`] if the loader does not support loading `uri`. /// - [`LoadError::Loading`] if the loading process failed. fn load( &self, ctx: &Context, uri: &str, texture_options: TextureOptions, size_hint: SizeHint, ) -> TextureLoadResult; /// Forget the given `uri`. /// /// If `uri` is cached, it should be evicted from cache, /// so that it may be fully reloaded. fn forget(&self, uri: &str); /// Forget all URIs ever given to this loader. /// /// If the loader caches any URIs, the entire cache should be cleared, /// so that all of them may be fully reloaded. fn forget_all(&self); /// Implementations may use this to perform work at the end of a pass, /// such as evicting unused entries from a cache. fn end_pass(&self, pass_index: u64) { let _ = pass_index; } /// If the loader caches any data, this should return the size of that cache. fn byte_size(&self) -> usize; } type BytesLoaderImpl = Arc<dyn BytesLoader + Send + Sync + 'static>; type ImageLoaderImpl = Arc<dyn ImageLoader + Send + Sync + 'static>; type TextureLoaderImpl = Arc<dyn TextureLoader + Send + Sync + 'static>; #[derive(Clone)] /// The loaders of bytes, images, and textures. pub struct Loaders { pub include: Arc<DefaultBytesLoader>, pub bytes: Mutex<Vec<BytesLoaderImpl>>, pub image: Mutex<Vec<ImageLoaderImpl>>, pub texture: Mutex<Vec<TextureLoaderImpl>>, } impl Default for Loaders { fn default() -> Self { let include = Arc::new(DefaultBytesLoader::default()); Self { bytes: Mutex::new(vec![Arc::clone(&include) as _]), image: Mutex::new(Vec::new()), // By default we only include `DefaultTextureLoader`. texture: Mutex::new(vec![Arc::new(DefaultTextureLoader::default())]), include, } } } impl Loaders { /// The given pass has just ended. pub fn end_pass(&self, pass_index: u64) { let Self { include, bytes, image, texture, } = self; include.end_pass(pass_index); for loader in bytes.lock().iter() { loader.end_pass(pass_index); } for loader in image.lock().iter() { loader.end_pass(pass_index); } for loader in texture.lock().iter() { loader.end_pass(pass_index); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/context.rs
crates/egui/src/context.rs
#![warn(missing_docs)] // Let's keep `Context` well-documented. use std::{borrow::Cow, cell::RefCell, panic::Location, sync::Arc, time::Duration}; use emath::GuiRounding as _; use epaint::{ ClippedPrimitive, ClippedShape, Color32, ImageData, Pos2, Rect, StrokeKind, TessellationOptions, TextureId, Vec2, emath::{self, TSTransform}, mutex::RwLock, stats::PaintStats, tessellator, text::{FontInsert, FontPriority, Fonts, FontsView}, vec2, }; use crate::{ Align2, CursorIcon, DeferredViewportUiCallback, FontDefinitions, Grid, Id, ImmediateViewport, ImmediateViewportRendererCallback, Key, KeyboardShortcut, Label, LayerId, Memory, ModifierNames, Modifiers, NumExt as _, Order, Painter, RawInput, Response, RichText, SafeAreaInsets, ScrollArea, Sense, Style, TextStyle, TextureHandle, TextureOptions, Ui, UiBuilder, ViewportBuilder, ViewportCommand, ViewportId, ViewportIdMap, ViewportIdPair, ViewportIdSet, ViewportOutput, Visuals, Widget as _, WidgetRect, WidgetText, animation_manager::AnimationManager, containers::{self, area::AreaState}, data::output::PlatformOutput, epaint, hit_test::WidgetHits, input_state::{InputState, MultiTouchInfo, PointerEvent, SurrenderFocusOn}, interaction::InteractionSnapshot, layers::GraphicLayers, load::{self, Bytes, Loaders, SizedTexture}, memory::{Options, Theme}, os::OperatingSystem, output::FullOutput, pass_state::PassState, plugin::{self, TypedPluginHandle}, resize, response, scroll_area, util::IdTypeMap, viewport::ViewportClass, }; use crate::IdMap; /// Information given to the backend about when it is time to repaint the ui. /// /// This is given in the callback set by [`Context::set_request_repaint_callback`]. #[derive(Clone, Copy, Debug)] pub struct RequestRepaintInfo { /// This is used to specify what viewport that should repaint. pub viewport_id: ViewportId, /// Repaint after this duration. If zero, repaint as soon as possible. pub delay: Duration, /// The number of fully completed passes, of the entire lifetime of the [`Context`]. /// /// This can be compared to [`Context::cumulative_pass_nr`] to see if we we still /// need another repaint (ui pass / frame), or if one has already happened. pub current_cumulative_pass_nr: u64, } // ---------------------------------------------------------------------------- thread_local! { static IMMEDIATE_VIEWPORT_RENDERER: RefCell<Option<Box<ImmediateViewportRendererCallback>>> = Default::default(); } // ---------------------------------------------------------------------------- struct WrappedTextureManager(Arc<RwLock<epaint::TextureManager>>); impl Default for WrappedTextureManager { fn default() -> Self { let mut tex_mngr = epaint::textures::TextureManager::default(); // Will be filled in later let font_id = tex_mngr.alloc( "egui_font_texture".into(), epaint::ColorImage::filled([0, 0], Color32::TRANSPARENT).into(), Default::default(), ); assert_eq!( font_id, TextureId::default(), "font id should be equal to TextureId::default(), but was {font_id:?}", ); Self(Arc::new(RwLock::new(tex_mngr))) } } // ---------------------------------------------------------------------------- /// Repaint-logic impl ContextImpl { /// This is where we update the repaint logic. fn begin_pass_repaint_logic(&mut self, viewport_id: ViewportId) { let viewport = self.viewports.entry(viewport_id).or_default(); std::mem::swap( &mut viewport.repaint.prev_causes, &mut viewport.repaint.causes, ); viewport.repaint.causes.clear(); viewport.repaint.prev_pass_paint_delay = viewport.repaint.repaint_delay; if viewport.repaint.outstanding == 0 { // We are repainting now, so we can wait a while for the next repaint. viewport.repaint.repaint_delay = Duration::MAX; } else { viewport.repaint.repaint_delay = Duration::ZERO; viewport.repaint.outstanding -= 1; if let Some(callback) = &self.request_repaint_callback { (callback)(RequestRepaintInfo { viewport_id, delay: Duration::ZERO, current_cumulative_pass_nr: viewport.repaint.cumulative_pass_nr, }); } } } fn request_repaint(&mut self, viewport_id: ViewportId, cause: RepaintCause) { self.request_repaint_after(Duration::ZERO, viewport_id, cause); } fn request_repaint_after( &mut self, mut delay: Duration, viewport_id: ViewportId, cause: RepaintCause, ) { let viewport = self.viewports.entry(viewport_id).or_default(); if delay == Duration::ZERO { // Each request results in two repaints, just to give some things time to settle. // This solves some corner-cases of missing repaints on frame-delayed responses. viewport.repaint.outstanding = 1; } else { // For non-zero delays, we only repaint once, because // otherwise we would just schedule an immediate repaint _now_, // which would then clear the delay and repaint again. // Hovering a tooltip is a good example of a case where we want to repaint after a delay. } if let Ok(predicted_frame_time) = Duration::try_from_secs_f32(viewport.input.predicted_dt) { // Make it less likely we over-shoot the target: delay = delay.saturating_sub(predicted_frame_time); } viewport.repaint.causes.push(cause); // We save some CPU time by only calling the callback if we need to. // If the new delay is greater or equal to the previous lowest, // it means we have already called the callback, and don't need to do it again. if delay < viewport.repaint.repaint_delay { viewport.repaint.repaint_delay = delay; if let Some(callback) = &self.request_repaint_callback { (callback)(RequestRepaintInfo { viewport_id, delay, current_cumulative_pass_nr: viewport.repaint.cumulative_pass_nr, }); } } } #[must_use] fn requested_immediate_repaint_prev_pass(&self, viewport_id: &ViewportId) -> bool { self.viewports .get(viewport_id) .is_some_and(|v| v.repaint.requested_immediate_repaint_prev_pass()) } #[must_use] fn has_requested_repaint(&self, viewport_id: &ViewportId) -> bool { self.viewports .get(viewport_id) .is_some_and(|v| 0 < v.repaint.outstanding || v.repaint.repaint_delay < Duration::MAX) } } // ---------------------------------------------------------------------------- /// State stored per viewport. /// /// Mostly for internal use. /// Things here may move and change without warning. #[derive(Default)] pub struct ViewportState { /// The type of viewport. /// /// This will never be [`ViewportClass::EmbeddedWindow`], /// since those don't result in real viewports. pub class: ViewportClass, /// The latest delta pub builder: ViewportBuilder, /// The user-code that shows the GUI, used for deferred viewports. /// /// `None` for immediate viewports. pub viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>, pub input: InputState, /// State that is collected during a pass and then cleared. pub this_pass: PassState, /// The final [`PassState`] from last pass. /// /// Only read from. pub prev_pass: PassState, /// Has this viewport been updated this pass? pub used: bool, /// State related to repaint scheduling. repaint: ViewportRepaintInfo, // ---------------------- // Updated at the start of the pass: // /// Which widgets are under the pointer? pub hits: WidgetHits, /// What widgets are being interacted with this pass? /// /// Based on the widgets from last pass, and input in this pass. pub interact_widgets: InteractionSnapshot, // ---------------------- // The output of a pass: // pub graphics: GraphicLayers, // Most of the things in `PlatformOutput` are not actually viewport dependent. pub output: PlatformOutput, pub commands: Vec<ViewportCommand>, // ---------------------- // Cross-frame statistics: pub num_multipass_in_row: usize, } /// What called [`Context::request_repaint`] or [`Context::request_discard`]? #[derive(Clone, PartialEq, Eq, Hash)] pub struct RepaintCause { /// What file had the call that requested the repaint? pub file: &'static str, /// What line number of the call that requested the repaint? pub line: u32, /// Explicit reason; human readable. pub reason: Cow<'static, str>, } impl std::fmt::Debug for RepaintCause { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}:{} {}", self.file, self.line, self.reason) } } impl std::fmt::Display for RepaintCause { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}:{} {}", self.file, self.line, self.reason) } } impl RepaintCause { /// Capture the file and line number of the call site. #[expect(clippy::new_without_default)] #[track_caller] pub fn new() -> Self { let caller = Location::caller(); Self { file: caller.file(), line: caller.line(), reason: "".into(), } } /// Capture the file and line number of the call site, /// as well as add a reason. #[track_caller] pub fn new_reason(reason: impl Into<Cow<'static, str>>) -> Self { let caller = Location::caller(); Self { file: caller.file(), line: caller.line(), reason: reason.into(), } } } /// Per-viewport state related to repaint scheduling. struct ViewportRepaintInfo { /// Monotonically increasing counter. /// /// Incremented at the end of [`Context::run`]. /// This can be smaller than [`Self::cumulative_pass_nr`], /// but never larger. cumulative_frame_nr: u64, /// Monotonically increasing counter, counting the number of passes. /// This can be larger than [`Self::cumulative_frame_nr`], /// but never smaller. cumulative_pass_nr: u64, /// The duration which the backend will poll for new events /// before forcing another egui update, even if there's no new events. /// /// Also used to suppress multiple calls to the repaint callback during the same pass. /// /// This is also returned in [`crate::ViewportOutput`]. repaint_delay: Duration, /// While positive, keep requesting repaints. Decrement at the start of each pass. outstanding: u8, /// What caused repaints during this pass? causes: Vec<RepaintCause>, /// What triggered a repaint the previous pass? /// (i.e: why are we updating now?) prev_causes: Vec<RepaintCause>, /// What was the output of `repaint_delay` on the previous pass? /// /// If this was zero, we are repainting as quickly as possible /// (as far as we know). prev_pass_paint_delay: Duration, } impl Default for ViewportRepaintInfo { fn default() -> Self { Self { cumulative_frame_nr: 0, cumulative_pass_nr: 0, // We haven't scheduled a repaint yet. repaint_delay: Duration::MAX, // Let's run a couple of frames at the start, because why not. outstanding: 1, causes: Default::default(), prev_causes: Default::default(), prev_pass_paint_delay: Duration::MAX, } } } impl ViewportRepaintInfo { pub fn requested_immediate_repaint_prev_pass(&self) -> bool { self.prev_pass_paint_delay == Duration::ZERO } } // ---------------------------------------------------------------------------- #[derive(Default)] struct ContextImpl { fonts: Option<Fonts>, font_definitions: FontDefinitions, memory: Memory, animation_manager: AnimationManager, plugins: plugin::Plugins, safe_area: SafeAreaInsets, /// All viewports share the same texture manager and texture namespace. /// /// In all viewports, [`TextureId::default`] is special, and points to the font atlas. /// The font-atlas texture _may_ be different across viewports, as they may have different /// `pixels_per_point`, so we do special book-keeping for that. /// See <https://github.com/emilk/egui/issues/3664>. tex_manager: WrappedTextureManager, /// Set during the pass, becomes active at the start of the next pass. new_zoom_factor: Option<f32>, os: OperatingSystem, /// How deeply nested are we? viewport_stack: Vec<ViewportIdPair>, /// What is the last viewport rendered? last_viewport: ViewportId, paint_stats: PaintStats, request_repaint_callback: Option<Box<dyn Fn(RequestRepaintInfo) + Send + Sync>>, viewport_parents: ViewportIdMap<ViewportId>, viewports: ViewportIdMap<ViewportState>, embed_viewports: bool, is_accesskit_enabled: bool, loaders: Arc<Loaders>, } impl ContextImpl { fn begin_pass(&mut self, mut new_raw_input: RawInput) { let viewport_id = new_raw_input.viewport_id; let parent_id = new_raw_input .viewports .get(&viewport_id) .and_then(|v| v.parent) .unwrap_or_default(); let ids = ViewportIdPair::from_self_and_parent(viewport_id, parent_id); if let Some(safe_area) = new_raw_input.safe_area_insets { self.safe_area = safe_area; } let is_outermost_viewport = self.viewport_stack.is_empty(); // not necessarily root, just outermost immediate viewport self.viewport_stack.push(ids); self.begin_pass_repaint_logic(viewport_id); let viewport = self.viewports.entry(viewport_id).or_default(); if is_outermost_viewport && let Some(new_zoom_factor) = self.new_zoom_factor.take() { let ratio = self.memory.options.zoom_factor / new_zoom_factor; self.memory.options.zoom_factor = new_zoom_factor; let input = &viewport.input; // This is a bit hacky, but is required to avoid jitter: let mut rect = input.content_rect(); rect.min = (ratio * rect.min.to_vec2()).to_pos2(); rect.max = (ratio * rect.max.to_vec2()).to_pos2(); new_raw_input.screen_rect = Some(rect); // We should really scale everything else in the input too, // but the `screen_rect` is the most important part. } let native_pixels_per_point = new_raw_input .viewport() .native_pixels_per_point .unwrap_or(1.0); let pixels_per_point = self.memory.options.zoom_factor * native_pixels_per_point; let all_viewport_ids: ViewportIdSet = self.all_viewport_ids(); let viewport = self.viewports.entry(self.viewport_id()).or_default(); self.memory.begin_pass(&new_raw_input, &all_viewport_ids); viewport.input = std::mem::take(&mut viewport.input).begin_pass( new_raw_input, viewport.repaint.requested_immediate_repaint_prev_pass(), pixels_per_point, self.memory.options.input_options, ); let repaint_after = viewport.input.wants_repaint_after(); let content_rect = viewport.input.content_rect(); viewport.this_pass.begin_pass(content_rect); { let mut layers: Vec<LayerId> = viewport.prev_pass.widgets.layer_ids().collect(); layers.sort_by(|&a, &b| self.memory.areas().compare_order(a, b)); viewport.hits = if let Some(pos) = viewport.input.pointer.interact_pos() { let interact_radius = self.memory.options.style().interaction.interact_radius; crate::hit_test::hit_test( &viewport.prev_pass.widgets, &layers, &self.memory.to_global, pos, interact_radius, ) } else { WidgetHits::default() }; viewport.interact_widgets = crate::interaction::interact( &viewport.interact_widgets, &viewport.prev_pass.widgets, &viewport.hits, &viewport.input, self.memory.interaction_mut(), ); } // Ensure we register the background area so panels and background ui can catch clicks: self.memory.areas_mut().set_state( LayerId::background(), AreaState { pivot_pos: Some(content_rect.left_top()), pivot: Align2::LEFT_TOP, size: Some(content_rect.size()), interactable: true, last_became_visible_at: None, }, ); if self.is_accesskit_enabled { profiling::scope!("accesskit"); use crate::pass_state::AccessKitPassState; let id = crate::accesskit_root_id(); let mut root_node = accesskit::Node::new(accesskit::Role::Window); let pixels_per_point = viewport.input.pixels_per_point(); root_node.set_transform(accesskit::Affine::scale(pixels_per_point.into())); let mut nodes = IdMap::default(); nodes.insert(id, root_node); viewport.this_pass.accesskit_state = Some(AccessKitPassState { nodes, parent_map: IdMap::default(), }); } self.update_fonts_mut(); if let Some(delay) = repaint_after { self.request_repaint_after(delay, viewport_id, RepaintCause::new()); } } /// Load fonts unless already loaded. fn update_fonts_mut(&mut self) { profiling::function_scope!(); let input = &self.viewport().input; let max_texture_side = input.max_texture_side; if let Some(font_definitions) = self.memory.new_font_definitions.take() { // New font definition loaded, so we need to reload all fonts. self.fonts = None; self.font_definitions = font_definitions; log::trace!("Loading new font definitions"); } if !self.memory.add_fonts.is_empty() { let fonts = self.memory.add_fonts.drain(..); for font in fonts { self.fonts = None; // recreate all the fonts for family in font.families { let fam = self .font_definitions .families .entry(family.family) .or_default(); match family.priority { FontPriority::Highest => fam.insert(0, font.name.clone()), FontPriority::Lowest => fam.push(font.name.clone()), } } self.font_definitions .font_data .insert(font.name, Arc::new(font.data)); } log::trace!("Adding new fonts"); } let Visuals { mut text_options, .. } = self.memory.options.style().visuals; text_options.max_texture_side = max_texture_side; let mut is_new = false; let fonts = self.fonts.get_or_insert_with(|| { log::trace!("Creating new Fonts"); is_new = true; profiling::scope!("Fonts::new"); Fonts::new(text_options, self.font_definitions.clone()) }); { profiling::scope!("Fonts::begin_pass"); fonts.begin_pass(text_options); } } fn accesskit_node_builder(&mut self, id: Id) -> Option<&mut accesskit::Node> { let state = self.viewport().this_pass.accesskit_state.as_mut()?; let builders = &mut state.nodes; if let std::collections::hash_map::Entry::Vacant(entry) = builders.entry(id) { entry.insert(Default::default()); /// Find the first ancestor that already has an accesskit node. fn find_accesskit_parent( parent_map: &IdMap<Id>, node_map: &IdMap<accesskit::Node>, id: Id, ) -> Option<Id> { if let Some(parent_id) = parent_map.get(&id) { if node_map.contains_key(parent_id) { Some(*parent_id) } else { find_accesskit_parent(parent_map, node_map, *parent_id) } } else { None } } let parent_id = find_accesskit_parent(&state.parent_map, builders, id) .unwrap_or_else(crate::accesskit_root_id); let parent_builder = builders.get_mut(&parent_id)?; parent_builder.push_child(id.accesskit_id()); } builders.get_mut(&id) } fn pixels_per_point(&mut self) -> f32 { self.viewport().input.pixels_per_point } /// Return the `ViewportId` of the current viewport. /// /// For the root viewport this will return [`ViewportId::ROOT`]. pub(crate) fn viewport_id(&self) -> ViewportId { self.viewport_stack.last().copied().unwrap_or_default().this } /// Return the `ViewportId` of his parent. /// /// For the root viewport this will return [`ViewportId::ROOT`]. pub(crate) fn parent_viewport_id(&self) -> ViewportId { let viewport_id = self.viewport_id(); *self .viewport_parents .get(&viewport_id) .unwrap_or(&ViewportId::ROOT) } fn all_viewport_ids(&self) -> ViewportIdSet { self.viewports .keys() .copied() .chain([ViewportId::ROOT]) .collect() } /// The current active viewport pub(crate) fn viewport(&mut self) -> &mut ViewportState { self.viewports.entry(self.viewport_id()).or_default() } fn viewport_for(&mut self, viewport_id: ViewportId) -> &mut ViewportState { self.viewports.entry(viewport_id).or_default() } } // ---------------------------------------------------------------------------- /// Your handle to egui. /// /// This is the first thing you need when working with egui. /// Contains the [`InputState`], [`Memory`], [`PlatformOutput`], and more. /// /// [`Context`] is cheap to clone, and any clones refers to the same mutable data /// ([`Context`] uses refcounting internally). /// /// ## Locking /// All methods are marked `&self`; [`Context`] has interior mutability protected by an [`RwLock`]. /// /// To access parts of a `Context` you need to use some of the helper functions that take closures: /// /// ``` /// # let ctx = egui::Context::default(); /// if ctx.input(|i| i.key_pressed(egui::Key::A)) { /// ctx.copy_text("Hello!".to_owned()); /// } /// ``` /// /// Within such a closure you may NOT recursively lock the same [`Context`], as that can lead to a deadlock. /// Therefore it is important that any lock of [`Context`] is short-lived. /// /// These are effectively transactional accesses. /// /// [`Ui`] has many of the same accessor functions, and the same applies there. /// /// ## Example: /// /// ``` no_run /// # fn handle_platform_output(_: egui::PlatformOutput) {} /// # fn paint(textures_delta: egui::TexturesDelta, _: Vec<egui::ClippedPrimitive>) {} /// let mut ctx = egui::Context::default(); /// /// // Game loop: /// loop { /// let raw_input = egui::RawInput::default(); /// let full_output = ctx.run(raw_input, |ctx| { /// egui::CentralPanel::default().show(&ctx, |ui| { /// ui.label("Hello world!"); /// if ui.button("Click me").clicked() { /// // take some action here /// } /// }); /// }); /// handle_platform_output(full_output.platform_output); /// let clipped_primitives = ctx.tessellate(full_output.shapes, full_output.pixels_per_point); /// paint(full_output.textures_delta, clipped_primitives); /// } /// ``` #[derive(Clone)] pub struct Context(Arc<RwLock<ContextImpl>>); impl std::fmt::Debug for Context { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Context").finish_non_exhaustive() } } impl std::cmp::PartialEq for Context { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl Default for Context { fn default() -> Self { let ctx_impl = ContextImpl { embed_viewports: true, viewports: std::iter::once((ViewportId::ROOT, ViewportState::default())).collect(), ..Default::default() }; let ctx = Self(Arc::new(RwLock::new(ctx_impl))); ctx.add_plugin(plugin::CallbackPlugin::default()); // Register built-in plugins: ctx.add_plugin(crate::debug_text::DebugTextPlugin::default()); ctx.add_plugin(crate::text_selection::LabelSelectionState::default()); ctx.add_plugin(crate::DragAndDrop::default()); ctx } } impl Context { /// Do read-only (shared access) transaction on Context fn read<R>(&self, reader: impl FnOnce(&ContextImpl) -> R) -> R { reader(&self.0.read()) } /// Do read-write (exclusive access) transaction on Context fn write<R>(&self, writer: impl FnOnce(&mut ContextImpl) -> R) -> R { writer(&mut self.0.write()) } /// Run the ui code for one frame. /// /// At most [`Options::max_passes`] calls will be issued to `run_ui`, /// and only on the rare occasion that [`Context::request_discard`] is called. /// Usually, it `run_ui` will only be called once. /// /// The [`Ui`] given to the callback will cover the entire [`Self::content_rect`], /// with no margin or background color. Use [`crate::Frame`] to add that. /// /// You can organize your GUI using [`crate::Panel`]. /// /// Instead of calling `run_ui`, you can alternatively use [`Self::begin_pass`] and [`Context::end_pass`]. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// let full_output = ctx.run_ui(input, |ui| { /// ui.label("Hello egui!"); /// }); /// // handle full_output /// ``` /// /// ## See also /// * [`Self::run`] #[must_use] pub fn run_ui(&self, new_input: RawInput, mut run_ui: impl FnMut(&mut Ui)) -> FullOutput { self.run_ui_dyn(new_input, &mut run_ui) } #[must_use] fn run_ui_dyn(&self, new_input: RawInput, run_ui: &mut dyn FnMut(&mut Ui)) -> FullOutput { let plugins = self.read(|ctx| ctx.plugins.ordered_plugins()); #[expect(deprecated)] self.run(new_input, |ctx| { let mut top_ui = Ui::new( ctx.clone(), Id::new((ctx.viewport_id(), "__top_ui")), UiBuilder::new() .layer_id(LayerId::background()) .max_rect(ctx.available_rect().round_ui()), ); { plugins.on_begin_pass(&mut top_ui); run_ui(&mut top_ui); plugins.on_end_pass(&mut top_ui); } // Inform ctx about what we actually used, so we can shrink the native window to fit. // TODO(emilk): make better use of this somehow ctx.pass_state_mut(|state| state.allocate_central_panel(top_ui.min_rect())); }) } /// Run the ui code for one frame. /// /// At most [`Options::max_passes`] calls will be issued to `run_ui`, /// and only on the rare occasion that [`Context::request_discard`] is called. /// Usually, it `run_ui` will only be called once. /// /// Put your widgets into a [`crate::Panel`], [`crate::CentralPanel`], [`crate::Window`] or [`crate::Area`]. /// /// Instead of calling `run`, you can alternatively use [`Self::begin_pass`] and [`Context::end_pass`]. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// let full_output = ctx.run(input, |ctx| { /// egui::CentralPanel::default().show(&ctx, |ui| { /// ui.label("Hello egui!"); /// }); /// }); /// // handle full_output /// ``` /// /// ## See also /// * [`Self::run_ui`] #[must_use] #[deprecated = "Call run_ui instead"] pub fn run(&self, new_input: RawInput, mut run_ui: impl FnMut(&Self)) -> FullOutput { self.run_dyn(new_input, &mut run_ui) } #[must_use] fn run_dyn(&self, mut new_input: RawInput, run_ui: &mut dyn FnMut(&Self)) -> FullOutput { profiling::function_scope!(); let viewport_id = new_input.viewport_id; let max_passes = self.write(|ctx| ctx.memory.options.max_passes.get()); let mut output = FullOutput::default(); debug_assert_eq!( output.platform_output.num_completed_passes, 0, "output must be fresh, but had {} passes", output.platform_output.num_completed_passes ); loop { profiling::scope!( "pass", output .platform_output .num_completed_passes .to_string() .as_str() ); // We must move the `num_passes` (back) to the viewport output so that [`Self::will_discard`] // has access to the latest pass count. self.write(|ctx| { let viewport = ctx.viewport_for(viewport_id); viewport.output.num_completed_passes = std::mem::take(&mut output.platform_output.num_completed_passes); output.platform_output.request_discard_reasons.clear(); }); self.begin_pass(new_input.take()); run_ui(self); output.append(self.end_pass()); debug_assert!( 0 < output.platform_output.num_completed_passes, "Completed passes was lower than 0, was {}", output.platform_output.num_completed_passes ); if !output.platform_output.requested_discard() { break; // no need for another pass } if max_passes <= output.platform_output.num_completed_passes { log::debug!( "Ignoring call request_discard, because max_passes={max_passes}. Requested from {:?}", output.platform_output.request_discard_reasons ); break; } } self.write(|ctx| { let did_multipass = 1 < output.platform_output.num_completed_passes; let viewport = ctx.viewport_for(viewport_id); if did_multipass { viewport.num_multipass_in_row += 1; } else { viewport.num_multipass_in_row = 0; } viewport.repaint.cumulative_frame_nr += 1; }); output } /// An alternative to calling [`Self::run`]. /// /// It is usually better to use [`Self::run`], because /// `run` supports multi-pass layout using [`Self::request_discard`]. /// /// ``` /// // One egui context that you keep reusing: /// let mut ctx = egui::Context::default(); /// /// // Each frame: /// let input = egui::RawInput::default(); /// ctx.begin_pass(input); /// /// egui::CentralPanel::default().show(&ctx, |ui| { /// ui.label("Hello egui!"); /// }); /// /// let full_output = ctx.end_pass(); /// // handle full_output /// ``` pub fn begin_pass(&self, mut new_input: RawInput) { profiling::function_scope!(); let plugins = self.read(|ctx| ctx.plugins.ordered_plugins()); plugins.on_input(&mut new_input); self.write(|ctx| ctx.begin_pass(new_input)); } /// See [`Self::begin_pass`].
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/sense.rs
crates/egui/src/sense.rs
/// What sort of interaction is a widget sensitive to? #[derive(Clone, Copy, Eq, PartialEq)] // #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct Sense(u8); bitflags::bitflags! { impl Sense: u8 { const HOVER = 0; /// Buttons, sliders, windows, … const CLICK = 1<<0; /// Sliders, windows, scroll bars, scroll areas, … const DRAG = 1<<1; /// This widget wants focus. /// /// Anything interactive + labels that can be focused /// for the benefit of screen readers. const FOCUSABLE = 1<<2; } } impl std::fmt::Debug for Sense { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Sense {{")?; if self.senses_click() { write!(f, " click")?; } if self.senses_drag() { write!(f, " drag")?; } if self.is_focusable() { write!(f, " focusable")?; } write!(f, " }}") } } impl Sense { /// Senses no clicks or drags. Only senses mouse hover. #[doc(alias = "none")] #[inline] pub fn hover() -> Self { Self::empty() } /// Senses no clicks or drags, but can be focused with the keyboard. /// Used for labels that can be focused for the benefit of screen readers. #[inline] pub fn focusable_noninteractive() -> Self { Self::FOCUSABLE } /// Sense clicks and hover, but not drags. #[inline] pub fn click() -> Self { Self::CLICK | Self::FOCUSABLE } /// Sense drags and hover, but not clicks. #[inline] pub fn drag() -> Self { Self::DRAG | Self::FOCUSABLE } /// Sense both clicks, drags and hover (e.g. a slider or window). /// /// Note that this will introduce a latency when dragging, /// because when the user starts a press egui can't know if this is the start /// of a click or a drag, and it won't know until the cursor has /// either moved a certain distance, or the user has released the mouse button. /// /// See [`crate::PointerState::is_decidedly_dragging`] for details. #[inline] pub fn click_and_drag() -> Self { Self::CLICK | Self::FOCUSABLE | Self::DRAG } /// Returns true if we sense either clicks or drags. #[inline] pub fn interactive(&self) -> bool { self.intersects(Self::CLICK | Self::DRAG) } #[inline] pub fn senses_click(&self) -> bool { self.contains(Self::CLICK) } #[inline] pub fn senses_drag(&self) -> bool { self.contains(Self::DRAG) } #[inline] pub fn is_focusable(&self) -> bool { self.contains(Self::FOCUSABLE) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/debug_text.rs
crates/egui/src/debug_text.rs
//! This is an example of how to create a plugin for egui. //! //! A plugin is a struct that implements the [`Plugin`] trait and holds some state. //! The plugin is registered with the [`Context`] using [`Context::add_plugin`] //! to get callbacks on certain events ([`Plugin::on_begin_pass`], [`Plugin::on_end_pass`]). use crate::{ Align, Align2, Color32, Context, FontFamily, FontId, Plugin, Rect, Shape, Ui, Vec2, WidgetText, text, }; /// Print this text next to the cursor at the end of the pass. /// /// If you call this multiple times, the text will be appended. /// /// This only works if compiled with `debug_assertions`. /// /// ``` /// # let ctx = &egui::Context::default(); /// # let state = true; /// egui::debug_text::print(ctx, format!("State: {state:?}")); /// ``` #[track_caller] pub fn print(ctx: &Context, text: impl Into<WidgetText>) { if !cfg!(debug_assertions) { return; } let location = std::panic::Location::caller(); let location = format!("{}:{}", location.file(), location.line()); let plugin = ctx.plugin::<DebugTextPlugin>(); let mut state = plugin.lock(); state.entries.push(Entry { location, text: text.into(), }); } #[derive(Clone)] struct Entry { location: String, text: WidgetText, } /// A plugin for easily showing debug-text on-screen. /// /// This is a built-in plugin in egui, automatically registered during [`Context`] creation. #[derive(Clone, Default)] pub struct DebugTextPlugin { // This gets re-filled every pass. entries: Vec<Entry>, } impl Plugin for DebugTextPlugin { fn debug_name(&self) -> &'static str { "DebugTextPlugin" } fn on_end_pass(&mut self, ui: &mut Ui) { let entries = std::mem::take(&mut self.entries); Self::paint_entries(ui, entries); } } impl DebugTextPlugin { fn paint_entries(ctx: &Context, entries: Vec<Entry>) { if entries.is_empty() { return; } // Show debug-text next to the cursor. let mut pos = ctx .input(|i| i.pointer.latest_pos()) .unwrap_or_else(|| ctx.content_rect().center()) + 8.0 * Vec2::Y; let painter = ctx.debug_painter(); let where_to_put_background = painter.add(Shape::Noop); let mut bounding_rect = Rect::from_points(&[pos]); let color = Color32::GRAY; let font_id = FontId::new(10.0, FontFamily::Proportional); for Entry { location, text } in entries { { // Paint location to left of `pos`: let location_galley = ctx.fonts_mut(|f| f.layout(location, font_id.clone(), color, f32::INFINITY)); let location_rect = Align2::RIGHT_TOP.anchor_size(pos - 4.0 * Vec2::X, location_galley.size()); painter.galley(location_rect.min, location_galley, color); bounding_rect |= location_rect; } { // Paint `text` to right of `pos`: let available_width = ctx.content_rect().max.x - pos.x; let galley = text.into_galley_impl( ctx, &ctx.global_style(), text::TextWrapping::wrap_at_width(available_width), font_id.clone().into(), Align::TOP, ); let rect = Align2::LEFT_TOP.anchor_size(pos, galley.size()); painter.galley(rect.min, galley, color); bounding_rect |= rect; } pos.y = bounding_rect.max.y + 4.0; } painter.set( where_to_put_background, Shape::rect_filled( bounding_rect.expand(4.0), 2.0, Color32::from_black_alpha(192), ), ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/gui_zoom.rs
crates/egui/src/gui_zoom.rs
//! Helpers for zooming the whole GUI of an app (changing [`Context::pixels_per_point`]). //! use crate::{Button, Context, Key, KeyboardShortcut, Modifiers, Ui}; /// The suggested keyboard shortcuts for global gui zooming. pub mod kb_shortcuts { use super::{Key, KeyboardShortcut, Modifiers}; /// Primary keyboard shortcut for zooming in (`Cmd` + `+`). pub const ZOOM_IN: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Plus); /// Secondary keyboard shortcut for zooming in (`Cmd` + `=`). /// /// On an English keyboard `+` is `Shift` + `=`, /// but it is annoying to have to press shift. /// So most browsers also allow `Cmd` + `=` for zooming in. /// We do the same. pub const ZOOM_IN_SECONDARY: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Equals); /// Keyboard shortcut for zooming in (`Cmd` + `-`). pub const ZOOM_OUT: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Minus); /// Keyboard shortcut for resetting zoom in (`Cmd` + `0`). pub const ZOOM_RESET: KeyboardShortcut = KeyboardShortcut::new(Modifiers::COMMAND, Key::Num0); } /// Let the user scale the GUI (change [`Context::zoom_factor`]) by pressing /// Cmd+Plus, Cmd+Minus or Cmd+0, just like in a browser. /// /// By default, [`crate::Context`] calls this function at the end of each frame, /// controllable by [`crate::Options::zoom_with_keyboard`]. pub(crate) fn zoom_with_keyboard(ctx: &Context) { if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_RESET)) { ctx.set_zoom_factor(1.0); } else { if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_IN)) || ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_IN_SECONDARY)) { zoom_in(ctx); } if ctx.input_mut(|i| i.consume_shortcut(&kb_shortcuts::ZOOM_OUT)) { zoom_out(ctx); } } } const MIN_ZOOM_FACTOR: f32 = 0.2; const MAX_ZOOM_FACTOR: f32 = 5.0; /// Make everything larger by increasing [`Context::zoom_factor`]. pub fn zoom_in(ctx: &Context) { let mut zoom_factor = ctx.zoom_factor(); zoom_factor += 0.1; zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR); zoom_factor = (zoom_factor * 10.).round() / 10.; ctx.set_zoom_factor(zoom_factor); } /// Make everything smaller by decreasing [`Context::zoom_factor`]. pub fn zoom_out(ctx: &Context) { let mut zoom_factor = ctx.zoom_factor(); zoom_factor -= 0.1; zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR); zoom_factor = (zoom_factor * 10.).round() / 10.; ctx.set_zoom_factor(zoom_factor); } /// Show buttons for zooming the ui. /// /// This is meant to be called from within a menu (See [`Ui::menu_button`]). pub fn zoom_menu_buttons(ui: &mut Ui) { fn button(ctx: &Context, text: &str, shortcut: &KeyboardShortcut) -> Button<'static> { let btn = Button::new(text); let zoom_with_keyboard = ctx.options(|o| o.zoom_with_keyboard); if zoom_with_keyboard { btn.shortcut_text(ctx.format_shortcut(shortcut)) } else { btn } } if ui .add_enabled( ui.ctx().zoom_factor() < MAX_ZOOM_FACTOR, button(ui.ctx(), "Zoom In", &kb_shortcuts::ZOOM_IN), ) .clicked() { zoom_in(ui.ctx()); } if ui .add_enabled( ui.ctx().zoom_factor() > MIN_ZOOM_FACTOR, button(ui.ctx(), "Zoom Out", &kb_shortcuts::ZOOM_OUT), ) .clicked() { zoom_out(ui.ctx()); } if ui .add_enabled( ui.ctx().zoom_factor() != 1.0, button(ui.ctx(), "Reset Zoom", &kb_shortcuts::ZOOM_RESET), ) .clicked() { ui.ctx().set_zoom_factor(1.0); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/hit_test.rs
crates/egui/src/hit_test.rs
use ahash::HashMap; use emath::TSTransform; use crate::{LayerId, Pos2, Sense, WidgetRect, WidgetRects, ahash, emath, id::IdSet}; /// Result of a hit-test against [`WidgetRects`]. /// /// Answers the question "what is under the mouse pointer?". /// /// Note that this doesn't care if the mouse button is pressed or not, /// or if we're currently already dragging something. #[derive(Clone, Debug, Default)] pub struct WidgetHits { /// All widgets close to the pointer, back-to-front. /// /// This is a superset of all other widgets in this struct. pub close: Vec<WidgetRect>, /// All widgets that contains the pointer, back-to-front. /// /// i.e. both a Window and the Button in it can contain the pointer. /// /// Some of these may be widgets in a layer below the top-most layer. /// /// This will be used for hovering. pub contains_pointer: Vec<WidgetRect>, /// If the user would start a clicking now, this is what would be clicked. /// /// This is the top one under the pointer, or closest one of the top-most. pub click: Option<WidgetRect>, /// If the user would start a dragging now, this is what would be dragged. /// /// This is the top one under the pointer, or closest one of the top-most. pub drag: Option<WidgetRect>, } /// Find the top or closest widgets to the given position, /// none which is closer than `search_radius`. pub fn hit_test( widgets: &WidgetRects, layer_order: &[LayerId], layer_to_global: &HashMap<LayerId, TSTransform>, pos: Pos2, search_radius: f32, ) -> WidgetHits { profiling::function_scope!(); let search_radius_sq = search_radius * search_radius; // Transform the position into the local coordinate space of each layer: let pos_in_layers: HashMap<LayerId, Pos2> = layer_to_global .iter() .map(|(layer_id, to_global)| (*layer_id, to_global.inverse() * pos)) .collect(); let mut closest_dist_sq = f32::INFINITY; let mut closest_hit = None; // First pass: find the few widgets close to the given position, sorted back-to-front. let mut close: Vec<WidgetRect> = layer_order .iter() .filter(|layer| layer.order.allow_interaction()) .flat_map(|&layer_id| widgets.get_layer(layer_id)) .filter(|&w| { if w.interact_rect.is_negative() || w.interact_rect.any_nan() { return false; } let pos_in_layer = pos_in_layers.get(&w.layer_id).copied().unwrap_or(pos); // TODO(emilk): we should probably do the distance testing in global space instead let dist_sq = w.interact_rect.distance_sq_to_pos(pos_in_layer); // In tie, pick last = topmost. if dist_sq <= closest_dist_sq { closest_dist_sq = dist_sq; closest_hit = Some(w); } dist_sq <= search_radius_sq }) .copied() .collect(); // Transform to global coordinates: for hit in &mut close { if let Some(to_global) = layer_to_global.get(&hit.layer_id).copied() { *hit = hit.transform(to_global); } } close.retain(|rect| !rect.interact_rect.any_nan()); // Protect against bad input and transforms // When using layer transforms it is common to stack layers close to each other. // For instance, you may have a resize-separator on a panel, with two // transform-layers on either side. // The resize-separator is technically in a layer _behind_ the transform-layers, // but the user doesn't perceive it as such. // So how do we handle this case? // // If we just allow interactions with ALL close widgets, // then we might accidentally allow clicks through windows and other bad stuff. // // Let's try this: // * Set up a hit-area (based on search_radius) // * Iterate over all hits top-to-bottom // * Stop if any hit covers the whole hit-area, otherwise keep going // * Collect the layers ids in a set // * Remove all widgets not in the above layer set // // This will most often result in only one layer, // but if the pointer is at the edge of a layer, we might include widgets in // a layer behind it. let mut included_layers: ahash::HashSet<LayerId> = Default::default(); for hit in close.iter().rev() { included_layers.insert(hit.layer_id); let hit_covers_search_area = contains_circle(hit.interact_rect, pos, search_radius); if hit_covers_search_area { break; // nothing behind this layer could ever be interacted with } } close.retain(|hit| included_layers.contains(&hit.layer_id)); // If a widget is disabled, treat it as if it isn't sensing anything. // This simplifies the code in `hit_test_on_close` so it doesn't have to check // the `enabled` flag everywhere: for w in &mut close { if !w.enabled { w.sense -= Sense::CLICK; w.sense -= Sense::DRAG; } } // Find widgets which are hidden behind another widget and discard them. // This is the case when a widget fully contains another widget and is on a different layer. // It prevents "hovering through" widgets when there is a clickable widget behind. let mut hidden = IdSet::default(); for (i, current) in close.iter().enumerate().rev() { for next in &close[i + 1..] { if next.interact_rect.contains_rect(current.interact_rect) && current.layer_id != next.layer_id { hidden.insert(current.id); } } } close.retain(|c| !hidden.contains(&c.id)); let mut hits = hit_test_on_close(&close, pos); hits.contains_pointer = close .iter() .filter(|widget| widget.interact_rect.contains(pos)) .copied() .collect(); hits.close = close; { // Undo the to_global-transform we applied earlier, // go back to local layer-coordinates: let restore_widget_rect = |w: &mut WidgetRect| { *w = widgets.get(w.id).copied().unwrap_or(*w); }; for wr in &mut hits.close { restore_widget_rect(wr); } for wr in &mut hits.contains_pointer { restore_widget_rect(wr); } if let Some(wr) = &mut hits.drag { debug_assert!( wr.sense.senses_drag(), "We should only return drag hits if they sense drag" ); restore_widget_rect(wr); } if let Some(wr) = &mut hits.click { debug_assert!( wr.sense.senses_click(), "We should only return click hits if they sense click" ); restore_widget_rect(wr); } } hits } /// Returns true if the rectangle contains the whole circle. fn contains_circle(interact_rect: emath::Rect, pos: Pos2, radius: f32) -> bool { interact_rect.shrink(radius).contains(pos) } fn hit_test_on_close(close: &[WidgetRect], pos: Pos2) -> WidgetHits { #![expect(clippy::collapsible_else_if)] // First find the best direct hits: let hit_click = find_closest_within( close.iter().copied().filter(|w| w.sense.senses_click()), pos, 0.0, ); let hit_drag = find_closest_within( close.iter().copied().filter(|w| w.sense.senses_drag()), pos, 0.0, ); match (hit_click, hit_drag) { (None, None) => { // No direct hit on anything. Find the closest interactive widget. let closest = find_closest( close .iter() .copied() .filter(|w| w.sense.senses_click() || w.sense.senses_drag()), pos, ); if let Some(closest) = closest { WidgetHits { click: closest.sense.senses_click().then_some(closest), drag: closest.sense.senses_drag().then_some(closest), ..Default::default() } } else { // Found nothing WidgetHits { click: None, drag: None, ..Default::default() } } } (None, Some(hit_drag)) => { // We have a perfect hit on a drag, but not on click. // We have a direct hit on something that implements drag. // This could be a big background thing, like a `ScrollArea` background, // or a moveable window. // It could also be something small, like a slider, or panel resize handle. let closest_click = find_closest( close.iter().copied().filter(|w| w.sense.senses_click()), pos, ); if let Some(closest_click) = closest_click { if closest_click.sense.senses_drag() { // We have something close that sense both clicks and drag. // Should we use it over the direct drag-hit? if hit_drag .interact_rect .contains_rect(closest_click.interact_rect) { // This is a smaller thing on a big background - help the user hit it, // and ignore the big drag background. WidgetHits { click: Some(closest_click), drag: Some(closest_click), ..Default::default() } } else { // The drag-widget is separate from the click-widget, // so return only the drag-widget WidgetHits { click: None, drag: Some(hit_drag), ..Default::default() } } } else { // This is a close pure-click widget. // However, we should be careful to only return two different widgets // when it is absolutely not going to confuse the user. if hit_drag .interact_rect .contains_rect(closest_click.interact_rect) { // The drag widget is a big background thing (scroll area), // so returning a separate click widget should not be confusing WidgetHits { click: Some(closest_click), drag: Some(hit_drag), ..Default::default() } } else { // The two widgets are just two normal small widgets close to each other. // Highlighting both would be very confusing. WidgetHits { click: None, drag: Some(hit_drag), ..Default::default() } } } } else { // No close clicks. // Maybe there is a close drag widget, that is a smaller // widget floating on top of a big background? // If so, it would be nice to help the user click that. let closest_drag = find_closest( close .iter() .copied() .filter(|w| w.sense.senses_drag() && w.id != hit_drag.id), pos, ); if let Some(closest_drag) = closest_drag && hit_drag .interact_rect .contains_rect(closest_drag.interact_rect) { // `hit_drag` is a big background thing and `closest_drag` is something small on top of it. // Be helpful and return the small things: return WidgetHits { click: None, drag: Some(closest_drag), ..Default::default() }; } WidgetHits { click: None, drag: Some(hit_drag), ..Default::default() } } } (Some(hit_click), None) => { // We have a perfect hit on a click-widget, but not on a drag-widget. // // Note that we don't look for a close drag widget in this case, // because I can't think of a case where that would be helpful. // This is in contrast with the opposite case, // where when hovering directly over a drag-widget (like a big ScrollArea), // we look for close click-widgets (e.g. buttons). // This is because big background drag-widgets (ScrollArea, Window) are common, // but big clickable things aren't. // Even if they were, I think it would be confusing for a user if clicking // a drag-only widget would click something _behind_ it. WidgetHits { click: Some(hit_click), drag: None, ..Default::default() } } (Some(hit_click), Some(hit_drag)) => { // We have a perfect hit on both click and drag. Which is the topmost? #[expect(clippy::unwrap_used)] let click_idx = close.iter().position(|w| *w == hit_click).unwrap(); #[expect(clippy::unwrap_used)] let drag_idx = close.iter().position(|w| *w == hit_drag).unwrap(); let click_is_on_top_of_drag = drag_idx < click_idx; if click_is_on_top_of_drag { if hit_click.sense.senses_drag() { // The top thing senses both clicks and drags. WidgetHits { click: Some(hit_click), drag: Some(hit_click), ..Default::default() } } else { // They are interested in different things, // and click is on top. Report both hits, // e.g. the top Button and the ScrollArea behind it. WidgetHits { click: Some(hit_click), drag: Some(hit_drag), ..Default::default() } } } else { if hit_drag.sense.senses_click() { // The top thing senses both clicks and drags. WidgetHits { click: Some(hit_drag), drag: Some(hit_drag), ..Default::default() } } else { // The top things senses only drags, // so we ignore the click-widget, because it would be confusing // if clicking a drag-widget would actually click something else below it. WidgetHits { click: None, drag: Some(hit_drag), ..Default::default() } } } } } } fn find_closest(widgets: impl Iterator<Item = WidgetRect>, pos: Pos2) -> Option<WidgetRect> { find_closest_within(widgets, pos, f32::INFINITY) } fn find_closest_within( widgets: impl Iterator<Item = WidgetRect>, pos: Pos2, max_dist: f32, ) -> Option<WidgetRect> { let mut closest: Option<WidgetRect> = None; let mut closest_dist_sq = max_dist * max_dist; for widget in widgets { if widget.interact_rect.is_negative() { continue; } let dist_sq = widget.interact_rect.distance_sq_to_pos(pos); // In case of a tie, take the last one = the one on top. if dist_sq <= closest_dist_sq { closest_dist_sq = dist_sq; closest = Some(widget); } } closest } #[cfg(test)] mod tests { #![expect(clippy::print_stdout)] use emath::{Rect, pos2, vec2}; use crate::{Id, Sense}; use super::*; fn wr(id: Id, sense: Sense, rect: Rect) -> WidgetRect { WidgetRect { id, layer_id: LayerId::background(), rect, interact_rect: rect, sense, enabled: true, } } #[test] fn buttons_on_window() { let widgets = vec![ wr( Id::new("bg-area"), Sense::drag(), Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0)), ), wr( Id::new("click"), Sense::click(), Rect::from_min_size(pos2(10.0, 10.0), vec2(10.0, 10.0)), ), wr( Id::new("click-and-drag"), Sense::click_and_drag(), Rect::from_min_size(pos2(100.0, 10.0), vec2(10.0, 10.0)), ), ]; // Perfect hit: let hits = hit_test_on_close(&widgets, pos2(15.0, 15.0)); assert_eq!(hits.click.unwrap().id, Id::new("click")); assert_eq!(hits.drag.unwrap().id, Id::new("bg-area")); // Close hit: let hits = hit_test_on_close(&widgets, pos2(5.0, 5.0)); assert_eq!(hits.click.unwrap().id, Id::new("click")); assert_eq!(hits.drag.unwrap().id, Id::new("bg-area")); // Perfect hit: let hits = hit_test_on_close(&widgets, pos2(105.0, 15.0)); assert_eq!(hits.click.unwrap().id, Id::new("click-and-drag")); assert_eq!(hits.drag.unwrap().id, Id::new("click-and-drag")); // Close hit - should still ignore the drag-background so as not to confuse the user: let hits = hit_test_on_close(&widgets, pos2(105.0, 5.0)); assert_eq!(hits.click.unwrap().id, Id::new("click-and-drag")); assert_eq!(hits.drag.unwrap().id, Id::new("click-and-drag")); } #[test] fn thin_resize_handle_next_to_label() { let widgets = vec![ wr( Id::new("bg-area"), Sense::drag(), Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0)), ), wr( Id::new("bg-left-label"), Sense::click_and_drag(), Rect::from_min_size(pos2(0.0, 0.0), vec2(40.0, 100.0)), ), wr( Id::new("thin-drag-handle"), Sense::drag(), Rect::from_min_size(pos2(30.0, 0.0), vec2(70.0, 100.0)), ), wr( Id::new("fg-right-label"), Sense::click_and_drag(), Rect::from_min_size(pos2(60.0, 0.0), vec2(50.0, 100.0)), ), ]; for (i, w) in widgets.iter().enumerate() { println!("Widget {i}: {:?}", w.id); } // In the middle of the bg-left-label: let hits = hit_test_on_close(&widgets, pos2(25.0, 50.0)); assert_eq!(hits.click.unwrap().id, Id::new("bg-left-label")); assert_eq!(hits.drag.unwrap().id, Id::new("bg-left-label")); // On both the left click-and-drag and thin handle, but the thin handle is on top and should win: let hits = hit_test_on_close(&widgets, pos2(35.0, 50.0)); assert_eq!(hits.click, None); assert_eq!(hits.drag.unwrap().id, Id::new("thin-drag-handle")); // Only on the thin-drag-handle: let hits = hit_test_on_close(&widgets, pos2(50.0, 50.0)); assert_eq!(hits.click, None); assert_eq!(hits.drag.unwrap().id, Id::new("thin-drag-handle")); // On both the thin handle and right label. The label is on top and should win let hits = hit_test_on_close(&widgets, pos2(65.0, 50.0)); assert_eq!(hits.click.unwrap().id, Id::new("fg-right-label")); assert_eq!(hits.drag.unwrap().id, Id::new("fg-right-label")); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/ui_stack.rs
crates/egui/src/ui_stack.rs
use std::sync::Arc; use std::{any::Any, iter::FusedIterator}; use crate::{Direction, Frame, Id, Rect}; /// What kind is this [`crate::Ui`]? #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum UiKind { /// A [`crate::Window`]. Window, /// A [`crate::CentralPanel`]. CentralPanel, /// A left [`crate::Panel`]. LeftPanel, /// A right [`crate::Panel`]. RightPanel, /// A top [`crate::Panel`]. TopPanel, /// A bottom [`crate::Panel`]. BottomPanel, /// A modal [`crate::Modal`]. Modal, /// A [`crate::Frame`]. Frame, /// A [`crate::ScrollArea`]. ScrollArea, /// A [`crate::Resize`]. Resize, /// The content of a regular menu. Menu, /// The content of a popup menu. Popup, /// A tooltip, as shown by e.g. [`crate::Response::on_hover_ui`]. Tooltip, /// A picker, such as color picker. Picker, /// A table cell (from the `egui_extras` crate). TableCell, /// An [`crate::Area`] that is not of any other kind. GenericArea, /// A collapsible container, e.g. a [`crate::CollapsingHeader`]. Collapsible, } impl UiKind { /// Is this any kind of panel? #[inline] pub fn is_panel(&self) -> bool { matches!( self, Self::CentralPanel | Self::LeftPanel | Self::RightPanel | Self::TopPanel | Self::BottomPanel ) } /// Is this any kind of [`crate::Area`]? #[inline] pub fn is_area(&self) -> bool { match self { Self::CentralPanel | Self::LeftPanel | Self::RightPanel | Self::TopPanel | Self::BottomPanel | Self::Frame | Self::ScrollArea | Self::Resize | Self::Collapsible | Self::TableCell => false, Self::Window | Self::Menu | Self::Modal | Self::Popup | Self::Tooltip | Self::Picker | Self::GenericArea => true, } } } // ---------------------------------------------------------------------------- /// Information about a [`crate::Ui`] to be included in the corresponding [`UiStack`]. #[derive(Clone, Default, Debug)] pub struct UiStackInfo { pub kind: Option<UiKind>, pub frame: Frame, pub tags: UiTags, } impl UiStackInfo { /// Create a new [`UiStackInfo`] with the given kind and an empty frame. #[inline] pub fn new(kind: UiKind) -> Self { Self { kind: Some(kind), ..Default::default() } } #[inline] pub fn with_frame(mut self, frame: Frame) -> Self { self.frame = frame; self } /// Insert a tag with no value. #[inline] pub fn with_tag(mut self, key: impl Into<String>) -> Self { self.tags.insert(key, None); self } /// Insert a tag with some value. #[inline] pub fn with_tag_value( mut self, key: impl Into<String>, value: impl Any + Send + Sync + 'static, ) -> Self { self.tags.insert(key, Some(Arc::new(value))); self } } // ---------------------------------------------------------------------------- /// User-chosen tags. /// /// You can use this in any way you want, /// i.e. to set some tag on a [`crate::Ui`] and then in your own widget check /// for the existence of this tag up the [`UiStack`]. /// /// Note that egui never sets any tags itself, so this is purely for user code. /// /// All tagging is transient, and will only live as long as the parent [`crate::Ui`], i.e. within a single render frame. #[derive(Clone, Default, Debug)] pub struct UiTags(pub ahash::HashMap<String, Option<Arc<dyn Any + Send + Sync + 'static>>>); impl UiTags { #[inline] pub fn insert( &mut self, key: impl Into<String>, value: Option<Arc<dyn Any + Send + Sync + 'static>>, ) { self.0.insert(key.into(), value); } #[inline] pub fn contains(&self, key: &str) -> bool { self.0.contains_key(key) } /// Get the value of a tag. /// /// Note that `None` is returned both if the key is set to the value `None`, /// and if the key is not set at all. #[inline] pub fn get_any(&self, key: &str) -> Option<&Arc<dyn Any + Send + Sync + 'static>> { self.0.get(key)?.as_ref() } /// Get the value of a tag. /// /// Note that `None` is returned both if the key is set to the value `None`, /// and if the key is not set at all. pub fn get_downcast<T: Any + Send + Sync + 'static>(&self, key: &str) -> Option<&T> { self.0.get(key)?.as_ref().and_then(|any| any.downcast_ref()) } } // ---------------------------------------------------------------------------- /// Information about a [`crate::Ui`] and its parents. /// /// [`UiStack`] serves to keep track of the current hierarchy of [`crate::Ui`]s, such /// that nested widgets or user code may adapt to the surrounding context or obtain layout information /// from a [`crate::Ui`] that might be several steps higher in the hierarchy. /// /// Note: since [`UiStack`] contains a reference to its parent, it is both a stack, and a node within /// that stack. Most of its methods are about the specific node, but some methods walk up the /// hierarchy to provide information about the entire stack. #[derive(Debug)] pub struct UiStack { // stuff that `Ui::child_ui` can deal with directly pub id: Id, pub info: UiStackInfo, pub layout_direction: Direction, pub min_rect: Rect, pub max_rect: Rect, pub parent: Option<Arc<Self>>, } // these methods act on this specific node impl UiStack { #[inline] pub fn kind(&self) -> Option<UiKind> { self.info.kind } #[inline] pub fn frame(&self) -> &Frame { &self.info.frame } /// User tags. #[inline] pub fn tags(&self) -> &UiTags { &self.info.tags } /// Is this [`crate::Ui`] a panel? #[inline] pub fn is_panel_ui(&self) -> bool { self.kind().is_some_and(|kind| kind.is_panel()) } /// Is this [`crate::Ui`] an [`crate::Area`]? #[inline] pub fn is_area_ui(&self) -> bool { self.kind().is_some_and(|kind| kind.is_area()) } /// Is this a root [`crate::Ui`], i.e. created with [`crate::Ui::new()`]? #[inline] pub fn is_root_ui(&self) -> bool { self.parent.is_none() } /// This this [`crate::Ui`] a [`crate::Frame`] with a visible stroke? #[inline] pub fn has_visible_frame(&self) -> bool { !self.info.frame.stroke.is_empty() } } // these methods act on the entire stack impl UiStack { /// Return an iterator that walks the stack from this node to the root. #[expect(clippy::iter_without_into_iter)] pub fn iter(&self) -> UiStackIterator<'_> { UiStackIterator { next: Some(self) } } /// Check if this node is or is contained in a [`crate::Ui`] of a specific kind. pub fn contained_in(&self, kind: UiKind) -> bool { self.iter().any(|frame| frame.kind() == Some(kind)) } } // ---------------------------------------------------------------------------- /// Iterator that walks up a stack of `StackFrame`s. /// /// See [`UiStack::iter`]. pub struct UiStackIterator<'a> { next: Option<&'a UiStack>, } impl<'a> Iterator for UiStackIterator<'a> { type Item = &'a UiStack; #[inline] fn next(&mut self) -> Option<Self::Item> { let current = self.next; self.next = current.and_then(|frame| frame.parent.as_deref()); current } } impl FusedIterator for UiStackIterator<'_> {}
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/animation_manager.rs
crates/egui/src/animation_manager.rs
use crate::{ Id, IdMap, InputState, emath::{NumExt as _, remap_clamp}, }; #[derive(Clone, Default)] pub(crate) struct AnimationManager { bools: IdMap<BoolAnim>, values: IdMap<ValueAnim>, } #[derive(Clone, Debug)] struct BoolAnim { last_value: f32, last_tick: f64, } #[derive(Clone, Debug)] struct ValueAnim { from_value: f32, to_value: f32, /// when did `value` last toggle? toggle_time: f64, } impl AnimationManager { /// See [`crate::Context::animate_bool`] for documentation pub fn animate_bool( &mut self, input: &InputState, animation_time: f32, id: Id, value: bool, ) -> f32 { let (start, end) = if value { (0.0, 1.0) } else { (1.0, 0.0) }; match self.bools.get_mut(&id) { None => { self.bools.insert( id, BoolAnim { last_value: end, last_tick: input.time - input.stable_dt as f64, }, ); end } Some(anim) => { let BoolAnim { last_value, last_tick, } = anim; let current_time = input.time; let elapsed = ((current_time - *last_tick) as f32).at_most(input.stable_dt); let new_value = *last_value + (end - start) * elapsed / animation_time; *last_value = if new_value.is_finite() { new_value.clamp(0.0, 1.0) } else { end }; *last_tick = current_time; *last_value } } } pub fn animate_value( &mut self, input: &InputState, animation_time: f32, id: Id, value: f32, ) -> f32 { match self.values.get_mut(&id) { None => { self.values.insert( id, ValueAnim { from_value: value, to_value: value, toggle_time: -f64::INFINITY, // long time ago }, ); value } Some(anim) => { let time_since_toggle = (input.time - anim.toggle_time) as f32; // On the frame we toggle we don't want to return the old value, // so we extrapolate forwards by half a frame: let time_since_toggle = time_since_toggle + input.predicted_dt / 2.0; let current_value = remap_clamp( time_since_toggle, 0.0..=animation_time, anim.from_value..=anim.to_value, ); if anim.to_value != value { anim.from_value = current_value; //start new animation from current position of playing animation anim.to_value = value; anim.toggle_time = input.time; } if animation_time == 0.0 { anim.from_value = value; anim.to_value = value; } current_value } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/plugin.rs
crates/egui/src/plugin.rs
use crate::{Context, FullOutput, RawInput, Ui}; use ahash::HashMap; use epaint::mutex::{Mutex, MutexGuard}; use std::sync::Arc; /// A plugin to extend egui. /// /// Add plugins via [`Context::add_plugin`]. /// /// Plugins should not hold a reference to the [`Context`], since this would create a cycle /// (which would prevent the [`Context`] from being dropped). #[expect(unused_variables)] pub trait Plugin: Send + Sync + std::any::Any + 'static { /// Plugin name. /// /// Used when profiling. fn debug_name(&self) -> &'static str; /// Called once, when the plugin is registered. /// /// Useful to e.g. register image loaders. fn setup(&mut self, ctx: &Context) {} /// Called at the start of each pass. /// /// Can be used to show ui, e.g. a [`crate::Window`] or [`crate::Panel`]. fn on_begin_pass(&mut self, ui: &mut Ui) {} /// Called at the end of each pass. /// /// Can be used to show ui, e.g. a [`crate::Window`]. fn on_end_pass(&mut self, ui: &mut Ui) {} /// Called just before the input is processed. /// /// Useful to inspect or modify the input. /// Since this is called outside a pass, don't show ui here. Using `Context::debug_painter` is fine though. fn input_hook(&mut self, input: &mut RawInput) {} /// Called just before the output is passed to the backend. /// /// Useful to inspect or modify the output. /// Since this is called outside a pass, don't show ui here. Using `Context::debug_painter` is fine though. fn output_hook(&mut self, output: &mut FullOutput) {} /// Called when a widget is created and is under the pointer. /// /// Useful for capturing a stack trace so that widgets can be mapped back to their source code. /// Since this is called outside a pass, don't show ui here. Using `Context::debug_painter` is fine though. #[cfg(debug_assertions)] fn on_widget_under_pointer(&mut self, ctx: &Context, widget: &crate::WidgetRect) {} } pub(crate) struct PluginHandle { plugin: Box<dyn Plugin>, } pub struct TypedPluginHandle<P: Plugin> { handle: Arc<Mutex<PluginHandle>>, _type: std::marker::PhantomData<P>, } impl<P: Plugin> TypedPluginHandle<P> { pub(crate) fn new(handle: Arc<Mutex<PluginHandle>>) -> Self { Self { handle, _type: std::marker::PhantomData, } } pub fn lock(&self) -> TypedPluginGuard<'_, P> { TypedPluginGuard { guard: self.handle.lock(), _type: std::marker::PhantomData, } } } pub struct TypedPluginGuard<'a, P: Plugin> { guard: MutexGuard<'a, PluginHandle>, _type: std::marker::PhantomData<P>, } impl<P: Plugin> TypedPluginGuard<'_, P> {} impl<P: Plugin> std::ops::Deref for TypedPluginGuard<'_, P> { type Target = P; fn deref(&self) -> &Self::Target { self.guard.typed_plugin() } } impl<P: Plugin> std::ops::DerefMut for TypedPluginGuard<'_, P> { fn deref_mut(&mut self) -> &mut Self::Target { self.guard.typed_plugin_mut() } } impl PluginHandle { pub fn new<P: Plugin>(plugin: P) -> Arc<Mutex<Self>> { Arc::new(Mutex::new(Self { plugin: Box::new(plugin), })) } fn plugin_type_id(&self) -> std::any::TypeId { (*self.plugin).type_id() } pub fn dyn_plugin_mut(&mut self) -> &mut dyn Plugin { &mut *self.plugin } fn typed_plugin<P: Plugin + 'static>(&self) -> &P { (&*self.plugin as &dyn std::any::Any) .downcast_ref::<P>() .expect("PluginHandle: plugin is not of the expected type") } pub fn typed_plugin_mut<P: Plugin + 'static>(&mut self) -> &mut P { (&mut *self.plugin as &mut dyn std::any::Any) .downcast_mut::<P>() .expect("PluginHandle: plugin is not of the expected type") } } /// User-registered plugins. #[derive(Clone, Default)] pub(crate) struct Plugins { plugins: HashMap<std::any::TypeId, Arc<Mutex<PluginHandle>>>, plugins_ordered: PluginsOrdered, } #[derive(Clone, Default)] pub(crate) struct PluginsOrdered(Vec<Arc<Mutex<PluginHandle>>>); impl PluginsOrdered { fn for_each_dyn<F>(&self, mut f: F) where F: FnMut(&mut dyn Plugin), { for plugin in &self.0 { let mut plugin = plugin.lock(); profiling::scope!("plugin", plugin.dyn_plugin_mut().debug_name()); f(plugin.dyn_plugin_mut()); } } pub fn on_begin_pass(&self, ui: &mut Ui) { profiling::scope!("plugins", "on_begin_pass"); self.for_each_dyn(|p| { p.on_begin_pass(ui); }); } pub fn on_end_pass(&self, ui: &mut Ui) { profiling::scope!("plugins", "on_end_pass"); self.for_each_dyn(|p| { p.on_end_pass(ui); }); } pub fn on_input(&self, input: &mut RawInput) { profiling::scope!("plugins", "on_input"); self.for_each_dyn(|plugin| { plugin.input_hook(input); }); } pub fn on_output(&self, output: &mut FullOutput) { profiling::scope!("plugins", "on_output"); self.for_each_dyn(|plugin| { plugin.output_hook(output); }); } #[cfg(debug_assertions)] pub fn on_widget_under_pointer(&self, ctx: &Context, widget: &crate::WidgetRect) { profiling::scope!("plugins", "on_widget_under_pointer"); self.for_each_dyn(|plugin| { plugin.on_widget_under_pointer(ctx, widget); }); } } impl Plugins { pub fn ordered_plugins(&self) -> PluginsOrdered { self.plugins_ordered.clone() } /// Remember to call [`Plugin::setup`] on the plugin after adding it. /// /// Will not add the plugin if a plugin of the same type already exists. /// Returns `false` if the plugin was not added, `true` if it was added. pub fn add(&mut self, handle: Arc<Mutex<PluginHandle>>) -> bool { profiling::scope!("plugins", "add"); let type_id = handle.lock().plugin_type_id(); if self.plugins.contains_key(&type_id) { return false; } self.plugins.insert(type_id, Arc::clone(&handle)); self.plugins_ordered.0.push(handle); true } pub fn get(&self, type_id: std::any::TypeId) -> Option<Arc<Mutex<PluginHandle>>> { self.plugins.get(&type_id).cloned() } } /// Generic event callback. pub type ContextCallback = Arc<dyn Fn(&mut Ui) + Send + Sync>; #[derive(Default)] pub(crate) struct CallbackPlugin { pub on_begin_plugins: Vec<(&'static str, ContextCallback)>, pub on_end_plugins: Vec<(&'static str, ContextCallback)>, } impl Plugin for CallbackPlugin { fn debug_name(&self) -> &'static str { "CallbackPlugins" } fn on_begin_pass(&mut self, ui: &mut Ui) { profiling::function_scope!(); for (_debug_name, cb) in &self.on_begin_plugins { profiling::scope!("on_begin_pass", *_debug_name); (cb)(ui); } } fn on_end_pass(&mut self, ui: &mut Ui) { profiling::function_scope!(); for (_debug_name, cb) in &self.on_end_plugins { profiling::scope!("on_end_pass", *_debug_name); (cb)(ui); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/atom.rs
crates/egui/src/atomics/atom.rs
use crate::{AtomKind, FontSelection, Id, SizedAtom, Ui}; use emath::{NumExt as _, Vec2}; use epaint::text::TextWrapMode; /// A low-level ui building block. /// /// Implements [`From`] for [`String`], [`str`], [`crate::Image`] and much more for convenience. /// You can directly call the `atom_*` methods on anything that implements `Into<Atom>`. /// ``` /// # use egui::{Image, emath::Vec2}; /// use egui::AtomExt as _; /// let string_atom = "Hello".atom_grow(true); /// let image_atom = Image::new("some_image_url").atom_size(Vec2::splat(20.0)); /// ``` #[derive(Clone, Debug)] pub struct Atom<'a> { /// See [`crate::AtomExt::atom_size`] pub size: Option<Vec2>, /// See [`crate::AtomExt::atom_max_size`] pub max_size: Vec2, /// See [`crate::AtomExt::atom_grow`] pub grow: bool, /// See [`crate::AtomExt::atom_shrink`] pub shrink: bool, /// The atom type pub kind: AtomKind<'a>, } impl Default for Atom<'_> { fn default() -> Self { Atom { size: None, max_size: Vec2::INFINITY, grow: false, shrink: false, kind: AtomKind::Empty, } } } impl<'a> Atom<'a> { /// Create an empty [`Atom`] marked as `grow`. /// /// This will expand in size, allowing all preceding atoms to be left-aligned, /// and all following atoms to be right-aligned pub fn grow() -> Self { Atom { grow: true, ..Default::default() } } /// Create a [`AtomKind::Custom`] with a specific size. pub fn custom(id: Id, size: impl Into<Vec2>) -> Self { Atom { size: Some(size.into()), kind: AtomKind::Custom(id), ..Default::default() } } /// Turn this into a [`SizedAtom`]. pub fn into_sized( self, ui: &Ui, mut available_size: Vec2, mut wrap_mode: Option<TextWrapMode>, fallback_font: FontSelection, ) -> SizedAtom<'a> { if !self.shrink && self.max_size.x.is_infinite() { wrap_mode = Some(TextWrapMode::Extend); } available_size = available_size.at_most(self.max_size); if let Some(size) = self.size { available_size = available_size.at_most(size); } if self.max_size.x.is_finite() { wrap_mode = Some(TextWrapMode::Truncate); } let (intrinsic, kind) = self .kind .into_sized(ui, available_size, wrap_mode, fallback_font); let size = self .size .map_or_else(|| kind.size(), |s| s.at_most(self.max_size)); SizedAtom { size, intrinsic_size: intrinsic.at_least(self.size.unwrap_or_default()), grow: self.grow, kind, } } } impl<'a, T> From<T> for Atom<'a> where T: Into<AtomKind<'a>>, { fn from(value: T) -> Self { Atom { kind: value.into(), ..Default::default() } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/atom_kind.rs
crates/egui/src/atomics/atom_kind.rs
use crate::{FontSelection, Id, Image, ImageSource, SizedAtomKind, Ui, WidgetText}; use emath::Vec2; use epaint::text::TextWrapMode; /// The different kinds of [`crate::Atom`]s. #[derive(Clone, Default, Debug)] pub enum AtomKind<'a> { /// Empty, that can be used with [`crate::AtomExt::atom_grow`] to reserve space. #[default] Empty, /// Text atom. /// /// Truncation within [`crate::AtomLayout`] works like this: /// - /// - if `wrap_mode` is not Extend /// - if no atom is `shrink` /// - the first text atom is selected and will be marked as `shrink` /// - the atom marked as `shrink` will shrink / wrap based on the selected wrap mode /// - any other text atoms will have `wrap_mode` extend /// - if `wrap_mode` is extend, Text will extend as expected. /// /// Unless [`crate::AtomExt::atom_max_width`] is set, `wrap_mode` should only be set via [`crate::Style`] or /// [`crate::AtomLayout::wrap_mode`], as setting a wrap mode on a [`WidgetText`] atom /// that is not `shrink` will have unexpected results. /// /// The size is determined by converting the [`WidgetText`] into a galley and using the galleys /// size. You can use [`crate::AtomExt::atom_size`] to override this, and [`crate::AtomExt::atom_max_width`] /// to limit the width (Causing the text to wrap or truncate, depending on the `wrap_mode`. /// [`crate::AtomExt::atom_max_height`] has no effect on text. Text(WidgetText), /// Image atom. /// /// By default the size is determined via [`Image::calc_size`]. /// You can use [`crate::AtomExt::atom_max_size`] or [`crate::AtomExt::atom_size`] to customize the size. /// There is also a helper [`crate::AtomExt::atom_max_height_font_size`] to set the max height to the /// default font height, which is convenient for icons. Image(Image<'a>), /// For custom rendering. /// /// You can get the [`crate::Rect`] with the [`Id`] from [`crate::AtomLayoutResponse`] and use a /// [`crate::Painter`] or [`Ui::place`] to add/draw some custom content. /// /// Example: /// ``` /// # use egui::{AtomExt, AtomKind, Atom, Button, Id, __run_test_ui}; /// # use emath::Vec2; /// # __run_test_ui(|ui| { /// let id = Id::new("my_button"); /// let response = Button::new(("Hi!", Atom::custom(id, Vec2::splat(18.0)))).atom_ui(ui); /// /// let rect = response.rect(id); /// if let Some(rect) = rect { /// ui.place(rect, Button::new("⏵")); /// } /// # }); /// ``` Custom(Id), } impl<'a> AtomKind<'a> { pub fn text(text: impl Into<WidgetText>) -> Self { AtomKind::Text(text.into()) } pub fn image(image: impl Into<Image<'a>>) -> Self { AtomKind::Image(image.into()) } /// Turn this [`AtomKind`] into a [`SizedAtomKind`]. /// /// This converts [`WidgetText`] into [`crate::Galley`] and tries to load and size [`Image`]. /// The first returned argument is the preferred size. pub fn into_sized( self, ui: &Ui, available_size: Vec2, wrap_mode: Option<TextWrapMode>, fallback_font: FontSelection, ) -> (Vec2, SizedAtomKind<'a>) { match self { AtomKind::Text(text) => { let wrap_mode = wrap_mode.unwrap_or_else(|| ui.wrap_mode()); let galley = text.into_galley(ui, Some(wrap_mode), available_size.x, fallback_font); (galley.intrinsic_size(), SizedAtomKind::Text(galley)) } AtomKind::Image(image) => { let size = image.load_and_calc_size(ui, available_size); let size = size.unwrap_or(Vec2::ZERO); (size, SizedAtomKind::Image(image, size)) } AtomKind::Custom(id) => (Vec2::ZERO, SizedAtomKind::Custom(id)), AtomKind::Empty => (Vec2::ZERO, SizedAtomKind::Empty), } } } impl<'a> From<ImageSource<'a>> for AtomKind<'a> { fn from(value: ImageSource<'a>) -> Self { AtomKind::Image(value.into()) } } impl<'a> From<Image<'a>> for AtomKind<'a> { fn from(value: Image<'a>) -> Self { AtomKind::Image(value) } } impl<T> From<T> for AtomKind<'_> where T: Into<WidgetText>, { fn from(value: T) -> Self { AtomKind::Text(value.into()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/atoms.rs
crates/egui/src/atomics/atoms.rs
use crate::{Atom, AtomKind, Image, WidgetText}; use smallvec::SmallVec; use std::borrow::Cow; use std::ops::{Deref, DerefMut}; // Rarely there should be more than 2 atoms in one Widget. // I guess it could happen in a menu button with Image and right text... pub(crate) const ATOMS_SMALL_VEC_SIZE: usize = 2; /// A list of [`Atom`]s. #[derive(Clone, Debug, Default)] pub struct Atoms<'a>(SmallVec<[Atom<'a>; ATOMS_SMALL_VEC_SIZE]>); impl<'a> Atoms<'a> { pub fn new(atoms: impl IntoAtoms<'a>) -> Self { atoms.into_atoms() } /// Insert a new [`Atom`] at the end of the list (right side). pub fn push_right(&mut self, atom: impl Into<Atom<'a>>) { self.0.push(atom.into()); } /// Insert a new [`Atom`] at the beginning of the list (left side). pub fn push_left(&mut self, atom: impl Into<Atom<'a>>) { self.0.insert(0, atom.into()); } /// Concatenate and return the text contents. // TODO(lucasmerlin): It might not always make sense to return the concatenated text, e.g. // in a submenu button there is a right text '⏵' which is now passed to the screen reader. pub fn text(&self) -> Option<Cow<'_, str>> { let mut string: Option<Cow<'_, str>> = None; for atom in &self.0 { if let AtomKind::Text(text) = &atom.kind { if let Some(string) = &mut string { let string = string.to_mut(); string.push(' '); string.push_str(text.text()); } else { string = Some(Cow::Borrowed(text.text())); } } } // If there is no text, try to find an image with alt text. if string.is_none() { string = self.iter().find_map(|a| match &a.kind { AtomKind::Image(image) => image.alt_text.as_deref().map(Cow::Borrowed), _ => None, }); } string } pub fn iter_kinds(&self) -> impl Iterator<Item = &AtomKind<'a>> { self.0.iter().map(|atom| &atom.kind) } pub fn iter_kinds_mut(&mut self) -> impl Iterator<Item = &mut AtomKind<'a>> { self.0.iter_mut().map(|atom| &mut atom.kind) } pub fn iter_images(&self) -> impl Iterator<Item = &Image<'a>> { self.iter_kinds().filter_map(|kind| { if let AtomKind::Image(image) = kind { Some(image) } else { None } }) } pub fn iter_images_mut(&mut self) -> impl Iterator<Item = &mut Image<'a>> { self.iter_kinds_mut().filter_map(|kind| { if let AtomKind::Image(image) = kind { Some(image) } else { None } }) } pub fn iter_texts(&self) -> impl Iterator<Item = &WidgetText> + use<'_, 'a> { self.iter_kinds().filter_map(|kind| { if let AtomKind::Text(text) = kind { Some(text) } else { None } }) } pub fn iter_texts_mut(&mut self) -> impl Iterator<Item = &mut WidgetText> + use<'a, '_> { self.iter_kinds_mut().filter_map(|kind| { if let AtomKind::Text(text) = kind { Some(text) } else { None } }) } pub fn map_atoms(&mut self, mut f: impl FnMut(Atom<'a>) -> Atom<'a>) { self.iter_mut() .for_each(|atom| *atom = f(std::mem::take(atom))); } pub fn map_kind<F>(&mut self, mut f: F) where F: FnMut(AtomKind<'a>) -> AtomKind<'a>, { for kind in self.iter_kinds_mut() { *kind = f(std::mem::take(kind)); } } pub fn map_images<F>(&mut self, mut f: F) where F: FnMut(Image<'a>) -> Image<'a>, { self.map_kind(|kind| { if let AtomKind::Image(image) = kind { AtomKind::Image(f(image)) } else { kind } }); } pub fn map_texts<F>(&mut self, mut f: F) where F: FnMut(WidgetText) -> WidgetText, { self.map_kind(|kind| { if let AtomKind::Text(text) = kind { AtomKind::Text(f(text)) } else { kind } }); } } impl<'a> IntoIterator for Atoms<'a> { type Item = Atom<'a>; type IntoIter = smallvec::IntoIter<[Atom<'a>; ATOMS_SMALL_VEC_SIZE]>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } /// Helper trait to convert a tuple of atoms into [`Atoms`]. /// /// ``` /// use egui::{Atoms, Image, IntoAtoms, RichText}; /// let atoms: Atoms = ( /// "Some text", /// RichText::new("Some RichText"), /// Image::new("some_image_url"), /// ).into_atoms(); /// ``` impl<'a, T> IntoAtoms<'a> for T where T: Into<Atom<'a>>, { fn collect(self, atoms: &mut Atoms<'a>) { atoms.push_right(self); } } /// Trait for turning a tuple of [`Atom`]s into [`Atoms`]. pub trait IntoAtoms<'a> { fn collect(self, atoms: &mut Atoms<'a>); fn into_atoms(self) -> Atoms<'a> where Self: Sized, { let mut atoms = Atoms::default(); self.collect(&mut atoms); atoms } } impl<'a> IntoAtoms<'a> for Atoms<'a> { fn collect(self, atoms: &mut Self) { atoms.0.extend(self.0); } } macro_rules! all_the_atoms { ($($T:ident),*) => { impl<'a, $($T),*> IntoAtoms<'a> for ($($T),*) where $($T: IntoAtoms<'a>),* { fn collect(self, _atoms: &mut Atoms<'a>) { #[allow(clippy::allow_attributes, non_snake_case)] let ($($T),*) = self; $($T.collect(_atoms);)* } } }; } all_the_atoms!(); all_the_atoms!(T0, T1); all_the_atoms!(T0, T1, T2); all_the_atoms!(T0, T1, T2, T3); all_the_atoms!(T0, T1, T2, T3, T4); all_the_atoms!(T0, T1, T2, T3, T4, T5); impl<'a> Deref for Atoms<'a> { type Target = [Atom<'a>]; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Atoms<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<'a, T: Into<Atom<'a>>> From<Vec<T>> for Atoms<'a> { fn from(vec: Vec<T>) -> Self { Atoms(vec.into_iter().map(Into::into).collect()) } } impl<'a, T: Into<Atom<'a>> + Clone> From<&[T]> for Atoms<'a> { fn from(slice: &[T]) -> Self { Atoms(slice.iter().cloned().map(Into::into).collect()) } } impl<'a, Item: Into<Atom<'a>>> FromIterator<Item> for Atoms<'a> { fn from_iter<T: IntoIterator<Item = Item>>(iter: T) -> Self { Atoms(iter.into_iter().map(Into::into).collect()) } } #[cfg(test)] mod tests { use crate::Atoms; #[test] fn collect_atoms() { let _: Atoms<'_> = ["Hello", "World"].into_iter().collect(); let _ = Atoms::from(vec!["Hi"]); let _ = Atoms::from(["Hi"].as_slice()); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/sized_atom_kind.rs
crates/egui/src/atomics/sized_atom_kind.rs
use crate::{Id, Image}; use emath::Vec2; use epaint::Galley; use std::sync::Arc; /// A sized [`crate::AtomKind`]. #[derive(Clone, Default, Debug)] pub enum SizedAtomKind<'a> { #[default] Empty, Text(Arc<Galley>), Image(Image<'a>, Vec2), Custom(Id), } impl SizedAtomKind<'_> { /// Get the calculated size. pub fn size(&self) -> Vec2 { match self { SizedAtomKind::Text(galley) => galley.size(), SizedAtomKind::Image(_, size) => *size, SizedAtomKind::Empty | SizedAtomKind::Custom(_) => Vec2::ZERO, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/mod.rs
crates/egui/src/atomics/mod.rs
mod atom; mod atom_ext; mod atom_kind; mod atom_layout; mod atoms; mod sized_atom; mod sized_atom_kind; pub use atom::*; pub use atom_ext::*; pub use atom_kind::*; pub use atom_layout::*; pub use atoms::*; pub use sized_atom::*; pub use sized_atom_kind::*;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/atom_ext.rs
crates/egui/src/atomics/atom_ext.rs
use crate::{Atom, FontSelection, Ui}; use emath::Vec2; /// A trait for conveniently building [`Atom`]s. /// /// The functions are prefixed with `atom_` to avoid conflicts with e.g. [`crate::RichText::size`]. pub trait AtomExt<'a> { /// Set the atom to a fixed size. /// /// If [`Atom::grow`] is `true`, this will be the minimum width. /// If [`Atom::shrink`] is `true`, this will be the maximum width. /// If both are true, the width will have no effect. /// /// [`Self::atom_max_size`] will limit size. /// /// See [`crate::AtomKind`] docs to see how the size affects the different types. fn atom_size(self, size: Vec2) -> Atom<'a>; /// Grow this atom to the available space. /// /// This will affect the size of the [`Atom`] in the main direction. Since /// [`crate::AtomLayout`] today only supports horizontal layout, it will affect the width. /// /// You can also combine this with [`Self::atom_shrink`] to make it always take exactly the /// remaining space. fn atom_grow(self, grow: bool) -> Atom<'a>; /// Shrink this atom if there isn't enough space. /// /// This will affect the size of the [`Atom`] in the main direction. Since /// [`crate::AtomLayout`] today only supports horizontal layout, it will affect the width. /// /// NOTE: Only a single [`Atom`] may shrink for each widget. /// /// If no atom was set to shrink and `wrap_mode != TextWrapMode::Extend`, the first /// `AtomKind::Text` is set to shrink. fn atom_shrink(self, shrink: bool) -> Atom<'a>; /// Set the maximum size of this atom. /// /// Will not affect the space taken by `grow` (All atoms marked as grow will always grow /// equally to fill the available space). fn atom_max_size(self, max_size: Vec2) -> Atom<'a>; /// Set the maximum width of this atom. /// /// Will not affect the space taken by `grow` (All atoms marked as grow will always grow /// equally to fill the available space). fn atom_max_width(self, max_width: f32) -> Atom<'a>; /// Set the maximum height of this atom. fn atom_max_height(self, max_height: f32) -> Atom<'a>; /// Set the max height of this atom to match the font size. /// /// This is useful for e.g. limiting the height of icons in buttons. fn atom_max_height_font_size(self, ui: &Ui) -> Atom<'a> where Self: Sized, { let font_selection = FontSelection::default(); let font_id = font_selection.resolve(ui.style()); let height = ui.fonts_mut(|f| f.row_height(&font_id)); self.atom_max_height(height) } } impl<'a, T> AtomExt<'a> for T where T: Into<Atom<'a>> + Sized, { fn atom_size(self, size: Vec2) -> Atom<'a> { let mut atom = self.into(); atom.size = Some(size); atom } fn atom_grow(self, grow: bool) -> Atom<'a> { let mut atom = self.into(); atom.grow = grow; atom } fn atom_shrink(self, shrink: bool) -> Atom<'a> { let mut atom = self.into(); atom.shrink = shrink; atom } fn atom_max_size(self, max_size: Vec2) -> Atom<'a> { let mut atom = self.into(); atom.max_size = max_size; atom } fn atom_max_width(self, max_width: f32) -> Atom<'a> { let mut atom = self.into(); atom.max_size.x = max_width; atom } fn atom_max_height(self, max_height: f32) -> Atom<'a> { let mut atom = self.into(); atom.max_size.y = max_height; atom } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/atom_layout.rs
crates/egui/src/atomics/atom_layout.rs
use crate::atomics::ATOMS_SMALL_VEC_SIZE; use crate::{ AtomKind, Atoms, FontSelection, Frame, Id, Image, IntoAtoms, Response, Sense, SizedAtom, SizedAtomKind, Ui, Widget, }; use emath::{Align2, GuiRounding as _, NumExt as _, Rect, Vec2}; use epaint::text::TextWrapMode; use epaint::{Color32, Galley}; use smallvec::SmallVec; use std::ops::{Deref, DerefMut}; use std::sync::Arc; /// Intra-widget layout utility. /// /// Used to lay out and paint [`crate::Atom`]s. /// This is used internally by widgets like [`crate::Button`] and [`crate::Checkbox`]. /// You can use it to make your own widgets. /// /// Painting the atoms can be split in two phases: /// - [`AtomLayout::allocate`] /// - calculates sizes /// - converts texts to [`Galley`]s /// - allocates a [`Response`] /// - returns a [`AllocatedAtomLayout`] /// - [`AllocatedAtomLayout::paint`] /// - paints the [`Frame`] /// - calculates individual [`crate::Atom`] positions /// - paints each single atom /// /// You can use this to first allocate a response and then modify, e.g., the [`Frame`] on the /// [`AllocatedAtomLayout`] for interaction styling. pub struct AtomLayout<'a> { id: Option<Id>, pub atoms: Atoms<'a>, gap: Option<f32>, pub(crate) frame: Frame, pub(crate) sense: Sense, fallback_text_color: Option<Color32>, fallback_font: Option<FontSelection>, min_size: Vec2, wrap_mode: Option<TextWrapMode>, align2: Option<Align2>, } impl Default for AtomLayout<'_> { fn default() -> Self { Self::new(()) } } impl<'a> AtomLayout<'a> { pub fn new(atoms: impl IntoAtoms<'a>) -> Self { Self { id: None, atoms: atoms.into_atoms(), gap: None, frame: Frame::default(), sense: Sense::hover(), fallback_text_color: None, fallback_font: None, min_size: Vec2::ZERO, wrap_mode: None, align2: None, } } /// Set the gap between atoms. /// /// Default: `Spacing::icon_spacing` #[inline] pub fn gap(mut self, gap: f32) -> Self { self.gap = Some(gap); self } /// Set the [`Frame`]. #[inline] pub fn frame(mut self, frame: Frame) -> Self { self.frame = frame; self } /// Set the [`Sense`] used when allocating the [`Response`]. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = sense; self } /// Set the fallback (default) text color. /// /// Default: [`crate::Visuals::text_color`] #[inline] pub fn fallback_text_color(mut self, color: Color32) -> Self { self.fallback_text_color = Some(color); self } /// Set the fallback (default) font. #[inline] pub fn fallback_font(mut self, font: impl Into<FontSelection>) -> Self { self.fallback_font = Some(font.into()); self } /// Set the minimum size of the Widget. /// /// This will find and expand atoms with `grow: true`. /// If there are no growable atoms then everything will be left-aligned. #[inline] pub fn min_size(mut self, size: Vec2) -> Self { self.min_size = size; self } /// Set the [`Id`] used to allocate a [`Response`]. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = Some(id); self } /// Set the [`TextWrapMode`] for the [`crate::Atom`] marked as `shrink`. /// /// Only a single [`crate::Atom`] may shrink. If this (or `ui.wrap_mode()`) is not /// [`TextWrapMode::Extend`] and no item is set to shrink, the first (left-most) /// [`AtomKind::Text`] will be set to shrink. #[inline] pub fn wrap_mode(mut self, wrap_mode: TextWrapMode) -> Self { self.wrap_mode = Some(wrap_mode); self } /// Set the [`Align2`]. /// /// This will align the [`crate::Atom`]s within the [`Rect`] returned by [`Ui::allocate_space`]. /// /// The default is chosen based on the [`Ui`]s [`crate::Layout`]. See /// [this snapshot](https://github.com/emilk/egui/blob/master/tests/egui_tests/tests/snapshots/layout/button.png) /// for info on how the [`crate::Layout`] affects the alignment. #[inline] pub fn align2(mut self, align2: Align2) -> Self { self.align2 = Some(align2); self } /// [`AtomLayout::allocate`] and [`AllocatedAtomLayout::paint`] in one go. pub fn show(self, ui: &mut Ui) -> AtomLayoutResponse { self.allocate(ui).paint(ui) } /// Calculate sizes, create [`Galley`]s and allocate a [`Response`]. /// /// Use the returned [`AllocatedAtomLayout`] for painting. pub fn allocate(self, ui: &mut Ui) -> AllocatedAtomLayout<'a> { let Self { id, mut atoms, gap, frame, sense, fallback_text_color, min_size, wrap_mode, align2, fallback_font, } = self; let fallback_font = fallback_font.unwrap_or_default(); let wrap_mode = wrap_mode.unwrap_or_else(|| ui.wrap_mode()); // If the TextWrapMode is not Extend, ensure there is some item marked as `shrink`. // If none is found, mark the first text item as `shrink`. if wrap_mode != TextWrapMode::Extend { let any_shrink = atoms.iter().any(|a| a.shrink); if !any_shrink { let first_text = atoms .iter_mut() .find(|a| matches!(a.kind, AtomKind::Text(..))); if let Some(atom) = first_text { atom.shrink = true; // Will make the text truncate or shrink depending on wrap_mode } } } let id = id.unwrap_or_else(|| ui.next_auto_id()); let fallback_text_color = fallback_text_color.unwrap_or_else(|| ui.style().visuals.text_color()); let gap = gap.unwrap_or_else(|| ui.spacing().icon_spacing); // The size available for the content let available_inner_size = ui.available_size() - frame.total_margin().sum(); let mut desired_width = 0.0; // intrinsic width / height is the ideal size of the widget, e.g. the size where the // text is not wrapped. Used to set Response::intrinsic_size. let mut intrinsic_width = 0.0; let mut intrinsic_height = 0.0; let mut height: f32 = 0.0; let mut sized_items = SmallVec::new(); let mut grow_count = 0; let mut shrink_item = None; let align2 = align2.unwrap_or_else(|| { Align2([ui.layout().horizontal_align(), ui.layout().vertical_align()]) }); if atoms.len() > 1 { let gap_space = gap * (atoms.len() as f32 - 1.0); desired_width += gap_space; intrinsic_width += gap_space; } for (idx, item) in atoms.into_iter().enumerate() { if item.grow { grow_count += 1; } if item.shrink { debug_assert!( shrink_item.is_none(), "Only one atomic may be marked as shrink. {item:?}" ); if shrink_item.is_none() { shrink_item = Some((idx, item)); continue; } } let sized = item.into_sized( ui, available_inner_size, Some(wrap_mode), fallback_font.clone(), ); let size = sized.size; desired_width += size.x; intrinsic_width += sized.intrinsic_size.x; height = height.at_least(size.y); intrinsic_height = intrinsic_height.at_least(sized.intrinsic_size.y); sized_items.push(sized); } if let Some((index, item)) = shrink_item { // The `shrink` item gets the remaining space let available_size_for_shrink_item = Vec2::new( available_inner_size.x - desired_width, available_inner_size.y, ); let sized = item.into_sized( ui, available_size_for_shrink_item, Some(wrap_mode), fallback_font, ); let size = sized.size; desired_width += size.x; intrinsic_width += sized.intrinsic_size.x; height = height.at_least(size.y); intrinsic_height = intrinsic_height.at_least(sized.intrinsic_size.y); sized_items.insert(index, sized); } let margin = frame.total_margin(); let desired_size = Vec2::new(desired_width, height); let frame_size = (desired_size + margin.sum()).at_least(min_size); let (_, rect) = ui.allocate_space(frame_size); let mut response = ui.interact(rect, id, sense); response.intrinsic_size = Some((Vec2::new(intrinsic_width, intrinsic_height) + margin.sum()).at_least(min_size)); AllocatedAtomLayout { sized_atoms: sized_items, frame, fallback_text_color, response, grow_count, desired_size, align2, gap, } } } /// Instructions for painting an [`AtomLayout`]. #[derive(Clone, Debug)] pub struct AllocatedAtomLayout<'a> { pub sized_atoms: SmallVec<[SizedAtom<'a>; ATOMS_SMALL_VEC_SIZE]>, pub frame: Frame, pub fallback_text_color: Color32, pub response: Response, grow_count: usize, // The size of the inner content, before any growing. desired_size: Vec2, align2: Align2, gap: f32, } impl<'atom> AllocatedAtomLayout<'atom> { pub fn iter_kinds(&self) -> impl Iterator<Item = &SizedAtomKind<'atom>> { self.sized_atoms.iter().map(|atom| &atom.kind) } pub fn iter_kinds_mut(&mut self) -> impl Iterator<Item = &mut SizedAtomKind<'atom>> { self.sized_atoms.iter_mut().map(|atom| &mut atom.kind) } pub fn iter_images(&self) -> impl Iterator<Item = &Image<'atom>> { self.iter_kinds().filter_map(|kind| { if let SizedAtomKind::Image(image, _) = kind { Some(image) } else { None } }) } pub fn iter_images_mut(&mut self) -> impl Iterator<Item = &mut Image<'atom>> { self.iter_kinds_mut().filter_map(|kind| { if let SizedAtomKind::Image(image, _) = kind { Some(image) } else { None } }) } pub fn iter_texts(&self) -> impl Iterator<Item = &Arc<Galley>> + use<'atom, '_> { self.iter_kinds().filter_map(|kind| { if let SizedAtomKind::Text(text) = kind { Some(text) } else { None } }) } pub fn iter_texts_mut(&mut self) -> impl Iterator<Item = &mut Arc<Galley>> + use<'atom, '_> { self.iter_kinds_mut().filter_map(|kind| { if let SizedAtomKind::Text(text) = kind { Some(text) } else { None } }) } pub fn map_kind<F>(&mut self, mut f: F) where F: FnMut(SizedAtomKind<'atom>) -> SizedAtomKind<'atom>, { for kind in self.iter_kinds_mut() { *kind = f(std::mem::take(kind)); } } pub fn map_images<F>(&mut self, mut f: F) where F: FnMut(Image<'atom>) -> Image<'atom>, { self.map_kind(|kind| { if let SizedAtomKind::Image(image, size) = kind { SizedAtomKind::Image(f(image), size) } else { kind } }); } /// Paint the [`Frame`] and individual [`crate::Atom`]s. pub fn paint(self, ui: &Ui) -> AtomLayoutResponse { let Self { sized_atoms, frame, fallback_text_color, response, grow_count, desired_size, align2, gap, } = self; let inner_rect = response.rect - self.frame.total_margin(); ui.painter().add(frame.paint(inner_rect)); let width_to_fill = inner_rect.width(); let extra_space = f32::max(width_to_fill - desired_size.x, 0.0); let grow_width = f32::max(extra_space / grow_count as f32, 0.0).floor_ui(); let aligned_rect = if grow_count > 0 { align2.align_size_within_rect(Vec2::new(width_to_fill, desired_size.y), inner_rect) } else { align2.align_size_within_rect(desired_size, inner_rect) }; let mut cursor = aligned_rect.left(); let mut response = AtomLayoutResponse::empty(response); for sized in sized_atoms { let size = sized.size; // TODO(lucasmerlin): This is not ideal, since this might lead to accumulated rounding errors // https://github.com/emilk/egui/pull/5830#discussion_r2079627864 let growth = if sized.is_grow() { grow_width } else { 0.0 }; let frame = aligned_rect .with_min_x(cursor) .with_max_x(cursor + size.x + growth); cursor = frame.right() + gap; let align = Align2::CENTER_CENTER; let rect = align.align_size_within_rect(size, frame); match sized.kind { SizedAtomKind::Text(galley) => { ui.painter().galley(rect.min, galley, fallback_text_color); } SizedAtomKind::Image(image, _) => { image.paint_at(ui, rect); } SizedAtomKind::Custom(id) => { debug_assert!( !response.custom_rects.iter().any(|(i, _)| *i == id), "Duplicate custom id" ); response.custom_rects.push((id, rect)); } SizedAtomKind::Empty => {} } } response } } /// Response from a [`AtomLayout::show`] or [`AllocatedAtomLayout::paint`]. /// /// Use [`AtomLayoutResponse::rect`] to get the response rects from [`AtomKind::Custom`]. #[derive(Clone, Debug)] pub struct AtomLayoutResponse { pub response: Response, // There should rarely be more than one custom rect. custom_rects: SmallVec<[(Id, Rect); 1]>, } impl AtomLayoutResponse { pub fn empty(response: Response) -> Self { Self { response, custom_rects: Default::default(), } } pub fn custom_rects(&self) -> impl Iterator<Item = (Id, Rect)> + '_ { self.custom_rects.iter().copied() } /// Use this together with [`AtomKind::Custom`] to add custom painting / child widgets. /// /// NOTE: Don't `unwrap` rects, they might be empty when the widget is not visible. pub fn rect(&self, id: Id) -> Option<Rect> { self.custom_rects .iter() .find_map(|(i, r)| if *i == id { Some(*r) } else { None }) } } impl Widget for AtomLayout<'_> { fn ui(self, ui: &mut Ui) -> Response { self.show(ui).response } } impl<'a> Deref for AtomLayout<'a> { type Target = Atoms<'a>; fn deref(&self) -> &Self::Target { &self.atoms } } impl DerefMut for AtomLayout<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.atoms } } impl<'a> Deref for AllocatedAtomLayout<'a> { type Target = [SizedAtom<'a>]; fn deref(&self) -> &Self::Target { &self.sized_atoms } } impl DerefMut for AllocatedAtomLayout<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.sized_atoms } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/atomics/sized_atom.rs
crates/egui/src/atomics/sized_atom.rs
use crate::SizedAtomKind; use emath::Vec2; /// A [`crate::Atom`] which has been sized. #[derive(Clone, Debug)] pub struct SizedAtom<'a> { pub(crate) grow: bool, /// The size of the atom. /// /// Used for placing this atom in [`crate::AtomLayout`], the cursor will advance by /// size.x + gap. pub size: Vec2, /// Intrinsic size of the atom. This is used to calculate `Response::intrinsic_size`. pub intrinsic_size: Vec2, pub kind: SizedAtomKind<'a>, } impl SizedAtom<'_> { /// Was this [`crate::Atom`] marked as `grow`? pub fn is_grow(&self) -> bool { self.grow } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/util/fixed_cache.rs
crates/egui/src/util/fixed_cache.rs
use epaint::util::hash; const FIXED_CACHE_SIZE: usize = 1024; // must be small for web/WASM build (for unknown reason) /// Very stupid/simple key-value cache. TODO(emilk): improve #[derive(Clone)] pub(crate) struct FixedCache<K, V>([Option<(K, V)>; FIXED_CACHE_SIZE]); impl<K, V> Default for FixedCache<K, V> where K: Copy, V: Copy, { fn default() -> Self { Self([None; FIXED_CACHE_SIZE]) } } impl<K, V> std::fmt::Debug for FixedCache<K, V> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Cache") } } impl<K, V> FixedCache<K, V> where K: std::hash::Hash + PartialEq, { pub fn get(&self, key: &K) -> Option<&V> { let bucket = (hash(key) % (FIXED_CACHE_SIZE as u64)) as usize; match &self.0[bucket] { Some((k, v)) if k == key => Some(v), _ => None, } } pub fn set(&mut self, key: K, value: V) { let bucket = (hash(&key) % (FIXED_CACHE_SIZE as u64)) as usize; self.0[bucket] = Some((key, value)); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/util/id_type_map.rs
crates/egui/src/util/id_type_map.rs
// TODO(emilk): it is possible we can simplify `Element` further by // assuming everything is possibly serializable, and by supplying serialize/deserialize functions for them. // For non-serializable types, these simply return `None`. // This will also allow users to pick their own serialization format per type. use std::{any::Any, sync::Arc}; // ----------------------------------------------------------------------------------------------- /// Like [`std::any::TypeId`], but can be serialized and deserialized. #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub struct TypeId(u64); impl TypeId { #[inline] pub fn of<T: Any + 'static>() -> Self { std::any::TypeId::of::<T>().into() } #[inline(always)] pub(crate) fn value(&self) -> u64 { self.0 } } impl From<std::any::TypeId> for TypeId { #[inline] fn from(id: std::any::TypeId) -> Self { Self(epaint::util::hash(id)) } } impl nohash_hasher::IsEnabled for TypeId {} // ----------------------------------------------------------------------------------------------- #[cfg(feature = "persistence")] pub trait SerializableAny: 'static + Any + Clone + serde::Serialize + for<'a> serde::Deserialize<'a> + Send + Sync { } #[cfg(feature = "persistence")] impl<T> SerializableAny for T where T: 'static + Any + Clone + serde::Serialize + for<'a> serde::Deserialize<'a> + Send + Sync { } #[cfg(not(feature = "persistence"))] pub trait SerializableAny: 'static + Any + Clone + for<'a> Send + Sync {} #[cfg(not(feature = "persistence"))] impl<T> SerializableAny for T where T: 'static + Any + Clone + for<'a> Send + Sync {} // ----------------------------------------------------------------------------------------------- #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug)] struct SerializedElement { /// The type of value we are storing. type_id: TypeId, /// The ron data we can deserialize. ron: Arc<str>, /// Increased by one each time we re-serialize an element that was never deserialized. /// /// Large value = old value that hasn't been read in a while. /// /// Used to garbage collect old values that hasn't been read in a while. generation: usize, } #[cfg(feature = "persistence")] type Serializer = fn(&Box<dyn Any + 'static + Send + Sync>) -> Option<String>; enum Element { /// A value, maybe serializable. Value { /// The actual value. value: Box<dyn Any + 'static + Send + Sync>, /// How to clone the value. clone_fn: fn(&Box<dyn Any + 'static + Send + Sync>) -> Box<dyn Any + 'static + Send + Sync>, /// How to serialize the value. /// None if non-serializable type. #[cfg(feature = "persistence")] serialize_fn: Option<Serializer>, }, /// A serialized value Serialized(SerializedElement), } impl Clone for Element { fn clone(&self) -> Self { match &self { Self::Value { value, clone_fn, #[cfg(feature = "persistence")] serialize_fn, } => Self::Value { value: clone_fn(value), clone_fn: *clone_fn, #[cfg(feature = "persistence")] serialize_fn: *serialize_fn, }, Self::Serialized(element) => Self::Serialized(element.clone()), } } } impl std::fmt::Debug for Element { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self { Self::Value { value, .. } => f .debug_struct("Element::Value") .field("type_id", &(**value).type_id()) .finish_non_exhaustive(), Self::Serialized(SerializedElement { type_id, ron, generation, }) => f .debug_struct("Element::Serialized") .field("type_id", type_id) .field("ron", ron) .field("generation", generation) .finish(), } } } impl Element { /// Create a value that won't be persisted. #[inline] pub(crate) fn new_temp<T: 'static + Any + Clone + Send + Sync>(t: T) -> Self { Self::Value { value: Box::new(t), clone_fn: |x| { // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with this type `T`, so type cannot change. #[expect(clippy::unwrap_used)] let x = x.downcast_ref::<T>().unwrap(); Box::new(x.clone()) }, #[cfg(feature = "persistence")] serialize_fn: None, } } /// Create a value that will be persisted. #[inline] pub(crate) fn new_persisted<T: SerializableAny>(t: T) -> Self { Self::Value { value: Box::new(t), clone_fn: |x| { // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with this type `T`, so type cannot change. #[expect(clippy::unwrap_used)] let x = x.downcast_ref::<T>().unwrap(); Box::new(x.clone()) }, #[cfg(feature = "persistence")] serialize_fn: Some(|x| { // This will never panic too, for same reason. #[expect(clippy::unwrap_used)] let x = x.downcast_ref::<T>().unwrap(); ron::to_string(x).ok() }), } } /// The type of the stored value. #[inline] pub(crate) fn type_id(&self) -> TypeId { match self { Self::Value { value, .. } => (**value).type_id().into(), Self::Serialized(SerializedElement { type_id, .. }) => *type_id, } } #[inline] pub(crate) fn get_temp<T: 'static>(&self) -> Option<&T> { match self { Self::Value { value, .. } => value.downcast_ref(), Self::Serialized(_) => None, } } #[inline] pub(crate) fn get_mut_temp<T: 'static>(&mut self) -> Option<&mut T> { match self { Self::Value { value, .. } => value.downcast_mut(), Self::Serialized(_) => None, } } #[inline] pub(crate) fn get_temp_mut_or_insert_with<T: 'static + Any + Clone + Send + Sync>( &mut self, insert_with: impl FnOnce() -> T, ) -> &mut T { match self { Self::Value { value, .. } => { if !value.is::<T>() { *self = Self::new_temp(insert_with()); } } Self::Serialized(_) => { *self = Self::new_temp(insert_with()); } } match self { // This unwrap will never panic because we already converted object to required type #[expect(clippy::unwrap_used)] Self::Value { value, .. } => value.downcast_mut().unwrap(), Self::Serialized(_) => unreachable!(), } } #[inline] pub(crate) fn get_persisted_mut_or_insert_with<T: SerializableAny>( &mut self, insert_with: impl FnOnce() -> T, ) -> &mut T { match self { Self::Value { value, .. } => { if !value.is::<T>() { *self = Self::new_persisted(insert_with()); } } #[cfg(feature = "persistence")] Self::Serialized(SerializedElement { ron, .. }) => { *self = Self::new_persisted(from_ron_str::<T>(ron).unwrap_or_else(insert_with)); } #[cfg(not(feature = "persistence"))] Self::Serialized(_) => { *self = Self::new_persisted(insert_with()); } } match self { // This unwrap will never panic because we already converted object to required type #[expect(clippy::unwrap_used)] Self::Value { value, .. } => value.downcast_mut().unwrap(), Self::Serialized(_) => unreachable!(), } } pub(crate) fn get_mut_persisted<T: SerializableAny>(&mut self) -> Option<&mut T> { match self { Self::Value { value, .. } => value.downcast_mut(), #[cfg(feature = "persistence")] Self::Serialized(SerializedElement { ron, .. }) => { *self = Self::new_persisted(from_ron_str::<T>(ron)?); match self { Self::Value { value, .. } => value.downcast_mut(), Self::Serialized(_) => unreachable!(), } } #[cfg(not(feature = "persistence"))] Self::Serialized(_) => None, } } #[cfg(feature = "persistence")] fn to_serialize(&self) -> Option<SerializedElement> { match self { Self::Value { value, serialize_fn, .. } => { if let Some(serialize_fn) = serialize_fn { let ron = serialize_fn(value)?; Some(SerializedElement { type_id: (**value).type_id().into(), ron: ron.into(), generation: 1, }) } else { None } } Self::Serialized(element) => Some(element.clone()), } } } #[cfg(feature = "persistence")] fn from_ron_str<T: serde::de::DeserializeOwned>(ron: &str) -> Option<T> { match ron::from_str::<T>(ron) { Ok(value) => Some(value), Err(_err) => { log::warn!( "egui: Failed to deserialize {} from memory: {}, ron error: {:?}", std::any::type_name::<T>(), _err, ron ); None } } } // ----------------------------------------------------------------------------------------------- use crate::Id; // TODO(emilk): make IdTypeMap generic over the key (`Id`), and make a library of IdTypeMap. /// Stores values identified by an [`Id`] AND the [`std::any::TypeId`] of the value. /// /// In other words, it maps `(Id, TypeId)` to any value you want. /// /// Values are cloned when read, so keep them small and light. /// If you want to store something bigger, wrap them in `Arc<Mutex<…>>`. /// Also try `Arc<ArcSwap<…>>`. /// /// Values can either be "persisted" (serializable) or "temporary" (cleared when egui is shut down). /// /// You can store state using the key [`Id::NULL`]. The state will then only be identified by its type. /// /// ``` /// # use egui::{Id, util::IdTypeMap}; /// let a = Id::new("a"); /// let b = Id::new("b"); /// let mut map: IdTypeMap = Default::default(); /// /// // `a` associated with an f64 and an i32 /// map.insert_persisted(a, 3.14); /// map.insert_temp(a, 42); /// /// // `b` associated with an f64 and a `&'static str` /// map.insert_persisted(b, 13.37); /// map.insert_temp(b, "Hello World".to_owned()); /// /// // we can retrieve all four values: /// assert_eq!(map.get_temp::<f64>(a), Some(3.14)); /// assert_eq!(map.get_temp::<i32>(a), Some(42)); /// assert_eq!(map.get_temp::<f64>(b), Some(13.37)); /// assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned())); /// /// // we can retrieve them like so also: /// assert_eq!(map.get_persisted::<f64>(a), Some(3.14)); /// assert_eq!(map.get_persisted::<i32>(a), Some(42)); /// assert_eq!(map.get_persisted::<f64>(b), Some(13.37)); /// assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned())); /// ``` #[derive(Clone, Debug)] // We use `id XOR typeid` as a key, so we don't need to hash again! pub struct IdTypeMap { map: nohash_hasher::IntMap<u64, Element>, max_bytes_per_type: usize, } impl Default for IdTypeMap { fn default() -> Self { Self { map: Default::default(), max_bytes_per_type: 256 * 1024, } } } impl IdTypeMap { /// Insert a value that will not be persisted. #[inline] pub fn insert_temp<T: 'static + Any + Clone + Send + Sync>(&mut self, id: Id, value: T) { let hash = hash(TypeId::of::<T>(), id); self.map.insert(hash, Element::new_temp(value)); } /// Insert a value that will be persisted next time you start the app. #[inline] pub fn insert_persisted<T: SerializableAny>(&mut self, id: Id, value: T) { let hash = hash(TypeId::of::<T>(), id); self.map.insert(hash, Element::new_persisted(value)); } /// Read a value without trying to deserialize a persisted value. /// /// The call clones the value (if found), so make sure it is cheap to clone! #[inline] pub fn get_temp<T: 'static + Clone>(&self, id: Id) -> Option<T> { let hash = hash(TypeId::of::<T>(), id); self.map.get(&hash).and_then(|x| x.get_temp()).cloned() } /// Read a value, optionally deserializing it if available. /// /// NOTE: A mutable `self` is needed because internally this deserializes on first call /// and caches the result (caching requires self-mutability). /// /// The call clones the value (if found), so make sure it is cheap to clone! #[inline] pub fn get_persisted<T: SerializableAny>(&mut self, id: Id) -> Option<T> { let hash = hash(TypeId::of::<T>(), id); self.map .get_mut(&hash) .and_then(|x| x.get_mut_persisted()) .cloned() } #[inline] pub fn get_temp_mut_or<T: 'static + Any + Clone + Send + Sync>( &mut self, id: Id, or_insert: T, ) -> &mut T { self.get_temp_mut_or_insert_with(id, || or_insert) } #[inline] pub fn get_persisted_mut_or<T: SerializableAny>(&mut self, id: Id, or_insert: T) -> &mut T { self.get_persisted_mut_or_insert_with(id, || or_insert) } #[inline] pub fn get_temp_mut_or_default<T: 'static + Any + Clone + Send + Sync + Default>( &mut self, id: Id, ) -> &mut T { self.get_temp_mut_or_insert_with(id, Default::default) } #[inline] pub fn get_persisted_mut_or_default<T: SerializableAny + Default>(&mut self, id: Id) -> &mut T { self.get_persisted_mut_or_insert_with(id, Default::default) } pub fn get_temp_mut_or_insert_with<T: 'static + Any + Clone + Send + Sync>( &mut self, id: Id, insert_with: impl FnOnce() -> T, ) -> &mut T { let hash = hash(TypeId::of::<T>(), id); use std::collections::hash_map::Entry; match self.map.entry(hash) { Entry::Vacant(vacant) => { // this unwrap will never panic, because we insert correct type right now #[expect(clippy::unwrap_used)] vacant .insert(Element::new_temp(insert_with())) .get_mut_temp() .unwrap() } Entry::Occupied(occupied) => { occupied.into_mut().get_temp_mut_or_insert_with(insert_with) } } } pub fn get_persisted_mut_or_insert_with<T: SerializableAny>( &mut self, id: Id, insert_with: impl FnOnce() -> T, ) -> &mut T { let hash = hash(TypeId::of::<T>(), id); use std::collections::hash_map::Entry; match self.map.entry(hash) { Entry::Vacant(vacant) => { // this unwrap will never panic, because we insert correct type right now #[expect(clippy::unwrap_used)] vacant .insert(Element::new_persisted(insert_with())) .get_mut_persisted() .unwrap() } Entry::Occupied(occupied) => occupied .into_mut() .get_persisted_mut_or_insert_with(insert_with), } } /// For tests #[cfg(feature = "persistence")] #[allow(clippy::allow_attributes, unused)] fn get_generation<T: SerializableAny>(&self, id: Id) -> Option<usize> { let element = self.map.get(&hash(TypeId::of::<T>(), id))?; match element { Element::Value { .. } => Some(0), Element::Serialized(SerializedElement { generation, .. }) => Some(*generation), } } /// Remove the state of this type and id. #[inline] pub fn remove<T: 'static>(&mut self, id: Id) { let hash = hash(TypeId::of::<T>(), id); self.map.remove(&hash); } /// Remove and fetch the state of this type and id. #[inline] pub fn remove_temp<T: 'static + Default>(&mut self, id: Id) -> Option<T> { let hash = hash(TypeId::of::<T>(), id); let mut element = self.map.remove(&hash)?; Some(std::mem::take(element.get_mut_temp()?)) } /// Note all state of the given type. pub fn remove_by_type<T: 'static>(&mut self) { let key = TypeId::of::<T>(); self.map.retain(|_, e| { let e: &Element = e; e.type_id() != key }); } #[inline] pub fn clear(&mut self) { self.map.clear(); } #[inline] pub fn is_empty(&self) -> bool { self.map.is_empty() } #[inline] pub fn len(&self) -> usize { self.map.len() } /// Count how many values are stored but not yet deserialized. #[inline] pub fn count_serialized(&self) -> usize { self.map .values() .filter(|e| matches!(e, Element::Serialized(_))) .count() } /// Count the number of values are stored with the given type. pub fn count<T: 'static>(&self) -> usize { let key = TypeId::of::<T>(); self.map .iter() .filter(|(_, e)| { let e: &Element = e; e.type_id() == key }) .count() } /// The maximum number of bytes that will be used to /// store the persisted state of a single widget type. /// /// Some egui widgets store persisted state that is /// serialized to disk by some backends (e.g. `eframe`). /// /// Example of such widgets is `CollapsingHeader` and `Window`. /// If you keep creating widgets with unique ids (e.g. `Windows` with many different names), /// egui will use up more and more space for these widgets, until this limit is reached. /// /// Once this limit is reached, the state that was read the longest time ago will be dropped first. /// /// This value in itself will not be serialized. pub fn max_bytes_per_type(&self) -> usize { self.max_bytes_per_type } /// See [`Self::max_bytes_per_type`]. pub fn set_max_bytes_per_type(&mut self, max_bytes_per_type: usize) { self.max_bytes_per_type = max_bytes_per_type; } } #[inline(always)] fn hash(type_id: TypeId, id: Id) -> u64 { type_id.value() ^ id.value() } // ---------------------------------------------------------------------------- /// How [`IdTypeMap`] is persisted. #[cfg(feature = "persistence")] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] struct PersistedMap(Vec<(u64, SerializedElement)>); #[cfg(feature = "persistence")] impl PersistedMap { fn from_map(map: &IdTypeMap) -> Self { #![expect(clippy::iter_over_hash_type)] // the serialized order doesn't matter profiling::function_scope!(); use std::collections::BTreeMap; let mut types_map: nohash_hasher::IntMap<TypeId, TypeStats> = Default::default(); #[derive(Default)] struct TypeStats { num_bytes: usize, generations: BTreeMap<usize, GenerationStats>, } #[derive(Default)] struct GenerationStats { num_bytes: usize, elements: Vec<(u64, SerializedElement)>, } let max_bytes_per_type = map.max_bytes_per_type; { profiling::scope!("gather"); for (hash, element) in &map.map { if let Some(element) = element.to_serialize() { let stats = types_map.entry(element.type_id).or_default(); stats.num_bytes += element.ron.len(); let generation_stats = stats.generations.entry(element.generation).or_default(); generation_stats.num_bytes += element.ron.len(); generation_stats.elements.push((*hash, element)); } else { // temporary value that shouldn't be serialized } } } let mut persisted = vec![]; { profiling::scope!("gc"); for stats in types_map.values() { let mut bytes_written = 0; // Start with the most recently read values, and then go as far as we are allowed. // Always include at least one generation. for generation in stats.generations.values() { if bytes_written == 0 || bytes_written + generation.num_bytes <= max_bytes_per_type { persisted.append(&mut generation.elements.clone()); bytes_written += generation.num_bytes; } else { // Omit the rest. The user hasn't read the values in a while. break; } } } } Self(persisted) } fn into_map(self) -> IdTypeMap { profiling::function_scope!(); let map = self .0 .into_iter() .map( |( hash, SerializedElement { type_id, ron, generation, }, )| { ( hash, Element::Serialized(SerializedElement { type_id, ron, generation: generation + 1, // This is where we increment the generation! }), ) }, ) .collect(); IdTypeMap { map, ..Default::default() } } } #[cfg(feature = "persistence")] impl serde::Serialize for IdTypeMap { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { profiling::scope!("IdTypeMap::serialize"); PersistedMap::from_map(self).serialize(serializer) } } #[cfg(feature = "persistence")] impl<'de> serde::Deserialize<'de> for IdTypeMap { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { profiling::scope!("IdTypeMap::deserialize"); <PersistedMap>::deserialize(deserializer).map(PersistedMap::into_map) } } // ---------------------------------------------------------------------------- #[test] fn test_two_id_two_type() { let a = Id::new("a"); let b = Id::new("b"); let mut map: IdTypeMap = Default::default(); map.insert_persisted(a, 13.37); map.insert_temp(b, 42); assert_eq!(map.get_persisted::<f64>(a), Some(13.37)); assert_eq!(map.get_persisted::<i32>(b), Some(42)); assert_eq!(map.get_temp::<f64>(a), Some(13.37)); assert_eq!(map.get_temp::<i32>(b), Some(42)); } #[test] fn test_two_id_x_two_types() { #![expect(clippy::approx_constant)] let a = Id::new("a"); let b = Id::new("b"); let mut map: IdTypeMap = Default::default(); // `a` associated with an f64 and an i32 map.insert_persisted(a, 3.14); map.insert_temp(a, 42); // `b` associated with an f64 and a `&'static str` map.insert_persisted(b, 13.37); map.insert_temp(b, "Hello World".to_owned()); // we can retrieve all four values: assert_eq!(map.get_temp::<f64>(a), Some(3.14)); assert_eq!(map.get_temp::<i32>(a), Some(42)); assert_eq!(map.get_temp::<f64>(b), Some(13.37)); assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned())); // we can retrieve them like so also: assert_eq!(map.get_persisted::<f64>(a), Some(3.14)); assert_eq!(map.get_persisted::<i32>(a), Some(42)); assert_eq!(map.get_persisted::<f64>(b), Some(13.37)); assert_eq!(map.get_temp::<String>(b), Some("Hello World".to_owned())); } #[test] fn test_one_id_two_types() { let id = Id::new("a"); let mut map: IdTypeMap = Default::default(); map.insert_persisted(id, 13.37); map.insert_temp(id, 42); assert_eq!(map.get_temp::<f64>(id), Some(13.37)); assert_eq!(map.get_persisted::<f64>(id), Some(13.37)); assert_eq!(map.get_temp::<i32>(id), Some(42)); // ------------ // Test removal: // We can remove: map.remove::<i32>(id); assert_eq!(map.get_temp::<i32>(id), None); // Other type is still there, even though it is the same if: assert_eq!(map.get_temp::<f64>(id), Some(13.37)); assert_eq!(map.get_persisted::<f64>(id), Some(13.37)); // But we can still remove the last: map.remove::<f64>(id); assert_eq!(map.get_temp::<f64>(id), None); assert_eq!(map.get_persisted::<f64>(id), None); } #[test] fn test_mix() { #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug, PartialEq)] struct Foo(i32); #[derive(Clone, Debug, PartialEq)] struct Bar(f32); let id = Id::new("a"); let mut map: IdTypeMap = Default::default(); map.insert_persisted(id, Foo(555)); map.insert_temp(id, Bar(1.0)); assert_eq!(map.get_temp::<Foo>(id), Some(Foo(555))); assert_eq!(map.get_persisted::<Foo>(id), Some(Foo(555))); assert_eq!(map.get_temp::<Bar>(id), Some(Bar(1.0))); // ------------ // Test removal: // We can remove: map.remove::<Bar>(id); assert_eq!(map.get_temp::<Bar>(id), None); // Other type is still there, even though it is the same if: assert_eq!(map.get_temp::<Foo>(id), Some(Foo(555))); assert_eq!(map.get_persisted::<Foo>(id), Some(Foo(555))); // But we can still remove the last: map.remove::<Foo>(id); assert_eq!(map.get_temp::<Foo>(id), None); assert_eq!(map.get_persisted::<Foo>(id), None); } #[cfg(feature = "persistence")] #[test] fn test_mix_serialize() { use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct Serializable(i32); #[derive(Clone, Debug, PartialEq)] struct NonSerializable(f32); let id = Id::new("a"); let mut map: IdTypeMap = Default::default(); map.insert_persisted(id, Serializable(555)); map.insert_temp(id, NonSerializable(1.0)); assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555))); assert_eq!( map.get_persisted::<Serializable>(id), Some(Serializable(555)) ); assert_eq!( map.get_temp::<NonSerializable>(id), Some(NonSerializable(1.0)) ); // ----------- let serialized = ron::to_string(&map).unwrap(); // ------------ // Test removal: // We can remove: map.remove::<NonSerializable>(id); assert_eq!(map.get_temp::<NonSerializable>(id), None); // Other type is still there, even though it is the same if: assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555))); assert_eq!( map.get_persisted::<Serializable>(id), Some(Serializable(555)) ); // But we can still remove the last: map.remove::<Serializable>(id); assert_eq!(map.get_temp::<Serializable>(id), None); assert_eq!(map.get_persisted::<Serializable>(id), None); // -------------------- // Test deserialization: let mut map: IdTypeMap = ron::from_str(&serialized).unwrap(); assert_eq!(map.get_temp::<Serializable>(id), None); assert_eq!( map.get_persisted::<Serializable>(id), Some(Serializable(555)) ); assert_eq!(map.get_temp::<Serializable>(id), Some(Serializable(555))); } #[cfg(feature = "persistence")] #[test] fn test_serialize_generations() { use serde::{Deserialize, Serialize}; fn serialize_and_deserialize(map: &IdTypeMap) -> IdTypeMap { let serialized = ron::to_string(map).unwrap(); ron::from_str(&serialized).unwrap() } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct A(i32); let mut map: IdTypeMap = Default::default(); for i in 0..3 { map.insert_persisted(Id::new(i), A(i)); } for i in 0..3 { assert_eq!(map.get_generation::<A>(Id::new(i)), Some(0)); } map = serialize_and_deserialize(&map); // We use generation 0 for non-serilized, // 1 for things that have been serialized but never deserialized, // and then we increment with 1 on each deserialize. // So we should have generation 2 now: for i in 0..3 { assert_eq!(map.get_generation::<A>(Id::new(i)), Some(2)); } // Reading should reset: assert_eq!(map.get_persisted::<A>(Id::new(0)), Some(A(0))); assert_eq!(map.get_generation::<A>(Id::new(0)), Some(0)); // Generations should increment: map = serialize_and_deserialize(&map); assert_eq!(map.get_generation::<A>(Id::new(0)), Some(2)); assert_eq!(map.get_generation::<A>(Id::new(1)), Some(3)); } #[cfg(feature = "persistence")] #[test] fn test_serialize_gc() { use serde::{Deserialize, Serialize}; fn serialize_and_deserialize(mut map: IdTypeMap, max_bytes_per_type: usize) -> IdTypeMap { map.set_max_bytes_per_type(max_bytes_per_type); let serialized = ron::to_string(&map).unwrap(); ron::from_str(&serialized).unwrap() } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct A(usize); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct B(usize); let mut map: IdTypeMap = Default::default(); let num_a = 1_000; let num_b = 10; for i in 0..num_a { map.insert_persisted(Id::new(i), A(i)); } for i in 0..num_b { map.insert_persisted(Id::new(i), B(i)); } map = serialize_and_deserialize(map, 100); // We always serialize at least one generation: assert_eq!(map.count::<A>(), num_a); assert_eq!(map.count::<B>(), num_b); // Create a new small generation: map.insert_persisted(Id::new(1_000_000), A(1_000_000)); map.insert_persisted(Id::new(1_000_000), B(1_000_000)); assert_eq!(map.count::<A>(), num_a + 1); assert_eq!(map.count::<B>(), num_b + 1); // And read a value: assert_eq!(map.get_persisted::<A>(Id::new(0)), Some(A(0))); assert_eq!(map.get_persisted::<B>(Id::new(0)), Some(B(0))); map = serialize_and_deserialize(map, 100); assert_eq!( map.count::<A>(), 2, "We should have dropped the oldest generation, but kept the new value and the read value" ); assert_eq!( map.count::<B>(), num_b + 1, "B should fit under the byte limit" ); // Create another small generation: map.insert_persisted(Id::new(2_000_000), A(2_000_000)); map.insert_persisted(Id::new(2_000_000), B(2_000_000)); map = serialize_and_deserialize(map, 100); assert_eq!(map.count::<A>(), 3); // The read value, plus the two new ones assert_eq!(map.count::<B>(), num_b + 2); // all the old ones, plus two new ones // Lower the limit, and we should only have the latest generation: map = serialize_and_deserialize(map, 1); assert_eq!(map.count::<A>(), 1); assert_eq!(map.count::<B>(), 1); assert_eq!( map.get_persisted::<A>(Id::new(2_000_000)), Some(A(2_000_000)) ); assert_eq!( map.get_persisted::<B>(Id::new(2_000_000)), Some(B(2_000_000)) ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/util/undoer.rs
crates/egui/src/util/undoer.rs
use std::collections::VecDeque; #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Settings { /// Maximum number of undos. /// If your state is resource intensive, you should keep this low. /// /// Default: `100` pub max_undos: usize, /// When that state hasn't changed for this many seconds, /// create a new undo point (if one is needed). /// /// Default value: `1.0` seconds. pub stable_time: f32, /// If the state is changing so often that we never get to `stable_time`, /// then still create a save point every `auto_save_interval` seconds, /// so we have something to undo to. /// /// Default value: `30` seconds. pub auto_save_interval: f32, } impl Default for Settings { fn default() -> Self { Self { max_undos: 100, stable_time: 1.0, auto_save_interval: 30.0, } } } /// Automatic undo system. /// /// Every frame you feed it the most recent state. /// The [`Undoer`] compares it with the latest undo point /// and if there is a change it may create a new undo point. /// /// [`Undoer`] follows two simple rules: /// /// 1) If the state has changed since the latest undo point, but has /// remained stable for `stable_time` seconds, an new undo point is created. /// 2) If the state does not stabilize within `auto_save_interval` seconds, an undo point is created. /// /// Rule 1) will make sure an undo point is not created until you _stop_ dragging that slider. /// Rule 2) will make sure that you will get some undo points even if you are constantly changing the state. #[derive(Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Undoer<State> { settings: Settings, /// New undoes are added to the back. /// Two adjacent undo points are never equal. /// The latest undo point may (often) be the current state. undos: VecDeque<State>, /// Stores redos immediately after a sequence of undos. /// Gets cleared every time the state changes. /// Does not need to be a deque, because there can only be up to `undos.len()` redos, /// which is already limited to `settings.max_undos`. redos: Vec<State>, #[cfg_attr(feature = "serde", serde(skip))] flux: Option<Flux<State>>, } impl<State> std::fmt::Debug for Undoer<State> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { undos, redos, .. } = self; f.debug_struct("Undoer") .field("undo count", &undos.len()) .field("redo count", &redos.len()) .finish() } } impl<State> Default for Undoer<State> where State: Clone + PartialEq, { #[inline] fn default() -> Self { Self { settings: Settings::default(), undos: VecDeque::new(), redos: Vec::new(), flux: None, } } } /// Represents how the current state is changing #[derive(Clone)] struct Flux<State> { start_time: f64, latest_change_time: f64, latest_state: State, } impl<State> Undoer<State> where State: Clone + PartialEq, { /// Create a new [`Undoer`] with the given [`Settings`]. pub fn with_settings(settings: Settings) -> Self { Self { settings, ..Default::default() } } /// Do we have an undo point different from the given state? pub fn has_undo(&self, current_state: &State) -> bool { match self.undos.len() { 0 => false, 1 => self.undos.back() != Some(current_state), _ => true, } } pub fn has_redo(&self, current_state: &State) -> bool { !self.redos.is_empty() && self.undos.back() == Some(current_state) } /// Return true if the state is currently changing pub fn is_in_flux(&self) -> bool { self.flux.is_some() } pub fn undo(&mut self, current_state: &State) -> Option<&State> { if self.has_undo(current_state) { self.flux = None; if self.undos.back() == Some(current_state) { #[expect(clippy::unwrap_used)] // we just checked that undos is not empty self.redos.push(self.undos.pop_back().unwrap()); } else { self.redos.push(current_state.clone()); } // Note: we keep the undo point intact. self.undos.back() } else { None } } pub fn redo(&mut self, current_state: &State) -> Option<&State> { if !self.undos.is_empty() && self.undos.back() != Some(current_state) { // state changed since the last undo, redos should be cleared. self.redos.clear(); None } else if let Some(state) = self.redos.pop() { self.undos.push_back(state); self.undos.back() } else { None } } /// Add an undo point if, and only if, there has been a change since the latest undo point. pub fn add_undo(&mut self, current_state: &State) { if self.undos.back() != Some(current_state) { self.undos.push_back(current_state.clone()); } while self.undos.len() > self.settings.max_undos { self.undos.pop_front(); } self.flux = None; } /// Call this as often as you want (e.g. every frame) /// and [`Undoer`] will determine if a new undo point should be created. /// /// * `current_time`: current time in seconds. pub fn feed_state(&mut self, current_time: f64, current_state: &State) { match self.undos.back() { None => { // First time feed_state is called. // always create an undo point: self.add_undo(current_state); } Some(latest_undo) => { if latest_undo == current_state { self.flux = None; } else { self.redos.clear(); match self.flux.as_mut() { None => { self.flux = Some(Flux { start_time: current_time, latest_change_time: current_time, latest_state: current_state.clone(), }); } Some(flux) => { if &flux.latest_state == current_state { let time_since_latest_change = (current_time - flux.latest_change_time) as f32; if time_since_latest_change >= self.settings.stable_time { self.add_undo(current_state); } } else { let time_since_flux_start = (current_time - flux.start_time) as f32; if time_since_flux_start >= self.settings.auto_save_interval { self.add_undo(current_state); } else { flux.latest_change_time = current_time; flux.latest_state = current_state.clone(); } } } } } } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/util/mod.rs
crates/egui/src/util/mod.rs
//! Miscellaneous tools used by the rest of egui. pub(crate) mod fixed_cache; pub mod id_type_map; pub mod undoer; pub use id_type_map::IdTypeMap; pub use epaint::emath::History; pub use epaint::util::{hash, hash_with}; /// Deprecated alias for [`crate::cache`]. #[deprecated = "Use egui::cache instead"] pub use crate::cache;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/input_state/touch_state.rs
crates/egui/src/input_state/touch_state.rs
use std::{collections::BTreeMap, fmt::Debug}; use crate::{ Event, RawInput, TouchId, TouchPhase, data::input::TouchDeviceId, emath::{Pos2, Vec2, normalized_angle}, }; /// All you probably need to know about a multi-touch gesture. #[derive(Clone, Copy, Debug, PartialEq)] pub struct MultiTouchInfo { /// Point in time when the gesture started. pub start_time: f64, /// Position of the pointer at the time the gesture started. pub start_pos: Pos2, /// Center position of the current gesture (average of all touch points). pub center_pos: Pos2, /// Number of touches (fingers) on the surface. Value is ≥ 2 since for a single touch no /// [`MultiTouchInfo`] is created. pub num_touches: usize, /// Proportional zoom factor (pinch gesture). /// * `zoom = 1`: no change /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread pub zoom_delta: f32, /// 2D non-proportional zoom factor (pinch gesture). /// /// For horizontal pinches, this will return `[z, 1]`, /// for vertical pinches this will return `[1, z]`, /// and otherwise this will return `[z, z]`, /// where `z` is the zoom factor: /// * `zoom = 1`: no change /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread pub zoom_delta_2d: Vec2, /// Rotation in radians. Moving fingers around each other will change this value. This is a /// relative value, comparing the orientation of fingers in the current frame with the previous /// frame. If all fingers are resting, this value is `0.0`. pub rotation_delta: f32, /// Relative movement (comparing previous frame and current frame) of the average position of /// all touch points. Without movement this value is `Vec2::ZERO`. /// /// Note that this may not necessarily be measured in screen points (although it _will_ be for /// most mobile devices). In general (depending on the touch device), touch coordinates cannot /// be directly mapped to the screen. A touch always is considered to start at the position of /// the pointer, but touch movement is always measured in the units delivered by the device, /// and may depend on hardware and system settings. pub translation_delta: Vec2, /// Current force of the touch (average of the forces of the individual fingers). This is a /// value in the interval `[0.0 .. =1.0]`. /// /// Note 1: A value of `0.0` either indicates a very light touch, or it means that the device /// is not capable of measuring the touch force at all. /// /// Note 2: Just increasing the physical pressure without actually moving the finger may not /// necessarily lead to a change of this value. pub force: f32, } /// The current state (for a specific touch device) of touch events and gestures. #[derive(Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct TouchState { /// Technical identifier of the touch device. This is used to identify relevant touch events /// for this [`TouchState`] instance. device_id: TouchDeviceId, /// Active touches, if any. /// /// `TouchId` is the unique identifier of the touch. It is valid as long as the finger/pen touches the surface. The /// next touch will receive a new unique ID. /// /// Refer to [`ActiveTouch`]. active_touches: BTreeMap<TouchId, ActiveTouch>, /// If a gesture has been recognized (i.e. when exactly two fingers touch the surface), this /// holds state information gesture_state: Option<GestureState>, } #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct GestureState { start_time: f64, start_pointer_pos: Pos2, pinch_type: PinchType, previous: Option<DynGestureState>, current: DynGestureState, } /// Gesture data that can change over time #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct DynGestureState { /// used for proportional zooming avg_distance: f32, /// used for non-proportional zooming avg_abs_distance2: Vec2, avg_pos: Pos2, avg_force: f32, heading: f32, } /// Describes an individual touch (finger or digitizer) on the touch surface. Instances exist as /// long as the finger/pen touches the surface. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct ActiveTouch { /// Current position of this touch, in device coordinates (not necessarily screen position) pos: Pos2, /// Current force of the touch. A value in the interval [0.0 .. 1.0] /// /// Note that a value of 0.0 either indicates a very light touch, or it means that the device /// is not capable of measuring the touch force. force: Option<f32>, } impl TouchState { pub fn new(device_id: TouchDeviceId) -> Self { Self { device_id, active_touches: Default::default(), gesture_state: None, } } pub fn begin_pass(&mut self, time: f64, new: &RawInput, pointer_pos: Option<Pos2>) { let mut added_or_removed_touches = false; for event in &new.events { match *event { Event::Touch { device_id, id, phase, pos, force, } if device_id == self.device_id => match phase { TouchPhase::Start => { self.active_touches.insert(id, ActiveTouch { pos, force }); added_or_removed_touches = true; } TouchPhase::Move => { if let Some(touch) = self.active_touches.get_mut(&id) { touch.pos = pos; touch.force = force; } } TouchPhase::End | TouchPhase::Cancel => { self.active_touches.remove(&id); added_or_removed_touches = true; } }, _ => (), } } // This needs to be called each frame, even if there are no new touch events. // Otherwise, we would send the same old delta information multiple times: self.update_gesture(time, pointer_pos); if added_or_removed_touches { // Adding or removing fingers makes the average values "jump". We better forget // about the previous values, and don't create delta information for this frame: if let Some(state) = &mut self.gesture_state { state.previous = None; } } } /// Are there currently any fingers touching the surface? pub fn any_touches(&self) -> bool { !self.active_touches.is_empty() } pub fn info(&self) -> Option<MultiTouchInfo> { self.gesture_state.as_ref().map(|state| { // state.previous can be `None` when the number of simultaneous touches has just // changed. In this case, we take `current` as `previous`, pretending that there // was no change for the current frame. let state_previous = state.previous.unwrap_or(state.current); let zoom_delta = state.current.avg_distance / state_previous.avg_distance; let zoom_delta_2d = match state.pinch_type { PinchType::Horizontal => Vec2::new( state.current.avg_abs_distance2.x / state_previous.avg_abs_distance2.x, 1.0, ), PinchType::Vertical => Vec2::new( 1.0, state.current.avg_abs_distance2.y / state_previous.avg_abs_distance2.y, ), PinchType::Proportional => Vec2::splat(zoom_delta), }; let center_pos = state.current.avg_pos; MultiTouchInfo { start_time: state.start_time, start_pos: state.start_pointer_pos, num_touches: self.active_touches.len(), zoom_delta, zoom_delta_2d, rotation_delta: normalized_angle(state.current.heading - state_previous.heading), translation_delta: state.current.avg_pos - state_previous.avg_pos, force: state.current.avg_force, center_pos, } }) } fn update_gesture(&mut self, time: f64, pointer_pos: Option<Pos2>) { if let Some(dyn_state) = self.calc_dynamic_state() { if let Some(state) = &mut self.gesture_state { // updating an ongoing gesture state.previous = Some(state.current); state.current = dyn_state; } else if let Some(pointer_pos) = pointer_pos { // starting a new gesture self.gesture_state = Some(GestureState { start_time: time, start_pointer_pos: pointer_pos, pinch_type: PinchType::classify(&self.active_touches), previous: None, current: dyn_state, }); } } else { // the end of a gesture (if there is any) self.gesture_state = None; } } /// `None` if less than two fingers fn calc_dynamic_state(&self) -> Option<DynGestureState> { let num_touches = self.active_touches.len(); if num_touches < 2 { None } else { let mut state = DynGestureState { avg_distance: 0.0, avg_abs_distance2: Vec2::ZERO, avg_pos: Pos2::ZERO, avg_force: 0.0, heading: 0.0, }; let num_touches_recip = 1. / num_touches as f32; // first pass: calculate force and center of touch positions: for touch in self.active_touches.values() { state.avg_force += touch.force.unwrap_or(0.0); state.avg_pos.x += touch.pos.x; state.avg_pos.y += touch.pos.y; } state.avg_force *= num_touches_recip; state.avg_pos.x *= num_touches_recip; state.avg_pos.y *= num_touches_recip; // second pass: calculate distances from center: for touch in self.active_touches.values() { state.avg_distance += state.avg_pos.distance(touch.pos); state.avg_abs_distance2.x += (state.avg_pos.x - touch.pos.x).abs(); state.avg_abs_distance2.y += (state.avg_pos.y - touch.pos.y).abs(); } state.avg_distance *= num_touches_recip; state.avg_abs_distance2 *= num_touches_recip; // Calculate the direction from the first touch to the center position. // This is not the perfect way of calculating the direction if more than two fingers // are involved, but as long as all fingers rotate more or less at the same angular // velocity, the shortcomings of this method will not be noticed. One can see the // issues though, when touching with three or more fingers, and moving only one of them // (it takes two hands to do this in a controlled manner). A better technique would be // to store the current and previous directions (with reference to the center) for each // touch individually, and then calculate the average of all individual changes in // direction. But this approach cannot be implemented locally in this method, making // everything a bit more complicated. #[expect(clippy::unwrap_used)] // guarded against already let first_touch = self.active_touches.values().next().unwrap(); state.heading = (state.avg_pos - first_touch.pos).angle(); Some(state) } } } impl TouchState { pub fn ui(&self, ui: &mut crate::Ui) { ui.label(format!("{self:?}")); } } impl Debug for TouchState { // This outputs less clutter than `#[derive(Debug)]`: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for (id, touch) in &self.active_touches { f.write_fmt(format_args!("#{id:?}: {touch:#?}\n"))?; } f.write_fmt(format_args!("gesture: {:#?}\n", self.gesture_state))?; Ok(()) } } #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] enum PinchType { Horizontal, Vertical, Proportional, } impl PinchType { fn classify(touches: &BTreeMap<TouchId, ActiveTouch>) -> Self { #![expect(clippy::unwrap_used)] // For non-proportional 2d zooming: // If the user is pinching with two fingers that have roughly the same Y coord, // then the Y zoom is unstable and should be 1. // Similarly, if the fingers are directly above/below each other, // we should only zoom on the Y axis. // If the fingers are roughly on a diagonal, we revert to the proportional zooming. if touches.len() == 2 { let mut touches = touches.values(); let t0 = touches.next().unwrap().pos; let t1 = touches.next().unwrap().pos; let dx = (t0.x - t1.x).abs(); let dy = (t0.y - t1.y).abs(); if dx > 3.0 * dy { Self::Horizontal } else if dy > 3.0 * dx { Self::Vertical } else { Self::Proportional } } else { Self::Proportional } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/input_state/mod.rs
crates/egui/src/input_state/mod.rs
mod touch_state; mod wheel_state; use crate::{ SafeAreaInsets, emath::{NumExt as _, Pos2, Rect, Vec2, vec2}, util::History, }; use crate::{ data::input::{ Event, EventFilter, KeyboardShortcut, Modifiers, NUM_POINTER_BUTTONS, PointerButton, RawInput, TouchDeviceId, ViewportInfo, }, input_state::wheel_state::WheelState, }; use std::{ collections::{BTreeMap, HashSet}, time::Duration, }; pub use crate::Key; pub use touch_state::MultiTouchInfo; use touch_state::TouchState; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum SurrenderFocusOn { /// Surrender focus if the user _presses_ somewhere outside the focused widget. Presses, /// Surrender focus if the user _clicks_ somewhere outside the focused widget. #[default] Clicks, /// Never surrender focus. Never, } impl SurrenderFocusOn { pub fn ui(&mut self, ui: &mut crate::Ui) { ui.horizontal(|ui| { ui.selectable_value(self, Self::Presses, "Presses") .on_hover_text( "Surrender focus if the user presses somewhere outside the focused widget.", ); ui.selectable_value(self, Self::Clicks, "Clicks") .on_hover_text( "Surrender focus if the user clicks somewhere outside the focused widget.", ); ui.selectable_value(self, Self::Never, "Never") .on_hover_text("Never surrender focus."); }); } } /// Options for input state handling. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InputOptions { /// Multiplier for the scroll speed when reported in [`crate::MouseWheelUnit::Line`]s. pub line_scroll_speed: f32, /// Controls the speed at which we zoom in when doing ctrl/cmd + scroll. pub scroll_zoom_speed: f32, /// After a pointer-down event, if the pointer moves more than this, it won't become a click. pub max_click_dist: f32, /// If the pointer is down for longer than this it will no longer register as a click. /// /// If a touch is held for this many seconds while still, then it will register as a /// "long-touch" which is equivalent to a secondary click. /// /// This is to support "press and hold for context menu" on touch screens. pub max_click_duration: f64, /// The new pointer press must come within this many seconds from previous pointer release /// for double click (or when this value is doubled, triple click) to count. pub max_double_click_delay: f64, /// When this modifier is down, all scroll events are treated as zoom events. /// /// The default is CTRL/CMD, and it is STRONGLY recommended to NOT change this. pub zoom_modifier: Modifiers, /// When this modifier is down, all scroll events are treated as horizontal scrolls, /// and when combined with [`Self::zoom_modifier`] it will result in zooming /// on only the horizontal axis. /// /// The default is SHIFT, and it is STRONGLY recommended to NOT change this. pub horizontal_scroll_modifier: Modifiers, /// When this modifier is down, all scroll events are treated as vertical scrolls, /// and when combined with [`Self::zoom_modifier`] it will result in zooming /// on only the vertical axis. pub vertical_scroll_modifier: Modifiers, /// When should we surrender focus from the focused widget? pub surrender_focus_on: SurrenderFocusOn, } impl Default for InputOptions { fn default() -> Self { // TODO(emilk): figure out why these constants need to be different on web and on native (winit). let is_web = cfg!(target_arch = "wasm32"); let line_scroll_speed = if is_web { 8.0 } else { 40.0 // Scroll speed decided by consensus: https://github.com/emilk/egui/issues/461 }; Self { line_scroll_speed, scroll_zoom_speed: 1.0 / 200.0, max_click_dist: 6.0, max_click_duration: 0.8, max_double_click_delay: 0.3, zoom_modifier: Modifiers::COMMAND, horizontal_scroll_modifier: Modifiers::SHIFT, vertical_scroll_modifier: Modifiers::ALT, surrender_focus_on: SurrenderFocusOn::default(), } } } impl InputOptions { /// Show the options in the ui. pub fn ui(&mut self, ui: &mut crate::Ui) { let Self { line_scroll_speed, scroll_zoom_speed, max_click_dist, max_click_duration, max_double_click_delay, zoom_modifier, horizontal_scroll_modifier, vertical_scroll_modifier, surrender_focus_on, } = self; crate::Grid::new("InputOptions") .num_columns(2) .striped(true) .show(ui, |ui| { ui.label("Line scroll speed"); ui.add(crate::DragValue::new(line_scroll_speed).range(0.0..=f32::INFINITY)) .on_hover_text( "How many lines to scroll with each tick of the mouse wheel", ); ui.end_row(); ui.label("Scroll zoom speed"); ui.add( crate::DragValue::new(scroll_zoom_speed) .range(0.0..=f32::INFINITY) .speed(0.001), ) .on_hover_text("How fast to zoom with ctrl/cmd + scroll"); ui.end_row(); ui.label("Max click distance"); ui.add(crate::DragValue::new(max_click_dist).range(0.0..=f32::INFINITY)) .on_hover_text( "If the pointer moves more than this, it won't become a click", ); ui.end_row(); ui.label("Max click duration"); ui.add( crate::DragValue::new(max_click_duration) .range(0.1..=f64::INFINITY) .speed(0.1), ) .on_hover_text( "If the pointer is down for longer than this it will no longer register as a click", ); ui.end_row(); ui.label("Max double click delay"); ui.add( crate::DragValue::new(max_double_click_delay) .range(0.01..=f64::INFINITY) .speed(0.1), ) .on_hover_text("Max time interval for double click to count"); ui.end_row(); ui.label("zoom_modifier"); zoom_modifier.ui(ui); ui.end_row(); ui.label("horizontal_scroll_modifier"); horizontal_scroll_modifier.ui(ui); ui.end_row(); ui.label("vertical_scroll_modifier"); vertical_scroll_modifier.ui(ui); ui.end_row(); ui.label("surrender_focus_on"); surrender_focus_on.ui(ui); ui.end_row(); }); } } /// Input state that egui updates each frame. /// /// You can access this with [`crate::Context::input`]. /// /// You can check if `egui` is using the inputs using /// [`crate::Context::wants_pointer_input`] and [`crate::Context::wants_keyboard_input`]. #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct InputState { /// The raw input we got this frame from the backend. pub raw: RawInput, /// State of the mouse or simple touch gestures which can be mapped to mouse operations. pub pointer: PointerState, /// State of touches, except those covered by `PointerState` (like clicks and drags). /// (We keep a separate [`TouchState`] for each encountered touch device.) touch_states: BTreeMap<TouchDeviceId, TouchState>, // ---------------------------------------------- // Scrolling: #[cfg_attr(feature = "serde", serde(skip))] wheel: WheelState, /// How many points the user scrolled, smoothed over a few frames. /// /// The delta dictates how the _content_ should move. /// /// A positive X-value indicates the content is being moved right, /// as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, /// as when swiping down on a touch-screen or track-pad with natural scrolling. /// /// [`crate::ScrollArea`] will both read and write to this field, so that /// at the end of the frame this will be zero if a scroll-area consumed the delta. pub smooth_scroll_delta: Vec2, /// Zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture). /// /// * `zoom = 1`: no change. /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread zoom_factor_delta: f32, /// Rotation in radians this frame, measuring clockwise (e.g. from a rotation gesture). rotation_radians: f32, // ---------------------------------------------- /// Position and size of the egui area. /// /// This is including the area that may be covered by the `safe_area_insets`. viewport_rect: Rect, /// The safe area insets, subtracted from the `viewport_rect` in [`Self::content_rect`]. safe_area_insets: SafeAreaInsets, /// Also known as device pixel ratio, > 1 for high resolution screens. pub pixels_per_point: f32, /// Maximum size of one side of a texture. /// /// This depends on the backend. pub max_texture_side: usize, /// Time in seconds. Relative to whatever. Used for animation. pub time: f64, /// Time since last frame, in seconds. /// /// This can be very unstable in reactive mode (when we don't paint each frame). /// For animations it is therefore better to use [`Self::stable_dt`]. pub unstable_dt: f32, /// Estimated time until next frame (provided we repaint right away). /// /// Used for animations to get instant feedback (avoid frame delay). /// Should be set to the expected time between frames when painting at vsync speeds. /// /// On most integrations this has a fixed value of `1.0 / 60.0`, so it is not a very accurate estimate. pub predicted_dt: f32, /// Time since last frame (in seconds), but gracefully handles the first frame after sleeping in reactive mode. /// /// In reactive mode (available in e.g. `eframe`), `egui` only updates when there is new input /// or something is animating. /// This can lead to large gaps of time (sleep), leading to large [`Self::unstable_dt`]. /// /// If `egui` requested a repaint the previous frame, then `egui` will use /// `stable_dt = unstable_dt;`, but if `egui` did not not request a repaint last frame, /// then `egui` will assume `unstable_dt` is too large, and will use /// `stable_dt = predicted_dt;`. /// /// This means that for the first frame after a sleep, /// `stable_dt` will be a prediction of the delta-time until the next frame, /// and in all other situations this will be an accurate measurement of time passed /// since the previous frame. /// /// Note that a frame can still stall for various reasons, so `stable_dt` can /// still be unusually large in some situations. /// /// When animating something, it is recommended that you use something like /// `stable_dt.min(0.1)` - this will give you smooth animations when the framerate is good /// (even in reactive mode), but will avoid large jumps when framerate is bad, /// and will effectively slow down the animation when FPS drops below 10. pub stable_dt: f32, /// The native window has the keyboard focus (i.e. is receiving key presses). /// /// False when the user alt-tab away from the application, for instance. pub focused: bool, /// Which modifier keys are down at the start of the frame? pub modifiers: Modifiers, // The keys that are currently being held down. pub keys_down: HashSet<Key>, /// In-order events received this frame pub events: Vec<Event>, /// Input state management configuration. /// /// This gets copied from `egui::Options` at the start of each frame for convenience. options: InputOptions, } impl Default for InputState { fn default() -> Self { Self { raw: Default::default(), pointer: Default::default(), touch_states: Default::default(), wheel: Default::default(), smooth_scroll_delta: Vec2::ZERO, zoom_factor_delta: 1.0, rotation_radians: 0.0, viewport_rect: Rect::from_min_size(Default::default(), vec2(10_000.0, 10_000.0)), safe_area_insets: Default::default(), pixels_per_point: 1.0, max_texture_side: 2048, time: 0.0, unstable_dt: 1.0 / 60.0, predicted_dt: 1.0 / 60.0, stable_dt: 1.0 / 60.0, focused: false, modifiers: Default::default(), keys_down: Default::default(), events: Default::default(), options: Default::default(), } } } impl InputState { #[must_use] pub fn begin_pass( mut self, mut new: RawInput, requested_immediate_repaint_prev_frame: bool, pixels_per_point: f32, options: InputOptions, ) -> Self { profiling::function_scope!(); let time = new.time.unwrap_or(self.time + new.predicted_dt as f64); let unstable_dt = (time - self.time) as f32; let stable_dt = if requested_immediate_repaint_prev_frame { // we should have had a repaint straight away, // so this should be trustable. unstable_dt } else { new.predicted_dt }; let safe_area_insets = new.safe_area_insets.unwrap_or(self.safe_area_insets); let viewport_rect = new.screen_rect.unwrap_or(self.viewport_rect); self.create_touch_states_for_new_devices(&new.events); for touch_state in self.touch_states.values_mut() { touch_state.begin_pass(time, &new, self.pointer.interact_pos); } let pointer = self.pointer.begin_pass(time, &new, options); let mut keys_down = self.keys_down; let mut zoom_factor_delta = 1.0; // TODO(emilk): smoothing for zoom factor let mut rotation_radians = 0.0; self.wheel.smooth_wheel_delta = Vec2::ZERO; for event in &mut new.events { match event { Event::Key { key, pressed, repeat, .. } => { if *pressed { let first_press = keys_down.insert(*key); *repeat = !first_press; } else { keys_down.remove(key); } } Event::MouseWheel { unit, delta, phase, modifiers, } => { self.wheel.on_wheel_event( viewport_rect, &options, time, *unit, *delta, *phase, *modifiers, ); } Event::Zoom(factor) => { zoom_factor_delta *= *factor; } Event::Rotate(radians) => { rotation_radians += *radians; } Event::WindowFocused(false) => { // Example: pressing `Cmd+S` brings up a save-dialog (e.g. using rfd), // but we get no key-up event for the `S` key (in winit). // This leads to `S` being mistakenly marked as down when we switch back to the app. // So we take the safe route and just clear all the keys and modifiers when // the app loses focus. keys_down.clear(); } _ => {} } } let mut smooth_scroll_delta = Vec2::ZERO; { let dt = stable_dt.at_most(0.1); self.wheel.after_events(time, dt); let is_zoom = self.wheel.modifiers.matches_any(options.zoom_modifier); if is_zoom { zoom_factor_delta *= (options.scroll_zoom_speed * (self.wheel.smooth_wheel_delta.x + self.wheel.smooth_wheel_delta.y)) .exp(); } else { smooth_scroll_delta = self.wheel.smooth_wheel_delta; } } Self { pointer, touch_states: self.touch_states, wheel: self.wheel, smooth_scroll_delta, zoom_factor_delta, rotation_radians, viewport_rect, safe_area_insets, pixels_per_point, max_texture_side: new.max_texture_side.unwrap_or(self.max_texture_side), time, unstable_dt, predicted_dt: new.predicted_dt, stable_dt, focused: new.focused, modifiers: new.modifiers, keys_down, events: new.events.clone(), // TODO(emilk): remove clone() and use raw.events raw: new, options, } } /// Info about the active viewport #[inline] pub fn viewport(&self) -> &ViewportInfo { self.raw.viewport() } /// Returns the region of the screen that is safe for content rendering /// /// Returns the `viewport_rect` with the `safe_area_insets` removed. /// /// If you want to render behind e.g. the dynamic island on iOS, use [`Self::viewport_rect`]. /// /// See also [`RawInput::safe_area_insets`]. #[inline(always)] pub fn content_rect(&self) -> Rect { self.viewport_rect - self.safe_area_insets } /// Returns the full area available to egui, including parts that might be partially covered, /// for example, by the OS status bar or notches (see [`Self::safe_area_insets`]). /// /// Usually you want to use [`Self::content_rect`] instead. /// /// This rectangle includes e.g. the dynamic island on iOS. /// If you want to only render _below_ the that (not behind), then you should use /// [`Self::content_rect`] instead. /// /// See also [`RawInput::safe_area_insets`]. pub fn viewport_rect(&self) -> Rect { self.viewport_rect } /// Position and size of the egui area. #[deprecated( note = "screen_rect has been split into viewport_rect() and content_rect(). You likely should use content_rect()" )] pub fn screen_rect(&self) -> Rect { self.content_rect() } /// Get the safe area insets. /// /// This represents the area of the screen covered by status bars, navigation controls, notches, /// or other items that obscure part of the screen. /// /// See [`Self::content_rect`] to get the `viewport_rect` with the safe area insets removed. pub fn safe_area_insets(&self) -> SafeAreaInsets { self.safe_area_insets } /// How many points the user scrolled, smoothed over a few frames. /// /// The delta dictates how the _content_ should move. /// /// A positive X-value indicates the content is being moved right, /// as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, /// as when swiping down on a touch-screen or track-pad with natural scrolling. /// /// [`crate::ScrollArea`] will both read and write to this field, so that /// at the end of the frame this will be zero if a scroll-area consumed the delta. pub fn smooth_scroll_delta(&self) -> Vec2 { self.smooth_scroll_delta } /// Uniform zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture). /// * `zoom = 1`: no change /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread /// /// If your application supports non-proportional zooming, /// then you probably want to use [`Self::zoom_delta_2d`] instead. #[inline(always)] pub fn zoom_delta(&self) -> f32 { // If a multi touch gesture is detected, it measures the exact and linear proportions of // the distances of the finger tips. It is therefore potentially more accurate than // `zoom_factor_delta` which is based on the `ctrl-scroll` event which, in turn, may be // synthesized from an original touch gesture. self.multi_touch() .map_or(self.zoom_factor_delta, |touch| touch.zoom_delta) } /// 2D non-proportional zoom scale factor this frame (e.g. from ctrl-scroll or pinch gesture). /// /// For multitouch devices the user can do a horizontal or vertical pinch gesture. /// In these cases a non-proportional zoom factor is a available. /// In other cases, this reverts to `Vec2::splat(self.zoom_delta())`. /// /// For horizontal pinches, this will return `[z, 1]`, /// for vertical pinches this will return `[1, z]`, /// and otherwise this will return `[z, z]`, /// where `z` is the zoom factor: /// * `zoom = 1`: no change /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread #[inline(always)] pub fn zoom_delta_2d(&self) -> Vec2 { // If a multi touch gesture is detected, it measures the exact and linear proportions of // the distances of the finger tips. It is therefore potentially more accurate than // `zoom_factor_delta` which is based on the `ctrl-scroll` event which, in turn, may be // synthesized from an original touch gesture. if let Some(multi_touch) = self.multi_touch() { multi_touch.zoom_delta_2d } else { let mut zoom = Vec2::splat(self.zoom_factor_delta); let is_horizontal = self .modifiers .matches_any(self.options.horizontal_scroll_modifier); let is_vertical = self .modifiers .matches_any(self.options.vertical_scroll_modifier); if is_horizontal && !is_vertical { // Horizontal-only zooming. zoom.y = 1.0; } if !is_horizontal && is_vertical { // Vertical-only zooming. zoom.x = 1.0; } zoom } } /// Rotation in radians this frame, measuring clockwise (e.g. from a rotation gesture). #[inline(always)] pub fn rotation_delta(&self) -> f32 { self.multi_touch() .map_or(self.rotation_radians, |touch| touch.rotation_delta) } /// Panning translation in pixels this frame (e.g. from scrolling or a pan gesture) /// /// The delta indicates how the **content** should move. /// /// A positive X-value indicates the content is being moved right, as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, as when swiping down on a touch-screen or track-pad with natural scrolling. #[inline(always)] pub fn translation_delta(&self) -> Vec2 { self.multi_touch().map_or_else( || self.smooth_scroll_delta(), |touch| touch.translation_delta, ) } /// True if there is an active scroll action that might scroll more when using [`Self::smooth_scroll_delta`]. pub fn is_scrolling(&self) -> bool { self.wheel.is_scrolling() } /// How long has it been (in seconds) since the last scroll event? #[inline(always)] pub fn time_since_last_scroll(&self) -> f32 { (self.time - self.wheel.last_wheel_event) as f32 } /// The [`crate::Context`] will call this at the beginning of each frame to see if we need a repaint. /// /// Returns how long to wait for a repaint. /// /// NOTE: It's important to call this immediately after [`Self::begin_pass`] since calls to /// [`Self::consume_key`] will remove events from the vec, meaning those key presses wouldn't /// cause a repaint. pub(crate) fn wants_repaint_after(&self) -> Option<Duration> { if self.pointer.wants_repaint() || self.wheel.unprocessed_wheel_delta.abs().max_elem() > 0.2 || !self.events.is_empty() { // Immediate repaint return Some(Duration::ZERO); } if self.any_touches() && !self.pointer.is_decidedly_dragging() { // We need to wake up and check for press-and-hold for the context menu. if let Some(press_start_time) = self.pointer.press_start_time { let press_duration = self.time - press_start_time; if self.options.max_click_duration.is_finite() && press_duration < self.options.max_click_duration { let secs_until_menu = self.options.max_click_duration - press_duration; return Some(Duration::from_secs_f64(secs_until_menu)); } } } None } /// Count presses of a key. If non-zero, the presses are consumed, so that this will only return non-zero once. /// /// Includes key-repeat events. /// /// This uses [`Modifiers::matches_logically`] to match modifiers, /// meaning extra Shift and Alt modifiers are ignored. /// Therefore, you should match most specific shortcuts first, /// i.e. check for `Cmd-Shift-S` ("Save as…") before `Cmd-S` ("Save"), /// so that a user pressing `Cmd-Shift-S` won't trigger the wrong command! pub fn count_and_consume_key(&mut self, modifiers: Modifiers, logical_key: Key) -> usize { let mut count = 0usize; self.events.retain(|event| { let is_match = matches!( event, Event::Key { key: ev_key, modifiers: ev_mods, pressed: true, .. } if *ev_key == logical_key && ev_mods.matches_logically(modifiers) ); count += is_match as usize; !is_match }); count } /// Check for a key press. If found, `true` is returned and the key pressed is consumed, so that this will only return `true` once. /// /// Includes key-repeat events. /// /// This uses [`Modifiers::matches_logically`] to match modifiers, /// meaning extra Shift and Alt modifiers are ignored. /// Therefore, you should match most specific shortcuts first, /// i.e. check for `Cmd-Shift-S` ("Save as…") before `Cmd-S` ("Save"), /// so that a user pressing `Cmd-Shift-S` won't trigger the wrong command! pub fn consume_key(&mut self, modifiers: Modifiers, logical_key: Key) -> bool { self.count_and_consume_key(modifiers, logical_key) > 0 } /// Check if the given shortcut has been pressed. /// /// If so, `true` is returned and the key pressed is consumed, so that this will only return `true` once. /// /// This uses [`Modifiers::matches_logically`] to match modifiers, /// meaning extra Shift and Alt modifiers are ignored. /// Therefore, you should match most specific shortcuts first, /// i.e. check for `Cmd-Shift-S` ("Save as…") before `Cmd-S` ("Save"), /// so that a user pressing `Cmd-Shift-S` won't trigger the wrong command! pub fn consume_shortcut(&mut self, shortcut: &KeyboardShortcut) -> bool { let KeyboardShortcut { modifiers, logical_key, } = *shortcut; self.consume_key(modifiers, logical_key) } /// Was the given key pressed this frame? /// /// Includes key-repeat events. pub fn key_pressed(&self, desired_key: Key) -> bool { self.num_presses(desired_key) > 0 } /// How many times was the given key pressed this frame? /// /// Includes key-repeat events. pub fn num_presses(&self, desired_key: Key) -> usize { self.events .iter() .filter(|event| { matches!( event, Event::Key { key, pressed: true, .. } if *key == desired_key ) }) .count() } /// Is the given key currently held down? pub fn key_down(&self, desired_key: Key) -> bool { self.keys_down.contains(&desired_key) } /// Was the given key released this frame? pub fn key_released(&self, desired_key: Key) -> bool { self.events.iter().any(|event| { matches!( event, Event::Key { key, pressed: false, .. } if *key == desired_key ) }) } /// Also known as device pixel ratio, > 1 for high resolution screens. #[inline(always)] pub fn pixels_per_point(&self) -> f32 { self.pixels_per_point } /// Size of a physical pixel in logical gui coordinates (points). #[inline(always)] pub fn physical_pixel_size(&self) -> f32 { 1.0 / self.pixels_per_point() } /// How imprecise do we expect the mouse/touch input to be? /// Returns imprecision in points. #[inline(always)] pub fn aim_radius(&self) -> f32 { // TODO(emilk): multiply by ~3 for touch inputs because fingers are fat self.physical_pixel_size() } /// Returns details about the currently ongoing multi-touch gesture, if any. Note that this /// method returns `None` for single-touch gestures (click, drag, …). /// /// ``` /// # use egui::emath::Rot2; /// # egui::__run_test_ui(|ui| { /// let mut zoom = 1.0; // no zoom /// let mut rotation = 0.0; // no rotation /// let multi_touch = ui.input(|i| i.multi_touch()); /// if let Some(multi_touch) = multi_touch { /// zoom *= multi_touch.zoom_delta; /// rotation += multi_touch.rotation_delta; /// } /// let transform = zoom * Rot2::from_angle(rotation); /// # }); /// ``` /// /// By far not all touch devices are supported, and the details depend on the `egui` /// integration backend you are using. `eframe` web supports multi touch for most mobile /// devices, but not for a `Trackpad` on `MacOS`, for example. The backend has to be able to /// capture native touch events, but many browsers seem to pass such events only for touch /// _screens_, but not touch _pads._ /// /// Refer to [`MultiTouchInfo`] for details about the touch information available. /// /// Consider using `zoom_delta()` instead of `MultiTouchInfo::zoom_delta` as the former /// delivers a synthetic zoom factor based on ctrl-scroll events, as a fallback. pub fn multi_touch(&self) -> Option<MultiTouchInfo> { // In case of multiple touch devices simply pick the touch_state of the first active device self.touch_states.values().find_map(|t| t.info()) } /// True if there currently are any fingers touching egui. pub fn any_touches(&self) -> bool { self.touch_states.values().any(|t| t.any_touches()) } /// True if we have ever received a touch event. pub fn has_touch_screen(&self) -> bool { !self.touch_states.is_empty() } /// Scans `events` for device IDs of touch devices we have not seen before, /// and creates a new [`TouchState`] for each such device. fn create_touch_states_for_new_devices(&mut self, events: &[Event]) { for event in events { if let Event::Touch { device_id, .. } = event { self.touch_states .entry(*device_id) .or_insert_with(|| TouchState::new(*device_id)); } } } pub fn accesskit_action_requests( &self, id: crate::Id, action: accesskit::Action,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/input_state/wheel_state.rs
crates/egui/src/input_state/wheel_state.rs
use emath::{Rect, Vec2, vec2}; use crate::{InputOptions, Modifiers, MouseWheelUnit, TouchPhase}; /// The current state of scrolling. /// /// There are two important types of scroll input deviced: /// * Discreen scroll wheels on a mouse /// * Smooth scroll input from a trackpad /// /// Scroll wheels will usually fire one single scroll event, /// so it is important that egui smooths it out over time. /// /// On the contrary, trackpads usually provide smooth scroll input, /// and with kinetic scrolling (which on Mac is implemented by the OS) /// scroll events can arrive _after_ the user lets go of the trackpad. /// /// In either case, we consider use to be scrolling until there is no more /// scroll events expected. /// /// This means there are a few different states we can be in: /// * Not scrolling /// * "Smooth scrolling" (low-pass filter of discreet scroll events) /// * Trackpad-scrolling (we receive begin/end phases for these) #[derive(Clone, Debug, PartialEq, Eq)] pub enum Status { /// Not scrolling, Static, /// We're smoothing out previous scroll events Smoothing, // We're in-between [`TouchPhase::Start`] and [`TouchPhase::End`] of a trackpad scroll. InTouch, } /// Keeps track of wheel (scroll) input. #[derive(Clone, Debug)] pub struct WheelState { /// Are we currently in a scroll action? /// /// This may be true even if no scroll events came in this frame, /// but we are in a kinetic scroll or in a smoothed scroll. pub status: Status, /// The modifiers at the start of the scroll. pub modifiers: Modifiers, /// Time of the last scroll event. pub last_wheel_event: f64, /// Used for smoothing the scroll delta. pub unprocessed_wheel_delta: Vec2, /// How many points the user scrolled, smoothed over a few frames. /// /// The delta dictates how the _content_ should move. /// /// A positive X-value indicates the content is being moved right, /// as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, /// as when swiping down on a touch-screen or track-pad with natural scrolling. /// /// [`crate::ScrollArea`] will both read and write to this field, so that /// at the end of the frame this will be zero if a scroll-area consumed the delta. pub smooth_wheel_delta: Vec2, } impl Default for WheelState { fn default() -> Self { Self { status: Status::Static, modifiers: Default::default(), last_wheel_event: f64::NEG_INFINITY, unprocessed_wheel_delta: Vec2::ZERO, smooth_wheel_delta: Vec2::ZERO, } } } impl WheelState { #[expect(clippy::too_many_arguments)] pub fn on_wheel_event( &mut self, viewport_rect: Rect, options: &InputOptions, time: f64, unit: MouseWheelUnit, delta: Vec2, phase: TouchPhase, latest_modifiers: Modifiers, ) { self.last_wheel_event = time; match phase { crate::TouchPhase::Start => { self.status = Status::InTouch; self.modifiers = latest_modifiers; } crate::TouchPhase::Move => { match self.status { Status::Static | Status::Smoothing => { self.modifiers = latest_modifiers; self.status = Status::Smoothing; } Status::InTouch => { // If the user lets go of a modifier - ignore it. // More kinematic scrolling may arrive. // But if the users presses down new modifiers - heed it! self.modifiers |= latest_modifiers; } } let mut delta = match unit { MouseWheelUnit::Point => delta, MouseWheelUnit::Line => options.line_scroll_speed * delta, MouseWheelUnit::Page => viewport_rect.height() * delta, }; let is_horizontal = self .modifiers .matches_any(options.horizontal_scroll_modifier); let is_vertical = self.modifiers.matches_any(options.vertical_scroll_modifier); if is_horizontal && !is_vertical { // Treat all scrolling as horizontal scrolling. // Note: one Mac we already get horizontal scroll events when shift is down. delta = vec2(delta.x + delta.y, 0.0); } if !is_horizontal && is_vertical { // Treat all scrolling as vertical scrolling. delta = vec2(0.0, delta.x + delta.y); } // Mouse wheels often go very large steps. // A single notch on a logitech mouse wheel connected to a Macbook returns 14.0 raw scroll delta. // So we smooth it out over several frames for a nicer user experience when scrolling in egui. // BUT: if the user is using a nice smooth mac trackpad, we don't add smoothing, // because it adds latency. let is_smooth = self.status == Status::InTouch || match unit { MouseWheelUnit::Point => delta.length() < 8.0, // a bit arbitrary here MouseWheelUnit::Line | MouseWheelUnit::Page => false, }; if is_smooth { self.smooth_wheel_delta += delta; } else { self.unprocessed_wheel_delta += delta; } } crate::TouchPhase::End | crate::TouchPhase::Cancel => { self.status = Status::Static; self.modifiers = Default::default(); self.unprocessed_wheel_delta = Default::default(); self.smooth_wheel_delta = Default::default(); } } } pub fn after_events(&mut self, time: f64, dt: f32) { let t = crate::emath::exponential_smooth_factor(0.90, 0.1, dt); // reach _% in _ seconds. TODO(emilk): parameterize if self.unprocessed_wheel_delta != Vec2::ZERO { for d in 0..2 { if self.unprocessed_wheel_delta[d].abs() < 1.0 { self.smooth_wheel_delta[d] += self.unprocessed_wheel_delta[d]; self.unprocessed_wheel_delta[d] = 0.0; } else { let applied = t * self.unprocessed_wheel_delta[d]; self.smooth_wheel_delta[d] += applied; self.unprocessed_wheel_delta[d] -= applied; } } } let time_since_last_scroll = time - self.last_wheel_event; if self.status == Status::Smoothing && self.smooth_wheel_delta == Vec2::ZERO && 0.150 < time_since_last_scroll { // On certain platforms, like web, we don't get the start & stop scrolling events, so // we rely on a timer there. // // Tested on a mac touchpad 2025, where the largest observed gap between scroll events // was 68 ms. But we add some margin to be safe self.status = Status::Static; self.modifiers = Default::default(); } } /// True if there is an active scroll action that might scroll more when using [`Self::smooth_wheel_delta`]. pub fn is_scrolling(&self) -> bool { self.status != Status::Static } pub fn ui(&self, ui: &mut crate::Ui) { let Self { status, modifiers, last_wheel_event, unprocessed_wheel_delta, smooth_wheel_delta, } = self; let time = ui.input(|i| i.time); crate::Grid::new("ScrollState") .num_columns(2) .show(ui, |ui| { ui.label("status"); ui.monospace(format!("{status:?}")); ui.end_row(); ui.label("modifiers"); ui.monospace(format!("{modifiers:?}")); ui.end_row(); ui.label("last_wheel_event"); ui.monospace(format!("{:.1}s ago", time - *last_wheel_event)); ui.end_row(); ui.label("unprocessed_wheel_delta"); ui.monospace(unprocessed_wheel_delta.to_string()); ui.end_row(); ui.label("smooth_wheel_delta"); ui.monospace(smooth_wheel_delta.to_string()); ui.end_row(); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/cache/cache_storage.rs
crates/egui/src/cache/cache_storage.rs
use super::CacheTrait; /// A typemap of many caches, all implemented with [`CacheTrait`]. /// /// You can access egui's caches via [`crate::Memory::caches`], /// found with [`crate::Context::memory_mut`]. /// /// ``` /// use egui::cache::{CacheStorage, ComputerMut, FrameCache}; /// /// #[derive(Default)] /// struct CharCounter {} /// impl ComputerMut<&str, usize> for CharCounter { /// fn compute(&mut self, s: &str) -> usize { /// s.chars().count() /// } /// } /// type CharCountCache<'a> = FrameCache<usize, CharCounter>; /// /// # let mut cache_storage = CacheStorage::default(); /// let mut cache = cache_storage.cache::<CharCountCache<'_>>(); /// assert_eq!(cache.get("hello"), 5); /// ``` #[derive(Default)] pub struct CacheStorage { caches: ahash::HashMap<std::any::TypeId, Box<dyn CacheTrait>>, } impl CacheStorage { pub fn cache<Cache: CacheTrait + Default>(&mut self) -> &mut Cache { #[expect(clippy::unwrap_used)] self.caches .entry(std::any::TypeId::of::<Cache>()) .or_insert_with(|| Box::<Cache>::default()) .as_any_mut() .downcast_mut::<Cache>() .unwrap() } /// Total number of cached values fn num_values(&self) -> usize { self.caches.values().map(|cache| cache.len()).sum() } /// Call once per frame to evict cache. pub fn update(&mut self) { self.caches.retain(|_, cache| { cache.update(); cache.len() > 0 }); } } impl Clone for CacheStorage { fn clone(&self) -> Self { // We return an empty cache that can be filled in again. Self::default() } } impl std::fmt::Debug for CacheStorage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "FrameCacheStorage[{} caches with {} elements]", self.caches.len(), self.num_values() ) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/cache/cache_trait.rs
crates/egui/src/cache/cache_trait.rs
/// A cache, storing some value for some length of time. #[expect(clippy::len_without_is_empty)] pub trait CacheTrait: 'static + Send + Sync { /// Call once per frame to evict cache. fn update(&mut self); /// Number of values currently in the cache. fn len(&self) -> usize; fn as_any_mut(&mut self) -> &mut dyn std::any::Any; }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/cache/frame_publisher.rs
crates/egui/src/cache/frame_publisher.rs
use std::hash::Hash; use super::CacheTrait; /// Stores a key:value pair for the duration of this frame and the next. pub struct FramePublisher<Key: Eq + Hash, Value> { generation: u32, cache: ahash::HashMap<Key, (u32, Value)>, } impl<Key: Eq + Hash, Value> Default for FramePublisher<Key, Value> { fn default() -> Self { Self::new() } } impl<Key: Eq + Hash, Value> FramePublisher<Key, Value> { pub fn new() -> Self { Self { generation: 0, cache: Default::default(), } } /// Publish the value. It will be available for the duration of this and the next frame. pub fn set(&mut self, key: Key, value: Value) { self.cache.insert(key, (self.generation, value)); } /// Retrieve a value if it was published this or the previous frame. pub fn get(&self, key: &Key) -> Option<&Value> { self.cache.get(key).map(|(_, value)| value) } /// Must be called once per frame to clear the cache. pub fn evict_cache(&mut self) { let current_generation = self.generation; self.cache.retain(|_key, cached| { cached.0 == current_generation // only keep those that were published this frame }); self.generation = self.generation.wrapping_add(1); } } impl<Key, Value> CacheTrait for FramePublisher<Key, Value> where Key: 'static + Eq + Hash + Send + Sync, Value: 'static + Send + Sync, { fn update(&mut self) { self.evict_cache(); } fn len(&self) -> usize { self.cache.len() } fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/cache/mod.rs
crates/egui/src/cache/mod.rs
//! Caches for preventing the same value from being recomputed every frame. //! //! Computing the same thing each frame can be expensive, //! so often you want to save the result from the previous frame and reuse it. //! //! Enter [`FrameCache`]: it caches the results of a computation for one frame. //! If it is still used next frame, it is not recomputed. //! If it is not used next frame, it is evicted from the cache to save memory. //! //! You can access egui's caches via [`crate::Memory::caches`], //! found with [`crate::Context::memory_mut`]. mod cache_storage; mod cache_trait; mod frame_cache; mod frame_publisher; pub use cache_storage::CacheStorage; pub use cache_trait::CacheTrait; pub use frame_cache::{ComputerMut, FrameCache}; pub use frame_publisher::FramePublisher;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/cache/frame_cache.rs
crates/egui/src/cache/frame_cache.rs
use super::CacheTrait; /// Something that does an expensive computation that we want to cache /// to save us from recomputing it each frame. pub trait ComputerMut<Key, Value>: 'static + Send + Sync { fn compute(&mut self, key: Key) -> Value; } /// Caches the results of a computation for one frame. /// If it is still used next frame, it is not recomputed. /// If it is not used next frame, it is evicted from the cache to save memory. pub struct FrameCache<Value, Computer> { generation: u32, computer: Computer, cache: nohash_hasher::IntMap<u64, (u32, Value)>, } impl<Value, Computer> Default for FrameCache<Value, Computer> where Computer: Default, { fn default() -> Self { Self::new(Computer::default()) } } impl<Value, Computer> FrameCache<Value, Computer> { pub fn new(computer: Computer) -> Self { Self { generation: 0, computer, cache: Default::default(), } } /// Must be called once per frame to clear the cache. pub fn evict_cache(&mut self) { let current_generation = self.generation; self.cache.retain(|_key, cached| { cached.0 == current_generation // only keep those that were used this frame }); self.generation = self.generation.wrapping_add(1); } } impl<Value, Computer> FrameCache<Value, Computer> { /// Get from cache (if the same key was used last frame) /// or recompute and store in the cache. pub fn get<Key>(&mut self, key: Key) -> Value where Key: Copy + std::hash::Hash, Value: Clone, Computer: ComputerMut<Key, Value>, { let hash = crate::util::hash(key); match self.cache.entry(hash) { std::collections::hash_map::Entry::Occupied(entry) => { let cached = entry.into_mut(); cached.0 = self.generation; cached.1.clone() } std::collections::hash_map::Entry::Vacant(entry) => { let value = self.computer.compute(key); entry.insert((self.generation, value.clone())); value } } } } impl<Value: 'static + Send + Sync, Computer: 'static + Send + Sync> CacheTrait for FrameCache<Value, Computer> { fn update(&mut self) { self.evict_cache(); } fn len(&self) -> usize { self.cache.len() } fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/memory/theme.rs
crates/egui/src/memory/theme.rs
use crate::Button; /// Dark or Light theme. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Theme { /// Dark mode: light text on a dark background. Dark, /// Light mode: dark text on a light background. Light, } impl Theme { /// Default visuals for this theme. pub fn default_visuals(self) -> crate::Visuals { match self { Self::Dark => crate::Visuals::dark(), Self::Light => crate::Visuals::light(), } } /// Default style for this theme. pub fn default_style(self) -> crate::Style { crate::Style { visuals: self.default_visuals(), ..Default::default() } } /// Chooses between [`Self::Dark`] or [`Self::Light`] based on a boolean value. pub fn from_dark_mode(dark_mode: bool) -> Self { if dark_mode { Self::Dark } else { Self::Light } } } impl Theme { /// Show small toggle-button for light and dark mode. /// This is not the best design as it doesn't allow switching back to "follow system". #[must_use] pub(crate) fn small_toggle_button(self, ui: &mut crate::Ui) -> Option<Self> { #![expect(clippy::collapsible_else_if)] if self == Self::Dark { if ui .add(Button::new("☀").frame(false)) .on_hover_text("Switch to light mode") .clicked() { return Some(Self::Light); } } else { if ui .add(Button::new("🌙").frame(false)) .on_hover_text("Switch to dark mode") .clicked() { return Some(Self::Dark); } } None } } /// The user's theme preference. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ThemePreference { /// Dark mode: light text on a dark background. Dark, /// Light mode: dark text on a light background. Light, /// Follow the system's theme preference. #[default] System, } impl From<Theme> for ThemePreference { fn from(value: Theme) -> Self { match value { Theme::Dark => Self::Dark, Theme::Light => Self::Light, } } } impl ThemePreference { /// Show radio-buttons to switch between light mode, dark mode and following the system theme. pub fn radio_buttons(&mut self, ui: &mut crate::Ui) { ui.horizontal(|ui| { let system_theme = ui.input(|i| i.raw.system_theme); ui.selectable_value(self, Self::System, "💻 System") .on_hover_ui(|ui| { ui.label("Follow the system theme preference."); ui.add_space(4.0); if let Some(system_theme) = system_theme { ui.label(format!( "The current system theme is: {}", match system_theme { Theme::Dark => "dark", Theme::Light => "light", } )); } else { ui.label("The system theme is unknown."); } }); ui.selectable_value(self, Self::Dark, "🌙 Dark") .on_hover_text("Use the dark mode theme"); ui.selectable_value(self, Self::Light, "☀ Light") .on_hover_text("Use the light mode theme"); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/memory/mod.rs
crates/egui/src/memory/mod.rs
#![warn(missing_docs)] // Let's keep this file well-documented.` to memory.rs use std::num::NonZeroUsize; use ahash::{HashMap, HashSet}; use epaint::emath::TSTransform; use crate::{ EventFilter, Id, IdMap, LayerId, Order, Pos2, Rangef, RawInput, Rect, Style, Vec2, ViewportId, ViewportIdMap, ViewportIdSet, area, vec2, }; mod theme; pub use theme::{Theme, ThemePreference}; // ---------------------------------------------------------------------------- /// The data that egui persists between frames. /// /// This includes window positions and sizes, /// how far the user has scrolled in a [`ScrollArea`](crate::ScrollArea) etc. /// /// If you want this to persist when closing your app, you should serialize [`Memory`] and store it. /// For this you need to enable the `persistence` feature. /// /// If you want to store data for your widgets, you should look at [`Memory::data`] #[derive(Clone, Debug)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "persistence", serde(default))] pub struct Memory { /// Global egui options. pub options: Options, /// This map stores some superficial state for all widgets with custom [`Id`]s. /// /// This includes storing whether a [`crate::CollapsingHeader`] is open, how far scrolled a /// [`crate::ScrollArea`] is, where the cursor in a [`crate::TextEdit`] is, etc. /// /// This is NOT meant to store any important data. Store that in your own structures! /// /// Each read clones the data, so keep your values cheap to clone. /// If you want to store a lot of data, you should wrap it in `Arc<Mutex<…>>` so it is cheap to clone. /// /// This will be saved between different program runs if you use the `persistence` feature. /// /// To store a state common for all your widgets (a singleton), use [`Id::NULL`] as the key. pub data: crate::util::IdTypeMap, // ------------------------------------------ /// Can be used to cache computations from one frame to another. /// /// This is for saving CPU time when you have something that may take 1-100ms to compute. /// Very slow operations (>100ms) should instead be done async (i.e. in another thread) /// so as not to lock the UI thread. /// /// ``` /// use egui::cache::{ComputerMut, FrameCache}; /// /// #[derive(Default)] /// struct CharCounter {} /// impl ComputerMut<&str, usize> for CharCounter { /// fn compute(&mut self, s: &str) -> usize { /// s.chars().count() // you probably want to cache something more expensive than this /// } /// } /// type CharCountCache<'a> = FrameCache<usize, CharCounter>; /// /// # let mut ctx = egui::Context::default(); /// ctx.memory_mut(|mem| { /// let cache = mem.caches.cache::<CharCountCache<'_>>(); /// assert_eq!(cache.get("hello"), 5); /// }); /// ``` #[cfg_attr(feature = "persistence", serde(skip))] pub caches: crate::cache::CacheStorage, // ------------------------------------------ /// new fonts that will be applied at the start of the next frame #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) new_font_definitions: Option<epaint::text::FontDefinitions>, /// add new font that will be applied at the start of the next frame #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) add_fonts: Vec<epaint::text::FontInsert>, // Current active viewport #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) viewport_id: ViewportId, #[cfg_attr(feature = "persistence", serde(skip))] everything_is_visible: bool, /// Transforms per layer. /// /// Instead of using this directly, use: /// * [`crate::Context::set_transform_layer`] /// * [`crate::Context::layer_transform_to_global`] /// * [`crate::Context::layer_transform_from_global`] pub to_global: HashMap<LayerId, TSTransform>, // ------------------------------------------------- // Per-viewport: areas: ViewportIdMap<Areas>, #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) interactions: ViewportIdMap<InteractionState>, #[cfg_attr(feature = "persistence", serde(skip))] pub(crate) focus: ViewportIdMap<Focus>, /// Which popup-window is open on a viewport (if any)? /// Could be a combo box, color picker, menu, etc. /// Optionally stores the position of the popup (usually this would be the position where /// the user clicked). /// If position is [`None`], the popup position will be calculated based on some configuration /// (e.g. relative to some other widget). #[cfg_attr(feature = "persistence", serde(skip))] popups: ViewportIdMap<OpenPopup>, } impl Default for Memory { fn default() -> Self { let mut slf = Self { options: Default::default(), data: Default::default(), caches: Default::default(), new_font_definitions: Default::default(), interactions: Default::default(), focus: Default::default(), viewport_id: Default::default(), areas: Default::default(), to_global: Default::default(), popups: Default::default(), everything_is_visible: Default::default(), add_fonts: Default::default(), }; slf.interactions.entry(slf.viewport_id).or_default(); slf.areas.entry(slf.viewport_id).or_default(); slf } } /// A direction in which to move the keyboard focus. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum FocusDirection { /// Select the widget closest above the current focused widget. Up, /// Select the widget to the right of the current focused widget. Right, /// Select the widget below the current focused widget. Down, /// Select the widget to the left of the current focused widget. Left, /// Select the previous widget that had focus. Previous, /// Select the next widget that wants focus. Next, /// Don't change focus. #[default] None, } impl FocusDirection { fn is_cardinal(&self) -> bool { match self { Self::Up | Self::Right | Self::Down | Self::Left => true, Self::Previous | Self::Next | Self::None => false, } } } // ---------------------------------------------------------------------------- /// Some global options that you can read and write. /// /// See also [`crate::style::DebugOptions`]. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Options { /// The default style for new [`Ui`](crate::Ui):s in dark mode. #[cfg_attr(feature = "serde", serde(skip))] pub dark_style: std::sync::Arc<Style>, /// The default style for new [`Ui`](crate::Ui):s in light mode. #[cfg_attr(feature = "serde", serde(skip))] pub light_style: std::sync::Arc<Style>, /// Preference for selection between dark and light [`crate::Context::style`] /// as the active style used by all subsequent windows, panels, etc. /// /// Default: `ThemePreference::System`. pub theme_preference: ThemePreference, /// Which theme to use in case [`Self::theme_preference`] is [`ThemePreference::System`] /// and egui fails to detect the system theme. /// /// Default: [`crate::Theme::Dark`]. pub fallback_theme: Theme, /// The current system theme, used to choose between /// dark and light style in case [`Self::theme_preference`] is [`ThemePreference::System`]. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) system_theme: Option<Theme>, /// Global zoom factor of the UI. /// /// This is used to calculate the `pixels_per_point` /// for the UI as `pixels_per_point = zoom_fator * native_pixels_per_point`. /// /// The default is 1.0. Increase it to make all UI elements larger. /// /// You should call [`crate::Context::set_zoom_factor`] /// instead of modifying this directly! pub zoom_factor: f32, /// If `true`, egui will change the scale of the ui ([`crate::Context::zoom_factor`]) when the user /// presses Cmd+Plus, Cmd+Minus or Cmd+0, just like in a browser. /// /// This is `true` by default. /// /// On the web-backend of `eframe` this is set to false by default, /// so that the zoom shortcuts are handled exclusively by the browser, /// which will change the `native_pixels_per_point` (`devicePixelRatio`). /// You can still zoom egui independently by calling [`crate::Context::set_zoom_factor`], /// which will be applied on top of the browsers global zoom. #[cfg_attr(feature = "serde", serde(skip))] pub zoom_with_keyboard: bool, /// Controls the tessellator. pub tessellation_options: epaint::TessellationOptions, /// If any widget moves or changes id, repaint everything. /// /// It is recommended you keep this OFF, as it may /// lead to endless repaints for an unknown reason. See /// (<https://github.com/rerun-io/rerun/issues/5018>). pub repaint_on_widget_change: bool, /// Maximum number of passes to run in one frame. /// /// Set to `1` for pure single-pass immediate mode. /// Set to something larger than `1` to allow multi-pass when needed. /// /// Default is `2`. This means sometimes a frame will cost twice as much, /// but usually only rarely (e.g. when showing a new panel for the first time). /// /// egui will usually only ever run one pass, even if `max_passes` is large. /// /// If this is `1`, [`crate::Context::request_discard`] will be ignored. /// /// Multi-pass is supported by [`crate::Context::run`]. /// /// See [`crate::Context::request_discard`] for more. pub max_passes: NonZeroUsize, /// This is a signal to any backend that we want the [`crate::PlatformOutput::events`] read out loud. /// /// The only change to egui is that labels can be focused by pressing tab. /// /// Screen readers are an experimental feature of egui, and not supported on all platforms. /// `eframe` only supports it on web. /// /// Consider using [AccessKit](https://github.com/AccessKit/accesskit) instead, /// which is supported by `eframe`. pub screen_reader: bool, /// Check reusing of [`Id`]s, and show a visual warning on screen when one is found. /// /// By default this is `true` in debug builds. pub warn_on_id_clash: bool, /// Options related to input state handling. pub input_options: crate::input_state::InputOptions, /// If `true`, `egui` will discard the loaded image data after /// the texture is loaded onto the GPU to reduce memory usage. /// /// In modern GPU rendering, the texture data is not required after the texture is loaded. /// /// This is beneficial when using a large number or resolution of images and there is no need to /// retain the image data, potentially saving a significant amount of memory. /// /// The drawback is that it becomes impossible to serialize the loaded images or render in non-GPU systems. /// /// Default is `false`. pub reduce_texture_memory: bool, } impl Default for Options { fn default() -> Self { Self { dark_style: std::sync::Arc::new(Theme::Dark.default_style()), light_style: std::sync::Arc::new(Theme::Light.default_style()), theme_preference: Default::default(), fallback_theme: Theme::Dark, system_theme: None, zoom_factor: 1.0, zoom_with_keyboard: true, tessellation_options: Default::default(), repaint_on_widget_change: false, #[expect(clippy::unwrap_used)] max_passes: NonZeroUsize::new(2).unwrap(), screen_reader: false, warn_on_id_clash: cfg!(debug_assertions), // Input: input_options: Default::default(), reduce_texture_memory: false, } } } impl Options { // Needs to be pub because we need to set the system_theme early in the eframe glow renderer. #[doc(hidden)] pub fn begin_pass(&mut self, new_raw_input: &RawInput) { self.system_theme = new_raw_input.system_theme; } /// The currently active theme (may depend on the system theme). pub(crate) fn theme(&self) -> Theme { match self.theme_preference { ThemePreference::Dark => Theme::Dark, ThemePreference::Light => Theme::Light, ThemePreference::System => self.system_theme.unwrap_or(self.fallback_theme), } } pub(crate) fn style(&self) -> &std::sync::Arc<Style> { match self.theme() { Theme::Dark => &self.dark_style, Theme::Light => &self.light_style, } } pub(crate) fn style_mut(&mut self) -> &mut std::sync::Arc<Style> { match self.theme() { Theme::Dark => &mut self.dark_style, Theme::Light => &mut self.light_style, } } } impl Options { /// Show the options in the ui. pub fn ui(&mut self, ui: &mut crate::Ui) { let theme = self.theme(); let Self { dark_style, // covered above light_style, theme_preference, fallback_theme: _, system_theme: _, zoom_factor, zoom_with_keyboard, tessellation_options, repaint_on_widget_change, max_passes, screen_reader: _, // needs to come from the integration warn_on_id_clash, input_options, reduce_texture_memory, } = self; use crate::Widget as _; use crate::containers::CollapsingHeader; CollapsingHeader::new("⚙ Options") .default_open(false) .show(ui, |ui| { ui.horizontal(|ui| { ui.label("Max passes:"); ui.add(crate::DragValue::new(max_passes).range(0..=10)); }); ui.checkbox( repaint_on_widget_change, "Repaint if any widget moves or changes id", ); ui.horizontal(|ui| { ui.label("Zoom factor:"); ui.add(crate::DragValue::new(zoom_factor).range(0.10..=10.0)); }); ui.checkbox( zoom_with_keyboard, "Zoom with keyboard (Cmd +, Cmd -, Cmd 0)", ); ui.checkbox(warn_on_id_clash, "Warn if two widgets have the same Id"); ui.checkbox(reduce_texture_memory, "Reduce texture memory"); }); CollapsingHeader::new("🎑 Style") .default_open(true) .show(ui, |ui| { theme_preference.radio_buttons(ui); let style = std::sync::Arc::make_mut(match theme { Theme::Dark => dark_style, Theme::Light => light_style, }); style.ui(ui); }); CollapsingHeader::new("✒ Painting") .default_open(false) .show(ui, |ui| { tessellation_options.ui(ui); ui.vertical_centered(|ui| { crate::reset_button(ui, tessellation_options, "Reset paint settings"); }); }); CollapsingHeader::new("🖱 Input") .default_open(false) .show(ui, |ui| { input_options.ui(ui); }); ui.vertical_centered(|ui| crate::reset_button(ui, self, "Reset all")); } } // ---------------------------------------------------------------------------- /// The state of the interaction in egui, /// i.e. what is being dragged. /// /// Say there is a button in a scroll area. /// If the user clicks the button, the button should click. /// If the user drags the button we should scroll the scroll area. /// Therefore, when the mouse is pressed, we register both the button /// and the scroll area (as `click_id`/`drag_id`). /// If the user releases the button without moving the mouse, we register it as a click on `click_id`. /// If the cursor moves too much, we clear the `click_id` and start passing move events to `drag_id`. #[derive(Clone, Debug, Default)] pub(crate) struct InteractionState { /// A widget interested in clicks that has a mouse press on it. pub potential_click_id: Option<Id>, /// A widget interested in drags that has a mouse press on it. /// /// Note that this is set as soon as the mouse is pressed, /// so the widget may not yet be marked as "dragged" /// as that can only happen after the mouse has moved a bit /// (at least if the widget is interesated in both clicks and drags). pub potential_drag_id: Option<Id>, } /// Keeps tracks of what widget has keyboard focus #[derive(Clone, Debug, Default)] pub(crate) struct Focus { /// The widget with keyboard focus (i.e. a text input field). focused_widget: Option<FocusWidget>, /// The ID of a widget that had keyboard focus during the previous frame. id_previous_frame: Option<Id>, /// The ID of a widget to give the focus to in the next frame. id_next_frame: Option<Id>, id_requested_by_accesskit: Option<accesskit::NodeId>, /// If set, the next widget that is interested in focus will automatically get it. /// Probably because the user pressed Tab. give_to_next: bool, /// The last widget interested in focus. last_interested: Option<Id>, /// Set when looking for widget with navigational keys like arrows, tab, shift+tab. focus_direction: FocusDirection, /// The top-most modal layer from the previous frame. top_modal_layer: Option<LayerId>, /// The top-most modal layer from the current frame. top_modal_layer_current_frame: Option<LayerId>, /// A cache of widget IDs that are interested in focus with their corresponding rectangles. focus_widgets_cache: IdMap<Rect>, } /// The widget with focus. #[derive(Clone, Copy, Debug)] struct FocusWidget { pub id: Id, pub filter: EventFilter, } impl FocusWidget { pub fn new(id: Id) -> Self { Self { id, filter: Default::default(), } } } impl InteractionState { /// Are we currently clicking or dragging an egui widget? pub fn is_using_pointer(&self) -> bool { self.potential_click_id.is_some() || self.potential_drag_id.is_some() } } impl Focus { /// Which widget currently has keyboard focus? pub fn focused(&self) -> Option<Id> { self.focused_widget.as_ref().map(|w| w.id) } fn begin_pass(&mut self, new_input: &crate::data::input::RawInput) { self.id_previous_frame = self.focused(); if let Some(id) = self.id_next_frame.take() { self.focused_widget = Some(FocusWidget::new(id)); } let event_filter = self.focused_widget.map(|w| w.filter).unwrap_or_default(); self.id_requested_by_accesskit = None; self.focus_direction = FocusDirection::None; for event in &new_input.events { if !event_filter.matches(event) && let crate::Event::Key { key, pressed: true, modifiers, .. } = event && let Some(cardinality) = match key { crate::Key::ArrowUp => Some(FocusDirection::Up), crate::Key::ArrowRight => Some(FocusDirection::Right), crate::Key::ArrowDown => Some(FocusDirection::Down), crate::Key::ArrowLeft => Some(FocusDirection::Left), crate::Key::Tab => { if modifiers.shift { Some(FocusDirection::Previous) } else { Some(FocusDirection::Next) } } crate::Key::Escape => { self.focused_widget = None; Some(FocusDirection::None) } _ => None, } { self.focus_direction = cardinality; } if let crate::Event::AccessKitActionRequest(accesskit::ActionRequest { action: accesskit::Action::Focus, target, data: None, }) = event { self.id_requested_by_accesskit = Some(*target); } } } pub(crate) fn end_pass(&mut self, used_ids: &IdMap<Rect>) { if self.focus_direction.is_cardinal() && let Some(found_widget) = self.find_widget_in_direction(used_ids) { self.focused_widget = Some(FocusWidget::new(found_widget)); } if let Some(focused_widget) = self.focused_widget { // Allow calling `request_focus` one frame and not using it until next frame let recently_gained_focus = self.id_previous_frame != Some(focused_widget.id); if !recently_gained_focus && !used_ids.contains_key(&focused_widget.id) { // Dead-mans-switch: the widget with focus has disappeared! self.focused_widget = None; } } self.top_modal_layer = self.top_modal_layer_current_frame.take(); } pub(crate) fn had_focus_last_frame(&self, id: Id) -> bool { self.id_previous_frame == Some(id) } fn interested_in_focus(&mut self, id: Id) { if self.id_requested_by_accesskit == Some(id.accesskit_id()) { self.focused_widget = Some(FocusWidget::new(id)); self.id_requested_by_accesskit = None; self.give_to_next = false; self.reset_focus(); } // The rect is updated at the end of the frame. self.focus_widgets_cache .entry(id) .or_insert(Rect::EVERYTHING); if self.give_to_next && !self.had_focus_last_frame(id) { self.focused_widget = Some(FocusWidget::new(id)); self.give_to_next = false; } else if self.focused() == Some(id) { if self.focus_direction == FocusDirection::Next { self.focused_widget = None; self.give_to_next = true; self.reset_focus(); } else if self.focus_direction == FocusDirection::Previous { self.id_next_frame = self.last_interested; // frame-delay so gained_focus works self.reset_focus(); } } else if self.focus_direction == FocusDirection::Next && self.focused_widget.is_none() && !self.give_to_next { // nothing has focus and the user pressed tab - give focus to the first widgets that wants it: self.focused_widget = Some(FocusWidget::new(id)); self.reset_focus(); } else if self.focus_direction == FocusDirection::Previous && self.focused_widget.is_none() && !self.give_to_next { // nothing has focus and the user pressed Shift+Tab - give focus to the last widgets that wants it: self.focused_widget = self.last_interested.map(FocusWidget::new); self.reset_focus(); } self.last_interested = Some(id); } fn set_modal_layer(&mut self, layer_id: LayerId) { self.top_modal_layer_current_frame = Some(layer_id); } pub(crate) fn top_modal_layer(&self) -> Option<LayerId> { self.top_modal_layer } fn reset_focus(&mut self) { self.focus_direction = FocusDirection::None; } fn find_widget_in_direction(&mut self, new_rects: &IdMap<Rect>) -> Option<Id> { // NOTE: `new_rects` here include some widgets _not_ interested in focus. /// * negative if `a` is left of `b` /// * positive if `a` is right of `b` /// * zero if the ranges overlap significantly fn range_diff(a: Rangef, b: Rangef) -> f32 { let has_significant_overlap = a.intersection(b).span() >= 0.5 * b.span().min(a.span()); if has_significant_overlap { 0.0 } else { a.center() - b.center() } } let current_focused = self.focused_widget?; // In what direction we are looking for the next widget. let search_direction = match self.focus_direction { FocusDirection::Up => Vec2::UP, FocusDirection::Right => Vec2::RIGHT, FocusDirection::Down => Vec2::DOWN, FocusDirection::Left => Vec2::LEFT, _ => { return None; } }; // Update cache with new rects self.focus_widgets_cache.retain(|id, old_rect| { if let Some(new_rect) = new_rects.get(id) { *old_rect = *new_rect; true // Keep the item } else { false // Remove the item } }); let current_rect = self.focus_widgets_cache.get(&current_focused.id)?; let mut best_score = f32::INFINITY; let mut best_id = None; // iteration order should only matter in case of a tie, and that should be very rare #[expect(clippy::iter_over_hash_type)] for (candidate_id, candidate_rect) in &self.focus_widgets_cache { if *candidate_id == current_focused.id { continue; } // There is a lot of room for improvement here. let to_candidate = vec2( range_diff(candidate_rect.x_range(), current_rect.x_range()), range_diff(candidate_rect.y_range(), current_rect.y_range()), ); let acos_angle = to_candidate.normalized().dot(search_direction); // Only interested in widgets that fall in a 90° cone (±45°) // of the search direction. let is_in_search_cone = 0.5_f32.sqrt() <= acos_angle; if is_in_search_cone { let distance = to_candidate.length(); // There is a lot of room for improvement here. let score = distance / (acos_angle * acos_angle); if score < best_score { best_score = score; best_id = Some(*candidate_id); } } } best_id } } impl Memory { pub(crate) fn begin_pass(&mut self, new_raw_input: &RawInput, viewports: &ViewportIdSet) { profiling::function_scope!(); self.viewport_id = new_raw_input.viewport_id; // Cleanup self.interactions.retain(|id, _| viewports.contains(id)); self.areas.retain(|id, _| viewports.contains(id)); self.popups.retain(|id, _| viewports.contains(id)); self.areas.entry(self.viewport_id).or_default(); // self.interactions is handled elsewhere self.options.begin_pass(new_raw_input); self.focus .entry(self.viewport_id) .or_default() .begin_pass(new_raw_input); } pub(crate) fn end_pass(&mut self, used_ids: &IdMap<Rect>) { self.caches.update(); self.areas_mut().end_pass(); self.focus_mut().end_pass(used_ids); // Clean up abandoned popups. if let Some(popup) = self.popups.get_mut(&self.viewport_id) { if popup.open_this_frame { popup.open_this_frame = false; } else { self.popups.remove(&self.viewport_id); } } } pub(crate) fn set_viewport_id(&mut self, viewport_id: ViewportId) { self.viewport_id = viewport_id; } /// Access memory of the [`Area`](crate::containers::area::Area)s, such as `Window`s. pub fn areas(&self) -> &Areas { self.areas .get(&self.viewport_id) .expect("Memory broken: no area for the current viewport") } /// Access memory of the [`Area`](crate::containers::area::Area)s, such as `Window`s. pub fn areas_mut(&mut self) -> &mut Areas { self.areas.entry(self.viewport_id).or_default() } /// Top-most layer at the given position. pub fn layer_id_at(&self, pos: Pos2) -> Option<LayerId> { let layer_id = self.areas().layer_id_at(pos, &self.to_global)?; if self.is_above_modal_layer(layer_id) { Some(layer_id) } else { self.top_modal_layer() } } /// The currently set transform of a layer. #[deprecated = "Use `Context::layer_transform_to_global` instead"] pub fn layer_transforms(&self, layer_id: LayerId) -> Option<TSTransform> { self.to_global.get(&layer_id).copied() } /// An iterator over all layers. Back-to-front, top is last. pub fn layer_ids(&self) -> impl ExactSizeIterator<Item = LayerId> + '_ { self.areas().order().iter().copied() } /// Check if the layer had focus last frame. /// returns `true` if the layer had focus last frame, but not this one. pub fn had_focus_last_frame(&self, id: Id) -> bool { self.focus().and_then(|f| f.id_previous_frame) == Some(id) } /// Check if the layer lost focus last frame. /// returns `true` if the layer lost focus last frame, but not this one. pub(crate) fn lost_focus(&self, id: Id) -> bool { self.had_focus_last_frame(id) && !self.has_focus(id) } /// Check if the layer gained focus this frame. /// returns `true` if the layer gained focus this frame, but not last one. pub(crate) fn gained_focus(&self, id: Id) -> bool { !self.had_focus_last_frame(id) && self.has_focus(id) } /// Does this widget have keyboard focus? /// /// This function does not consider whether the UI as a whole (e.g. window) /// has the keyboard focus. That makes this function suitable for deciding /// widget state that should not be disrupted if the user moves away from /// the window and back. #[inline(always)] pub fn has_focus(&self, id: Id) -> bool { self.focused() == Some(id) } /// Which widget has keyboard focus? pub fn focused(&self) -> Option<Id> { self.focus()?.focused() } /// Set an event filter for a widget. /// /// This allows you to control whether the widget will loose focus /// when the user presses tab, arrow keys, or escape. /// /// You must first give focus to the widget before calling this. pub fn set_focus_lock_filter(&mut self, id: Id, event_filter: EventFilter) { if self.had_focus_last_frame(id) && self.has_focus(id) && let Some(focused) = &mut self.focus_mut().focused_widget && focused.id == id { focused.filter = event_filter; } } /// Give keyboard focus to a specific widget. /// See also [`crate::Response::request_focus`]. #[inline(always)] pub fn request_focus(&mut self, id: Id) { self.focus_mut().focused_widget = Some(FocusWidget::new(id)); } /// Surrender keyboard focus for a specific widget. /// See also [`crate::Response::surrender_focus`]. #[inline(always)] pub fn surrender_focus(&mut self, id: Id) { let focus = self.focus_mut(); if focus.focused() == Some(id) { focus.focused_widget = None; } } /// Move keyboard focus in a specific direction. pub fn move_focus(&mut self, direction: FocusDirection) { self.focus_mut().focus_direction = direction; } /// Returns true if /// - this layer is the top-most modal layer or above it /// - there is no modal layer pub fn is_above_modal_layer(&self, layer_id: LayerId) -> bool { if let Some(modal_layer) = self.focus().and_then(|f| f.top_modal_layer) { matches!( self.areas().compare_order(layer_id, modal_layer), std::cmp::Ordering::Equal | std::cmp::Ordering::Greater ) } else { true } } /// Does this layer allow interaction? /// Returns true if /// - the layer is not behind a modal layer /// - the [`Order`] allows interaction pub fn allows_interaction(&self, layer_id: LayerId) -> bool {
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/text_cursor_state.rs
crates/egui/src/text_selection/text_cursor_state.rs
//! Text cursor changes/interaction, without modifying the text. use epaint::text::{Galley, cursor::CCursor}; use unicode_segmentation::UnicodeSegmentation as _; use crate::{NumExt as _, Rect, Response, Ui, epaint}; use super::CCursorRange; /// The state of a text cursor selection. /// /// Used for [`crate::TextEdit`] and [`crate::Label`]. #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TextCursorState { ccursor_range: Option<CCursorRange>, } impl From<CCursorRange> for TextCursorState { fn from(ccursor_range: CCursorRange) -> Self { Self { ccursor_range: Some(ccursor_range), } } } impl TextCursorState { pub fn is_empty(&self) -> bool { self.ccursor_range.is_none() } /// The currently selected range of characters. pub fn char_range(&self) -> Option<CCursorRange> { self.ccursor_range } /// The currently selected range of characters, clamped within the character /// range of the given [`Galley`]. pub fn range(&self, galley: &Galley) -> Option<CCursorRange> { self.ccursor_range.map(|mut range| { range.primary = galley.clamp_cursor(&range.primary); range.secondary = galley.clamp_cursor(&range.secondary); range }) } /// Sets the currently selected range of characters. pub fn set_char_range(&mut self, ccursor_range: Option<CCursorRange>) { self.ccursor_range = ccursor_range; } } impl TextCursorState { /// Handle clicking and/or dragging text. /// /// Returns `true` if there was interaction. pub fn pointer_interaction( &mut self, ui: &Ui, response: &Response, cursor_at_pointer: CCursor, galley: &Galley, is_being_dragged: bool, ) -> bool { let text = galley.text(); if response.double_clicked() { // Select word: let ccursor_range = select_word_at(text, cursor_at_pointer); self.set_char_range(Some(ccursor_range)); true } else if response.triple_clicked() { // Select line: let ccursor_range = select_line_at(text, cursor_at_pointer); self.set_char_range(Some(ccursor_range)); true } else if response.sense.senses_drag() { if response.hovered() && ui.input(|i| i.pointer.any_pressed()) { // The start of a drag (or a click). if ui.input(|i| i.modifiers.shift) { if let Some(mut cursor_range) = self.range(galley) { cursor_range.primary = cursor_at_pointer; self.set_char_range(Some(cursor_range)); } else { self.set_char_range(Some(CCursorRange::one(cursor_at_pointer))); } } else { self.set_char_range(Some(CCursorRange::one(cursor_at_pointer))); } true } else if is_being_dragged { // Drag to select text: if let Some(mut cursor_range) = self.range(galley) { cursor_range.primary = cursor_at_pointer; self.set_char_range(Some(cursor_range)); } true } else { false } } else { false } } } fn select_word_at(text: &str, ccursor: CCursor) -> CCursorRange { if ccursor.index == 0 { CCursorRange::two(ccursor, ccursor_next_word(text, ccursor)) } else { let it = text.chars(); let mut it = it.skip(ccursor.index - 1); if let Some(char_before_cursor) = it.next() { if let Some(char_after_cursor) = it.next() { if is_word_char(char_before_cursor) && is_word_char(char_after_cursor) { let min = ccursor_previous_word(text, ccursor + 1); let max = ccursor_next_word(text, min); CCursorRange::two(min, max) } else if is_word_char(char_before_cursor) { let min = ccursor_previous_word(text, ccursor); let max = ccursor_next_word(text, min); CCursorRange::two(min, max) } else if is_word_char(char_after_cursor) { let max = ccursor_next_word(text, ccursor); CCursorRange::two(ccursor, max) } else { let min = ccursor_previous_word(text, ccursor); let max = ccursor_next_word(text, ccursor); CCursorRange::two(min, max) } } else { let min = ccursor_previous_word(text, ccursor); CCursorRange::two(min, ccursor) } } else { let max = ccursor_next_word(text, ccursor); CCursorRange::two(ccursor, max) } } } fn select_line_at(text: &str, ccursor: CCursor) -> CCursorRange { if ccursor.index == 0 { CCursorRange::two(ccursor, ccursor_next_line(text, ccursor)) } else { let it = text.chars(); let mut it = it.skip(ccursor.index - 1); if let Some(char_before_cursor) = it.next() { if let Some(char_after_cursor) = it.next() { if (!is_linebreak(char_before_cursor)) && (!is_linebreak(char_after_cursor)) { let min = ccursor_previous_line(text, ccursor + 1); let max = ccursor_next_line(text, min); CCursorRange::two(min, max) } else if !is_linebreak(char_before_cursor) { let min = ccursor_previous_line(text, ccursor); let max = ccursor_next_line(text, min); CCursorRange::two(min, max) } else if !is_linebreak(char_after_cursor) { let max = ccursor_next_line(text, ccursor); CCursorRange::two(ccursor, max) } else { let min = ccursor_previous_line(text, ccursor); let max = ccursor_next_line(text, ccursor); CCursorRange::two(min, max) } } else { let min = ccursor_previous_line(text, ccursor); CCursorRange::two(min, ccursor) } } else { let max = ccursor_next_line(text, ccursor); CCursorRange::two(ccursor, max) } } } pub fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor { CCursor { index: next_word_boundary_char_index(text, ccursor.index), prefer_next_row: false, } } fn ccursor_next_line(text: &str, ccursor: CCursor) -> CCursor { CCursor { index: next_line_boundary_char_index(text.chars(), ccursor.index), prefer_next_row: false, } } pub fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor { let num_chars = text.chars().count(); let reversed: String = text.graphemes(true).rev().collect(); CCursor { index: num_chars - next_word_boundary_char_index(&reversed, num_chars - ccursor.index).min(num_chars), prefer_next_row: true, } } fn ccursor_previous_line(text: &str, ccursor: CCursor) -> CCursor { let num_chars = text.chars().count(); CCursor { index: num_chars - next_line_boundary_char_index(text.chars().rev(), num_chars - ccursor.index), prefer_next_row: true, } } fn next_word_boundary_char_index(text: &str, cursor_ci: usize) -> usize { for (word_byte_index, word) in text.split_word_bound_indices() { let word_ci = char_index_from_byte_index(text, word_byte_index); // We consider `.` a word boundary. // At least that's how Mac works when navigating something like `www.example.com`. for (dot_ci_offset, chr) in word.chars().enumerate() { let dot_ci = word_ci + dot_ci_offset; if chr == '.' && cursor_ci < dot_ci { return dot_ci; } } // Splitting considers contiguous whitespace as one word, such words must be skipped, // this handles cases for example ' abc' (a space and a word), the cursor is at the beginning // (before space) - this jumps at the end of 'abc' (this is consistent with text editors // or browsers) if cursor_ci < word_ci && !all_word_chars(word) { return word_ci; } } char_index_from_byte_index(text, text.len()) } fn all_word_chars(text: &str) -> bool { text.chars().all(is_word_char) } fn next_line_boundary_char_index(it: impl Iterator<Item = char>, mut index: usize) -> usize { let mut it = it.skip(index); if let Some(_first) = it.next() { index += 1; if let Some(second) = it.next() { index += 1; for next in it { if is_linebreak(next) != is_linebreak(second) { break; } index += 1; } } } index } pub fn is_word_char(c: char) -> bool { c.is_alphanumeric() || c == '_' } fn is_linebreak(c: char) -> bool { c == '\r' || c == '\n' } /// Accepts and returns character offset (NOT byte offset!). pub fn find_line_start(text: &str, current_index: CCursor) -> CCursor { // We know that new lines, '\n', are a single byte char, but we have to // work with char offsets because before the new line there may be any // number of multi byte chars. // We need to know the char index to be able to correctly set the cursor // later. let chars_count = text.chars().count(); let position = text .chars() .rev() .skip(chars_count - current_index.index) .position(|x| x == '\n'); match position { Some(pos) => CCursor::new(current_index.index - pos), None => CCursor::new(0), } } pub fn byte_index_from_char_index(s: &str, char_index: usize) -> usize { for (ci, (bi, _)) in s.char_indices().enumerate() { if ci == char_index { return bi; } } s.len() } pub fn char_index_from_byte_index(input: &str, byte_index: usize) -> usize { for (ci, (bi, _)) in input.char_indices().enumerate() { if bi == byte_index { return ci; } } input.char_indices().last().map_or(0, |(i, _)| i + 1) } pub fn slice_char_range(s: &str, char_range: std::ops::Range<usize>) -> &str { assert!( char_range.start <= char_range.end, "Invalid range, start must be less than end, but start = {}, end = {}", char_range.start, char_range.end ); let start_byte = byte_index_from_char_index(s, char_range.start); let end_byte = byte_index_from_char_index(s, char_range.end); &s[start_byte..end_byte] } /// The thin rectangle of one end of the selection, e.g. the primary cursor, in local galley coordinates. pub fn cursor_rect(galley: &Galley, cursor: &CCursor, row_height: f32) -> Rect { let mut cursor_pos = galley.pos_from_cursor(*cursor); // Handle completely empty galleys cursor_pos.max.y = cursor_pos.max.y.at_least(cursor_pos.min.y + row_height); cursor_pos = cursor_pos.expand(1.5); // slightly above/below row cursor_pos } #[cfg(test)] mod test { use crate::text_selection::text_cursor_state::next_word_boundary_char_index; #[test] fn test_next_word_boundary_char_index() { // ASCII only let text = "abc d3f g_h i-j"; assert_eq!(next_word_boundary_char_index(text, 1), 3); assert_eq!(next_word_boundary_char_index(text, 3), 7); assert_eq!(next_word_boundary_char_index(text, 9), 11); assert_eq!(next_word_boundary_char_index(text, 12), 13); assert_eq!(next_word_boundary_char_index(text, 13), 15); assert_eq!(next_word_boundary_char_index(text, 15), 15); assert_eq!(next_word_boundary_char_index("", 0), 0); assert_eq!(next_word_boundary_char_index("", 1), 0); // ASCII only let text = "abc.def.ghi"; assert_eq!(next_word_boundary_char_index(text, 1), 3); assert_eq!(next_word_boundary_char_index(text, 3), 7); assert_eq!(next_word_boundary_char_index(text, 7), 11); // Unicode graphemes, some of which consist of multiple Unicode characters, // !!! Unicode character is not always what is tranditionally considered a character, // the values below are correct despite not seeming that way on the first look, // handling of and around emojis is kind of weird and is not consistent across // text editors and browsers let text = "❤️👍 skvělá knihovna 👍❤️"; assert_eq!(next_word_boundary_char_index(text, 0), 2); assert_eq!(next_word_boundary_char_index(text, 2), 3); // this does not skip the space between thumbs-up and 'skvělá' assert_eq!(next_word_boundary_char_index(text, 6), 10); assert_eq!(next_word_boundary_char_index(text, 9), 10); assert_eq!(next_word_boundary_char_index(text, 12), 19); assert_eq!(next_word_boundary_char_index(text, 15), 19); assert_eq!(next_word_boundary_char_index(text, 19), 20); assert_eq!(next_word_boundary_char_index(text, 20), 21); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/accesskit_text.rs
crates/egui/src/text_selection/accesskit_text.rs
use emath::TSTransform; use crate::{Context, Galley, Id}; use super::{CCursorRange, text_cursor_state::is_word_char}; /// Update accesskit with the current text state. pub fn update_accesskit_for_text_widget( ctx: &Context, widget_id: Id, cursor_range: Option<CCursorRange>, role: accesskit::Role, global_from_galley: TSTransform, galley: &Galley, ) { let parent_id = ctx.accesskit_node_builder(widget_id, |builder| { let parent_id = widget_id; if let Some(cursor_range) = &cursor_range { let anchor = galley.layout_from_cursor(cursor_range.secondary); let focus = galley.layout_from_cursor(cursor_range.primary); builder.set_text_selection(accesskit::TextSelection { anchor: accesskit::TextPosition { node: parent_id.with(anchor.row).accesskit_id(), character_index: anchor.column, }, focus: accesskit::TextPosition { node: parent_id.with(focus.row).accesskit_id(), character_index: focus.column, }, }); } builder.set_role(role); parent_id }); let Some(parent_id) = parent_id else { return; }; for (row_index, row) in galley.rows.iter().enumerate() { let row_id = parent_id.with(row_index); ctx.register_accesskit_parent(row_id, parent_id); ctx.accesskit_node_builder(row_id, |builder| { builder.set_role(accesskit::Role::TextRun); let rect = global_from_galley * row.rect_without_leading_space(); builder.set_bounds(accesskit::Rect { x0: rect.min.x.into(), y0: rect.min.y.into(), x1: rect.max.x.into(), y1: rect.max.y.into(), }); builder.set_text_direction(accesskit::TextDirection::LeftToRight); // TODO(mwcampbell): Set more node fields for the row // once AccessKit adapters expose text formatting info. let glyph_count = row.glyphs.len(); let mut value = String::new(); value.reserve(glyph_count); let mut character_lengths = Vec::<u8>::with_capacity(glyph_count); let mut character_positions = Vec::<f32>::with_capacity(glyph_count); let mut character_widths = Vec::<f32>::with_capacity(glyph_count); let mut word_lengths = Vec::<u8>::new(); let mut was_at_word_end = false; let mut last_word_start = 0usize; for glyph in &row.glyphs { let is_word_char = is_word_char(glyph.chr); if is_word_char && was_at_word_end { word_lengths.push((character_lengths.len() - last_word_start) as _); last_word_start = character_lengths.len(); } was_at_word_end = !is_word_char; let old_len = value.len(); value.push(glyph.chr); character_lengths.push((value.len() - old_len) as _); character_positions.push(glyph.pos.x - row.pos.x); character_widths.push(glyph.advance_width); } if row.ends_with_newline { value.push('\n'); character_lengths.push(1); character_positions.push(row.size.x); character_widths.push(0.0); } word_lengths.push((character_lengths.len() - last_word_start) as _); builder.set_value(value); builder.set_character_lengths(character_lengths); builder.set_character_positions(character_positions); builder.set_character_widths(character_widths); builder.set_word_lengths(word_lengths); }); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/mod.rs
crates/egui/src/text_selection/mod.rs
//! Helpers regarding text selection for labels and text edit. pub mod accesskit_text; mod cursor_range; mod label_text_selection; pub mod text_cursor_state; pub mod visuals; pub use cursor_range::CCursorRange; pub use label_text_selection::LabelSelectionState; pub use text_cursor_state::TextCursorState;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/cursor_range.rs
crates/egui/src/text_selection/cursor_range.rs
use epaint::{Galley, text::cursor::CCursor}; use crate::{Event, Id, Key, Modifiers, os::OperatingSystem}; use super::text_cursor_state::{ccursor_next_word, ccursor_previous_word, slice_char_range}; /// A selected text range (could be a range of length zero). /// /// The selection is based on character count (NOT byte count!). #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct CCursorRange { /// When selecting with a mouse, this is where the mouse was released. /// When moving with e.g. shift+arrows, this is what moves. /// Note that the two ends can come in any order, and also be equal (no selection). pub primary: CCursor, /// When selecting with a mouse, this is where the mouse was first pressed. /// This part of the cursor does not move when shift is down. pub secondary: CCursor, /// Saved horizontal position of the cursor. pub h_pos: Option<f32>, } impl CCursorRange { /// The empty range. #[inline] pub fn one(ccursor: CCursor) -> Self { Self { primary: ccursor, secondary: ccursor, h_pos: None, } } #[inline] pub fn two(min: impl Into<CCursor>, max: impl Into<CCursor>) -> Self { Self { primary: max.into(), secondary: min.into(), h_pos: None, } } /// Select all the text in a galley pub fn select_all(galley: &Galley) -> Self { Self::two(galley.begin(), galley.end()) } /// The range of selected character indices. pub fn as_sorted_char_range(&self) -> std::ops::Range<usize> { let [start, end] = self.sorted_cursors(); std::ops::Range { start: start.index, end: end.index, } } /// True if the selected range contains no characters. #[inline] pub fn is_empty(&self) -> bool { self.primary == self.secondary } /// Is `self` a super-set of the other range? pub fn contains(&self, other: Self) -> bool { let [self_min, self_max] = self.sorted_cursors(); let [other_min, other_max] = other.sorted_cursors(); self_min.index <= other_min.index && other_max.index <= self_max.index } /// If there is a selection, None is returned. /// If the two ends are the same, that is returned. pub fn single(&self) -> Option<CCursor> { if self.is_empty() { Some(self.primary) } else { None } } #[inline] pub fn is_sorted(&self) -> bool { let p = self.primary; let s = self.secondary; (p.index, p.prefer_next_row) <= (s.index, s.prefer_next_row) } /// returns the two ends ordered #[inline] pub fn sorted_cursors(&self) -> [CCursor; 2] { if self.is_sorted() { [self.primary, self.secondary] } else { [self.secondary, self.primary] } } #[inline] #[deprecated = "Use `self.sorted_cursors` instead."] pub fn sorted(&self) -> [CCursor; 2] { self.sorted_cursors() } pub fn slice_str<'s>(&self, text: &'s str) -> &'s str { let [min, max] = self.sorted_cursors(); slice_char_range(text, min.index..max.index) } /// Check for key presses that are moving the cursor. /// /// Returns `true` if we did mutate `self`. pub fn on_key_press( &mut self, os: OperatingSystem, galley: &Galley, modifiers: &Modifiers, key: Key, ) -> bool { match key { Key::A if modifiers.command => { *self = Self::select_all(galley); true } Key::ArrowLeft | Key::ArrowRight if modifiers.is_none() && !self.is_empty() => { if key == Key::ArrowLeft { *self = Self::one(self.sorted_cursors()[0]); } else { *self = Self::one(self.sorted_cursors()[1]); } true } Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End => { move_single_cursor( os, &mut self.primary, &mut self.h_pos, galley, key, modifiers, ); if !modifiers.shift { self.secondary = self.primary; } true } Key::P | Key::N | Key::B | Key::F | Key::A | Key::E if os == OperatingSystem::Mac && modifiers.ctrl && !modifiers.shift => { move_single_cursor( os, &mut self.primary, &mut self.h_pos, galley, key, modifiers, ); self.secondary = self.primary; true } _ => false, } } /// Check for events that modify the cursor range. /// /// Returns `true` if such an event was found and handled. pub fn on_event( &mut self, os: OperatingSystem, event: &Event, galley: &Galley, _widget_id: Id, ) -> bool { match event { Event::Key { modifiers, key, pressed: true, .. } => self.on_key_press(os, galley, modifiers, *key), Event::AccessKitActionRequest(accesskit::ActionRequest { action: accesskit::Action::SetTextSelection, target, data: Some(accesskit::ActionData::SetTextSelection(selection)), }) => { if _widget_id.accesskit_id() == *target { let primary = ccursor_from_accesskit_text_position(_widget_id, galley, &selection.focus); let secondary = ccursor_from_accesskit_text_position(_widget_id, galley, &selection.anchor); if let (Some(primary), Some(secondary)) = (primary, secondary) { *self = Self { primary, secondary, h_pos: None, }; return true; } } false } _ => false, } } } // ---------------------------------------------------------------------------- fn ccursor_from_accesskit_text_position( id: Id, galley: &Galley, position: &accesskit::TextPosition, ) -> Option<CCursor> { let mut total_length = 0usize; for (i, row) in galley.rows.iter().enumerate() { let row_id = id.with(i); if row_id.accesskit_id() == position.node { return Some(CCursor { index: total_length + position.character_index, prefer_next_row: !(position.character_index == row.glyphs.len() && !row.ends_with_newline && (i + 1) < galley.rows.len()), }); } total_length += row.glyphs.len() + (row.ends_with_newline as usize); } None } // ---------------------------------------------------------------------------- /// Move a text cursor based on keyboard fn move_single_cursor( os: OperatingSystem, cursor: &mut CCursor, h_pos: &mut Option<f32>, galley: &Galley, key: Key, modifiers: &Modifiers, ) { let (new_cursor, new_h_pos) = if os == OperatingSystem::Mac && modifiers.ctrl && !modifiers.shift { match key { Key::A => (galley.cursor_begin_of_row(cursor), None), Key::E => (galley.cursor_end_of_row(cursor), None), Key::P => galley.cursor_up_one_row(cursor, *h_pos), Key::N => galley.cursor_down_one_row(cursor, *h_pos), Key::B => (galley.cursor_left_one_character(cursor), None), Key::F => (galley.cursor_right_one_character(cursor), None), _ => return, } } else { match key { Key::ArrowLeft => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows (ccursor_previous_word(galley, *cursor), None) } else if modifiers.mac_cmd { (galley.cursor_begin_of_row(cursor), None) } else { (galley.cursor_left_one_character(cursor), None) } } Key::ArrowRight => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows (ccursor_next_word(galley, *cursor), None) } else if modifiers.mac_cmd { (galley.cursor_end_of_row(cursor), None) } else { (galley.cursor_right_one_character(cursor), None) } } Key::ArrowUp => { if modifiers.command { // mac and windows behavior (galley.begin(), None) } else { galley.cursor_up_one_row(cursor, *h_pos) } } Key::ArrowDown => { if modifiers.command { // mac and windows behavior (galley.end(), None) } else { galley.cursor_down_one_row(cursor, *h_pos) } } Key::Home => { if modifiers.ctrl { // windows behavior (galley.begin(), None) } else { (galley.cursor_begin_of_row(cursor), None) } } Key::End => { if modifiers.ctrl { // windows behavior (galley.end(), None) } else { (galley.cursor_end_of_row(cursor), None) } } _ => unreachable!(), } }; *cursor = new_cursor; *h_pos = new_h_pos; }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/visuals.rs
crates/egui/src/text_selection/visuals.rs
use std::sync::Arc; use crate::{Galley, Painter, Rect, Ui, Visuals, pos2, vec2}; use super::CCursorRange; #[derive(Clone, Debug)] pub struct RowVertexIndices { pub row: usize, pub vertex_indices: [u32; 6], } /// Adds text selection rectangles to the galley. pub fn paint_text_selection( galley: &mut Arc<Galley>, visuals: &Visuals, cursor_range: &CCursorRange, mut new_vertex_indices: Option<&mut Vec<RowVertexIndices>>, ) { if cursor_range.is_empty() { return; } // We need to modify the galley (add text selection painting to it), // and so we need to clone it if it is shared: let galley: &mut Galley = Arc::make_mut(galley); let background_color = visuals.selection.bg_fill; let text_color = visuals.selection.stroke.color; let [min, max] = cursor_range.sorted_cursors(); let min = galley.layout_from_cursor(min); let max = galley.layout_from_cursor(max); for ri in min.row..=max.row { let placed_row = &mut galley.rows[ri]; let row = Arc::make_mut(&mut placed_row.row); let left = if ri == min.row { row.x_offset(min.column) } else { 0.0 }; let right = if ri == max.row { row.x_offset(max.column) } else { let newline_size = if placed_row.ends_with_newline { row.height() / 2.0 // visualize that we select the newline } else { 0.0 }; row.size.x + newline_size }; let rect = Rect::from_min_max(pos2(left, 0.0), pos2(right, row.size.y)); let mesh = &mut row.visuals.mesh; if !row.glyphs.is_empty() { // Change color of the selected text: let first_glyph_index = if ri == min.row { min.column } else { 0 }; let last_glyph_index = if ri == max.row { max.column } else { row.glyphs.len() - 1 }; let first_vertex_index = row .glyphs .get(first_glyph_index) .map_or(row.visuals.glyph_vertex_range.start, |g| { g.first_vertex as _ }); let last_vertex_index = row .glyphs .get(last_glyph_index) .map_or(row.visuals.glyph_vertex_range.end, |g| g.first_vertex as _); for vi in first_vertex_index..last_vertex_index { mesh.vertices[vi].color = text_color; } } // Time to insert the selection rectangle into the row mesh. // It should be on top (after) of any background in the galley, // but behind (before) any glyphs. The row visuals has this information: let glyph_index_start = row.visuals.glyph_index_start; // Start by appending the selection rectangle to end of the mesh, as two triangles (= 6 indices): let num_indices_before = mesh.indices.len(); mesh.add_colored_rect(rect, background_color); assert_eq!( num_indices_before + 6, mesh.indices.len(), "We expect exactly 6 new indices" ); // Copy out the new triangles: let selection_triangles = [ mesh.indices[num_indices_before], mesh.indices[num_indices_before + 1], mesh.indices[num_indices_before + 2], mesh.indices[num_indices_before + 3], mesh.indices[num_indices_before + 4], mesh.indices[num_indices_before + 5], ]; // Move every old triangle forwards by 6 indices to make room for the new triangle: for i in (glyph_index_start..num_indices_before).rev() { mesh.indices.swap(i, i + 6); } // Put the new triangle in place: mesh.indices[glyph_index_start..glyph_index_start + 6] .clone_from_slice(&selection_triangles); row.visuals.mesh_bounds = mesh.calc_bounds(); if let Some(new_vertex_indices) = &mut new_vertex_indices { new_vertex_indices.push(RowVertexIndices { row: ri, vertex_indices: selection_triangles, }); } } } /// Paint one end of the selection, e.g. the primary cursor. /// /// This will never blink. pub fn paint_cursor_end(painter: &Painter, visuals: &Visuals, cursor_rect: Rect) { let stroke = visuals.text_cursor.stroke; let top = cursor_rect.center_top(); let bottom = cursor_rect.center_bottom(); painter.line_segment([top, bottom], (stroke.width, stroke.color)); if false { // Roof/floor: let extrusion = 3.0; let width = 1.0; painter.line_segment( [top - vec2(extrusion, 0.0), top + vec2(extrusion, 0.0)], (width, stroke.color), ); painter.line_segment( [bottom - vec2(extrusion, 0.0), bottom + vec2(extrusion, 0.0)], (width, stroke.color), ); } } /// Paint one end of the selection, e.g. the primary cursor, with blinking (if enabled). pub fn paint_text_cursor( ui: &Ui, painter: &Painter, primary_cursor_rect: Rect, time_since_last_interaction: f64, ) { if ui.visuals().text_cursor.blink { let on_duration = ui.visuals().text_cursor.on_duration; let off_duration = ui.visuals().text_cursor.off_duration; let total_duration = on_duration + off_duration; let time_in_cycle = (time_since_last_interaction % (total_duration as f64)) as f32; let wake_in = if time_in_cycle < on_duration { // Cursor is visible paint_cursor_end(painter, ui.visuals(), primary_cursor_rect); on_duration - time_in_cycle } else { // Cursor is not visible total_duration - time_in_cycle }; ui.request_repaint_after_secs(wake_in); } else { paint_cursor_end(painter, ui.visuals(), primary_cursor_rect); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/text_selection/label_text_selection.rs
crates/egui/src/text_selection/label_text_selection.rs
use std::sync::Arc; use emath::TSTransform; use crate::{ Context, CursorIcon, Event, Galley, Id, LayerId, Plugin, Pos2, Rect, Response, Ui, layers::ShapeIdx, text::CCursor, text_selection::CCursorRange, }; use super::{ TextCursorState, text_cursor_state::cursor_rect, visuals::{RowVertexIndices, paint_text_selection}, }; /// Turn on to help debug this const DEBUG: bool = false; // Don't merge `true`! /// One end of a text selection, inside any widget. #[derive(Clone, Copy)] struct WidgetTextCursor { widget_id: Id, ccursor: CCursor, /// Last known screen position pos: Pos2, } impl WidgetTextCursor { fn new( widget_id: Id, cursor: impl Into<CCursor>, global_from_galley: TSTransform, galley: &Galley, ) -> Self { let ccursor = cursor.into(); let pos = global_from_galley * pos_in_galley(galley, ccursor); Self { widget_id, ccursor, pos, } } } fn pos_in_galley(galley: &Galley, ccursor: CCursor) -> Pos2 { galley.pos_from_cursor(ccursor).center() } impl std::fmt::Debug for WidgetTextCursor { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("WidgetTextCursor") .field("widget_id", &self.widget_id.short_debug_format()) .field("ccursor", &self.ccursor.index) .finish() } } #[derive(Clone, Copy, Debug)] struct CurrentSelection { /// The selection is in this layer. /// /// This is to constrain a selection to a single Window. pub layer_id: LayerId, /// When selecting with a mouse, this is where the mouse was released. /// When moving with e.g. shift+arrows, this is what moves. /// Note that the two ends can come in any order, and also be equal (no selection). pub primary: WidgetTextCursor, /// When selecting with a mouse, this is where the mouse was first pressed. /// This part of the cursor does not move when shift is down. pub secondary: WidgetTextCursor, } /// Handles text selection in labels (NOT in [`crate::TextEdit`])s. /// /// One state for all labels, because we only support text selection in one label at a time. #[derive(Clone, Debug)] pub struct LabelSelectionState { /// The current selection, if any. selection: Option<CurrentSelection>, selection_bbox_last_frame: Rect, selection_bbox_this_frame: Rect, /// Any label hovered this frame? any_hovered: bool, /// Are we in drag-to-select state? is_dragging: bool, /// Have we reached the widget containing the primary selection? has_reached_primary: bool, /// Have we reached the widget containing the secondary selection? has_reached_secondary: bool, /// Accumulated text to copy. text_to_copy: String, last_copied_galley_rect: Option<Rect>, /// Painted selections this frame. /// /// Kept so we can undo a bad selection visualization if we don't see both ends of the selection this frame. painted_selections: Vec<(ShapeIdx, Vec<RowVertexIndices>)>, } impl Default for LabelSelectionState { fn default() -> Self { Self { selection: Default::default(), selection_bbox_last_frame: Rect::NOTHING, selection_bbox_this_frame: Rect::NOTHING, any_hovered: Default::default(), is_dragging: Default::default(), has_reached_primary: Default::default(), has_reached_secondary: Default::default(), text_to_copy: Default::default(), last_copied_galley_rect: Default::default(), painted_selections: Default::default(), } } } impl Plugin for LabelSelectionState { fn debug_name(&self) -> &'static str { "LabelSelectionState" } fn on_begin_pass(&mut self, ui: &mut Ui) { if ui.input(|i| i.pointer.any_pressed() && !i.modifiers.shift) { // Maybe a new selection is about to begin, but the old one is over: // state.selection = None; // TODO(emilk): this makes sense, but doesn't work as expected. } self.selection_bbox_last_frame = self.selection_bbox_this_frame; self.selection_bbox_this_frame = Rect::NOTHING; self.any_hovered = false; self.has_reached_primary = false; self.has_reached_secondary = false; self.text_to_copy.clear(); self.last_copied_galley_rect = None; self.painted_selections.clear(); } fn on_end_pass(&mut self, ui: &mut Ui) { if self.is_dragging { ui.set_cursor_icon(CursorIcon::Text); } if !self.has_reached_primary || !self.has_reached_secondary { // We didn't see both cursors this frame, // maybe because they are outside the visible area (scrolling), // or one disappeared. In either case we will have horrible glitches, so let's just deselect. let prev_selection = self.selection.take(); if let Some(selection) = prev_selection { // This was the first frame of glitch, so hide the // glitching by removing all painted selections: ui.graphics_mut(|layers| { if let Some(list) = layers.get_mut(selection.layer_id) { for (shape_idx, row_selections) in self.painted_selections.drain(..) { list.mutate_shape(shape_idx, |shape| { if let epaint::Shape::Text(text_shape) = &mut shape.shape { let galley = Arc::make_mut(&mut text_shape.galley); for row_selection in row_selections { if let Some(placed_row) = galley.rows.get_mut(row_selection.row) { let row = Arc::make_mut(&mut placed_row.row); for vertex_index in row_selection.vertex_indices { if let Some(vertex) = row .visuals .mesh .vertices .get_mut(vertex_index as usize) { vertex.color = epaint::Color32::TRANSPARENT; } } } } } }); } } }); } } let pressed_escape = ui.input(|i| i.key_pressed(crate::Key::Escape)); let clicked_something_else = ui.input(|i| i.pointer.any_pressed()) && !self.any_hovered; let delected_everything = pressed_escape || clicked_something_else; if delected_everything { self.selection = None; } if ui.input(|i| i.pointer.any_released()) { self.is_dragging = false; } let text_to_copy = std::mem::take(&mut self.text_to_copy); if !text_to_copy.is_empty() { ui.copy_text(text_to_copy); } } } impl LabelSelectionState { pub fn has_selection(&self) -> bool { self.selection.is_some() } pub fn clear_selection(&mut self) { self.selection = None; } fn copy_text(&mut self, new_galley_rect: Rect, galley: &Galley, cursor_range: &CCursorRange) { let new_text = selected_text(galley, cursor_range); if new_text.is_empty() { return; } if self.text_to_copy.is_empty() { self.text_to_copy = new_text; self.last_copied_galley_rect = Some(new_galley_rect); return; } let Some(last_copied_galley_rect) = self.last_copied_galley_rect else { self.text_to_copy = new_text; self.last_copied_galley_rect = Some(new_galley_rect); return; }; // We need to append or prepend the new text to the already copied text. // We need to do so intelligently. if last_copied_galley_rect.bottom() <= new_galley_rect.top() { self.text_to_copy.push('\n'); let vertical_distance = new_galley_rect.top() - last_copied_galley_rect.bottom(); if estimate_row_height(galley) * 0.5 < vertical_distance { self.text_to_copy.push('\n'); } } else { let existing_ends_with_space = self.text_to_copy.chars().last().map(|c| c.is_whitespace()); let new_text_starts_with_space_or_punctuation = new_text .chars() .next() .is_some_and(|c| c.is_whitespace() || c.is_ascii_punctuation()); if existing_ends_with_space == Some(false) && !new_text_starts_with_space_or_punctuation { self.text_to_copy.push(' '); } } self.text_to_copy.push_str(&new_text); self.last_copied_galley_rect = Some(new_galley_rect); } /// Handle text selection state for a label or similar widget. /// /// Make sure the widget senses clicks and drags. /// /// This also takes care of painting the galley. pub fn label_text_selection( ui: &Ui, response: &Response, galley_pos: Pos2, mut galley: Arc<Galley>, fallback_color: epaint::Color32, underline: epaint::Stroke, ) { let plugin = ui.ctx().plugin::<Self>(); let mut state = plugin.lock(); let new_vertex_indices = state.on_label(ui, response, galley_pos, &mut galley); let shape_idx = ui.painter().add( epaint::TextShape::new(galley_pos, galley, fallback_color).with_underline(underline), ); if !new_vertex_indices.is_empty() { state .painted_selections .push((shape_idx, new_vertex_indices)); } } fn cursor_for( &mut self, ui: &Ui, response: &Response, global_from_galley: TSTransform, galley: &Galley, ) -> TextCursorState { let Some(selection) = &mut self.selection else { // Nothing selected. return TextCursorState::default(); }; if selection.layer_id != response.layer_id { // Selection is in another layer return TextCursorState::default(); } let galley_from_global = global_from_galley.inverse(); let multi_widget_text_select = ui.style().interaction.multi_widget_text_select; let may_select_widget = multi_widget_text_select || selection.primary.widget_id == response.id; if self.is_dragging && may_select_widget && let Some(pointer_pos) = ui.ctx().pointer_interact_pos() { let galley_rect = global_from_galley * Rect::from_min_size(Pos2::ZERO, galley.size()); let galley_rect = galley_rect.intersect(ui.clip_rect()); let is_in_same_column = galley_rect .x_range() .intersects(self.selection_bbox_last_frame.x_range()); let has_reached_primary = self.has_reached_primary || response.id == selection.primary.widget_id; let has_reached_secondary = self.has_reached_secondary || response.id == selection.secondary.widget_id; let new_primary = if response.contains_pointer() { // Dragging into this widget - easy case: Some(galley.cursor_from_pos((galley_from_global * pointer_pos).to_vec2())) } else if is_in_same_column && !self.has_reached_primary && selection.primary.pos.y <= selection.secondary.pos.y && pointer_pos.y <= galley_rect.top() && galley_rect.top() <= selection.secondary.pos.y { // The user is dragging the text selection upwards, above the first selected widget (this one): if DEBUG { ui.ctx() .debug_text(format!("Upwards drag; include {:?}", response.id)); } Some(galley.begin()) } else if is_in_same_column && has_reached_secondary && has_reached_primary && selection.secondary.pos.y <= selection.primary.pos.y && selection.secondary.pos.y <= galley_rect.bottom() && galley_rect.bottom() <= pointer_pos.y { // The user is dragging the text selection downwards, below this widget. // We move the cursor to the end of this widget, // (and we may do the same for the next widget too). if DEBUG { ui.ctx() .debug_text(format!("Downwards drag; include {:?}", response.id)); } Some(galley.end()) } else { None }; if let Some(new_primary) = new_primary { selection.primary = WidgetTextCursor::new(response.id, new_primary, global_from_galley, galley); // We don't want the latency of `drag_started`. let drag_started = ui.input(|i| i.pointer.any_pressed()); if drag_started { if selection.layer_id == response.layer_id { if ui.input(|i| i.modifiers.shift) { // A continuation of a previous selection. } else { // A new selection in the same layer. selection.secondary = selection.primary; } } else { // A new selection in a new layer. selection.layer_id = response.layer_id; selection.secondary = selection.primary; } } } } let has_primary = response.id == selection.primary.widget_id; let has_secondary = response.id == selection.secondary.widget_id; if has_primary { selection.primary.pos = global_from_galley * pos_in_galley(galley, selection.primary.ccursor); } if has_secondary { selection.secondary.pos = global_from_galley * pos_in_galley(galley, selection.secondary.ccursor); } self.has_reached_primary |= has_primary; self.has_reached_secondary |= has_secondary; let primary = has_primary.then_some(selection.primary.ccursor); let secondary = has_secondary.then_some(selection.secondary.ccursor); // The following code assumes we will encounter both ends of the cursor // at some point (but in any order). // If we don't (e.g. because one endpoint is outside the visible scroll areas), // we will have annoying failure cases. match (primary, secondary) { (Some(primary), Some(secondary)) => { // This is the only selected label. TextCursorState::from(CCursorRange { primary, secondary, h_pos: None, }) } (Some(primary), None) => { // This labels contains only the primary cursor. let secondary = if self.has_reached_secondary { // Secondary was before primary. // Select everything up to the cursor. // We assume normal left-to-right and top-down layout order here. galley.begin() } else { // Select everything from the cursor onward: galley.end() }; TextCursorState::from(CCursorRange { primary, secondary, h_pos: None, }) } (None, Some(secondary)) => { // This labels contains only the secondary cursor let primary = if self.has_reached_primary { // Primary was before secondary. // Select everything up to the cursor. // We assume normal left-to-right and top-down layout order here. galley.begin() } else { // Select everything from the cursor onward: galley.end() }; TextCursorState::from(CCursorRange { primary, secondary, h_pos: None, }) } (None, None) => { // This widget has neither the primary or secondary cursor. let is_in_middle = self.has_reached_primary != self.has_reached_secondary; if is_in_middle { if DEBUG { response.ctx.debug_text(format!( "widget in middle: {:?}, between {:?} and {:?}", response.id, selection.primary.widget_id, selection.secondary.widget_id, )); } // …but it is between the two selection endpoints, and so is fully selected. TextCursorState::from(CCursorRange::two(galley.begin(), galley.end())) } else { // Outside the selected range TextCursorState::default() } } } } /// Returns the painted selections, if any. fn on_label( &mut self, ui: &Ui, response: &Response, galley_pos_in_layer: Pos2, galley: &mut Arc<Galley>, ) -> Vec<RowVertexIndices> { let widget_id = response.id; let global_from_layer = ui .ctx() .layer_transform_to_global(ui.layer_id()) .unwrap_or_default(); let layer_from_galley = TSTransform::from_translation(galley_pos_in_layer.to_vec2()); let galley_from_layer = layer_from_galley.inverse(); let layer_from_global = global_from_layer.inverse(); let galley_from_global = galley_from_layer * layer_from_global; let global_from_galley = global_from_layer * layer_from_galley; if response.hovered() { ui.set_cursor_icon(CursorIcon::Text); } self.any_hovered |= response.hovered(); self.is_dragging |= response.is_pointer_button_down_on(); // we don't want the initial latency of drag vs click decision let old_selection = self.selection; let mut cursor_state = self.cursor_for(ui, response, global_from_galley, galley); let old_range = cursor_state.range(galley); if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() && response.contains_pointer() { let cursor_at_pointer = galley.cursor_from_pos((galley_from_global * pointer_pos).to_vec2()); // This is where we handle start-of-drag and double-click-to-select. // Actual drag-to-select happens elsewhere. let dragged = false; cursor_state.pointer_interaction(ui, response, cursor_at_pointer, galley, dragged); } if let Some(mut cursor_range) = cursor_state.range(galley) { let galley_rect = global_from_galley * Rect::from_min_size(Pos2::ZERO, galley.size()); self.selection_bbox_this_frame |= galley_rect; if let Some(selection) = &self.selection && selection.primary.widget_id == response.id { process_selection_key_events(ui.ctx(), galley, response.id, &mut cursor_range); } if got_copy_event(ui.ctx()) { self.copy_text(galley_rect, galley, &cursor_range); } cursor_state.set_char_range(Some(cursor_range)); } // Look for changes due to keyboard and/or mouse interaction: let new_range = cursor_state.range(galley); let selection_changed = old_range != new_range; if let (true, Some(range)) = (selection_changed, new_range) { // -------------- // Store results: if let Some(selection) = &mut self.selection { let primary_changed = Some(range.primary) != old_range.map(|r| r.primary); let secondary_changed = Some(range.secondary) != old_range.map(|r| r.secondary); selection.layer_id = response.layer_id; if primary_changed || !ui.style().interaction.multi_widget_text_select { selection.primary = WidgetTextCursor::new(widget_id, range.primary, global_from_galley, galley); self.has_reached_primary = true; } if secondary_changed || !ui.style().interaction.multi_widget_text_select { selection.secondary = WidgetTextCursor::new( widget_id, range.secondary, global_from_galley, galley, ); self.has_reached_secondary = true; } } else { // Start of a new selection self.selection = Some(CurrentSelection { layer_id: response.layer_id, primary: WidgetTextCursor::new( widget_id, range.primary, global_from_galley, galley, ), secondary: WidgetTextCursor::new( widget_id, range.secondary, global_from_galley, galley, ), }); self.has_reached_primary = true; self.has_reached_secondary = true; } } // Scroll containing ScrollArea on cursor change: if let Some(range) = new_range { let old_primary = old_selection.map(|s| s.primary); let new_primary = self.selection.as_ref().map(|s| s.primary); if let Some(new_primary) = new_primary { let primary_changed = old_primary.is_none_or(|old| { old.widget_id != new_primary.widget_id || old.ccursor != new_primary.ccursor }); if primary_changed && new_primary.widget_id == widget_id { let is_fully_visible = ui.clip_rect().contains_rect(response.rect); // TODO(emilk): remove this HACK workaround for https://github.com/emilk/egui/issues/1531 if selection_changed && !is_fully_visible { // Scroll to keep primary cursor in view: let row_height = estimate_row_height(galley); let primary_cursor_rect = global_from_galley * cursor_rect(galley, &range.primary, row_height); ui.scroll_to_rect(primary_cursor_rect, None); } } } } let cursor_range = cursor_state.range(galley); let mut new_vertex_indices = vec![]; if let Some(cursor_range) = cursor_range { paint_text_selection( galley, ui.visuals(), &cursor_range, Some(&mut new_vertex_indices), ); } super::accesskit_text::update_accesskit_for_text_widget( ui.ctx(), response.id, cursor_range, accesskit::Role::Label, global_from_galley, galley, ); new_vertex_indices } } fn got_copy_event(ctx: &Context) -> bool { ctx.input(|i| { i.events .iter() .any(|e| matches!(e, Event::Copy | Event::Cut)) }) } /// Returns true if the cursor changed fn process_selection_key_events( ctx: &Context, galley: &Galley, widget_id: Id, cursor_range: &mut CCursorRange, ) -> bool { let os = ctx.os(); let mut changed = false; ctx.input(|i| { // NOTE: we have a lock on ui/ctx here, // so be careful to not call into `ui` or `ctx` again. for event in &i.events { changed |= cursor_range.on_event(os, event, galley, widget_id); } }); changed } fn selected_text(galley: &Galley, cursor_range: &CCursorRange) -> String { // This logic means we can select everything in an elided label (including the `…`) // and still copy the entire un-elided text! let everything_is_selected = cursor_range.contains(CCursorRange::select_all(galley)); let copy_everything = cursor_range.is_empty() || everything_is_selected; if copy_everything { galley.text().to_owned() } else { cursor_range.slice_str(galley).to_owned() } } fn estimate_row_height(galley: &Galley) -> f32 { if let Some(placed_row) = galley.rows.first() { placed_row.height() } else { galley.size().y } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/button.rs
crates/egui/src/widgets/button.rs
use epaint::Margin; use crate::{ Atom, AtomExt as _, AtomKind, AtomLayout, AtomLayoutResponse, Color32, CornerRadius, Frame, Image, IntoAtoms, NumExt as _, Response, Sense, Stroke, TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetType, widget_style::{ButtonStyle, WidgetState}, }; /// Clickable button with text. /// /// See also [`Ui::button`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # fn do_stuff() {} /// /// if ui.add(egui::Button::new("Click me")).clicked() { /// do_stuff(); /// } /// /// // A greyed-out and non-interactive button: /// if ui.add_enabled(false, egui::Button::new("Can't click this")).clicked() { /// unreachable!(); /// } /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Button<'a> { layout: AtomLayout<'a>, fill: Option<Color32>, stroke: Option<Stroke>, small: bool, frame: Option<bool>, frame_when_inactive: bool, min_size: Vec2, corner_radius: Option<CornerRadius>, selected: bool, image_tint_follows_text_color: bool, limit_image_size: bool, } impl<'a> Button<'a> { pub fn new(atoms: impl IntoAtoms<'a>) -> Self { Self { layout: AtomLayout::new(atoms.into_atoms()) .sense(Sense::click()) .fallback_font(TextStyle::Button), fill: None, stroke: None, small: false, frame: None, frame_when_inactive: true, min_size: Vec2::ZERO, corner_radius: None, selected: false, image_tint_follows_text_color: false, limit_image_size: false, } } /// Show a selectable button. /// /// Equivalent to: /// ```rust /// # use egui::{Button, IntoAtoms, __run_test_ui}; /// # __run_test_ui(|ui| { /// let selected = true; /// ui.add(Button::new("toggle me").selected(selected).frame_when_inactive(!selected).frame(true)); /// # }); /// ``` /// /// See also: /// - [`Ui::selectable_value`] /// - [`Ui::selectable_label`] pub fn selectable(selected: bool, atoms: impl IntoAtoms<'a>) -> Self { Self::new(atoms) .selected(selected) .frame_when_inactive(selected) .frame(true) } /// Creates a button with an image. The size of the image as displayed is defined by the provided size. /// /// Note: In contrast to [`Button::new`], this limits the image size to the default font height /// (using [`crate::AtomExt::atom_max_height_font_size`]). pub fn image(image: impl Into<Image<'a>>) -> Self { Self::opt_image_and_text(Some(image.into()), None) } /// Creates a button with an image to the left of the text. /// /// Note: In contrast to [`Button::new`], this limits the image size to the default font height /// (using [`crate::AtomExt::atom_max_height_font_size`]). pub fn image_and_text(image: impl Into<Image<'a>>, text: impl Into<WidgetText>) -> Self { Self::opt_image_and_text(Some(image.into()), Some(text.into())) } /// Create a button with an optional image and optional text. /// /// Note: In contrast to [`Button::new`], this limits the image size to the default font height /// (using [`crate::AtomExt::atom_max_height_font_size`]). pub fn opt_image_and_text(image: Option<Image<'a>>, text: Option<WidgetText>) -> Self { let mut button = Self::new(()); if let Some(image) = image { button.layout.push_right(image); } if let Some(text) = text { button.layout.push_right(text); } button.limit_image_size = true; button } /// Set the wrap mode for the text. /// /// By default, [`crate::Ui::wrap_mode`] will be used, which can be overridden with [`crate::Style::wrap_mode`]. /// /// Note that any `\n` in the text will always produce a new line. #[inline] pub fn wrap_mode(mut self, wrap_mode: TextWrapMode) -> Self { self.layout = self.layout.wrap_mode(wrap_mode); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Wrap`]. #[inline] pub fn wrap(self) -> Self { self.wrap_mode(TextWrapMode::Wrap) } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Truncate`]. #[inline] pub fn truncate(self) -> Self { self.wrap_mode(TextWrapMode::Truncate) } /// Override background fill color. Note that this will override any on-hover effects. /// Calling this will also turn on the frame. #[inline] pub fn fill(mut self, fill: impl Into<Color32>) -> Self { self.fill = Some(fill.into()); self } /// Override button stroke. Note that this will override any on-hover effects. /// Calling this will also turn on the frame. #[inline] pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self { self.stroke = Some(stroke.into()); self.frame = Some(true); self } /// Make this a small button, suitable for embedding into text. #[inline] pub fn small(mut self) -> Self { self.small = true; self } /// Turn off the frame #[inline] pub fn frame(mut self, frame: bool) -> Self { self.frame = Some(frame); self } /// If `false`, the button will not have a frame when inactive. /// /// Default: `true`. /// /// Note: When [`Self::frame`] (or `ui.visuals().button_frame`) is `false`, this setting /// has no effect. #[inline] pub fn frame_when_inactive(mut self, frame_when_inactive: bool) -> Self { self.frame_when_inactive = frame_when_inactive; self } /// By default, buttons senses clicks. /// Change this to a drag-button with `Sense::drag()`. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.layout = self.layout.sense(sense); self } /// Set the minimum size of the button. #[inline] pub fn min_size(mut self, min_size: Vec2) -> Self { self.min_size = min_size; self } /// Set the rounding of the button. #[inline] pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius = Some(corner_radius.into()); self } #[inline] #[deprecated = "Renamed to `corner_radius`"] pub fn rounding(self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius(corner_radius) } /// If true, the tint of the image is multiplied by the widget text color. /// /// This makes sense for images that are white, that should have the same color as the text color. /// This will also make the icon color depend on hover state. /// /// Default: `false`. #[inline] pub fn image_tint_follows_text_color(mut self, image_tint_follows_text_color: bool) -> Self { self.image_tint_follows_text_color = image_tint_follows_text_color; self } /// Show some text on the right side of the button, in weak color. /// /// Designed for menu buttons, for setting a keyboard shortcut text (e.g. `Ctrl+S`). /// /// The text can be created with [`crate::Context::format_shortcut`]. /// /// See also [`Self::right_text`]. #[inline] pub fn shortcut_text(mut self, shortcut_text: impl IntoAtoms<'a>) -> Self { self.layout.push_right(Atom::grow()); for mut atom in shortcut_text.into_atoms() { atom.kind = match atom.kind { AtomKind::Text(text) => AtomKind::Text(text.weak()), other => other, }; self.layout.push_right(atom); } self } /// Show some text on the right side of the button. #[inline] pub fn right_text(mut self, right_text: impl IntoAtoms<'a>) -> Self { self.layout.push_right(Atom::grow()); for atom in right_text.into_atoms() { self.layout.push_right(atom); } self } /// If `true`, mark this button as "selected". #[inline] pub fn selected(mut self, selected: bool) -> Self { self.selected = selected; self } /// Show the button and return a [`AtomLayoutResponse`] for painting custom contents. pub fn atom_ui(self, ui: &mut Ui) -> AtomLayoutResponse { let Button { mut layout, fill, stroke, small, frame, frame_when_inactive, mut min_size, corner_radius, selected, image_tint_follows_text_color, limit_image_size, } = self; // Min size height always equal or greater than interact size if not small if !small { min_size.y = min_size.y.at_least(ui.spacing().interact_size.y); } if limit_image_size { layout.map_atoms(|atom| { if matches!(&atom.kind, AtomKind::Image(_)) { atom.atom_max_height_font_size(ui) } else { atom } }); } let text = layout.text().map(String::from); let has_frame_margin = frame.unwrap_or_else(|| ui.visuals().button_frame); let id = ui.next_auto_id(); let response: Option<Response> = ui.ctx().read_response(id); let state = response.map(|r| r.widget_state()).unwrap_or_default(); let ButtonStyle { frame, text_style } = ui.style().button_style(state, selected); let mut button_padding = if has_frame_margin { frame.inner_margin } else { Margin::ZERO }; if small { button_padding.bottom = 0; button_padding.top = 0; } // Override global style by local style let mut frame = frame; if let Some(fill) = fill { frame = frame.fill(fill); } if let Some(corner_radius) = corner_radius { frame = frame.corner_radius(corner_radius); } if let Some(stroke) = stroke { frame = frame.stroke(stroke); } frame = frame.inner_margin(button_padding); // Apply the style font and color as fallback layout = layout .fallback_font(text_style.font_id.clone()) .fallback_text_color(text_style.color); // Retrocompatibility with button settings layout = if has_frame_margin && (state != WidgetState::Inactive || frame_when_inactive) { layout.frame(frame) } else { layout.frame(Frame::new().inner_margin(frame.inner_margin)) }; let mut prepared = layout.min_size(min_size).allocate(ui); // Get AtomLayoutResponse, empty if not visible let response = if ui.is_rect_visible(prepared.response.rect) { if image_tint_follows_text_color { prepared.map_images(|image| image.tint(text_style.color)); } prepared.fallback_text_color = text_style.color; prepared.paint(ui) } else { AtomLayoutResponse::empty(prepared.response) }; response.response.widget_info(|| { if let Some(text) = &text { WidgetInfo::labeled(WidgetType::Button, ui.is_enabled(), text) } else { WidgetInfo::new(WidgetType::Button) } }); response } } impl Widget for Button<'_> { fn ui(self, ui: &mut Ui) -> Response { self.atom_ui(ui).response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/image.rs
crates/egui/src/widgets/image.rs
use std::{borrow::Cow, slice::Iter, sync::Arc, time::Duration}; use emath::{Align, Float as _, GuiRounding as _, NumExt as _, Rot2}; use epaint::{ RectShape, text::{LayoutJob, TextFormat, TextWrapping}, }; use crate::{ Color32, Context, CornerRadius, Id, Mesh, Painter, Rect, Response, Sense, Shape, Spinner, TextStyle, TextureOptions, Ui, Vec2, Widget, WidgetInfo, WidgetType, load::{Bytes, SizeHint, SizedTexture, TextureLoadResult, TexturePoll}, pos2, }; /// A widget which displays an image. /// /// The task of actually loading the image is deferred to when the `Image` is added to the [`Ui`], /// and how it is loaded depends on the provided [`ImageSource`]: /// /// - [`ImageSource::Uri`] will load the image using the [asynchronous loading process][`crate::load`]. /// - [`ImageSource::Bytes`] will also load the image using the [asynchronous loading process][`crate::load`], but with lower latency. /// - [`ImageSource::Texture`] will use the provided texture. /// /// See [`crate::load`] for more information. /// /// ### Examples /// // Using it in a layout: /// ``` /// # egui::__run_test_ui(|ui| { /// ui.add( /// egui::Image::new(egui::include_image!("../../assets/ferris.png")) /// .corner_radius(5) /// ); /// # }); /// ``` /// /// // Using it just to paint: /// ``` /// # egui::__run_test_ui(|ui| { /// # let rect = egui::Rect::from_min_size(Default::default(), egui::Vec2::splat(100.0)); /// egui::Image::new(egui::include_image!("../../assets/ferris.png")) /// .corner_radius(5) /// .tint(egui::Color32::LIGHT_BLUE) /// .paint_at(ui, rect); /// # }); /// ``` /// #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] #[derive(Debug, Clone)] pub struct Image<'a> { source: ImageSource<'a>, texture_options: TextureOptions, image_options: ImageOptions, sense: Sense, size: ImageSize, pub(crate) show_loading_spinner: Option<bool>, pub(crate) alt_text: Option<String>, } impl<'a> Image<'a> { /// Load the image from some source. pub fn new(source: impl Into<ImageSource<'a>>) -> Self { fn new_mono(source: ImageSource<'_>) -> Image<'_> { let size = if let ImageSource::Texture(tex) = &source { // User is probably expecting their texture to have // the exact size of the provided `SizedTexture`. ImageSize { maintain_aspect_ratio: true, max_size: Vec2::INFINITY, fit: ImageFit::Exact(tex.size), } } else { Default::default() }; Image { source, texture_options: Default::default(), image_options: Default::default(), sense: Sense::hover(), size, show_loading_spinner: None, alt_text: None, } } new_mono(source.into()) } /// Load the image from a URI. /// /// See [`ImageSource::Uri`]. pub fn from_uri(uri: impl Into<Cow<'a, str>>) -> Self { Self::new(ImageSource::Uri(uri.into())) } /// Load the image from an existing texture. /// /// See [`ImageSource::Texture`]. pub fn from_texture(texture: impl Into<SizedTexture>) -> Self { Self::new(ImageSource::Texture(texture.into())) } /// Load the image from some raw bytes. /// /// For better error messages, use the `bytes://` prefix for the URI. /// /// See [`ImageSource::Bytes`]. pub fn from_bytes(uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) -> Self { Self::new(ImageSource::Bytes { uri: uri.into(), bytes: bytes.into(), }) } /// Texture options used when creating the texture. #[inline] pub fn texture_options(mut self, texture_options: TextureOptions) -> Self { self.texture_options = texture_options; self } /// Set the max width of the image. /// /// No matter what the image is scaled to, it will never exceed this limit. #[inline] pub fn max_width(mut self, width: f32) -> Self { self.size.max_size.x = width; self } /// Set the max height of the image. /// /// No matter what the image is scaled to, it will never exceed this limit. #[inline] pub fn max_height(mut self, height: f32) -> Self { self.size.max_size.y = height; self } /// Set the max size of the image. /// /// No matter what the image is scaled to, it will never exceed this limit. #[inline] pub fn max_size(mut self, size: Vec2) -> Self { self.size.max_size = size; self } /// Whether or not the [`ImageFit`] should maintain the image's original aspect ratio. #[inline] pub fn maintain_aspect_ratio(mut self, value: bool) -> Self { self.size.maintain_aspect_ratio = value; self } /// Fit the image to its original size with some scaling. /// /// The texel size of the source image will be multiplied by the `scale` factor, /// and then become the _ui_ size of the [`Image`]. /// /// This will cause the image to overflow if it is larger than the available space. /// /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit. #[inline] pub fn fit_to_original_size(mut self, scale: f32) -> Self { self.size.fit = ImageFit::Original { scale }; self } /// Fit the image to an exact size. /// /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit. #[inline] pub fn fit_to_exact_size(mut self, size: Vec2) -> Self { self.size.fit = ImageFit::Exact(size); self } /// Fit the image to a fraction of the available space. /// /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit. #[inline] pub fn fit_to_fraction(mut self, fraction: Vec2) -> Self { self.size.fit = ImageFit::Fraction(fraction); self } /// Fit the image to 100% of its available size, shrinking it if necessary. /// /// This is a shorthand for [`Image::fit_to_fraction`] with `1.0` for both width and height. /// /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit. #[inline] pub fn shrink_to_fit(self) -> Self { self.fit_to_fraction(Vec2::new(1.0, 1.0)) } /// Make the image respond to clicks and/or drags. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = sense; self } /// Select UV range. Default is (0,0) in top-left, (1,1) bottom right. #[inline] pub fn uv(mut self, uv: impl Into<Rect>) -> Self { self.image_options.uv = uv.into(); self } /// A solid color to put behind the image. Useful for transparent images. #[inline] pub fn bg_fill(mut self, bg_fill: impl Into<Color32>) -> Self { self.image_options.bg_fill = bg_fill.into(); self } /// Multiply image color with this. Default is WHITE (no tint). #[inline] pub fn tint(mut self, tint: impl Into<Color32>) -> Self { self.image_options.tint = tint.into(); self } /// Rotate the image about an origin by some angle /// /// Positive angle is clockwise. /// Origin is a vector in normalized UV space ((0,0) in top-left, (1,1) bottom right). /// /// To rotate about the center you can pass `Vec2::splat(0.5)` as the origin. /// /// Due to limitations in the current implementation, /// this will turn off rounding of the image. #[inline] pub fn rotate(mut self, angle: f32, origin: Vec2) -> Self { self.image_options.rotation = Some((Rot2::from_angle(angle), origin)); self.image_options.corner_radius = CornerRadius::ZERO; // incompatible with rotation self } /// Round the corners of the image. /// /// The default is no rounding ([`CornerRadius::ZERO`]). /// /// Due to limitations in the current implementation, /// this will turn off any rotation of the image. #[inline] pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self { self.image_options.corner_radius = corner_radius.into(); if self.image_options.corner_radius != CornerRadius::ZERO { self.image_options.rotation = None; // incompatible with rounding } self } /// Round the corners of the image. /// /// The default is no rounding ([`CornerRadius::ZERO`]). /// /// Due to limitations in the current implementation, /// this will turn off any rotation of the image. #[inline] #[deprecated = "Renamed to `corner_radius`"] pub fn rounding(self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius(corner_radius) } /// Show a spinner when the image is loading. /// /// By default this uses the value of [`crate::Visuals::image_loading_spinners`]. #[inline] pub fn show_loading_spinner(mut self, show: bool) -> Self { self.show_loading_spinner = Some(show); self } /// Set alt text for the image. This will be shown when the image fails to load. /// /// It will also be used for accessibility (e.g. read by screen readers). #[inline] pub fn alt_text(mut self, label: impl Into<String>) -> Self { self.alt_text = Some(label.into()); self } } impl<'a, T: Into<ImageSource<'a>>> From<T> for Image<'a> { fn from(value: T) -> Self { Image::new(value) } } impl<'a> Image<'a> { /// Returns the size the image will occupy in the final UI. #[inline] pub fn calc_size(&self, available_size: Vec2, image_source_size: Option<Vec2>) -> Vec2 { let image_source_size = image_source_size.unwrap_or(Vec2::splat(24.0)); // Fallback for still-loading textures, or failure to load. self.size.calc_size(available_size, image_source_size) } pub fn load_and_calc_size(&self, ui: &Ui, available_size: Vec2) -> Option<Vec2> { let image_size = self.load_for_size(ui.ctx(), available_size).ok()?.size()?; Some(self.size.calc_size(available_size, image_size)) } #[inline] pub fn size(&self) -> Option<Vec2> { match &self.source { ImageSource::Texture(texture) => Some(texture.size), ImageSource::Uri(_) | ImageSource::Bytes { .. } => None, } } /// Returns the URI of the image. /// /// For animated images, returns the URI without the frame number. #[inline] pub fn uri(&self) -> Option<&str> { let uri = self.source.uri()?; if let Ok((gif_uri, _index)) = decode_animated_image_uri(uri) { Some(gif_uri) } else { Some(uri) } } #[inline] pub fn image_options(&self) -> &ImageOptions { &self.image_options } #[inline] pub fn source(&'a self, ctx: &Context) -> ImageSource<'a> { match &self.source { ImageSource::Uri(uri) if is_animated_image_uri(uri) => { let frame_uri = encode_animated_image_uri(uri, animated_image_frame_index(ctx, uri)); ImageSource::Uri(Cow::Owned(frame_uri)) } ImageSource::Bytes { uri, bytes } if are_animated_image_bytes(bytes) => { let frame_uri = encode_animated_image_uri(uri, animated_image_frame_index(ctx, uri)); ctx.include_bytes(uri.clone(), bytes.clone()); ImageSource::Uri(Cow::Owned(frame_uri)) } _ => self.source.clone(), } } /// Load the image from its [`Image::source`], returning the resulting [`SizedTexture`]. /// /// The `available_size` is used as a hint when e.g. rendering an svg. /// /// # Errors /// May fail if they underlying [`Context::try_load_texture`] call fails. pub fn load_for_size(&self, ctx: &Context, available_size: Vec2) -> TextureLoadResult { let size_hint = self.size.hint(available_size, ctx.pixels_per_point()); self.source(ctx) .clone() .load(ctx, self.texture_options, size_hint) } /// Paint the image in the given rectangle. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let rect = egui::Rect::from_min_size(Default::default(), egui::Vec2::splat(100.0)); /// egui::Image::new(egui::include_image!("../../assets/ferris.png")) /// .corner_radius(5) /// .tint(egui::Color32::LIGHT_BLUE) /// .paint_at(ui, rect); /// # }); /// ``` #[inline] pub fn paint_at(&self, ui: &Ui, rect: Rect) { let pixels_per_point = ui.pixels_per_point(); let rect = rect.round_to_pixels(pixels_per_point); // Load exactly the size of the rectangle we are painting to. // This is important for getting crisp SVG:s. let pixel_size = (pixels_per_point * rect.size()).round(); let texture = self.source(ui.ctx()).clone().load( ui.ctx(), self.texture_options, SizeHint::Size { width: pixel_size.x as _, height: pixel_size.y as _, maintain_aspect_ratio: false, // no - just get exactly what we asked for }, ); paint_texture_load_result( ui, &texture, rect, self.show_loading_spinner, &self.image_options, self.alt_text.as_deref(), ); } } impl Widget for Image<'_> { fn ui(self, ui: &mut Ui) -> Response { let tlr = self.load_for_size(ui.ctx(), ui.available_size()); let image_source_size = tlr.as_ref().ok().and_then(|t| t.size()); let ui_size = self.calc_size(ui.available_size(), image_source_size); let (rect, response) = ui.allocate_exact_size(ui_size, self.sense); response.widget_info(|| { let mut info = WidgetInfo::new(WidgetType::Image); info.label = self.alt_text.clone(); info }); if ui.is_rect_visible(rect) { paint_texture_load_result( ui, &tlr, rect, self.show_loading_spinner, &self.image_options, self.alt_text.as_deref(), ); } texture_load_result_response(&self.source(ui.ctx()), &tlr, response) } } /// This type determines the constraints on how /// the size of an image should be calculated. #[derive(Debug, Clone, Copy)] pub struct ImageSize { /// Whether or not the final size should maintain the original aspect ratio. /// /// This setting is applied last. /// /// This defaults to `true`. pub maintain_aspect_ratio: bool, /// Determines the maximum size of the image. /// /// Defaults to `Vec2::INFINITY` (no limit). pub max_size: Vec2, /// Determines how the image should shrink/expand/stretch/etc. to fit within its allocated space. /// /// This setting is applied first. /// /// Defaults to `ImageFit::Fraction([1, 1])` pub fit: ImageFit, } /// This type determines how the image should try to fit within the UI. /// /// The final fit will be clamped to [`ImageSize::max_size`]. #[derive(Debug, Clone, Copy)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ImageFit { /// Fit the image to its original srce size, scaled by some factor. /// /// The original size of the image is usually its texel resolution, /// but for an SVG it's the point size of the SVG. /// /// Ignores how much space is actually available in the ui. Original { scale: f32 }, /// Fit the image to a fraction of the available size. Fraction(Vec2), /// Fit the image to an exact size. /// /// Ignores how much space is actually available in the ui. Exact(Vec2), } impl ImageFit { pub fn resolve(self, available_size: Vec2, image_size: Vec2) -> Vec2 { match self { Self::Original { scale } => image_size * scale, Self::Fraction(fract) => available_size * fract, Self::Exact(size) => size, } } } impl ImageSize { /// Size hint for e.g. rasterizing an svg. pub fn hint(&self, available_size: Vec2, pixels_per_point: f32) -> SizeHint { let Self { maintain_aspect_ratio, max_size, fit, } = *self; let point_size = match fit { ImageFit::Original { scale } => { return SizeHint::Scale((pixels_per_point * scale).ord()); } ImageFit::Fraction(fract) => available_size * fract, ImageFit::Exact(size) => size, }; let point_size = point_size.at_most(max_size); let pixel_size = pixels_per_point * point_size; // `inf` on an axis means "any value" match (pixel_size.x.is_finite(), pixel_size.y.is_finite()) { (true, true) => SizeHint::Size { width: pixel_size.x.round() as u32, height: pixel_size.y.round() as u32, maintain_aspect_ratio, }, (true, false) => SizeHint::Width(pixel_size.x.round() as u32), (false, true) => SizeHint::Height(pixel_size.y.round() as u32), (false, false) => SizeHint::Scale(pixels_per_point.ord()), } } /// Calculate the final on-screen size in points. pub fn calc_size(&self, available_size: Vec2, image_source_size: Vec2) -> Vec2 { let Self { maintain_aspect_ratio, max_size, fit, } = *self; match fit { ImageFit::Original { scale } => { let image_size = scale * image_source_size; if image_size.x <= max_size.x && image_size.y <= max_size.y { image_size } else { scale_to_fit(image_size, max_size, maintain_aspect_ratio) } } ImageFit::Fraction(fract) => { let scale_to_size = (available_size * fract).min(max_size); scale_to_fit(image_source_size, scale_to_size, maintain_aspect_ratio) } ImageFit::Exact(size) => { let scale_to_size = size.min(max_size); scale_to_fit(image_source_size, scale_to_size, maintain_aspect_ratio) } } } } // TODO(jprochazk): unit-tests fn scale_to_fit(image_size: Vec2, available_size: Vec2, maintain_aspect_ratio: bool) -> Vec2 { if maintain_aspect_ratio { let ratio_x = available_size.x / image_size.x; let ratio_y = available_size.y / image_size.y; let ratio = if ratio_x < ratio_y { ratio_x } else { ratio_y }; let ratio = if ratio.is_finite() { ratio } else { 1.0 }; image_size * ratio } else { available_size } } impl Default for ImageSize { #[inline] fn default() -> Self { Self { max_size: Vec2::INFINITY, fit: ImageFit::Fraction(Vec2::new(1.0, 1.0)), maintain_aspect_ratio: true, } } } /// This type tells the [`Ui`] how to load an image. /// /// This is used by [`Image::new`] and [`Ui::image`]. #[derive(Clone)] pub enum ImageSource<'a> { /// Load the image from a URI, e.g. `https://example.com/image.png`. /// /// This could be a `file://` path, `https://` url, `bytes://` identifier, or some other scheme. /// /// How the URI will be turned into a texture for rendering purposes is /// up to the registered loaders to handle. /// /// See [`crate::load`] for more information. Uri(Cow<'a, str>), /// Load the image from an existing texture. /// /// The user is responsible for loading the texture, determining its size, /// and allocating a [`crate::TextureId`] for it. Texture(SizedTexture), /// Load the image from some raw bytes. /// /// The [`Bytes`] may be: /// - `'static`, obtained from `include_bytes!` or similar /// - Anything that can be converted to `Arc<[u8]>` /// /// This instructs the [`Ui`] to cache the raw bytes, which are then further processed by any registered loaders. /// /// See also [`crate::include_image`] for an easy way to load and display static images. /// /// See [`crate::load`] for more information. Bytes { /// The unique identifier for this image, e.g. `bytes://my_logo.png`. /// /// You should use a proper extension (`.jpg`, `.png`, `.svg`, etc) for the image to load properly. /// /// Use the `bytes://` scheme for the URI for better error messages. uri: Cow<'static, str>, bytes: Bytes, }, } impl std::fmt::Debug for ImageSource<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ImageSource::Bytes { uri, .. } | ImageSource::Uri(uri) => uri.as_ref().fmt(f), ImageSource::Texture(st) => st.id.fmt(f), } } } impl ImageSource<'_> { /// Size of the texture, if known. #[inline] pub fn texture_size(&self) -> Option<Vec2> { match self { ImageSource::Texture(texture) => Some(texture.size), ImageSource::Uri(_) | ImageSource::Bytes { .. } => None, } } /// # Errors /// Failure to load the texture. pub fn load( self, ctx: &Context, texture_options: TextureOptions, size_hint: SizeHint, ) -> TextureLoadResult { match self { Self::Texture(texture) => Ok(TexturePoll::Ready { texture }), Self::Uri(uri) => ctx.try_load_texture(uri.as_ref(), texture_options, size_hint), Self::Bytes { uri, bytes } => { ctx.include_bytes(uri.clone(), bytes); ctx.try_load_texture(uri.as_ref(), texture_options, size_hint) } } } /// Get the `uri` that this image was constructed from. /// /// This will return `None` for [`Self::Texture`]. pub fn uri(&self) -> Option<&str> { match self { ImageSource::Bytes { uri, .. } | ImageSource::Uri(uri) => Some(uri), ImageSource::Texture(_) => None, } } } pub fn paint_texture_load_result( ui: &Ui, tlr: &TextureLoadResult, rect: Rect, show_loading_spinner: Option<bool>, options: &ImageOptions, alt_text: Option<&str>, ) { match tlr { Ok(TexturePoll::Ready { texture }) => { paint_texture_at(ui.painter(), rect, options, texture); } Ok(TexturePoll::Pending { .. }) => { let show_loading_spinner = show_loading_spinner.unwrap_or_else(|| ui.visuals().image_loading_spinners); if show_loading_spinner { Spinner::new().paint_at(ui, rect); } } Err(_) => { let font_id = TextStyle::Body.resolve(ui.style()); let mut job = LayoutJob { wrap: TextWrapping::truncate_at_width(rect.width()), halign: Align::Center, ..Default::default() }; job.append( "⚠", 0.0, TextFormat::simple(font_id.clone(), ui.visuals().error_fg_color), ); if let Some(alt_text) = alt_text { job.append( alt_text, ui.spacing().item_spacing.x, TextFormat::simple(font_id, ui.visuals().text_color()), ); } let galley = ui.painter().layout_job(job); ui.painter().galley( rect.center() - Vec2::Y * galley.size().y * 0.5, galley, ui.visuals().text_color(), ); } } } /// Attach tooltips like "Loading…" or "Failed loading: …". pub fn texture_load_result_response( source: &ImageSource<'_>, tlr: &TextureLoadResult, response: Response, ) -> Response { match tlr { Ok(TexturePoll::Ready { .. }) => response, Ok(TexturePoll::Pending { .. }) => { let uri = source.uri().unwrap_or("image"); response.on_hover_text(format!("Loading {uri}…")) } Err(err) => { let uri = source.uri().unwrap_or("image"); response.on_hover_text(format!("Failed loading {uri}: {err}")) } } } impl<'a> From<&'a str> for ImageSource<'a> { #[inline] fn from(value: &'a str) -> Self { Self::Uri(value.into()) } } impl<'a> From<&'a String> for ImageSource<'a> { #[inline] fn from(value: &'a String) -> Self { Self::Uri(value.as_str().into()) } } impl From<String> for ImageSource<'static> { fn from(value: String) -> Self { Self::Uri(value.into()) } } impl<'a> From<&'a Cow<'a, str>> for ImageSource<'a> { #[inline] fn from(value: &'a Cow<'a, str>) -> Self { Self::Uri(value.clone()) } } impl<'a> From<Cow<'a, str>> for ImageSource<'a> { #[inline] fn from(value: Cow<'a, str>) -> Self { Self::Uri(value) } } impl<T: Into<Bytes>> From<(&'static str, T)> for ImageSource<'static> { #[inline] fn from((uri, bytes): (&'static str, T)) -> Self { Self::Bytes { uri: uri.into(), bytes: bytes.into(), } } } impl<T: Into<Bytes>> From<(Cow<'static, str>, T)> for ImageSource<'static> { #[inline] fn from((uri, bytes): (Cow<'static, str>, T)) -> Self { Self::Bytes { uri, bytes: bytes.into(), } } } impl<T: Into<Bytes>> From<(String, T)> for ImageSource<'static> { #[inline] fn from((uri, bytes): (String, T)) -> Self { Self::Bytes { uri: uri.into(), bytes: bytes.into(), } } } impl<T: Into<SizedTexture>> From<T> for ImageSource<'static> { fn from(value: T) -> Self { Self::Texture(value.into()) } } #[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ImageOptions { /// Select UV range. Default is (0,0) in top-left, (1,1) bottom right. pub uv: Rect, /// A solid color to put behind the image. Useful for transparent images. pub bg_fill: Color32, /// Multiply image color with this. Default is WHITE (no tint). pub tint: Color32, /// Rotate the image about an origin by some angle /// /// Positive angle is clockwise. /// Origin is a vector in normalized UV space ((0,0) in top-left, (1,1) bottom right). /// /// To rotate about the center you can pass `Vec2::splat(0.5)` as the origin. /// /// Due to limitations in the current implementation, /// this will turn off rounding of the image. pub rotation: Option<(Rot2, Vec2)>, /// Round the corners of the image. /// /// The default is no rounding ([`CornerRadius::ZERO`]). /// /// Due to limitations in the current implementation, /// this will turn off any rotation of the image. pub corner_radius: CornerRadius, } impl Default for ImageOptions { fn default() -> Self { Self { uv: Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), bg_fill: Default::default(), tint: Color32::WHITE, rotation: None, corner_radius: CornerRadius::ZERO, } } } pub fn paint_texture_at( painter: &Painter, rect: Rect, options: &ImageOptions, texture: &SizedTexture, ) { if options.bg_fill != Default::default() { painter.add(RectShape::filled( rect, options.corner_radius, options.bg_fill, )); } match options.rotation { Some((rot, origin)) => { // TODO(emilk): implement this using `PathShape` (add texture support to it). // This will also give us anti-aliasing of rotated images. debug_assert!( options.corner_radius == CornerRadius::ZERO, "Image had both rounding and rotation. Please pick only one" ); let mut mesh = Mesh::with_texture(texture.id); mesh.add_rect_with_uv(rect, options.uv, options.tint); mesh.rotate(rot, rect.min + origin * rect.size()); painter.add(Shape::mesh(mesh)); } None => { painter.add( RectShape::filled(rect, options.corner_radius, options.tint) .with_texture(texture.id, options.uv), ); } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] /// Stores the durations between each frame of an animated image pub struct FrameDurations(Arc<Vec<Duration>>); impl FrameDurations { pub fn new(durations: Vec<Duration>) -> Self { Self(Arc::new(durations)) } pub fn all(&self) -> Iter<'_, Duration> { self.0.iter() } } /// Animated image uris contain the uri & the frame that will be displayed fn encode_animated_image_uri(uri: &str, frame_index: usize) -> String { format!("{uri}#{frame_index}") } /// Extracts uri and frame index /// # Errors /// Will return `Err` if `uri` does not match pattern {uri}-{frame_index} pub fn decode_animated_image_uri(uri: &str) -> Result<(&str, usize), String> { let (uri, index) = uri .rsplit_once('#') .ok_or("Failed to find index separator '#'")?; let index: usize = index.parse().map_err(|_err| { format!("Failed to parse animated image frame index: {index:?} is not an integer") })?; Ok((uri, index)) } /// Calculates at which frame the animated image is fn animated_image_frame_index(ctx: &Context, uri: &str) -> usize { let now = ctx.input(|input| Duration::from_secs_f64(input.time)); let durations: Option<FrameDurations> = ctx.data(|data| data.get_temp(Id::new(uri))); if let Some(durations) = durations { let frames: Duration = durations.all().sum(); let pos_ms = now.as_millis() % frames.as_millis().max(1); let mut cumulative_ms = 0; for (index, duration) in durations.all().enumerate() { cumulative_ms += duration.as_millis(); if pos_ms < cumulative_ms { let ms_until_next_frame = cumulative_ms - pos_ms; ctx.request_repaint_after(Duration::from_millis(ms_until_next_frame as u64)); return index; } } } 0 } /// Checks if uri is a gif file fn is_gif_uri(uri: &str) -> bool { uri.ends_with(".gif") || uri.contains(".gif#") } /// Checks if bytes are gifs pub fn has_gif_magic_header(bytes: &[u8]) -> bool { bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") } /// Checks if uri is a webp file fn is_webp_uri(uri: &str) -> bool { uri.ends_with(".webp") || uri.contains(".webp#") } /// Checks if bytes are webp pub fn has_webp_header(bytes: &[u8]) -> bool { bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" } fn is_animated_image_uri(uri: &str) -> bool { is_gif_uri(uri) || is_webp_uri(uri) } fn are_animated_image_bytes(bytes: &[u8]) -> bool { has_gif_magic_header(bytes) || has_webp_header(bytes) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/radio_button.rs
crates/egui/src/widgets/radio_button.rs
use crate::{ Atom, AtomLayout, Atoms, Id, IntoAtoms, NumExt as _, Response, Sense, Ui, Vec2, Widget, WidgetInfo, WidgetType, epaint, }; /// One out of several alternatives, either selected or not. /// /// Usually you'd use [`Ui::radio_value`] or [`Ui::radio`] instead. /// /// ``` /// # egui::__run_test_ui(|ui| { /// #[derive(PartialEq)] /// enum Enum { First, Second, Third } /// let mut my_enum = Enum::First; /// /// ui.radio_value(&mut my_enum, Enum::First, "First"); /// /// // is equivalent to: /// /// if ui.add(egui::RadioButton::new(my_enum == Enum::First, "First")).clicked() { /// my_enum = Enum::First /// } /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct RadioButton<'a> { checked: bool, atoms: Atoms<'a>, } impl<'a> RadioButton<'a> { pub fn new(checked: bool, atoms: impl IntoAtoms<'a>) -> Self { Self { checked, atoms: atoms.into_atoms(), } } } impl Widget for RadioButton<'_> { fn ui(self, ui: &mut Ui) -> Response { let Self { checked, mut atoms } = self; let spacing = &ui.spacing(); let icon_width = spacing.icon_width; let mut min_size = Vec2::splat(spacing.interact_size.y); min_size.y = min_size.y.at_least(icon_width); // In order to center the checkbox based on min_size we set the icon height to at least min_size.y let mut icon_size = Vec2::splat(icon_width); icon_size.y = icon_size.y.at_least(min_size.y); let rect_id = Id::new("egui::radio_button"); atoms.push_left(Atom::custom(rect_id, icon_size)); let text = atoms.text().map(String::from); let mut prepared = AtomLayout::new(atoms) .sense(Sense::click()) .min_size(min_size) .allocate(ui); prepared.response.widget_info(|| { WidgetInfo::selected( WidgetType::RadioButton, ui.is_enabled(), checked, text.as_deref().unwrap_or(""), ) }); if ui.is_rect_visible(prepared.response.rect) { // let visuals = ui.style().interact_selectable(&response, checked); // too colorful let visuals = *ui.style().interact(&prepared.response); prepared.fallback_text_color = visuals.text_color(); let response = prepared.paint(ui); if let Some(rect) = response.rect(rect_id) { let (small_icon_rect, big_icon_rect) = ui.spacing().icon_rectangles(rect); let painter = ui.painter(); painter.add(epaint::CircleShape { center: big_icon_rect.center(), radius: big_icon_rect.width() / 2.0 + visuals.expansion, fill: visuals.bg_fill, stroke: visuals.bg_stroke, }); if checked { painter.add(epaint::CircleShape { center: small_icon_rect.center(), radius: small_icon_rect.width() / 3.0, fill: visuals.fg_stroke.color, // Intentional to use stroke and not fill // fill: ui.visuals().selection.stroke.color, // too much color stroke: Default::default(), }); } } response.response } else { prepared.response } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/hyperlink.rs
crates/egui/src/widgets/hyperlink.rs
use crate::{ CursorIcon, Label, Response, Sense, Stroke, Ui, Widget, WidgetInfo, WidgetText, WidgetType, epaint, text_selection, }; use self::text_selection::LabelSelectionState; /// Clickable text, that looks like a hyperlink. /// /// To link to a web page, use [`Hyperlink`], [`Ui::hyperlink`] or [`Ui::hyperlink_to`]. /// /// See also [`Ui::link`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// // These are equivalent: /// if ui.link("Documentation").clicked() { /// // … /// } /// /// if ui.add(egui::Link::new("Documentation")).clicked() { /// // … /// } /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Link { text: WidgetText, } impl Link { pub fn new(text: impl Into<WidgetText>) -> Self { Self { text: text.into() } } } impl Widget for Link { fn ui(self, ui: &mut Ui) -> Response { let Self { text } = self; let label = Label::new(text).sense(Sense::click()); let (galley_pos, galley, response) = label.layout_in_ui(ui); response .widget_info(|| WidgetInfo::labeled(WidgetType::Link, ui.is_enabled(), galley.text())); if ui.is_rect_visible(response.rect) { let color = ui.visuals().hyperlink_color; let visuals = ui.style().interact(&response); let underline = if response.hovered() || response.has_focus() { Stroke::new(visuals.fg_stroke.width, color) } else { Stroke::NONE }; let selectable = ui.style().interaction.selectable_labels; if selectable { LabelSelectionState::label_text_selection( ui, &response, galley_pos, galley, color, underline, ); } else { ui.painter().add( epaint::TextShape::new(galley_pos, galley, color).with_underline(underline), ); } if response.hovered() { ui.set_cursor_icon(CursorIcon::PointingHand); } } response } } /// A clickable hyperlink, e.g. to `"https://github.com/emilk/egui"`. /// /// See also [`Ui::hyperlink`] and [`Ui::hyperlink_to`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// // These are equivalent: /// ui.hyperlink("https://github.com/emilk/egui"); /// ui.add(egui::Hyperlink::new("https://github.com/emilk/egui")); /// /// // These are equivalent: /// ui.hyperlink_to("My favorite repo", "https://github.com/emilk/egui"); /// ui.add(egui::Hyperlink::from_label_and_url("My favorite repo", "https://github.com/emilk/egui")); /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Hyperlink { url: String, text: WidgetText, new_tab: bool, } impl Hyperlink { #[expect(clippy::needless_pass_by_value)] pub fn new(url: impl ToString) -> Self { let url = url.to_string(); Self { url: url.clone(), text: url.into(), new_tab: false, } } #[expect(clippy::needless_pass_by_value)] pub fn from_label_and_url(text: impl Into<WidgetText>, url: impl ToString) -> Self { Self { url: url.to_string(), text: text.into(), new_tab: false, } } /// Always open this hyperlink in a new browser tab. #[inline] pub fn open_in_new_tab(mut self, new_tab: bool) -> Self { self.new_tab = new_tab; self } } impl Widget for Hyperlink { fn ui(self, ui: &mut Ui) -> Response { let Self { url, text, new_tab } = self; let response = ui.add(Link::new(text)); if response.clicked_with_open_in_background() { ui.open_url(crate::OpenUrl { url: url.clone(), new_tab: true, }); } else if response.clicked() { ui.open_url(crate::OpenUrl { url: url.clone(), new_tab, }); } if ui.style().url_in_tooltip { response.on_hover_text(url) } else { response } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/slider.rs
crates/egui/src/widgets/slider.rs
#![expect(clippy::needless_pass_by_value)] // False positives with `impl ToString` use std::ops::RangeInclusive; use crate::{ Color32, DragValue, EventFilter, Key, Label, MINUS_CHAR_STR, NumExt as _, Pos2, Rangef, Rect, Response, Sense, TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, emath, epaint, lerp, pos2, remap, remap_clamp, style, style::HandleShape, vec2, }; use super::drag_value::clamp_value_to_range; // ---------------------------------------------------------------------------- type NumFormatter<'a> = Box<dyn 'a + Fn(f64, RangeInclusive<usize>) -> String>; type NumParser<'a> = Box<dyn 'a + Fn(&str) -> Option<f64>>; // ---------------------------------------------------------------------------- /// Combined into one function (rather than two) to make it easier /// for the borrow checker. type GetSetValue<'a> = Box<dyn 'a + FnMut(Option<f64>) -> f64>; fn get(get_set_value: &mut GetSetValue<'_>) -> f64 { (get_set_value)(None) } fn set(get_set_value: &mut GetSetValue<'_>, value: f64) { (get_set_value)(Some(value)); } // ---------------------------------------------------------------------------- #[derive(Clone)] struct SliderSpec { logarithmic: bool, /// For logarithmic sliders, the smallest positive value we are interested in. /// 1 for integer sliders, maybe 1e-6 for others. smallest_positive: f64, /// For logarithmic sliders, the largest positive value we are interested in /// before the slider switches to `INFINITY`, if that is the higher end. /// Default: INFINITY. largest_finite: f64, } /// Specifies the orientation of a [`Slider`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum SliderOrientation { Horizontal, Vertical, } /// Specifies how values in a [`Slider`] are clamped. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum SliderClamping { /// Values are not clamped. /// /// This means editing the value with the keyboard, /// or dragging the number next to the slider will always work. /// /// The actual slider part is always clamped though. Never, /// Users cannot enter new values that are outside the range. /// /// Existing values remain intact though. Edits, /// Always clamp values, even existing ones. #[default] Always, } /// Control a number with a slider. /// /// The slider range defines the values you get when pulling the slider to the far edges. /// By default all values are clamped to this range, even when not interacted with. /// You can change this behavior by passing `false` to [`Slider::clamp_to_range`]. /// /// The range can include any numbers, and go from low-to-high or from high-to-low. /// /// The slider consists of three parts: a slider, a value display, and an optional text. /// The user can click the value display to edit its value. It can be turned off with `.show_value(false)`. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_f32: f32 = 0.0; /// ui.add(egui::Slider::new(&mut my_f32, 0.0..=100.0).text("My value")); /// # }); /// ``` /// /// The default [`Slider`] size is set by [`crate::style::Spacing::slider_width`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Slider<'a> { get_set_value: GetSetValue<'a>, range: RangeInclusive<f64>, spec: SliderSpec, clamping: SliderClamping, smart_aim: bool, show_value: bool, orientation: SliderOrientation, prefix: String, suffix: String, text: WidgetText, /// Sets the minimal step of the widget value step: Option<f64>, drag_value_speed: Option<f64>, min_decimals: usize, max_decimals: Option<usize>, custom_formatter: Option<NumFormatter<'a>>, custom_parser: Option<NumParser<'a>>, trailing_fill: Option<bool>, handle_shape: Option<HandleShape>, update_while_editing: bool, } impl<'a> Slider<'a> { /// Creates a new horizontal slider. /// /// The `value` given will be clamped to the `range`, /// unless you change this behavior with [`Self::clamping`]. pub fn new<Num: emath::Numeric>(value: &'a mut Num, range: RangeInclusive<Num>) -> Self { let range_f64 = range.start().to_f64()..=range.end().to_f64(); let slf = Self::from_get_set(range_f64, move |v: Option<f64>| { if let Some(v) = v { *value = Num::from_f64(v); } value.to_f64() }); if Num::INTEGRAL { slf.integer() } else { slf } } pub fn from_get_set( range: RangeInclusive<f64>, get_set_value: impl 'a + FnMut(Option<f64>) -> f64, ) -> Self { Self { get_set_value: Box::new(get_set_value), range, spec: SliderSpec { logarithmic: false, smallest_positive: 1e-6, largest_finite: f64::INFINITY, }, clamping: SliderClamping::default(), smart_aim: true, show_value: true, orientation: SliderOrientation::Horizontal, prefix: Default::default(), suffix: Default::default(), text: Default::default(), step: None, drag_value_speed: None, min_decimals: 0, max_decimals: None, custom_formatter: None, custom_parser: None, trailing_fill: None, handle_shape: None, update_while_editing: true, } } /// Control whether or not the slider shows the current value. /// Default: `true`. #[inline] pub fn show_value(mut self, show_value: bool) -> Self { self.show_value = show_value; self } /// Show a prefix before the number, e.g. "x: " #[inline] pub fn prefix(mut self, prefix: impl ToString) -> Self { self.prefix = prefix.to_string(); self } /// Add a suffix to the number, this can be e.g. a unit ("°" or " m") #[inline] pub fn suffix(mut self, suffix: impl ToString) -> Self { self.suffix = suffix.to_string(); self } /// Show a text next to the slider (e.g. explaining what the slider controls). #[inline] pub fn text(mut self, text: impl Into<WidgetText>) -> Self { self.text = text.into(); self } #[inline] pub fn text_color(mut self, text_color: Color32) -> Self { self.text = self.text.color(text_color); self } /// Vertical or horizontal slider? The default is horizontal. #[inline] pub fn orientation(mut self, orientation: SliderOrientation) -> Self { self.orientation = orientation; self } /// Make this a vertical slider. #[inline] pub fn vertical(mut self) -> Self { self.orientation = SliderOrientation::Vertical; self } /// Make this a logarithmic slider. /// This is great for when the slider spans a huge range, /// e.g. from one to a million. /// The default is OFF. #[inline] pub fn logarithmic(mut self, logarithmic: bool) -> Self { self.spec.logarithmic = logarithmic; self } /// For logarithmic sliders that includes zero: /// what is the smallest positive value you want to be able to select? /// The default is `1` for integer sliders and `1e-6` for real sliders. #[inline] pub fn smallest_positive(mut self, smallest_positive: f64) -> Self { self.spec.smallest_positive = smallest_positive; self } /// For logarithmic sliders, the largest positive value we are interested in /// before the slider switches to `INFINITY`, if that is the higher end. /// Default: INFINITY. #[inline] pub fn largest_finite(mut self, largest_finite: f64) -> Self { self.spec.largest_finite = largest_finite; self } /// Controls when the values will be clamped to the range. /// /// ### With `.clamping(SliderClamping::Always)` (default) /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// ui.add(egui::Slider::new(&mut my_value, 0.0..=1.0)); /// assert!(0.0 <= my_value && my_value <= 1.0, "Existing value should be clamped"); /// # }); /// ``` /// /// ### With `.clamping(SliderClamping::Edits)` /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// let response = ui.add( /// egui::Slider::new(&mut my_value, 0.0..=1.0) /// .clamping(egui::SliderClamping::Edits) /// ); /// if response.dragged() { /// // The user edited the value, so it should now be clamped to the range /// assert!(0.0 <= my_value && my_value <= 1.0); /// } /// # }); /// ``` /// /// ### With `.clamping(SliderClamping::Never)` /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// let response = ui.add( /// egui::Slider::new(&mut my_value, 0.0..=1.0) /// .clamping(egui::SliderClamping::Never) /// ); /// // The user could have set the value to anything /// # }); /// ``` #[inline] pub fn clamping(mut self, clamping: SliderClamping) -> Self { self.clamping = clamping; self } #[inline] #[deprecated = "Use `slider.clamping(…) instead"] pub fn clamp_to_range(self, clamp_to_range: bool) -> Self { self.clamping(if clamp_to_range { SliderClamping::Always } else { SliderClamping::Never }) } /// Turn smart aim on/off. Default is ON. /// There is almost no point in turning this off. #[inline] pub fn smart_aim(mut self, smart_aim: bool) -> Self { self.smart_aim = smart_aim; self } /// Sets the minimal change of the value. /// /// Value `0.0` effectively disables the feature. If the new value is out of range /// and `clamp_to_range` is enabled, you would not have the ability to change the value. /// /// Default: `0.0` (disabled). #[inline] pub fn step_by(mut self, step: f64) -> Self { self.step = if step != 0.0 { Some(step) } else { None }; self } /// When dragging the value, how fast does it move? /// /// Unit: values per point (logical pixel). /// See also [`DragValue::speed`]. /// /// By default this is the same speed as when dragging the slider, /// but you can change it here to for instance have a much finer control /// by dragging the slider value rather than the slider itself. #[inline] pub fn drag_value_speed(mut self, drag_value_speed: f64) -> Self { self.drag_value_speed = Some(drag_value_speed); self } // TODO(emilk): we should also have a "min precision". /// Set a minimum number of decimals to display. /// /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn min_decimals(mut self, min_decimals: usize) -> Self { self.min_decimals = min_decimals; self } // TODO(emilk): we should also have a "max precision". /// Set a maximum number of decimals to display. /// /// Values will also be rounded to this number of decimals. /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn max_decimals(mut self, max_decimals: usize) -> Self { self.max_decimals = Some(max_decimals); self } #[inline] pub fn max_decimals_opt(mut self, max_decimals: Option<usize>) -> Self { self.max_decimals = max_decimals; self } /// Set an exact number of decimals to display. /// /// Values will also be rounded to this number of decimals. /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn fixed_decimals(mut self, num_decimals: usize) -> Self { self.min_decimals = num_decimals; self.max_decimals = Some(num_decimals); self } /// Display trailing color behind the slider's circle. Default is OFF. /// /// This setting can be enabled globally for all sliders with [`crate::Visuals::slider_trailing_fill`]. /// Toggling it here will override the above setting ONLY for this individual slider. /// /// The fill color will be taken from `selection.bg_fill` in your [`crate::Visuals`], the same as a [`crate::ProgressBar`]. #[inline] pub fn trailing_fill(mut self, trailing_fill: bool) -> Self { self.trailing_fill = Some(trailing_fill); self } /// Change the shape of the slider handle /// /// This setting can be enabled globally for all sliders with [`crate::Visuals::handle_shape`]. /// Changing it here will override the above setting ONLY for this individual slider. #[inline] pub fn handle_shape(mut self, handle_shape: HandleShape) -> Self { self.handle_shape = Some(handle_shape); self } /// Set custom formatter defining how numbers are converted into text. /// /// A custom formatter takes a `f64` for the numeric value and a `RangeInclusive<usize>` representing /// the decimal range i.e. minimum and maximum number of decimal places shown. /// /// The default formatter is [`crate::Style::number_formatter`]. /// /// See also: [`Slider::custom_parser`] /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::Slider::new(&mut my_i32, 0..=((60 * 60 * 24) - 1)) /// .custom_formatter(|n, _| { /// let n = n as i32; /// let hours = n / (60 * 60); /// let mins = (n / 60) % 60; /// let secs = n % 60; /// format!("{hours:02}:{mins:02}:{secs:02}") /// }) /// .custom_parser(|s| { /// let parts: Vec<&str> = s.split(':').collect(); /// if parts.len() == 3 { /// parts[0].parse::<i32>().and_then(|h| { /// parts[1].parse::<i32>().and_then(|m| { /// parts[2].parse::<i32>().map(|s| { /// ((h * 60 * 60) + (m * 60) + s) as f64 /// }) /// }) /// }) /// .ok() /// } else { /// None /// } /// })); /// # }); /// ``` pub fn custom_formatter( mut self, formatter: impl 'a + Fn(f64, RangeInclusive<usize>) -> String, ) -> Self { self.custom_formatter = Some(Box::new(formatter)); self } /// Set custom parser defining how the text input is parsed into a number. /// /// A custom parser takes an `&str` to parse into a number and returns `Some` if it was successfully parsed /// or `None` otherwise. /// /// See also: [`Slider::custom_formatter`] /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::Slider::new(&mut my_i32, 0..=((60 * 60 * 24) - 1)) /// .custom_formatter(|n, _| { /// let n = n as i32; /// let hours = n / (60 * 60); /// let mins = (n / 60) % 60; /// let secs = n % 60; /// format!("{hours:02}:{mins:02}:{secs:02}") /// }) /// .custom_parser(|s| { /// let parts: Vec<&str> = s.split(':').collect(); /// if parts.len() == 3 { /// parts[0].parse::<i32>().and_then(|h| { /// parts[1].parse::<i32>().and_then(|m| { /// parts[2].parse::<i32>().map(|s| { /// ((h * 60 * 60) + (m * 60) + s) as f64 /// }) /// }) /// }) /// .ok() /// } else { /// None /// } /// })); /// # }); /// ``` #[inline] pub fn custom_parser(mut self, parser: impl 'a + Fn(&str) -> Option<f64>) -> Self { self.custom_parser = Some(Box::new(parser)); self } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as binary integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::Slider::new(&mut my_i32, -100..=100).binary(64, false)); /// # }); /// ``` pub fn binary(self, min_width: usize, twos_complement: bool) -> Self { assert!( min_width > 0, "Slider::binary: `min_width` must be greater than 0" ); if twos_complement { self.custom_formatter(move |n, _| format!("{:0>min_width$b}", n as i64)) } else { self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$b}", n.abs() as i64) }) } .custom_parser(|s| i64::from_str_radix(s, 2).map(|n| n as f64).ok()) } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as octal integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::Slider::new(&mut my_i32, -100..=100).octal(22, false)); /// # }); /// ``` pub fn octal(self, min_width: usize, twos_complement: bool) -> Self { assert!( min_width > 0, "Slider::octal: `min_width` must be greater than 0" ); if twos_complement { self.custom_formatter(move |n, _| format!("{:0>min_width$o}", n as i64)) } else { self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$o}", n.abs() as i64) }) } .custom_parser(|s| i64::from_str_radix(s, 8).map(|n| n as f64).ok()) } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as hexadecimal integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::Slider::new(&mut my_i32, -100..=100).hexadecimal(16, false, true)); /// # }); /// ``` pub fn hexadecimal(self, min_width: usize, twos_complement: bool, upper: bool) -> Self { assert!( min_width > 0, "Slider::hexadecimal: `min_width` must be greater than 0" ); match (twos_complement, upper) { (true, true) => { self.custom_formatter(move |n, _| format!("{:0>min_width$X}", n as i64)) } (true, false) => { self.custom_formatter(move |n, _| format!("{:0>min_width$x}", n as i64)) } (false, true) => self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$X}", n.abs() as i64) }), (false, false) => self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$x}", n.abs() as i64) }), } .custom_parser(|s| i64::from_str_radix(s, 16).map(|n| n as f64).ok()) } /// Helper: equivalent to `self.precision(0).smallest_positive(1.0)`. /// If you use one of the integer constructors (e.g. `Slider::i32`) this is called for you, /// but if you want to have a slider for picking integer values in an `Slider::f64`, use this. pub fn integer(self) -> Self { self.fixed_decimals(0).smallest_positive(1.0).step_by(1.0) } fn get_value(&mut self) -> f64 { let value = get(&mut self.get_set_value); if self.clamping == SliderClamping::Always { clamp_value_to_range(value, self.range.clone()) } else { value } } fn set_value(&mut self, mut value: f64) { if self.clamping != SliderClamping::Never { value = clamp_value_to_range(value, self.range.clone()); } if let Some(step) = self.step { let start = *self.range.start(); value = start + ((value - start) / step).round() * step; } if let Some(max_decimals) = self.max_decimals { value = emath::round_to_decimals(value, max_decimals); } set(&mut self.get_set_value, value); } fn range(&self) -> RangeInclusive<f64> { self.range.clone() } /// For instance, `position` is the mouse position and `position_range` is the physical location of the slider on the screen. fn value_from_position(&self, position: f32, position_range: Rangef) -> f64 { let normalized = remap_clamp(position, position_range, 0.0..=1.0) as f64; value_from_normalized(normalized, self.range(), &self.spec) } fn position_from_value(&self, value: f64, position_range: Rangef) -> f32 { let normalized = normalized_from_value(value, self.range(), &self.spec); lerp(position_range, normalized as f32) } /// Update the value on each key press when text-editing the value. /// /// Default: `true`. /// If `false`, the value will only be updated when user presses enter or deselects the value. #[inline] pub fn update_while_editing(mut self, update: bool) -> Self { self.update_while_editing = update; self } } impl Slider<'_> { /// Just the slider, no text fn allocate_slider_space(&self, ui: &mut Ui, thickness: f32) -> Response { let desired_size = match self.orientation { SliderOrientation::Horizontal => vec2(ui.spacing().slider_width, thickness), SliderOrientation::Vertical => vec2(thickness, ui.spacing().slider_width), }; ui.allocate_response(desired_size, Sense::drag()) } /// Just the slider, no text fn slider_ui(&mut self, ui: &Ui, response: &Response) { let rect = &response.rect; let handle_shape = self .handle_shape .unwrap_or_else(|| ui.style().visuals.handle_shape); let position_range = self.position_range(rect, &handle_shape); if let Some(pointer_position_2d) = response.interact_pointer_pos() { let position = self.pointer_position(pointer_position_2d); let new_value = if self.smart_aim { let aim_radius = ui.input(|i| i.aim_radius()); emath::smart_aim::best_in_range_f64( self.value_from_position(position - aim_radius, position_range), self.value_from_position(position + aim_radius, position_range), ) } else { self.value_from_position(position, position_range) }; self.set_value(new_value); } let mut decrement = 0usize; let mut increment = 0usize; if response.has_focus() { ui.memory_mut(|m| { m.set_focus_lock_filter( response.id, EventFilter { // pressing arrows in the orientation of the // slider should not move focus to next widget horizontal_arrows: matches!( self.orientation, SliderOrientation::Horizontal ), vertical_arrows: matches!(self.orientation, SliderOrientation::Vertical), ..Default::default() }, ); }); let (dec_key, inc_key) = match self.orientation { SliderOrientation::Horizontal => (Key::ArrowLeft, Key::ArrowRight), // Note that this is for moving the slider position, // so up = decrement y coordinate: SliderOrientation::Vertical => (Key::ArrowUp, Key::ArrowDown), }; ui.input(|input| { decrement += input.num_presses(dec_key); increment += input.num_presses(inc_key); }); } ui.input(|input| { use accesskit::Action; decrement += input.num_accesskit_action_requests(response.id, Action::Decrement); increment += input.num_accesskit_action_requests(response.id, Action::Increment); }); let kb_step = increment as f32 - decrement as f32; if kb_step != 0.0 { let ui_point_per_step = 1.0; // move this many ui points for each kb_step let prev_value = self.get_value(); let prev_position = self.position_from_value(prev_value, position_range); let new_position = prev_position + ui_point_per_step * kb_step; let mut new_value = match self.step { Some(step) => prev_value + (kb_step as f64 * step), None if self.smart_aim => { let aim_radius = 0.49 * ui_point_per_step; // Chosen so we don't include `prev_value` in the search. emath::smart_aim::best_in_range_f64( self.value_from_position(new_position - aim_radius, position_range), self.value_from_position(new_position + aim_radius, position_range), ) } _ => self.value_from_position(new_position, position_range), }; if let Some(max_decimals) = self.max_decimals { // self.set_value rounds, so ensure we reach at the least the next breakpoint // note: we give it a little bit of leeway due to floating point errors. (0.1 isn't representable in binary) // 'set_value' will round it to the nearest value. let min_increment = 1.0 / (10.0_f64.powi(max_decimals as i32)); new_value = if new_value > prev_value { f64::max(new_value, prev_value + min_increment * 1.001) } else if new_value < prev_value { f64::min(new_value, prev_value - min_increment * 1.001) } else { new_value }; } self.set_value(new_value); } ui.input(|input| { use accesskit::{Action, ActionData}; for request in input.accesskit_action_requests(response.id, Action::SetValue) { if let Some(ActionData::NumericValue(new_value)) = request.data { self.set_value(new_value); } } }); // Paint it: if ui.is_rect_visible(response.rect) { let value = self.get_value(); let visuals = ui.style().interact(response); let widget_visuals = &ui.visuals().widgets; let spacing = &ui.style().spacing; let rail_radius = (spacing.slider_rail_height / 2.0).at_least(0.0); let rail_rect = self.rail_rect(rect, rail_radius); let corner_radius = widget_visuals.inactive.corner_radius; ui.painter() .rect_filled(rail_rect, corner_radius, widget_visuals.inactive.bg_fill); let position_1d = self.position_from_value(value, position_range); let center = self.marker_center(position_1d, &rail_rect); // Decide if we should add trailing fill. let trailing_fill = self .trailing_fill .unwrap_or_else(|| ui.visuals().slider_trailing_fill); // Paint trailing fill. if trailing_fill { let mut trailing_rail_rect = rail_rect; // The trailing rect has to be drawn differently depending on the orientation. match self.orientation { SliderOrientation::Horizontal => { trailing_rail_rect.max.x = center.x + corner_radius.nw as f32; } SliderOrientation::Vertical => { trailing_rail_rect.min.y = center.y - corner_radius.se as f32; } } ui.painter().rect_filled( trailing_rail_rect, corner_radius, ui.visuals().selection.bg_fill, ); } let radius = self.handle_radius(rect); let handle_shape = self .handle_shape .unwrap_or_else(|| ui.style().visuals.handle_shape); match handle_shape { style::HandleShape::Circle => { ui.painter().add(epaint::CircleShape { center, radius: radius + visuals.expansion, fill: visuals.bg_fill, stroke: visuals.fg_stroke, }); } style::HandleShape::Rect { aspect_ratio } => { let v = match self.orientation { SliderOrientation::Horizontal => Vec2::new(radius * aspect_ratio, radius), SliderOrientation::Vertical => Vec2::new(radius, radius * aspect_ratio), }; let v = v + Vec2::splat(visuals.expansion); let rect = Rect::from_center_size(center, 2.0 * v); ui.painter().rect( rect, visuals.corner_radius, visuals.bg_fill, visuals.fg_stroke, epaint::StrokeKind::Inside, ); } } } } fn marker_center(&self, position_1d: f32, rail_rect: &Rect) -> Pos2 { match self.orientation { SliderOrientation::Horizontal => pos2(position_1d, rail_rect.center().y), SliderOrientation::Vertical => pos2(rail_rect.center().x, position_1d), } } fn pointer_position(&self, pointer_position_2d: Pos2) -> f32 { match self.orientation { SliderOrientation::Horizontal => pointer_position_2d.x, SliderOrientation::Vertical => pointer_position_2d.y, } } fn position_range(&self, rect: &Rect, handle_shape: &style::HandleShape) -> Rangef { let handle_radius = self.handle_radius(rect); let handle_radius = match handle_shape { style::HandleShape::Circle => handle_radius,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/image_button.rs
crates/egui/src/widgets/image_button.rs
use crate::{ Color32, CornerRadius, Image, Rect, Response, Sense, Ui, Vec2, Widget, WidgetInfo, WidgetType, widgets, }; /// A clickable image within a frame. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] #[derive(Clone, Debug)] #[deprecated(since = "0.33.0", note = "Use egui::Button::image instead")] pub struct ImageButton<'a> { pub(crate) image: Image<'a>, sense: Sense, frame: bool, selected: bool, alt_text: Option<String>, } #[expect(deprecated, reason = "Deprecated in egui 0.33.0")] impl<'a> ImageButton<'a> { pub fn new(image: impl Into<Image<'a>>) -> Self { Self { image: image.into(), sense: Sense::click(), frame: true, selected: false, alt_text: None, } } /// Select UV range. Default is (0,0) in top-left, (1,1) bottom right. #[inline] pub fn uv(mut self, uv: impl Into<Rect>) -> Self { self.image = self.image.uv(uv); self } /// Multiply image color with this. Default is WHITE (no tint). #[inline] pub fn tint(mut self, tint: impl Into<Color32>) -> Self { self.image = self.image.tint(tint); self } /// If `true`, mark this button as "selected". #[inline] pub fn selected(mut self, selected: bool) -> Self { self.selected = selected; self } /// Turn off the frame #[inline] pub fn frame(mut self, frame: bool) -> Self { self.frame = frame; self } /// By default, buttons senses clicks. /// Change this to a drag-button with `Sense::drag()`. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = sense; self } /// Set rounding for the `ImageButton`. /// /// If the underlying image already has rounding, this /// will override that value. #[inline] pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self { self.image = self.image.corner_radius(corner_radius.into()); self } /// Set rounding for the `ImageButton`. /// /// If the underlying image already has rounding, this /// will override that value. #[inline] #[deprecated = "Renamed to `corner_radius`"] pub fn rounding(self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius(corner_radius) } } #[expect(deprecated, reason = "Deprecated in egui 0.33.0")] impl Widget for ImageButton<'_> { fn ui(self, ui: &mut Ui) -> Response { let padding = if self.frame { // so we can see that it is a button: Vec2::splat(ui.spacing().button_padding.x) } else { Vec2::ZERO }; let available_size_for_image = ui.available_size() - 2.0 * padding; let tlr = self.image.load_for_size(ui.ctx(), available_size_for_image); let image_source_size = tlr.as_ref().ok().and_then(|t| t.size()); let image_size = self .image .calc_size(available_size_for_image, image_source_size); let padded_size = image_size + 2.0 * padding; let (rect, response) = ui.allocate_exact_size(padded_size, self.sense); response.widget_info(|| { let mut info = WidgetInfo::new(WidgetType::Button); info.label = self.alt_text.clone(); info }); if ui.is_rect_visible(rect) { let (expansion, rounding, fill, stroke) = if self.selected { let selection = ui.visuals().selection; ( Vec2::ZERO, self.image.image_options().corner_radius, selection.bg_fill, selection.stroke, ) } else if self.frame { let visuals = ui.style().interact(&response); let expansion = Vec2::splat(visuals.expansion); ( expansion, self.image.image_options().corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, ) } else { Default::default() }; // Draw frame background (for transparent images): ui.painter() .rect_filled(rect.expand2(expansion), rounding, fill); let image_rect = ui .layout() .align_size_within_rect(image_size, rect.shrink2(padding)); // let image_rect = image_rect.expand2(expansion); // can make it blurry, so let's not let image_options = self.image.image_options().clone(); widgets::image::paint_texture_load_result( ui, &tlr, image_rect, None, &image_options, self.alt_text.as_deref(), ); // Draw frame outline: ui.painter().rect_stroke( rect.expand2(expansion), rounding, stroke, epaint::StrokeKind::Inside, ); } widgets::image::texture_load_result_response(&self.image.source(ui.ctx()), &tlr, response) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/progress_bar.rs
crates/egui/src/widgets/progress_bar.rs
use crate::{ Color32, CornerRadius, NumExt as _, Pos2, Rect, Response, Rgba, Sense, Shape, Stroke, TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetType, lerp, vec2, }; enum ProgressBarText { Custom(WidgetText), Percentage, } /// A simple progress bar. /// /// See also: [`crate::Spinner`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct ProgressBar { progress: f32, desired_width: Option<f32>, desired_height: Option<f32>, text: Option<ProgressBarText>, fill: Option<Color32>, animate: bool, corner_radius: Option<CornerRadius>, } impl ProgressBar { /// Progress in the `[0, 1]` range, where `1` means "completed". pub fn new(progress: f32) -> Self { Self { progress: progress.clamp(0.0, 1.0), desired_width: None, desired_height: None, text: None, fill: None, animate: false, corner_radius: None, } } /// The desired width of the bar. Will use all horizontal space if not set. #[inline] pub fn desired_width(mut self, desired_width: f32) -> Self { self.desired_width = Some(desired_width); self } /// The desired height of the bar. Will use the default interaction size if not set. #[inline] pub fn desired_height(mut self, desired_height: f32) -> Self { self.desired_height = Some(desired_height); self } /// The fill color of the bar. #[inline] pub fn fill(mut self, color: Color32) -> Self { self.fill = Some(color); self } /// A custom text to display on the progress bar. #[inline] pub fn text(mut self, text: impl Into<WidgetText>) -> Self { self.text = Some(ProgressBarText::Custom(text.into())); self } /// Show the progress in percent on the progress bar. #[inline] pub fn show_percentage(mut self) -> Self { self.text = Some(ProgressBarText::Percentage); self } /// Whether to display a loading animation when progress `< 1`. /// Note that this will cause the UI to be redrawn. /// Defaults to `false`. /// /// If [`Self::corner_radius`] and [`Self::animate`] are used simultaneously, the animation is not /// rendered, since it requires a perfect circle to render correctly. However, the UI is still /// redrawn. #[inline] pub fn animate(mut self, animate: bool) -> Self { self.animate = animate; self } /// Set the rounding of the progress bar. /// /// If [`Self::corner_radius`] and [`Self::animate`] are used simultaneously, the animation is not /// rendered, since it requires a perfect circle to render correctly. However, the UI is still /// redrawn. #[inline] pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius = Some(corner_radius.into()); self } #[inline] #[deprecated = "Renamed to `corner_radius`"] pub fn rounding(self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius(corner_radius) } } impl Widget for ProgressBar { fn ui(self, ui: &mut Ui) -> Response { let Self { progress, desired_width, desired_height, text, fill, animate, corner_radius, } = self; let animate = animate && progress < 1.0; let desired_width = desired_width.unwrap_or_else(|| ui.available_size_before_wrap().x.at_least(96.0)); let height = desired_height.unwrap_or_else(|| ui.spacing().interact_size.y); let (outer_rect, response) = ui.allocate_exact_size(vec2(desired_width, height), Sense::hover()); response.widget_info(|| { let mut info = if let Some(ProgressBarText::Custom(text)) = &text { WidgetInfo::labeled(WidgetType::ProgressIndicator, ui.is_enabled(), text.text()) } else { WidgetInfo::new(WidgetType::ProgressIndicator) }; info.value = Some((progress as f64 * 100.0).floor()); info }); if ui.is_rect_visible(response.rect) { if animate { ui.request_repaint(); } let visuals = ui.style().visuals.clone(); let has_custom_cr = corner_radius.is_some(); let half_height = outer_rect.height() / 2.0; let corner_radius = corner_radius.unwrap_or_else(|| half_height.into()); ui.painter() .rect_filled(outer_rect, corner_radius, visuals.extreme_bg_color); let min_width = 2.0 * f32::max(corner_radius.sw as _, corner_radius.nw as _).at_most(half_height); let filled_width = (outer_rect.width() * progress).at_least(min_width); let inner_rect = Rect::from_min_size(outer_rect.min, vec2(filled_width, outer_rect.height())); let (dark, bright) = (0.7, 1.0); let color_factor = if animate { let time = ui.input(|i| i.time); lerp(dark..=bright, time.cos().abs()) } else { bright }; ui.painter().rect_filled( inner_rect, corner_radius, Color32::from( Rgba::from(fill.unwrap_or(visuals.selection.bg_fill)) * color_factor as f32, ), ); if animate && !has_custom_cr { let n_points = 20; let time = ui.input(|i| i.time); let start_angle = time * std::f64::consts::TAU; let end_angle = start_angle + 240f64.to_radians() * time.sin(); let circle_radius = half_height - 2.0; let points: Vec<Pos2> = (0..n_points) .map(|i| { let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64); let (sin, cos) = angle.sin_cos(); inner_rect.right_center() + circle_radius * vec2(cos as f32, sin as f32) + vec2(-half_height, 0.0) }) .collect(); ui.painter() .add(Shape::line(points, Stroke::new(2.0, visuals.text_color()))); } if let Some(text_kind) = text { let text = match text_kind { ProgressBarText::Custom(text) => text, ProgressBarText::Percentage => { format!("{}%", (progress * 100.0) as usize).into() } }; let galley = text.into_galley( ui, Some(TextWrapMode::Extend), f32::INFINITY, TextStyle::Button, ); let text_pos = outer_rect.left_center() - Vec2::new(0.0, galley.size().y / 2.0) + vec2(ui.spacing().item_spacing.x, 0.0); let text_color = visuals .override_text_color .unwrap_or(visuals.selection.stroke.color); ui.painter() .with_clip_rect(outer_rect) .galley(text_pos, galley, text_color); } } response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/separator.rs
crates/egui/src/widgets/separator.rs
use crate::{Response, Sense, Ui, Vec2, Widget, vec2, widget_style::SeparatorStyle}; /// A visual separator. A horizontal or vertical line (depending on [`crate::Layout`]). /// /// Usually you'd use the shorter version [`Ui::separator`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// // These are equivalent: /// ui.separator(); /// ui.add(egui::Separator::default()); /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Separator { spacing: Option<f32>, grow: f32, is_horizontal_line: Option<bool>, } impl Default for Separator { fn default() -> Self { Self { spacing: None, grow: 0.0, is_horizontal_line: None, } } } impl Separator { /// How much space we take up. The line is painted in the middle of this. /// /// In a vertical layout, with a horizontal Separator, /// this is the height of the separator widget. /// /// In a horizontal layout, with a vertical Separator, /// this is the width of the separator widget. #[inline] pub fn spacing(mut self, spacing: f32) -> Self { self.spacing = Some(spacing); self } /// Explicitly ask for a horizontal line. /// /// By default you will get a horizontal line in vertical layouts, /// and a vertical line in horizontal layouts. #[inline] pub fn horizontal(mut self) -> Self { self.is_horizontal_line = Some(true); self } /// Explicitly ask for a vertical line. /// /// By default you will get a horizontal line in vertical layouts, /// and a vertical line in horizontal layouts. #[inline] pub fn vertical(mut self) -> Self { self.is_horizontal_line = Some(false); self } /// Extend each end of the separator line by this much. /// /// The default is to take up the available width/height of the parent. /// /// This will make the line extend outside the parent ui. #[inline] pub fn grow(mut self, extra: f32) -> Self { self.grow += extra; self } /// Contract each end of the separator line by this much. /// /// The default is to take up the available width/height of the parent. /// /// This effectively adds margins to the line. #[inline] pub fn shrink(mut self, shrink: f32) -> Self { self.grow -= shrink; self } } impl Widget for Separator { fn ui(self, ui: &mut Ui) -> Response { let Self { spacing, grow, is_horizontal_line, } = self; // Get the widget style by reading the response from the previous pass let id = ui.next_auto_id(); let response: Option<Response> = ui.ctx().read_response(id); let state = response.map(|r| r.widget_state()).unwrap_or_default(); let SeparatorStyle { spacing: spacing_style, stroke, } = ui.style().separator_style(state); // override the spacing if not set let spacing = spacing.unwrap_or(spacing_style); let is_horizontal_line = is_horizontal_line .unwrap_or_else(|| ui.is_grid() || !ui.layout().main_dir().is_horizontal()); let available_space = if ui.is_sizing_pass() { Vec2::ZERO } else { ui.available_size_before_wrap() }; let size = if is_horizontal_line { vec2(available_space.x, spacing) } else { vec2(spacing, available_space.y) }; let (rect, response) = ui.allocate_at_least(size, Sense::hover()); if ui.is_rect_visible(response.rect) { let painter = ui.painter(); if is_horizontal_line { painter.hline( (rect.left() - grow)..=(rect.right() + grow), rect.center().y, stroke, ); } else { painter.vline( rect.center().x, (rect.top() - grow)..=(rect.bottom() + grow), stroke, ); } } response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/mod.rs
crates/egui/src/widgets/mod.rs
//! Widgets are pieces of GUI such as [`Label`], [`Button`], [`Slider`] etc. //! //! Example widget uses: //! * `ui.add(Label::new("Text").text_color(color::red));` //! * `if ui.add(Button::new("Click me")).clicked() { … }` use crate::{Response, Ui, epaint}; mod button; mod checkbox; pub mod color_picker; pub(crate) mod drag_value; mod hyperlink; mod image; mod image_button; mod label; mod progress_bar; mod radio_button; mod selected_label; mod separator; mod slider; mod spinner; pub mod text_edit; #[expect(deprecated)] pub use self::selected_label::SelectableLabel; #[expect(deprecated, reason = "Deprecated in egui 0.33.0")] pub use self::{ button::Button, checkbox::Checkbox, drag_value::DragValue, hyperlink::{Hyperlink, Link}, image::{ FrameDurations, Image, ImageFit, ImageOptions, ImageSize, ImageSource, decode_animated_image_uri, has_gif_magic_header, has_webp_header, paint_texture_at, }, image_button::ImageButton, label::Label, progress_bar::ProgressBar, radio_button::RadioButton, separator::Separator, slider::{Slider, SliderClamping, SliderOrientation}, spinner::Spinner, text_edit::{TextBuffer, TextEdit}, }; // ---------------------------------------------------------------------------- /// Anything implementing Widget can be added to a [`Ui`] with [`Ui::add`]. /// /// [`Button`], [`Label`], [`Slider`], etc all implement the [`Widget`] trait. /// /// You only need to implement `Widget` if you care about being able to do `ui.add(your_widget);`. /// /// Note that the widgets ([`Button`], [`TextEdit`] etc) are /// [builders](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html), /// and not objects that hold state. /// /// Tip: you can `impl Widget for &mut YourThing { }`. /// /// `|ui: &mut Ui| -> Response { … }` also implements [`Widget`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub trait Widget { /// Allocate space, interact, paint, and return a [`Response`]. /// /// Note that this consumes `self`. /// This is because most widgets ([`Button`], [`TextEdit`] etc) are /// [builders](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html) /// /// Tip: you can `impl Widget for &mut YourObject { }`. fn ui(self, ui: &mut Ui) -> Response; } /// This enables functions that return `impl Widget`, so that you can /// create a widget by just returning a lambda from a function. /// /// For instance: `ui.add(slider_vec2(&mut vec2));` with: /// /// ``` /// pub fn slider_vec2(value: &mut egui::Vec2) -> impl egui::Widget + '_ { /// move |ui: &mut egui::Ui| { /// ui.horizontal(|ui| { /// ui.add(egui::Slider::new(&mut value.x, 0.0..=1.0).text("x")); /// ui.add(egui::Slider::new(&mut value.y, 0.0..=1.0).text("y")); /// }) /// .response /// } /// } /// ``` impl<F> Widget for F where F: FnOnce(&mut Ui) -> Response, { fn ui(self, ui: &mut Ui) -> Response { self(ui) } } /// Helper so that you can do e.g. `TextEdit::State::load`. pub trait WidgetWithState { type State; } // ---------------------------------------------------------------------------- /// Show a button to reset a value to its default. /// The button is only enabled if the value does not already have its original value. /// /// The `text` could be something like "Reset foo". pub fn reset_button<T: Default + PartialEq>(ui: &mut Ui, value: &mut T, text: &str) { reset_button_with(ui, value, text, T::default()); } /// Show a button to reset a value to its default. /// The button is only enabled if the value does not already have its original value. /// /// The `text` could be something like "Reset foo". pub fn reset_button_with<T: PartialEq>(ui: &mut Ui, value: &mut T, text: &str, reset_value: T) { if ui .add_enabled(*value != reset_value, Button::new(text)) .clicked() { *value = reset_value; } } // ---------------------------------------------------------------------------- #[deprecated = "Use `ui.add(&mut stroke)` instead"] pub fn stroke_ui(ui: &mut crate::Ui, stroke: &mut epaint::Stroke, text: &str) { ui.horizontal(|ui| { ui.label(text); ui.add(stroke); }); } /// Show a small button to switch to/from dark/light mode (globally). pub fn global_theme_preference_switch(ui: &mut Ui) { if let Some(new_theme) = ui.ctx().theme().small_toggle_button(ui) { ui.ctx().set_theme(new_theme); } } /// Show larger buttons for switching between light and dark mode (globally). pub fn global_theme_preference_buttons(ui: &mut Ui) { let mut theme_preference = ui.options(|opt| opt.theme_preference); theme_preference.radio_buttons(ui); ui.ctx().set_theme(theme_preference); } /// Show a small button to switch to/from dark/light mode (globally). #[deprecated = "Use global_theme_preference_switch instead"] pub fn global_dark_light_mode_switch(ui: &mut Ui) { global_theme_preference_switch(ui); } /// Show larger buttons for switching between light and dark mode (globally). #[deprecated = "Use global_theme_preference_buttons instead"] pub fn global_dark_light_mode_buttons(ui: &mut Ui) { global_theme_preference_buttons(ui); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/checkbox.rs
crates/egui/src/widgets/checkbox.rs
use emath::Rect; use crate::{ Atom, AtomLayout, Atoms, Id, IntoAtoms, NumExt as _, Response, Sense, Shape, Ui, Vec2, Widget, WidgetInfo, WidgetType, epaint, pos2, widget_style::CheckboxStyle, }; // TODO(emilk): allow checkbox without a text label /// Boolean on/off control with text label. /// /// Usually you'd use [`Ui::checkbox`] instead. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_bool = true; /// // These are equivalent: /// ui.checkbox(&mut my_bool, "Checked"); /// ui.add(egui::Checkbox::new(&mut my_bool, "Checked")); /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Checkbox<'a> { checked: &'a mut bool, atoms: Atoms<'a>, indeterminate: bool, } impl<'a> Checkbox<'a> { pub fn new(checked: &'a mut bool, atoms: impl IntoAtoms<'a>) -> Self { Checkbox { checked, atoms: atoms.into_atoms(), indeterminate: false, } } pub fn without_text(checked: &'a mut bool) -> Self { Self::new(checked, ()) } /// Display an indeterminate state (neither checked nor unchecked) /// /// This only affects the checkbox's appearance. It will still toggle its boolean value when /// clicked. #[inline] pub fn indeterminate(mut self, indeterminate: bool) -> Self { self.indeterminate = indeterminate; self } } impl Widget for Checkbox<'_> { fn ui(self, ui: &mut Ui) -> Response { let Checkbox { checked, mut atoms, indeterminate, } = self; // Get the widget style by reading the response from the previous pass let id = ui.next_auto_id(); let response: Option<Response> = ui.ctx().read_response(id); let state = response.map(|r| r.widget_state()).unwrap_or_default(); let CheckboxStyle { check_size, checkbox_frame, checkbox_size, frame, check_stroke, text_style, } = ui.style().checkbox_style(state); let mut min_size = Vec2::splat(ui.spacing().interact_size.y); min_size.y = min_size.y.at_least(checkbox_size); // In order to center the checkbox based on min_size we set the icon height to at least min_size.y let mut icon_size = Vec2::splat(checkbox_size); icon_size.y = icon_size.y.at_least(min_size.y); let rect_id = Id::new("egui::checkbox"); atoms.push_left(Atom::custom(rect_id, icon_size)); let text = atoms.text().map(String::from); let mut prepared = AtomLayout::new(atoms) .sense(Sense::click()) .min_size(min_size) .frame(frame) .allocate(ui); if prepared.response.clicked() { *checked = !*checked; prepared.response.mark_changed(); } prepared.response.widget_info(|| { if indeterminate { WidgetInfo::labeled( WidgetType::Checkbox, ui.is_enabled(), text.as_deref().unwrap_or(""), ) } else { WidgetInfo::selected( WidgetType::Checkbox, ui.is_enabled(), *checked, text.as_deref().unwrap_or(""), ) } }); if ui.is_rect_visible(prepared.response.rect) { prepared.fallback_text_color = text_style.color; let response = prepared.paint(ui); if let Some(rect) = response.rect(rect_id) { let big_icon_rect = Rect::from_center_size( pos2(rect.left() + checkbox_size / 2.0, rect.center().y), Vec2::splat(checkbox_size), ); let small_icon_rect = Rect::from_center_size(big_icon_rect.center(), Vec2::splat(check_size)); ui.painter().add(epaint::RectShape::new( big_icon_rect.expand(checkbox_frame.inner_margin.left.into()), checkbox_frame.corner_radius, checkbox_frame.fill, checkbox_frame.stroke, epaint::StrokeKind::Inside, )); if indeterminate { // Horizontal line: ui.painter().add(Shape::hline( small_icon_rect.x_range(), small_icon_rect.center().y, check_stroke, )); } else if *checked { // Check mark: ui.painter().add(Shape::line( vec![ pos2(small_icon_rect.left(), small_icon_rect.center().y), pos2(small_icon_rect.center().x, small_icon_rect.bottom()), pos2(small_icon_rect.right(), small_icon_rect.top()), ], check_stroke, )); } } response.response } else { prepared.response } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/label.rs
crates/egui/src/widgets/label.rs
use std::sync::Arc; use crate::{ Align, Direction, FontSelection, Galley, Pos2, Response, Sense, Stroke, TextWrapMode, Ui, Widget, WidgetInfo, WidgetText, WidgetType, epaint, pos2, text_selection::LabelSelectionState, }; /// Static text. /// /// Usually it is more convenient to use [`Ui::label`]. /// /// ``` /// # use egui::TextWrapMode; /// # egui::__run_test_ui(|ui| { /// ui.label("Equivalent"); /// ui.add(egui::Label::new("Equivalent")); /// ui.add(egui::Label::new("With Options").truncate()); /// ui.label(egui::RichText::new("With formatting").underline()); /// # }); /// ``` /// /// For full control of the text you can use [`crate::text::LayoutJob`] /// as argument to [`Self::new`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct Label { text: WidgetText, wrap_mode: Option<TextWrapMode>, sense: Option<Sense>, selectable: Option<bool>, halign: Option<Align>, show_tooltip_when_elided: bool, } impl Label { pub fn new(text: impl Into<WidgetText>) -> Self { Self { text: text.into(), wrap_mode: None, sense: None, selectable: None, halign: None, show_tooltip_when_elided: true, } } pub fn text(&self) -> &str { self.text.text() } /// Set the wrap mode for the text. /// /// By default, [`crate::Ui::wrap_mode`] will be used, which can be overridden with [`crate::Style::wrap_mode`]. /// /// Note that any `\n` in the text will always produce a new line. #[inline] pub fn wrap_mode(mut self, wrap_mode: TextWrapMode) -> Self { self.wrap_mode = Some(wrap_mode); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Wrap`]. #[inline] pub fn wrap(mut self) -> Self { self.wrap_mode = Some(TextWrapMode::Wrap); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Truncate`]. #[inline] pub fn truncate(mut self) -> Self { self.wrap_mode = Some(TextWrapMode::Truncate); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Extend`], /// disabling wrapping and truncating, and instead expanding the parent [`Ui`]. #[inline] pub fn extend(mut self) -> Self { self.wrap_mode = Some(TextWrapMode::Extend); self } /// Sets the horizontal alignment of the Label to the given `Align` value. #[inline] pub fn halign(mut self, align: Align) -> Self { self.halign = Some(align); self } /// Can the user select the text with the mouse? /// /// Overrides [`crate::style::Interaction::selectable_labels`]. #[inline] pub fn selectable(mut self, selectable: bool) -> Self { self.selectable = Some(selectable); self } /// Make the label respond to clicks and/or drags. /// /// By default, a label is inert and does not respond to click or drags. /// By calling this you can turn the label into a button of sorts. /// This will also give the label the hover-effect of a button, but without the frame. /// /// ``` /// # use egui::{Label, Sense}; /// # egui::__run_test_ui(|ui| { /// if ui.add(Label::new("click me").sense(Sense::click())).clicked() { /// /* … */ /// } /// # }); /// ``` #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = Some(sense); self } /// Show the full text when hovered, if the text was elided. /// /// By default, this is true. /// /// ``` /// # use egui::{Label, Sense}; /// # egui::__run_test_ui(|ui| { /// ui.add(Label::new("some text").show_tooltip_when_elided(false)) /// .on_hover_text("completely different text"); /// # }); /// ``` #[inline] pub fn show_tooltip_when_elided(mut self, show: bool) -> Self { self.show_tooltip_when_elided = show; self } } impl Label { /// Do layout and position the galley in the ui, without painting it or adding widget info. pub fn layout_in_ui(self, ui: &mut Ui) -> (Pos2, Arc<Galley>, Response) { let selectable = self .selectable .unwrap_or_else(|| ui.style().interaction.selectable_labels); let mut sense = self.sense.unwrap_or_else(|| { if ui.memory(|mem| mem.options.screen_reader) { // We only want to focus labels if the screen reader is on. Sense::focusable_noninteractive() } else { Sense::hover() } }); if selectable { // On touch screens (e.g. mobile in `eframe` web), should // dragging select text, or scroll the enclosing [`ScrollArea`] (if any)? // Since currently copying selected text in not supported on `eframe` web, // we prioritize touch-scrolling: let allow_drag_to_select = ui.input(|i| !i.has_touch_screen()); let mut select_sense = if allow_drag_to_select { Sense::click_and_drag() } else { Sense::click() }; select_sense -= Sense::FOCUSABLE; // Don't move focus to labels with TAB key. sense |= select_sense; } if let WidgetText::Galley(galley) = self.text { // If the user said "use this specific galley", then just use it: let (rect, response) = ui.allocate_exact_size(galley.size(), sense); let pos = match galley.job.halign { Align::LEFT => rect.left_top(), Align::Center => rect.center_top(), Align::RIGHT => rect.right_top(), }; return (pos, galley, response); } let valign = ui.text_valign(); let mut layout_job = Arc::unwrap_or_clone(self.text.into_layout_job( ui.style(), FontSelection::Default, valign, )); let available_width = ui.available_width(); let wrap_mode = self.wrap_mode.unwrap_or_else(|| ui.wrap_mode()); if wrap_mode == TextWrapMode::Wrap && ui.layout().main_dir() == Direction::LeftToRight && ui.layout().main_wrap() && available_width.is_finite() { // On a wrapping horizontal layout we want text to start after the previous widget, // then continue on the line below! This will take some extra work: let cursor = ui.cursor(); let first_row_indentation = available_width - ui.available_size_before_wrap().x; debug_assert!( first_row_indentation.is_finite(), "first row indentation is not finite: {first_row_indentation}" ); layout_job.wrap.max_width = available_width; layout_job.first_row_min_height = cursor.height(); layout_job.halign = Align::Min; layout_job.justify = false; if let Some(first_section) = layout_job.sections.first_mut() { first_section.leading_space = first_row_indentation; } let galley = ui.fonts_mut(|fonts| fonts.layout_job(layout_job)); let pos = pos2(ui.max_rect().left(), ui.cursor().top()); assert!(!galley.rows.is_empty(), "Galleys are never empty"); // collect a response from many rows: let rect = galley.rows[0] .rect_without_leading_space() .translate(pos.to_vec2()); let mut response = ui.allocate_rect(rect, sense); response.intrinsic_size = Some(galley.intrinsic_size()); for placed_row in galley.rows.iter().skip(1) { let rect = placed_row.rect().translate(pos.to_vec2()); response |= ui.allocate_rect(rect, sense); } (pos, galley, response) } else { // Apply wrap_mode, but don't overwrite anything important // the user may have set manually on the layout_job: match wrap_mode { TextWrapMode::Extend => { layout_job.wrap.max_width = f32::INFINITY; } TextWrapMode::Wrap => { layout_job.wrap.max_width = available_width; } TextWrapMode::Truncate => { layout_job.wrap.max_width = available_width; layout_job.wrap.max_rows = 1; layout_job.wrap.break_anywhere = true; } } if ui.is_grid() { // TODO(emilk): remove special Grid hacks like these layout_job.halign = Align::LEFT; layout_job.justify = false; } else { layout_job.halign = self .halign .unwrap_or_else(|| ui.layout().horizontal_placement()); layout_job.justify = ui.layout().horizontal_justify(); } let galley = ui.fonts_mut(|fonts| fonts.layout_job(layout_job)); let (rect, mut response) = ui.allocate_exact_size(galley.size(), sense); response.intrinsic_size = Some(galley.intrinsic_size()); let galley_pos = match galley.job.halign { Align::LEFT => rect.left_top(), Align::Center => rect.center_top(), Align::RIGHT => rect.right_top(), }; (galley_pos, galley, response) } } } impl Widget for Label { fn ui(self, ui: &mut Ui) -> Response { // Interactive = the uses asked to sense interaction. // We DON'T want to have the color respond just because the text is selectable; // the cursor is enough to communicate that. let interactive = self.sense.is_some_and(|sense| sense != Sense::hover()); let selectable = self.selectable; let show_tooltip_when_elided = self.show_tooltip_when_elided; let (galley_pos, galley, mut response) = self.layout_in_ui(ui); response .widget_info(|| WidgetInfo::labeled(WidgetType::Label, ui.is_enabled(), galley.text())); if ui.is_rect_visible(response.rect) { if show_tooltip_when_elided && galley.elided { // Keep the sections and text, but reset everything else (especially wrapping): let job = crate::text::LayoutJob { sections: galley.job.sections.clone(), text: galley.job.text.clone(), ..crate::text::LayoutJob::default() }; // Show the full (non-elided) text on hover: response = response.on_hover_text(job); } let response_color = if interactive { ui.style().interact(&response).text_color() } else { ui.style().visuals.text_color() }; let underline = if response.has_focus() || response.highlighted() { Stroke::new(1.0, response_color) } else { Stroke::NONE }; let selectable = selectable.unwrap_or_else(|| ui.style().interaction.selectable_labels); if selectable { LabelSelectionState::label_text_selection( ui, &response, galley_pos, galley, response_color, underline, ); } else { ui.painter().add( epaint::TextShape::new(galley_pos, galley, response_color) .with_underline(underline), ); } } response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/color_picker.rs
crates/egui/src/widgets/color_picker.rs
//! Color picker widgets. use crate::util::fixed_cache::FixedCache; use crate::{ Context, DragValue, Id, Painter, Popup, PopupCloseBehavior, Response, Sense, Ui, Widget as _, WidgetInfo, WidgetType, epaint, lerp, remap_clamp, }; use epaint::{ Mesh, Rect, Shape, Stroke, StrokeKind, Vec2, ecolor::{Color32, Hsva, HsvaGamma, Rgba}, pos2, vec2, }; fn contrast_color(color: impl Into<Rgba>) -> Color32 { if color.into().intensity() < 0.5 { Color32::WHITE } else { Color32::BLACK } } /// Number of vertices per dimension in the color sliders. /// We need at least 6 for hues, and more for smooth 2D areas. /// Should always be a multiple of 6 to hit the peak hues in HSV/HSL (every 60°). const N: u32 = 6 * 6; fn background_checkers(painter: &Painter, rect: Rect) { let rect = rect.shrink(0.5); // Small hack to avoid the checkers from peeking through the sides if !rect.is_positive() { return; } let dark_color = Color32::from_gray(32); let bright_color = Color32::from_gray(128); let checker_size = Vec2::splat(rect.height() / 2.0); let n = (rect.width() / checker_size.x).round() as u32; let mut mesh = Mesh::default(); mesh.add_colored_rect(rect, dark_color); let mut top = true; for i in 0..n { let x = lerp(rect.left()..=rect.right(), i as f32 / (n as f32)); let small_rect = if top { Rect::from_min_size(pos2(x, rect.top()), checker_size) } else { Rect::from_min_size(pos2(x, rect.center().y), checker_size) }; mesh.add_colored_rect(small_rect, bright_color); top = !top; } painter.add(Shape::mesh(mesh)); } /// Show a color with background checkers to demonstrate transparency (if any). pub fn show_color(ui: &mut Ui, color: impl Into<Color32>, desired_size: Vec2) -> Response { show_color32(ui, color.into(), desired_size) } fn show_color32(ui: &mut Ui, color: Color32, desired_size: Vec2) -> Response { let (rect, response) = ui.allocate_at_least(desired_size, Sense::hover()); if ui.is_rect_visible(rect) { show_color_at(ui.painter(), color, rect); } response } /// Show a color with background checkers to demonstrate transparency (if any). pub fn show_color_at(painter: &Painter, color: Color32, rect: Rect) { if color.is_opaque() { painter.rect_filled(rect, 0.0, color); } else { // Transparent: how both the transparent and opaque versions of the color background_checkers(painter, rect); if color == Color32::TRANSPARENT { // There is no opaque version, so just show the background checkers } else { let left = Rect::from_min_max(rect.left_top(), rect.center_bottom()); let right = Rect::from_min_max(rect.center_top(), rect.right_bottom()); painter.rect_filled(left, 0.0, color); painter.rect_filled(right, 0.0, color.to_opaque()); } } } fn color_button(ui: &mut Ui, color: Color32, open: bool) -> Response { let size = ui.spacing().interact_size; let (rect, response) = ui.allocate_exact_size(size, Sense::click()); response.widget_info(|| WidgetInfo::new(WidgetType::ColorButton)); if ui.is_rect_visible(rect) { let visuals = if open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; let rect = rect.expand(visuals.expansion); let stroke_width = 1.0; show_color_at(ui.painter(), color, rect.shrink(stroke_width)); let corner_radius = visuals.corner_radius.at_most(2); // Can't do more rounding because the background grid doesn't do any rounding ui.painter().rect_stroke( rect, corner_radius, (stroke_width, visuals.bg_fill), // Using fill for stroke is intentional, because default style has no border StrokeKind::Inside, ); } response } fn color_slider_1d(ui: &mut Ui, value: &mut f32, color_at: impl Fn(f32) -> Color32) -> Response { #![expect(clippy::identity_op)] let desired_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y); let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag()); if let Some(mpos) = response.interact_pointer_pos() { *value = remap_clamp(mpos.x, rect.left()..=rect.right(), 0.0..=1.0); } if ui.is_rect_visible(rect) { let visuals = ui.style().interact(&response); background_checkers(ui.painter(), rect); // for alpha: { // fill color: let mut mesh = Mesh::default(); for i in 0..=N { let t = i as f32 / (N as f32); let color = color_at(t); let x = lerp(rect.left()..=rect.right(), t); mesh.colored_vertex(pos2(x, rect.top()), color); mesh.colored_vertex(pos2(x, rect.bottom()), color); if i < N { mesh.add_triangle(2 * i + 0, 2 * i + 1, 2 * i + 2); mesh.add_triangle(2 * i + 1, 2 * i + 2, 2 * i + 3); } } ui.painter().add(Shape::mesh(mesh)); } ui.painter() .rect_stroke(rect, 0.0, visuals.bg_stroke, StrokeKind::Inside); // outline { // Show where the slider is at: let x = lerp(rect.left()..=rect.right(), *value); let r = rect.height() / 4.0; let picked_color = color_at(*value); ui.painter().add(Shape::convex_polygon( vec![ pos2(x, rect.center().y), // tip pos2(x + r, rect.bottom()), // right bottom pos2(x - r, rect.bottom()), // left bottom ], picked_color, Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)), )); } } response } /// # Arguments /// * `x_value` - X axis, either saturation or value (0.0-1.0). /// * `y_value` - Y axis, either saturation or value (0.0-1.0). /// * `color_at` - A function that dictates how the mix of saturation and value will be displayed in the 2d slider. /// /// e.g.: `|x_value, y_value| HsvaGamma { h: 1.0, s: x_value, v: y_value, a: 1.0 }.into()` displays the colors as follows: /// * top-left: white `[s: 0.0, v: 1.0]` /// * top-right: fully saturated color `[s: 1.0, v: 1.0]` /// * bottom-right: black `[s: 0.0, v: 1.0].` fn color_slider_2d( ui: &mut Ui, x_value: &mut f32, y_value: &mut f32, color_at: impl Fn(f32, f32) -> Color32, ) -> Response { let desired_size = Vec2::splat(ui.spacing().slider_width); let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag()); if let Some(mpos) = response.interact_pointer_pos() { *x_value = remap_clamp(mpos.x, rect.left()..=rect.right(), 0.0..=1.0); *y_value = remap_clamp(mpos.y, rect.bottom()..=rect.top(), 0.0..=1.0); } if ui.is_rect_visible(rect) { let visuals = ui.style().interact(&response); let mut mesh = Mesh::default(); for xi in 0..=N { for yi in 0..=N { let xt = xi as f32 / (N as f32); let yt = yi as f32 / (N as f32); let color = color_at(xt, yt); let x = lerp(rect.left()..=rect.right(), xt); let y = lerp(rect.bottom()..=rect.top(), yt); mesh.colored_vertex(pos2(x, y), color); if xi < N && yi < N { let x_offset = 1; let y_offset = N + 1; let tl = yi * y_offset + xi; mesh.add_triangle(tl, tl + x_offset, tl + y_offset); mesh.add_triangle(tl + x_offset, tl + y_offset, tl + y_offset + x_offset); } } } ui.painter().add(Shape::mesh(mesh)); // fill ui.painter() .rect_stroke(rect, 0.0, visuals.bg_stroke, StrokeKind::Inside); // outline // Show where the slider is at: let x = lerp(rect.left()..=rect.right(), *x_value); let y = lerp(rect.bottom()..=rect.top(), *y_value); let picked_color = color_at(*x_value, *y_value); ui.painter().add(epaint::CircleShape { center: pos2(x, y), radius: rect.width() / 12.0, fill: picked_color, stroke: Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)), }); } response } /// We use a negative alpha for additive colors within this file (a bit ironic). /// /// We use alpha=0 to mean "transparent". fn is_additive_alpha(a: f32) -> bool { a < 0.0 } /// What options to show for alpha #[derive(Clone, Copy, PartialEq, Eq)] pub enum Alpha { /// Set alpha to 1.0, and show no option for it. Opaque, /// Only show normal blend options for alpha. OnlyBlend, /// Show both blend and additive options. BlendOrAdditive, } fn color_picker_hsvag_2d(ui: &mut Ui, hsvag: &mut HsvaGamma, alpha: Alpha) { use crate::style::NumericColorSpace; let alpha_control = if is_additive_alpha(hsvag.a) { Alpha::Opaque // no alpha control for additive colors } else { alpha }; match ui.style().visuals.numeric_color_space { NumericColorSpace::GammaByte => { let mut srgba_unmultiplied = Hsva::from(*hsvag).to_srgba_unmultiplied(); // Only update if changed to avoid rounding issues. if srgba_edit_ui(ui, &mut srgba_unmultiplied, alpha_control) { if is_additive_alpha(hsvag.a) { let alpha = hsvag.a; *hsvag = HsvaGamma::from(Hsva::from_additive_srgb([ srgba_unmultiplied[0], srgba_unmultiplied[1], srgba_unmultiplied[2], ])); // Don't edit the alpha: hsvag.a = alpha; } else { // Normal blending. *hsvag = HsvaGamma::from(Hsva::from_srgba_unmultiplied(srgba_unmultiplied)); } } } NumericColorSpace::Linear => { let mut rgba_unmultiplied = Hsva::from(*hsvag).to_rgba_unmultiplied(); // Only update if changed to avoid rounding issues. if rgba_edit_ui(ui, &mut rgba_unmultiplied, alpha_control) { if is_additive_alpha(hsvag.a) { let alpha = hsvag.a; *hsvag = HsvaGamma::from(Hsva::from_rgb([ rgba_unmultiplied[0], rgba_unmultiplied[1], rgba_unmultiplied[2], ])); // Don't edit the alpha: hsvag.a = alpha; } else { // Normal blending. *hsvag = HsvaGamma::from(Hsva::from_rgba_unmultiplied( rgba_unmultiplied[0], rgba_unmultiplied[1], rgba_unmultiplied[2], rgba_unmultiplied[3], )); } } } } let current_color_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y); show_color(ui, *hsvag, current_color_size).on_hover_text("Selected color"); if alpha == Alpha::BlendOrAdditive { let a = &mut hsvag.a; let mut additive = is_additive_alpha(*a); ui.horizontal(|ui| { ui.label("Blending:"); ui.radio_value(&mut additive, false, "Normal"); ui.radio_value(&mut additive, true, "Additive"); if additive { *a = -a.abs(); } if !additive { *a = a.abs(); } }); } let opaque = HsvaGamma { a: 1.0, ..*hsvag }; let HsvaGamma { h, s, v, a: _ } = hsvag; if false { color_slider_1d(ui, s, |s| HsvaGamma { s, ..opaque }.into()).on_hover_text("Saturation"); } if false { color_slider_1d(ui, v, |v| HsvaGamma { v, ..opaque }.into()).on_hover_text("Value"); } color_slider_2d(ui, s, v, |s, v| HsvaGamma { s, v, ..opaque }.into()); color_slider_1d(ui, h, |h| { HsvaGamma { h, s: 1.0, v: 1.0, a: 1.0, } .into() }) .on_hover_text("Hue"); let additive = is_additive_alpha(hsvag.a); if alpha == Alpha::Opaque { hsvag.a = 1.0; } else { let a = &mut hsvag.a; if alpha == Alpha::OnlyBlend { if is_additive_alpha(*a) { *a = 0.5; // was additive, but isn't allowed to be } color_slider_1d(ui, a, |a| HsvaGamma { a, ..opaque }.into()).on_hover_text("Alpha"); } else if !additive { color_slider_1d(ui, a, |a| HsvaGamma { a, ..opaque }.into()).on_hover_text("Alpha"); } } } fn input_type_button_ui(ui: &mut Ui) { let mut input_type = ui.global_style().visuals.numeric_color_space; if input_type.toggle_button_ui(ui).changed() { ui.ctx().all_styles_mut(|s| { s.visuals.numeric_color_space = input_type; }); } } /// Shows 4 `DragValue` widgets to be used to edit the RGBA u8 values. /// Alpha's `DragValue` is hidden when `Alpha::Opaque`. /// /// Returns `true` on change. fn srgba_edit_ui(ui: &mut Ui, [r, g, b, a]: &mut [u8; 4], alpha: Alpha) -> bool { let mut edited = false; ui.horizontal(|ui| { input_type_button_ui(ui); if ui .button("📋") .on_hover_text("Click to copy color values") .clicked() { if alpha == Alpha::Opaque { ui.copy_text(format!("{r}, {g}, {b}")); } else { ui.copy_text(format!("{r}, {g}, {b}, {a}")); } } edited |= DragValue::new(r).speed(0.5).prefix("R ").ui(ui).changed(); edited |= DragValue::new(g).speed(0.5).prefix("G ").ui(ui).changed(); edited |= DragValue::new(b).speed(0.5).prefix("B ").ui(ui).changed(); if alpha != Alpha::Opaque { edited |= DragValue::new(a).speed(0.5).prefix("A ").ui(ui).changed(); } }); edited } /// Shows 4 `DragValue` widgets to be used to edit the RGBA f32 values. /// Alpha's `DragValue` is hidden when `Alpha::Opaque`. /// /// Returns `true` on change. fn rgba_edit_ui(ui: &mut Ui, [r, g, b, a]: &mut [f32; 4], alpha: Alpha) -> bool { fn drag_value(ui: &mut Ui, prefix: &str, value: &mut f32) -> Response { DragValue::new(value) .speed(0.003) .prefix(prefix) .range(0.0..=1.0) .custom_formatter(|n, _| format!("{n:.03}")) .ui(ui) } let mut edited = false; ui.horizontal(|ui| { input_type_button_ui(ui); if ui .button("📋") .on_hover_text("Click to copy color values") .clicked() { if alpha == Alpha::Opaque { ui.copy_text(format!("{r:.03}, {g:.03}, {b:.03}")); } else { ui.copy_text(format!("{r:.03}, {g:.03}, {b:.03}, {a:.03}")); } } edited |= drag_value(ui, "R ", r).changed(); edited |= drag_value(ui, "G ", g).changed(); edited |= drag_value(ui, "B ", b).changed(); if alpha != Alpha::Opaque { edited |= drag_value(ui, "A ", a).changed(); } }); edited } /// Shows a color picker where the user can change the given [`Hsva`] color. /// /// Returns `true` on change. pub fn color_picker_hsva_2d(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> bool { let mut hsvag = HsvaGamma::from(*hsva); ui.vertical(|ui| { color_picker_hsvag_2d(ui, &mut hsvag, alpha); }); let new_hasva = Hsva::from(hsvag); if *hsva == new_hasva { false } else { *hsva = new_hasva; true } } /// Shows a color picker where the user can change the given [`Color32`] color. /// /// Returns `true` on change. pub fn color_picker_color32(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) -> bool { let mut hsva = color_cache_get(ui.ctx(), *srgba); let changed = color_picker_hsva_2d(ui, &mut hsva, alpha); *srgba = Color32::from(hsva); color_cache_set(ui.ctx(), *srgba, hsva); changed } pub fn color_edit_button_hsva(ui: &mut Ui, hsva: &mut Hsva, alpha: Alpha) -> Response { let popup_id = ui.auto_id_with("popup"); let open = Popup::is_id_open(ui.ctx(), popup_id); let mut button_response = color_button(ui, (*hsva).into(), open); if ui.style().explanation_tooltips { button_response = button_response.on_hover_text("Click to edit color"); } const COLOR_SLIDER_WIDTH: f32 = 275.0; Popup::menu(&button_response) .id(popup_id) .close_behavior(PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.spacing_mut().slider_width = COLOR_SLIDER_WIDTH; if color_picker_hsva_2d(ui, hsva, alpha) { button_response.mark_changed(); } }); button_response } /// Shows a button with the given color. /// If the user clicks the button, a full color picker is shown. pub fn color_edit_button_srgba(ui: &mut Ui, srgba: &mut Color32, alpha: Alpha) -> Response { let mut hsva = color_cache_get(ui.ctx(), *srgba); let response = color_edit_button_hsva(ui, &mut hsva, alpha); *srgba = Color32::from(hsva); color_cache_set(ui.ctx(), *srgba, hsva); response } /// Shows a button with the given color. /// If the user clicks the button, a full color picker is shown. /// The given color is in `sRGB` space. pub fn color_edit_button_srgb(ui: &mut Ui, srgb: &mut [u8; 3]) -> Response { let mut srgba = Color32::from_rgb(srgb[0], srgb[1], srgb[2]); let response = color_edit_button_srgba(ui, &mut srgba, Alpha::Opaque); srgb[0] = srgba[0]; srgb[1] = srgba[1]; srgb[2] = srgba[2]; response } /// Shows a button with the given color. /// If the user clicks the button, a full color picker is shown. pub fn color_edit_button_rgba(ui: &mut Ui, rgba: &mut Rgba, alpha: Alpha) -> Response { let mut hsva = color_cache_get(ui.ctx(), *rgba); let response = color_edit_button_hsva(ui, &mut hsva, alpha); *rgba = Rgba::from(hsva); color_cache_set(ui.ctx(), *rgba, hsva); response } /// Shows a button with the given color. /// If the user clicks the button, a full color picker is shown. pub fn color_edit_button_rgb(ui: &mut Ui, rgb: &mut [f32; 3]) -> Response { let mut rgba = Rgba::from_rgb(rgb[0], rgb[1], rgb[2]); let response = color_edit_button_rgba(ui, &mut rgba, Alpha::Opaque); rgb[0] = rgba[0]; rgb[1] = rgba[1]; rgb[2] = rgba[2]; response } // To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache: fn color_cache_get(ctx: &Context, rgba: impl Into<Rgba>) -> Hsva { let rgba = rgba.into(); use_color_cache(ctx, |cc| cc.get(&rgba).copied()).unwrap_or_else(|| Hsva::from(rgba)) } // To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache: fn color_cache_set(ctx: &Context, rgba: impl Into<Rgba>, hsva: Hsva) { let rgba = rgba.into(); use_color_cache(ctx, |cc| cc.set(rgba, hsva)); } // To ensure we keep hue slider when `srgba` is gray we store the full [`Hsva`] in a cache: fn use_color_cache<R>(ctx: &Context, f: impl FnOnce(&mut FixedCache<Rgba, Hsva>) -> R) -> R { ctx.data_mut(|d| f(d.get_temp_mut_or_default(Id::NULL))) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/spinner.rs
crates/egui/src/widgets/spinner.rs
use epaint::{Color32, Pos2, Rect, Shape, Stroke, emath::lerp, vec2}; use crate::{Response, Sense, Ui, Widget, WidgetInfo, WidgetType}; /// A spinner widget used to indicate loading. /// /// See also: [`crate::ProgressBar`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] #[derive(Default)] pub struct Spinner { /// Uses the style's `interact_size` if `None`. size: Option<f32>, color: Option<Color32>, } impl Spinner { /// Create a new spinner that uses the style's `interact_size` unless changed. pub fn new() -> Self { Self::default() } /// Sets the spinner's size. The size sets both the height and width, as the spinner is always /// square. If the size isn't set explicitly, the active style's `interact_size` is used. #[inline] pub fn size(mut self, size: f32) -> Self { self.size = Some(size); self } /// Sets the spinner's color. #[inline] pub fn color(mut self, color: impl Into<Color32>) -> Self { self.color = Some(color.into()); self } /// Paint the spinner in the given rectangle. pub fn paint_at(&self, ui: &Ui, rect: Rect) { if ui.is_rect_visible(rect) { ui.request_repaint(); // because it is animated let color = self .color .unwrap_or_else(|| ui.visuals().strong_text_color()); let radius = (rect.height().min(rect.width()) / 2.0) - 2.0; let n_points = (radius.round() as u32).clamp(8, 128); let time = ui.input(|i| i.time); let start_angle = time * std::f64::consts::TAU; let end_angle = start_angle + 240f64.to_radians() * time.sin(); let points: Vec<Pos2> = (0..n_points) .map(|i| { let angle = lerp(start_angle..=end_angle, i as f64 / n_points as f64); let (sin, cos) = angle.sin_cos(); rect.center() + radius * vec2(cos as f32, sin as f32) }) .collect(); ui.painter() .add(Shape::line(points, Stroke::new(3.0, color))); } } } impl Widget for Spinner { fn ui(self, ui: &mut Ui) -> Response { let size = self .size .unwrap_or_else(|| ui.style().spacing.interact_size.y); let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); response.widget_info(|| WidgetInfo::new(WidgetType::ProgressIndicator)); self.paint_at(ui, rect); response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/drag_value.rs
crates/egui/src/widgets/drag_value.rs
#![expect(clippy::needless_pass_by_value)] // False positives with `impl ToString` use std::{cmp::Ordering, ops::RangeInclusive}; use crate::{ Button, CursorIcon, Id, Key, MINUS_CHAR_STR, Modifiers, NumExt as _, Response, RichText, Sense, TextEdit, TextWrapMode, Ui, Widget, WidgetInfo, emath, text, }; // ---------------------------------------------------------------------------- type NumFormatter<'a> = Box<dyn 'a + Fn(f64, RangeInclusive<usize>) -> String>; type NumParser<'a> = Box<dyn 'a + Fn(&str) -> Option<f64>>; // ---------------------------------------------------------------------------- /// Combined into one function (rather than two) to make it easier /// for the borrow checker. type GetSetValue<'a> = Box<dyn 'a + FnMut(Option<f64>) -> f64>; fn get(get_set_value: &mut GetSetValue<'_>) -> f64 { (get_set_value)(None) } fn set(get_set_value: &mut GetSetValue<'_>, value: f64) { (get_set_value)(Some(value)); } /// A numeric value that you can change by dragging the number. More compact than a [`crate::Slider`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_f32: f32 = 0.0; /// ui.add(egui::DragValue::new(&mut my_f32).speed(0.1)); /// # }); /// ``` #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct DragValue<'a> { get_set_value: GetSetValue<'a>, speed: f64, prefix: String, suffix: String, range: RangeInclusive<f64>, clamp_existing_to_range: bool, min_decimals: usize, max_decimals: Option<usize>, custom_formatter: Option<NumFormatter<'a>>, custom_parser: Option<NumParser<'a>>, update_while_editing: bool, } impl<'a> DragValue<'a> { pub fn new<Num: emath::Numeric>(value: &'a mut Num) -> Self { let slf = Self::from_get_set(move |v: Option<f64>| { if let Some(v) = v { *value = Num::from_f64(v); } value.to_f64() }); if Num::INTEGRAL { slf.max_decimals(0).range(Num::MIN..=Num::MAX).speed(0.25) } else { slf } } pub fn from_get_set(get_set_value: impl 'a + FnMut(Option<f64>) -> f64) -> Self { Self { get_set_value: Box::new(get_set_value), speed: 1.0, prefix: Default::default(), suffix: Default::default(), range: f64::NEG_INFINITY..=f64::INFINITY, clamp_existing_to_range: true, min_decimals: 0, max_decimals: None, custom_formatter: None, custom_parser: None, update_while_editing: true, } } /// How much the value changes when dragged one point (logical pixel). /// /// Should be finite and greater than zero. #[inline] pub fn speed(mut self, speed: impl Into<f64>) -> Self { self.speed = speed.into(); self } /// Sets valid range for the value. /// /// By default all values are clamped to this range, even when not interacted with. /// You can change this behavior by passing `false` to [`Self::clamp_existing_to_range`]. #[deprecated = "Use `range` instead"] #[inline] pub fn clamp_range<Num: emath::Numeric>(self, range: RangeInclusive<Num>) -> Self { self.range(range) } /// Sets valid range for dragging the value. /// /// By default all values are clamped to this range, even when not interacted with. /// You can change this behavior by passing `false` to [`Self::clamp_existing_to_range`]. #[inline] pub fn range<Num: emath::Numeric>(mut self, range: RangeInclusive<Num>) -> Self { self.range = range.start().to_f64()..=range.end().to_f64(); self } /// If set to `true`, existing values will be clamped to [`Self::range`]. /// /// If `false`, only values entered by the user (via dragging or text editing) /// will be clamped to the range. /// /// ### Without calling `range` /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// ui.add(egui::DragValue::new(&mut my_value)); /// assert_eq!(my_value, 1337.0, "No range, no clamp"); /// # }); /// ``` /// /// ### With `.clamp_existing_to_range(true)` (default) /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// ui.add(egui::DragValue::new(&mut my_value).range(0.0..=1.0)); /// assert!(0.0 <= my_value && my_value <= 1.0, "Existing values should be clamped"); /// # }); /// ``` /// /// ### With `.clamp_existing_to_range(false)` /// ``` /// # egui::__run_test_ui(|ui| { /// let mut my_value: f32 = 1337.0; /// let response = ui.add( /// egui::DragValue::new(&mut my_value).range(0.0..=1.0) /// .clamp_existing_to_range(false) /// ); /// if response.dragged() { /// // The user edited the value, so it should be clamped to the range /// assert!(0.0 <= my_value && my_value <= 1.0); /// } else { /// // The user didn't edit, so our original value should still be here: /// assert_eq!(my_value, 1337.0); /// } /// # }); /// ``` #[inline] pub fn clamp_existing_to_range(mut self, clamp_existing_to_range: bool) -> Self { self.clamp_existing_to_range = clamp_existing_to_range; self } #[inline] #[deprecated = "Renamed clamp_existing_to_range"] pub fn clamp_to_range(self, clamp_to_range: bool) -> Self { self.clamp_existing_to_range(clamp_to_range) } /// Show a prefix before the number, e.g. "x: " #[inline] pub fn prefix(mut self, prefix: impl ToString) -> Self { self.prefix = prefix.to_string(); self } /// Add a suffix to the number, this can be e.g. a unit ("°" or " m") #[inline] pub fn suffix(mut self, suffix: impl ToString) -> Self { self.suffix = suffix.to_string(); self } // TODO(emilk): we should also have a "min precision". /// Set a minimum number of decimals to display. /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn min_decimals(mut self, min_decimals: usize) -> Self { self.min_decimals = min_decimals; self } // TODO(emilk): we should also have a "max precision". /// Set a maximum number of decimals to display. /// Values will also be rounded to this number of decimals. /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn max_decimals(mut self, max_decimals: usize) -> Self { self.max_decimals = Some(max_decimals); self } #[inline] pub fn max_decimals_opt(mut self, max_decimals: Option<usize>) -> Self { self.max_decimals = max_decimals; self } /// Set an exact number of decimals to display. /// Values will also be rounded to this number of decimals. /// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you. /// Regardless of precision the slider will use "smart aim" to help the user select nice, round values. #[inline] pub fn fixed_decimals(mut self, num_decimals: usize) -> Self { self.min_decimals = num_decimals; self.max_decimals = Some(num_decimals); self } /// Set custom formatter defining how numbers are converted into text. /// /// A custom formatter takes a `f64` for the numeric value and a `RangeInclusive<usize>` representing /// the decimal range i.e. minimum and maximum number of decimal places shown. /// /// The default formatter is [`crate::Style::number_formatter`]. /// /// See also: [`DragValue::custom_parser`] /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::DragValue::new(&mut my_i32) /// .range(0..=((60 * 60 * 24) - 1)) /// .custom_formatter(|n, _| { /// let n = n as i32; /// let hours = n / (60 * 60); /// let mins = (n / 60) % 60; /// let secs = n % 60; /// format!("{hours:02}:{mins:02}:{secs:02}") /// }) /// .custom_parser(|s| { /// let parts: Vec<&str> = s.split(':').collect(); /// if parts.len() == 3 { /// parts[0].parse::<i32>().and_then(|h| { /// parts[1].parse::<i32>().and_then(|m| { /// parts[2].parse::<i32>().map(|s| { /// ((h * 60 * 60) + (m * 60) + s) as f64 /// }) /// }) /// }) /// .ok() /// } else { /// None /// } /// })); /// # }); /// ``` pub fn custom_formatter( mut self, formatter: impl 'a + Fn(f64, RangeInclusive<usize>) -> String, ) -> Self { self.custom_formatter = Some(Box::new(formatter)); self } /// Set custom parser defining how the text input is parsed into a number. /// /// A custom parser takes an `&str` to parse into a number and returns a `f64` if it was successfully parsed /// or `None` otherwise. /// /// See also: [`DragValue::custom_formatter`] /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::DragValue::new(&mut my_i32) /// .range(0..=((60 * 60 * 24) - 1)) /// .custom_formatter(|n, _| { /// let n = n as i32; /// let hours = n / (60 * 60); /// let mins = (n / 60) % 60; /// let secs = n % 60; /// format!("{hours:02}:{mins:02}:{secs:02}") /// }) /// .custom_parser(|s| { /// let parts: Vec<&str> = s.split(':').collect(); /// if parts.len() == 3 { /// parts[0].parse::<i32>().and_then(|h| { /// parts[1].parse::<i32>().and_then(|m| { /// parts[2].parse::<i32>().map(|s| { /// ((h * 60 * 60) + (m * 60) + s) as f64 /// }) /// }) /// }) /// .ok() /// } else { /// None /// } /// })); /// # }); /// ``` #[inline] pub fn custom_parser(mut self, parser: impl 'a + Fn(&str) -> Option<f64>) -> Self { self.custom_parser = Some(Box::new(parser)); self } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as binary integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::DragValue::new(&mut my_i32).binary(64, false)); /// # }); /// ``` pub fn binary(self, min_width: usize, twos_complement: bool) -> Self { assert!( min_width > 0, "DragValue::binary: `min_width` must be greater than 0" ); if twos_complement { self.custom_formatter(move |n, _| format!("{:0>min_width$b}", n as i64)) } else { self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$b}", n.abs() as i64) }) } .custom_parser(|s| i64::from_str_radix(s, 2).map(|n| n as f64).ok()) } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as octal integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::DragValue::new(&mut my_i32).octal(22, false)); /// # }); /// ``` pub fn octal(self, min_width: usize, twos_complement: bool) -> Self { assert!( min_width > 0, "DragValue::octal: `min_width` must be greater than 0" ); if twos_complement { self.custom_formatter(move |n, _| format!("{:0>min_width$o}", n as i64)) } else { self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$o}", n.abs() as i64) }) } .custom_parser(|s| i64::from_str_radix(s, 8).map(|n| n as f64).ok()) } /// Set `custom_formatter` and `custom_parser` to display and parse numbers as hexadecimal integers. Floating point /// numbers are *not* supported. /// /// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be /// prefixed with additional 0s to match `min_width`. /// /// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise /// they will be prefixed with a '-' sign. /// /// # Panics /// /// Panics if `min_width` is 0. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_i32: i32 = 0; /// ui.add(egui::DragValue::new(&mut my_i32).hexadecimal(16, false, true)); /// # }); /// ``` pub fn hexadecimal(self, min_width: usize, twos_complement: bool, upper: bool) -> Self { assert!( min_width > 0, "DragValue::hexadecimal: `min_width` must be greater than 0" ); match (twos_complement, upper) { (true, true) => { self.custom_formatter(move |n, _| format!("{:0>min_width$X}", n as i64)) } (true, false) => { self.custom_formatter(move |n, _| format!("{:0>min_width$x}", n as i64)) } (false, true) => self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$X}", n.abs() as i64) }), (false, false) => self.custom_formatter(move |n, _| { let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" }; format!("{sign}{:0>min_width$x}", n.abs() as i64) }), } .custom_parser(|s| i64::from_str_radix(s, 16).map(|n| n as f64).ok()) } /// Update the value on each key press when text-editing the value. /// /// Default: `true`. /// If `false`, the value will only be updated when user presses enter or deselects the value. #[inline] pub fn update_while_editing(mut self, update: bool) -> Self { self.update_while_editing = update; self } } impl Widget for DragValue<'_> { fn ui(self, ui: &mut Ui) -> Response { let Self { mut get_set_value, speed, range, clamp_existing_to_range, prefix, suffix, min_decimals, max_decimals, custom_formatter, custom_parser, update_while_editing, } = self; let shift = ui.input(|i| i.modifiers.shift_only()); // The widget has the same ID whether it's in edit or button mode. let id = ui.next_auto_id(); let is_slow_speed = shift && ui.ctx().is_being_dragged(id); // The following ensures that when a `DragValue` receives focus, // it is immediately rendered in edit mode, rather than being rendered // in button mode for just one frame. This is important for // screen readers. let is_kb_editing = ui.is_enabled() && ui.memory_mut(|mem| { mem.interested_in_focus(id, ui.layer_id()); mem.has_focus(id) }); if ui.memory_mut(|mem| mem.gained_focus(id)) { ui.data_mut(|data| data.remove::<String>(id)); } let old_value = get(&mut get_set_value); let mut value = old_value; let aim_rad = ui.input(|i| i.aim_radius() as f64); let auto_decimals = (aim_rad / speed.abs()).log10().ceil().clamp(0.0, 15.0) as usize; let auto_decimals = auto_decimals + is_slow_speed as usize; let max_decimals = max_decimals .unwrap_or(auto_decimals + 2) .at_least(min_decimals); let auto_decimals = auto_decimals.clamp(min_decimals, max_decimals); let change = ui.input_mut(|input| { let mut change = 0.0; if is_kb_editing { // This deliberately doesn't listen for left and right arrow keys, // because when editing, these are used to move the caret. // This behavior is consistent with other editable spinner/stepper // implementations, such as Chromium's (for HTML5 number input). // It is also normal for such controls to go directly into edit mode // when they receive keyboard focus, and some screen readers // assume this behavior, so having a separate mode for incrementing // and decrementing, that supports all arrow keys, would be // problematic. change += input.count_and_consume_key(Modifiers::NONE, Key::ArrowUp) as f64 - input.count_and_consume_key(Modifiers::NONE, Key::ArrowDown) as f64; } use accesskit::Action; change += input.num_accesskit_action_requests(id, Action::Increment) as f64 - input.num_accesskit_action_requests(id, Action::Decrement) as f64; change }); ui.input(|input| { use accesskit::{Action, ActionData}; for request in input.accesskit_action_requests(id, Action::SetValue) { if let Some(ActionData::NumericValue(new_value)) = request.data { value = new_value; } } }); if clamp_existing_to_range { value = clamp_value_to_range(value, range.clone()); } if change != 0.0 { value += speed * change; value = emath::round_to_decimals(value, auto_decimals); } if old_value != value { set(&mut get_set_value, value); ui.data_mut(|data| data.remove::<String>(id)); } let value_text = match custom_formatter { Some(custom_formatter) => custom_formatter(value, auto_decimals..=max_decimals), None => ui .style() .number_formatter .format(value, auto_decimals..=max_decimals), }; let text_style = ui.style().drag_value_text_style.clone(); if ui.memory(|mem| mem.lost_focus(id)) && !ui.input(|i| i.key_pressed(Key::Escape)) { let value_text = ui.data_mut(|data| data.remove_temp::<String>(id)); if let Some(value_text) = value_text { // We were editing the value as text last frame, but lost focus. // Make sure we applied the last text value: let parsed_value = parse(&custom_parser, &value_text); if let Some(mut parsed_value) = parsed_value { // User edits always clamps: parsed_value = clamp_value_to_range(parsed_value, range.clone()); set(&mut get_set_value, parsed_value); } } } // some clones below are redundant if AccessKit is disabled #[expect(clippy::redundant_clone)] let mut response = if is_kb_editing { let mut value_text = ui .data_mut(|data| data.remove_temp::<String>(id)) .unwrap_or_else(|| value_text.clone()); let response = ui.add( TextEdit::singleline(&mut value_text) .clip_text(false) .horizontal_align(ui.layout().horizontal_align()) .vertical_align(ui.layout().vertical_align()) .margin(ui.spacing().button_padding) .min_size(ui.spacing().interact_size) .id(id) .desired_width( ui.spacing().interact_size.x - 2.0 * ui.spacing().button_padding.x, ) .font(text_style), ); // Select all text when the edit gains focus. if ui.memory_mut(|mem| mem.gained_focus(id)) { select_all_text(ui, id, response.id, &value_text); } let update = if update_while_editing { // Update when the edit content has changed. response.changed() } else { // Update only when the edit has lost focus. response.lost_focus() && !ui.input(|i| i.key_pressed(Key::Escape)) }; if update { let parsed_value = parse(&custom_parser, &value_text); if let Some(mut parsed_value) = parsed_value { // User edits always clamps: parsed_value = clamp_value_to_range(parsed_value, range.clone()); set(&mut get_set_value, parsed_value); } } ui.data_mut(|data| data.insert_temp(id, value_text)); response } else { let button = Button::new( RichText::new(format!("{}{}{}", prefix, value_text.clone(), suffix)) .text_style(text_style), ) .wrap_mode(TextWrapMode::Extend) .sense(Sense::click_and_drag()) .min_size(ui.spacing().interact_size); // TODO(emilk): find some more generic solution to `min_size` let cursor_icon = if value <= *range.start() { CursorIcon::ResizeEast } else if value < *range.end() { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeWest }; let response = ui.add(button); let mut response = response.on_hover_cursor(cursor_icon); if ui.style().explanation_tooltips { response = response.on_hover_text(format!( "{}{}{}\nDrag to edit or click to enter a value.\nPress 'Shift' while dragging for better control.", prefix, value as f32, // Show full precision value on-hover. TODO(emilk): figure out f64 vs f32 suffix )); } if ui.input(|i| i.pointer.any_pressed() || i.pointer.any_released()) { // Reset memory of preciely dagged value. ui.data_mut(|data| data.remove::<f64>(id)); } if response.clicked() { ui.data_mut(|data| data.remove::<String>(id)); ui.memory_mut(|mem| mem.request_focus(id)); select_all_text(ui, id, response.id, &value_text); } else if response.dragged() { ui.set_cursor_icon(cursor_icon); let mdelta = response.drag_delta(); let delta_points = mdelta.x - mdelta.y; // Increase to the right and up let speed = if is_slow_speed { speed / 10.0 } else { speed }; let delta_value = delta_points as f64 * speed; if delta_value != 0.0 { // Since we round the value being dragged, we need to store the full precision value in memory: let precise_value = ui.data_mut(|data| data.get_temp::<f64>(id)); let precise_value = precise_value.unwrap_or(value); let precise_value = precise_value + delta_value; let aim_delta = aim_rad * speed; let rounded_new_value = emath::smart_aim::best_in_range_f64( precise_value - aim_delta, precise_value + aim_delta, ); let rounded_new_value = emath::round_to_decimals(rounded_new_value, auto_decimals); // Dragging will always clamp the value to the range. let rounded_new_value = clamp_value_to_range(rounded_new_value, range.clone()); set(&mut get_set_value, rounded_new_value); ui.data_mut(|data| data.insert_temp::<f64>(id, precise_value)); } } response }; if get(&mut get_set_value) != old_value { response.mark_changed(); } response.widget_info(|| WidgetInfo::drag_value(ui.is_enabled(), value)); ui.ctx().accesskit_node_builder(response.id, |builder| { use accesskit::Action; // If either end of the range is unbounded, it's better // to leave the corresponding AccessKit field set to None, // to allow for platform-specific default behavior. if range.start().is_finite() { builder.set_min_numeric_value(*range.start()); } if range.end().is_finite() { builder.set_max_numeric_value(*range.end()); } builder.set_numeric_value_step(speed); builder.add_action(Action::SetValue); if value < *range.end() { builder.add_action(Action::Increment); } if value > *range.start() { builder.add_action(Action::Decrement); } // The name field is set to the current value by the button, // but we don't want it set that way on this widget type. builder.clear_label(); // Always expose the value as a string. This makes the widget // more stable to accessibility users as it switches // between edit and button modes. This is particularly important // for VoiceOver on macOS; if the value is not exposed as a string // when the widget is in button mode, then VoiceOver speaks // the value (or a percentage if the widget has a clamp range) // when the widget loses focus, overriding the announcement // of the newly focused widget. This is certainly a VoiceOver bug, // but it's good to make our software work as well as possible // with existing assistive technology. However, if the widget // has a prefix and/or suffix, expose those when in button mode, // just as they're exposed on the screen. This triggers the // VoiceOver bug just described, but exposing all information // is more important, and at least we can avoid the bug // for instances of the widget with no prefix or suffix. // // The value is exposed as a string by the text edit widget // when in edit mode. if !is_kb_editing { let value_text = format!("{prefix}{value_text}{suffix}"); builder.set_value(value_text); } }); response } } fn parse(custom_parser: &Option<NumParser<'_>>, value_text: &str) -> Option<f64> { match &custom_parser { Some(parser) => parser(value_text), None => default_parser(value_text), } } /// The default egui parser of numbers. /// /// It ignored whitespaces anywhere in the input, and treats the special minus character (U+2212) as a normal minus. fn default_parser(text: &str) -> Option<f64> { let text: String = text .chars() // Ignore whitespace (trailing, leading, and thousands separators): .filter(|c| !c.is_whitespace()) // Replace special minus character with normal minus (hyphen): .map(|c| if c == '−' { '-' } else { c }) .collect(); text.parse().ok() } /// Clamp the given value with careful handling of negative zero, and other corner cases. pub(crate) fn clamp_value_to_range(x: f64, range: RangeInclusive<f64>) -> f64 { let (mut min, mut max) = (*range.start(), *range.end()); if min.total_cmp(&max) == Ordering::Greater { (min, max) = (max, min); } match x.total_cmp(&min) { Ordering::Less | Ordering::Equal => min, Ordering::Greater => match x.total_cmp(&max) { Ordering::Greater | Ordering::Equal => max, Ordering::Less => x, }, } } /// Select all text in the `DragValue` text edit widget. fn select_all_text(ui: &Ui, widget_id: Id, response_id: Id, value_text: &str) { let mut state = TextEdit::load_state(ui.ctx(), widget_id).unwrap_or_default(); state.cursor.set_char_range(Some(text::CCursorRange::two( text::CCursor::default(), text::CCursor::new(value_text.chars().count()), ))); state.store(ui.ctx(), response_id); } #[cfg(test)] mod tests { use super::clamp_value_to_range; macro_rules! total_assert_eq { ($a:expr, $b:expr) => { assert!( matches!($a.total_cmp(&$b), std::cmp::Ordering::Equal), "{} != {}", $a, $b ); }; } #[test] fn test_total_cmp_clamp_value_to_range() { total_assert_eq!(0.0_f64, clamp_value_to_range(-0.0, 0.0..=f64::MAX)); total_assert_eq!(-0.0_f64, clamp_value_to_range(0.0, -1.0..=-0.0)); total_assert_eq!(-1.0_f64, clamp_value_to_range(-25.0, -1.0..=1.0)); total_assert_eq!(5.0_f64, clamp_value_to_range(5.0, -1.0..=10.0)); total_assert_eq!(15.0_f64, clamp_value_to_range(25.0, -1.0..=15.0)); total_assert_eq!(1.0_f64, clamp_value_to_range(1.0, 1.0..=10.0)); total_assert_eq!(10.0_f64, clamp_value_to_range(10.0, 1.0..=10.0)); total_assert_eq!(5.0_f64, clamp_value_to_range(5.0, 10.0..=1.0)); total_assert_eq!(5.0_f64, clamp_value_to_range(15.0, 5.0..=1.0)); total_assert_eq!(1.0_f64, clamp_value_to_range(-5.0, 5.0..=1.0)); } #[test] fn test_default_parser() { assert_eq!(super::default_parser("123"), Some(123.0)); assert_eq!(super::default_parser("1.23"), Some(1.230)); assert_eq!( super::default_parser(" 1.23 "), Some(1.230), "We should handle leading and trailing spaces" ); assert_eq!( super::default_parser("1 234 567"), Some(1_234_567.0), "We should handle thousands separators using half-space" ); assert_eq!( super::default_parser("-1.23"), Some(-1.23), "Should handle normal hyphen as minus character" ); assert_eq!( super::default_parser("−1.23"), Some(-1.23), "Should handle special minus character (https://www.compart.com/en/unicode/U+2212)" ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/selected_label.rs
crates/egui/src/widgets/selected_label.rs
#![expect(deprecated, clippy::new_ret_no_self)] use crate::WidgetText; #[deprecated = "Use `Button::selectable()` instead"] pub struct SelectableLabel {} impl SelectableLabel { #[deprecated = "Use `Button::selectable()` instead"] pub fn new(selected: bool, text: impl Into<WidgetText>) -> super::Button<'static> { crate::Button::selectable(selected, text) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/text_edit/builder.rs
crates/egui/src/widgets/text_edit/builder.rs
use std::sync::Arc; use emath::{Rect, TSTransform}; use epaint::{ StrokeKind, text::{Galley, LayoutJob, cursor::CCursor}, }; use crate::{ Align, Align2, Color32, Context, CursorIcon, Event, EventFilter, FontSelection, Id, ImeEvent, Key, KeyboardShortcut, Margin, Modifiers, NumExt as _, Response, Sense, Shape, TextBuffer, TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetWithState, epaint, os::OperatingSystem, output::OutputEvent, response, text_selection, text_selection::{CCursorRange, text_cursor_state::cursor_rect, visuals::paint_text_selection}, vec2, }; use super::{TextEditOutput, TextEditState}; type LayouterFn<'t> = &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>; /// A text region that the user can edit the contents of. /// /// See also [`Ui::text_edit_singleline`] and [`Ui::text_edit_multiline`]. /// /// Example: /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_string = String::new(); /// let response = ui.add(egui::TextEdit::singleline(&mut my_string)); /// if response.changed() { /// // … /// } /// if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { /// // … /// } /// # }); /// ``` /// /// To fill an [`Ui`] with a [`TextEdit`] use [`Ui::add_sized`]: /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_string = String::new(); /// ui.add_sized(ui.available_size(), egui::TextEdit::multiline(&mut my_string)); /// # }); /// ``` /// /// /// You can also use [`TextEdit`] to show text that can be selected, but not edited. /// To do so, pass in a `&mut` reference to a `&str`, for instance: /// /// ``` /// fn selectable_text(ui: &mut egui::Ui, mut text: &str) { /// ui.add(egui::TextEdit::multiline(&mut text)); /// } /// ``` /// /// ## Advanced usage /// See [`TextEdit::show`]. /// /// ## Other /// The background color of a [`crate::TextEdit`] is [`crate::Visuals::text_edit_bg_color`] or can be set with [`crate::TextEdit::background_color`]. #[must_use = "You should put this widget in a ui with `ui.add(widget);`"] pub struct TextEdit<'t> { text: &'t mut dyn TextBuffer, hint_text: WidgetText, hint_text_font: Option<FontSelection>, id: Option<Id>, id_salt: Option<Id>, font_selection: FontSelection, text_color: Option<Color32>, layouter: Option<LayouterFn<'t>>, password: bool, frame: bool, margin: Margin, multiline: bool, interactive: bool, desired_width: Option<f32>, desired_height_rows: usize, event_filter: EventFilter, cursor_at_end: bool, min_size: Vec2, align: Align2, clip_text: bool, char_limit: usize, return_key: Option<KeyboardShortcut>, background_color: Option<Color32>, } impl WidgetWithState for TextEdit<'_> { type State = TextEditState; } impl TextEdit<'_> { pub fn load_state(ctx: &Context, id: Id) -> Option<TextEditState> { TextEditState::load(ctx, id) } pub fn store_state(ctx: &Context, id: Id, state: TextEditState) { state.store(ctx, id); } } impl<'t> TextEdit<'t> { /// No newlines (`\n`) allowed. Pressing enter key will result in the [`TextEdit`] losing focus (`response.lost_focus`). pub fn singleline(text: &'t mut dyn TextBuffer) -> Self { Self { desired_height_rows: 1, multiline: false, clip_text: true, ..Self::multiline(text) } } /// A [`TextEdit`] for multiple lines. Pressing enter key will create a new line by default (can be changed with [`return_key`](TextEdit::return_key)). pub fn multiline(text: &'t mut dyn TextBuffer) -> Self { Self { text, hint_text: Default::default(), hint_text_font: None, id: None, id_salt: None, font_selection: Default::default(), text_color: None, layouter: None, password: false, frame: true, margin: Margin::symmetric(4, 2), multiline: true, interactive: true, desired_width: None, desired_height_rows: 4, event_filter: EventFilter { // moving the cursor is really important horizontal_arrows: true, vertical_arrows: true, tab: false, // tab is used to change focus, not to insert a tab character ..Default::default() }, cursor_at_end: true, min_size: Vec2::ZERO, align: Align2::LEFT_TOP, clip_text: false, char_limit: usize::MAX, return_key: Some(KeyboardShortcut::new(Modifiers::NONE, Key::Enter)), background_color: None, } } /// Build a [`TextEdit`] focused on code editing. /// By default it comes with: /// - monospaced font /// - focus lock (tab will insert a tab character instead of moving focus) pub fn code_editor(self) -> Self { self.font(TextStyle::Monospace).lock_focus(true) } /// Use if you want to set an explicit [`Id`] for this widget. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = Some(id); self } /// A source for the unique [`Id`], e.g. `.id_source("second_text_edit_field")` or `.id_source(loop_index)`. #[inline] pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self { self.id_salt(id_salt) } /// A source for the unique [`Id`], e.g. `.id_salt("second_text_edit_field")` or `.id_salt(loop_index)`. #[inline] pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self { self.id_salt = Some(Id::new(id_salt)); self } /// Show a faint hint text when the text field is empty. /// /// If the hint text needs to be persisted even when the text field has input, /// the following workaround can be used: /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_string = String::new(); /// # use egui::{ Color32, FontId }; /// let text_edit = egui::TextEdit::multiline(&mut my_string) /// .desired_width(f32::INFINITY); /// let output = text_edit.show(ui); /// let painter = ui.painter_at(output.response.rect); /// let text_color = Color32::from_rgba_premultiplied(100, 100, 100, 100); /// let galley = painter.layout( /// String::from("Enter text"), /// FontId::default(), /// text_color, /// f32::INFINITY /// ); /// painter.galley(output.galley_pos, galley, text_color); /// # }); /// ``` #[inline] pub fn hint_text(mut self, hint_text: impl Into<WidgetText>) -> Self { self.hint_text = hint_text.into(); self } /// Set the background color of the [`TextEdit`]. The default is [`crate::Visuals::text_edit_bg_color`]. // TODO(bircni): remove this once #3284 is implemented #[inline] pub fn background_color(mut self, color: Color32) -> Self { self.background_color = Some(color); self } /// Set a specific style for the hint text. #[inline] pub fn hint_text_font(mut self, hint_text_font: impl Into<FontSelection>) -> Self { self.hint_text_font = Some(hint_text_font.into()); self } /// If true, hide the letters from view and prevent copying from the field. #[inline] pub fn password(mut self, password: bool) -> Self { self.password = password; self } /// Pick a [`crate::FontId`] or [`TextStyle`]. #[inline] pub fn font(mut self, font_selection: impl Into<FontSelection>) -> Self { self.font_selection = font_selection.into(); self } #[inline] pub fn text_color(mut self, text_color: Color32) -> Self { self.text_color = Some(text_color); self } #[inline] pub fn text_color_opt(mut self, text_color: Option<Color32>) -> Self { self.text_color = text_color; self } /// Override how text is being shown inside the [`TextEdit`]. /// /// This can be used to implement things like syntax highlighting. /// /// This function will be called at least once per frame, /// so it is strongly suggested that you cache the results of any syntax highlighter /// so as not to waste CPU highlighting the same string every frame. /// /// The arguments is the enclosing [`Ui`] (so you can access e.g. [`Context::fonts`]), /// the text and the wrap width. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_code = String::new(); /// # fn my_memoized_highlighter(s: &str) -> egui::text::LayoutJob { Default::default() } /// let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap_width: f32| { /// let mut layout_job: egui::text::LayoutJob = my_memoized_highlighter(buf.as_str()); /// layout_job.wrap.max_width = wrap_width; /// ui.fonts_mut(|f| f.layout_job(layout_job)) /// }; /// ui.add(egui::TextEdit::multiline(&mut my_code).layouter(&mut layouter)); /// # }); /// ``` #[inline] pub fn layouter( mut self, layouter: &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>, ) -> Self { self.layouter = Some(layouter); self } /// Default is `true`. If set to `false` then you cannot interact with the text (neither edit or select it). /// /// Consider using [`Ui::add_enabled`] instead to also give the [`TextEdit`] a greyed out look. #[inline] pub fn interactive(mut self, interactive: bool) -> Self { self.interactive = interactive; self } /// Default is `true`. If set to `false` there will be no frame showing that this is editable text! #[inline] pub fn frame(mut self, frame: bool) -> Self { self.frame = frame; self } /// Set margin of text. Default is `Margin::symmetric(4.0, 2.0)` #[inline] pub fn margin(mut self, margin: impl Into<Margin>) -> Self { self.margin = margin.into(); self } /// Set to 0.0 to keep as small as possible. /// Set to [`f32::INFINITY`] to take up all available space (i.e. disable automatic word wrap). #[inline] pub fn desired_width(mut self, desired_width: f32) -> Self { self.desired_width = Some(desired_width); self } /// Set the number of rows to show by default. /// The default for singleline text is `1`. /// The default for multiline text is `4`. #[inline] pub fn desired_rows(mut self, desired_height_rows: usize) -> Self { self.desired_height_rows = desired_height_rows; self } /// When `false` (default), pressing TAB will move focus /// to the next widget. /// /// When `true`, the widget will keep the focus and pressing TAB /// will insert the `'\t'` character. #[inline] pub fn lock_focus(mut self, tab_will_indent: bool) -> Self { self.event_filter.tab = tab_will_indent; self } /// When `true` (default), the cursor will initially be placed at the end of the text. /// /// When `false`, the cursor will initially be placed at the beginning of the text. #[inline] pub fn cursor_at_end(mut self, b: bool) -> Self { self.cursor_at_end = b; self } /// When `true` (default), overflowing text will be clipped. /// /// When `false`, widget width will expand to make all text visible. /// /// This only works for singleline [`TextEdit`]. #[inline] pub fn clip_text(mut self, b: bool) -> Self { // always show everything in multiline if !self.multiline { self.clip_text = b; } self } /// Sets the limit for the amount of characters can be entered /// /// This only works for singleline [`TextEdit`] #[inline] pub fn char_limit(mut self, limit: usize) -> Self { self.char_limit = limit; self } /// Set the horizontal align of the inner text. #[inline] pub fn horizontal_align(mut self, align: Align) -> Self { self.align.0[0] = align; self } /// Set the vertical align of the inner text. #[inline] pub fn vertical_align(mut self, align: Align) -> Self { self.align.0[1] = align; self } /// Set the minimum size of the [`TextEdit`]. #[inline] pub fn min_size(mut self, min_size: Vec2) -> Self { self.min_size = min_size; self } /// Set the return key combination. /// /// This combination will cause a newline on multiline, /// whereas on singleline it will cause the widget to lose focus. /// /// This combination is optional and can be disabled by passing [`None`] into this function. #[inline] pub fn return_key(mut self, return_key: impl Into<Option<KeyboardShortcut>>) -> Self { self.return_key = return_key.into(); self } } // ---------------------------------------------------------------------------- impl Widget for TextEdit<'_> { fn ui(self, ui: &mut Ui) -> Response { self.show(ui).response } } impl TextEdit<'_> { /// Show the [`TextEdit`], returning a rich [`TextEditOutput`]. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut my_string = String::new(); /// let output = egui::TextEdit::singleline(&mut my_string).show(ui); /// if let Some(text_cursor_range) = output.cursor_range { /// use egui::TextBuffer as _; /// let selected_chars = text_cursor_range.as_sorted_char_range(); /// let selected_text = my_string.char_range(selected_chars); /// ui.label("Selected text: "); /// ui.monospace(selected_text); /// } /// # }); /// ``` pub fn show(self, ui: &mut Ui) -> TextEditOutput { let is_mutable = self.text.is_mutable(); let frame = self.frame; let where_to_put_background = ui.painter().add(Shape::Noop); let background_color = self .background_color .unwrap_or_else(|| ui.visuals().text_edit_bg_color()); let output = self.show_content(ui); if frame { let visuals = ui.style().interact(&output.response); let frame_rect = output.response.rect.expand(visuals.expansion); let shape = if is_mutable { if output.response.has_focus() { epaint::RectShape::new( frame_rect, visuals.corner_radius, background_color, ui.visuals().selection.stroke, StrokeKind::Inside, ) } else { epaint::RectShape::new( frame_rect, visuals.corner_radius, background_color, visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop". StrokeKind::Inside, ) } } else { let visuals = &ui.style().visuals.widgets.inactive; epaint::RectShape::stroke( frame_rect, visuals.corner_radius, visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop". StrokeKind::Inside, ) }; ui.painter().set(where_to_put_background, shape); } output } fn show_content(self, ui: &mut Ui) -> TextEditOutput { let TextEdit { text, hint_text, hint_text_font, id, id_salt, font_selection, text_color, layouter, password, frame: _, margin, multiline, interactive, desired_width, desired_height_rows, event_filter, cursor_at_end, min_size, align, clip_text, char_limit, return_key, background_color: _, } = self; let text_color = text_color .or_else(|| ui.visuals().override_text_color) // .unwrap_or_else(|| ui.style().interact(&response).text_color()); // too bright .unwrap_or_else(|| ui.visuals().widgets.inactive.text_color()); let prev_text = text.as_str().to_owned(); let hint_text_str = hint_text.text().to_owned(); let font_id = font_selection.resolve(ui.style()); let row_height = ui.fonts_mut(|f| f.row_height(&font_id)); const MIN_WIDTH: f32 = 24.0; // Never make a [`TextEdit`] more narrow than this. let available_width = (ui.available_width() - margin.sum().x).at_least(MIN_WIDTH); let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width); let wrap_width = if ui.layout().horizontal_justify() { available_width } else { desired_width.min(available_width) }; let font_id_clone = font_id.clone(); let mut default_layouter = move |ui: &Ui, text: &dyn TextBuffer, wrap_width: f32| { let text = mask_if_password(password, text.as_str()); let layout_job = if multiline { LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width) } else { LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color) }; ui.fonts_mut(|f| f.layout_job(layout_job)) }; let layouter = layouter.unwrap_or(&mut default_layouter); let mut galley = layouter(ui, text, wrap_width); let desired_inner_width = if clip_text { wrap_width // visual clipping with scroll in singleline input. } else { galley.size().x.max(wrap_width) }; let desired_height = (desired_height_rows.at_least(1) as f32) * row_height; let desired_inner_size = vec2(desired_inner_width, galley.size().y.max(desired_height)); let desired_outer_size = (desired_inner_size + margin.sum()).at_least(min_size); let (auto_id, outer_rect) = ui.allocate_space(desired_outer_size); let rect = outer_rect - margin; // inner rect (excluding frame/margin). let id = id.unwrap_or_else(|| { if let Some(id_salt) = id_salt { ui.make_persistent_id(id_salt) } else { auto_id // Since we are only storing the cursor a persistent Id is not super important } }); let mut state = TextEditState::load(ui.ctx(), id).unwrap_or_default(); // On touch screens (e.g. mobile in `eframe` web), should // dragging select text, or scroll the enclosing [`ScrollArea`] (if any)? // Since currently copying selected text in not supported on `eframe` web, // we prioritize touch-scrolling: let allow_drag_to_select = ui.input(|i| !i.has_touch_screen()) || ui.memory(|mem| mem.has_focus(id)); let sense = if interactive { if allow_drag_to_select { Sense::click_and_drag() } else { Sense::click() } } else { Sense::hover() }; let mut response = ui.interact(outer_rect, id, sense); response.intrinsic_size = Some(Vec2::new(desired_width, desired_outer_size.y)); // Don't sent `OutputEvent::Clicked` when a user presses the space bar response.flags -= response::Flags::FAKE_PRIMARY_CLICKED; let text_clip_rect = rect; let painter = ui.painter_at(text_clip_rect.expand(1.0)); // expand to avoid clipping cursor if interactive && let Some(pointer_pos) = response.interact_pointer_pos() { if response.hovered() && text.is_mutable() { ui.output_mut(|o| o.mutable_text_under_cursor = true); } // TODO(emilk): drag selected text to either move or clone (ctrl on windows, alt on mac) let cursor_at_pointer = galley.cursor_from_pos(pointer_pos - rect.min + state.text_offset); if ui.visuals().text_cursor.preview && response.hovered() && ui.input(|i| i.pointer.is_moving()) { // text cursor preview: let cursor_rect = TSTransform::from_translation(rect.min.to_vec2()) * cursor_rect(&galley, &cursor_at_pointer, row_height); text_selection::visuals::paint_cursor_end(&painter, ui.visuals(), cursor_rect); } let is_being_dragged = ui.ctx().is_being_dragged(response.id); let did_interact = state.cursor.pointer_interaction( ui, &response, cursor_at_pointer, &galley, is_being_dragged, ); if did_interact || response.clicked() { ui.memory_mut(|mem| mem.request_focus(response.id)); state.last_interaction_time = ui.input(|i| i.time); } } if interactive && response.hovered() { ui.set_cursor_icon(CursorIcon::Text); } let mut cursor_range = None; let prev_cursor_range = state.cursor.range(&galley); if interactive && ui.memory(|mem| mem.has_focus(id)) { ui.memory_mut(|mem| mem.set_focus_lock_filter(id, event_filter)); let default_cursor_range = if cursor_at_end { CCursorRange::one(galley.end()) } else { CCursorRange::default() }; let (changed, new_cursor_range) = events( ui, &mut state, text, &mut galley, layouter, id, wrap_width, multiline, password, default_cursor_range, char_limit, event_filter, return_key, ); if changed { response.mark_changed(); } cursor_range = Some(new_cursor_range); } let mut galley_pos = align .align_size_within_rect(galley.size(), rect) .intersect(rect) // limit pos to the response rect area .min; let align_offset = rect.left_top() - galley_pos; // Visual clipping for singleline text editor with text larger than width if clip_text && align_offset.x == 0.0 { let cursor_pos = match (cursor_range, ui.memory(|mem| mem.has_focus(id))) { (Some(cursor_range), true) => galley.pos_from_cursor(cursor_range.primary).min.x, _ => 0.0, }; let mut offset_x = state.text_offset.x; let visible_range = offset_x..=offset_x + desired_inner_size.x; if !visible_range.contains(&cursor_pos) { if cursor_pos < *visible_range.start() { offset_x = cursor_pos; } else { offset_x = cursor_pos - desired_inner_size.x; } } offset_x = offset_x .at_most(galley.size().x - desired_inner_size.x) .at_least(0.0); state.text_offset = vec2(offset_x, align_offset.y); galley_pos -= vec2(offset_x, 0.0); } else { state.text_offset = align_offset; } let selection_changed = if let (Some(cursor_range), Some(prev_cursor_range)) = (cursor_range, prev_cursor_range) { prev_cursor_range != cursor_range } else { false }; if ui.is_rect_visible(rect) { if text.as_str().is_empty() && !hint_text.is_empty() { let hint_text_color = ui.visuals().weak_text_color(); let hint_text_font_id = hint_text_font.unwrap_or_else(|| font_id.into()); let galley = if multiline { hint_text.into_galley( ui, Some(TextWrapMode::Wrap), desired_inner_size.x, hint_text_font_id, ) } else { hint_text.into_galley( ui, Some(TextWrapMode::Extend), f32::INFINITY, hint_text_font_id, ) }; let galley_pos = align .align_size_within_rect(galley.size(), rect) .intersect(rect) .min; painter.galley(galley_pos, galley, hint_text_color); } let has_focus = ui.memory(|mem| mem.has_focus(id)); if has_focus && let Some(cursor_range) = state.cursor.range(&galley) { // Add text selection rectangles to the galley: paint_text_selection(&mut galley, ui.visuals(), &cursor_range, None); } // Allocate additional space if edits were made this frame that changed the size. This is important so that, // if there's a ScrollArea, it can properly scroll to the cursor. // Condition `!clip_text` is important to avoid breaking layout for `TextEdit::singleline` (PR #5640) if !clip_text && let extra_size = galley.size() - rect.size() && (extra_size.x > 0.0 || extra_size.y > 0.0) { match ui.layout().main_dir() { crate::Direction::LeftToRight | crate::Direction::TopDown => { ui.allocate_rect( Rect::from_min_size(outer_rect.max, extra_size), Sense::hover(), ); } crate::Direction::RightToLeft => { ui.allocate_rect( Rect::from_min_size( emath::pos2(outer_rect.min.x - extra_size.x, outer_rect.max.y), extra_size, ), Sense::hover(), ); } crate::Direction::BottomUp => { ui.allocate_rect( Rect::from_min_size( emath::pos2(outer_rect.min.x, outer_rect.max.y - extra_size.y), extra_size, ), Sense::hover(), ); } } } else { // Avoid an ID shift during this pass if the textedit grow ui.skip_ahead_auto_ids(1); } painter.galley(galley_pos, Arc::clone(&galley), text_color); if has_focus && let Some(cursor_range) = state.cursor.range(&galley) { let primary_cursor_rect = cursor_rect(&galley, &cursor_range.primary, row_height) .translate(galley_pos.to_vec2()); if response.changed() || selection_changed { // Scroll to keep primary cursor in view: ui.scroll_to_rect(primary_cursor_rect + margin, None); } if text.is_mutable() && interactive { let now = ui.input(|i| i.time); if response.changed() || selection_changed { state.last_interaction_time = now; } // Only show (and blink) cursor if the egui viewport has focus. // This is for two reasons: // * Don't give the impression that the user can type into a window without focus // * Don't repaint the ui because of a blinking cursor in an app that is not in focus let viewport_has_focus = ui.input(|i| i.focused); if viewport_has_focus { text_selection::visuals::paint_text_cursor( ui, &painter, primary_cursor_rect, now - state.last_interaction_time, ); } // Set IME output (in screen coords) when text is editable and visible let to_global = ui .ctx() .layer_transform_to_global(ui.layer_id()) .unwrap_or_default(); ui.ctx().output_mut(|o| { o.ime = Some(crate::output::IMEOutput { rect: to_global * rect, cursor_rect: to_global * primary_cursor_rect, }); }); } } } // Ensures correct IME behavior when the text input area gains or loses focus. if state.ime_enabled && (response.gained_focus() || response.lost_focus()) { state.ime_enabled = false; if let Some(mut ccursor_range) = state.cursor.char_range() { ccursor_range.secondary.index = ccursor_range.primary.index; state.cursor.set_char_range(Some(ccursor_range)); } ui.input_mut(|i| i.events.retain(|e| !matches!(e, Event::Ime(_)))); } state.clone().store(ui.ctx(), id); if response.changed() { response.widget_info(|| { WidgetInfo::text_edit( ui.is_enabled(), mask_if_password(password, prev_text.as_str()), mask_if_password(password, text.as_str()), hint_text_str.as_str(), ) }); } else if selection_changed && let Some(cursor_range) = cursor_range { let char_range = cursor_range.primary.index..=cursor_range.secondary.index; let info = WidgetInfo::text_selection_changed( ui.is_enabled(), char_range, mask_if_password(password, text.as_str()), ); response.output_event(OutputEvent::TextSelectionChanged(info)); } else { response.widget_info(|| { WidgetInfo::text_edit( ui.is_enabled(), mask_if_password(password, prev_text.as_str()), mask_if_password(password, text.as_str()), hint_text_str.as_str(), ) }); } { let role = if password { accesskit::Role::PasswordInput } else if multiline { accesskit::Role::MultilineTextInput } else { accesskit::Role::TextInput }; crate::text_selection::accesskit_text::update_accesskit_for_text_widget( ui.ctx(), id, cursor_range, role, TSTransform::from_translation(galley_pos.to_vec2()), &galley, ); } TextEditOutput { response, galley, galley_pos, text_clip_rect, state, cursor_range, } } } fn mask_if_password(is_password: bool, text: &str) -> String { fn mask_password(text: &str) -> String { std::iter::repeat_n( epaint::text::PASSWORD_REPLACEMENT_CHAR, text.chars().count(), ) .collect::<String>() } if is_password { mask_password(text) } else { text.to_owned() } } // ---------------------------------------------------------------------------- /// Check for (keyboard) events to edit the cursor and/or text. #[expect(clippy::too_many_arguments)] fn events( ui: &crate::Ui, state: &mut TextEditState, text: &mut dyn TextBuffer, galley: &mut Arc<Galley>, layouter: &mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>, id: Id, wrap_width: f32, multiline: bool, password: bool, default_cursor_range: CCursorRange, char_limit: usize, event_filter: EventFilter,
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/text_edit/state.rs
crates/egui/src/widgets/text_edit/state.rs
use std::sync::Arc; use crate::mutex::Mutex; use crate::{ Context, Id, Vec2, text_selection::{CCursorRange, TextCursorState}, }; pub type TextEditUndoer = crate::util::undoer::Undoer<(CCursorRange, String)>; /// The text edit state stored between frames. /// /// Attention: You also need to `store` the updated state. /// ``` /// # egui::__run_test_ui(|ui| { /// # let mut text = String::new(); /// use egui::text::{CCursor, CCursorRange}; /// /// let mut output = egui::TextEdit::singleline(&mut text).show(ui); /// /// // Create a new selection range /// let min = CCursor::new(0); /// let max = CCursor::new(0); /// let new_range = CCursorRange::two(min, max); /// /// // Update the state /// output.state.cursor.set_char_range(Some(new_range)); /// // Store the updated state /// output.state.store(ui.ctx(), output.response.id); /// # }); /// ``` #[derive(Clone, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct TextEditState { /// Controls the text selection. pub cursor: TextCursorState, /// Wrapped in Arc for cheaper clones. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) undoer: Arc<Mutex<TextEditUndoer>>, // If IME candidate window is shown on this text edit. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) ime_enabled: bool, // cursor range for IME candidate. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) ime_cursor_range: CCursorRange, // Text offset within the widget area. // Used for sensing and singleline text clipping. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) text_offset: Vec2, /// When did the user last press a key or click on the `TextEdit`. /// Used to pause the cursor animation when typing. #[cfg_attr(feature = "serde", serde(skip))] pub(crate) last_interaction_time: f64, } impl TextEditState { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_persisted(id)) } pub fn store(self, ctx: &Context, id: Id) { ctx.data_mut(|d| d.insert_persisted(id, self)); } pub fn undoer(&self) -> TextEditUndoer { self.undoer.lock().clone() } #[expect(clippy::needless_pass_by_ref_mut)] // Intentionally hide interiority of mutability pub fn set_undoer(&mut self, undoer: TextEditUndoer) { *self.undoer.lock() = undoer; } pub fn clear_undoer(&mut self) { self.set_undoer(TextEditUndoer::default()); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/text_edit/mod.rs
crates/egui/src/widgets/text_edit/mod.rs
mod builder; mod output; mod state; mod text_buffer; pub use { crate::text_selection::TextCursorState, builder::TextEdit, output::TextEditOutput, state::TextEditState, text_buffer::TextBuffer, };
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/text_edit/text_buffer.rs
crates/egui/src/widgets/text_edit/text_buffer.rs
use std::{borrow::Cow, ops::Range}; use epaint::{ Galley, text::{TAB_SIZE, cursor::CCursor}, }; use crate::{ text::CCursorRange, text_selection::text_cursor_state::{ byte_index_from_char_index, ccursor_next_word, ccursor_previous_word, char_index_from_byte_index, find_line_start, slice_char_range, }, }; /// Trait constraining what types [`crate::TextEdit`] may use as /// an underlying buffer. /// /// Most likely you will use a [`String`] which implements [`TextBuffer`]. pub trait TextBuffer { /// Can this text be edited? fn is_mutable(&self) -> bool; /// Returns this buffer as a `str`. fn as_str(&self) -> &str; /// Inserts text `text` into this buffer at character index `char_index`. /// /// # Notes /// `char_index` is a *character index*, not a byte index. /// /// # Return /// Returns how many *characters* were successfully inserted fn insert_text(&mut self, text: &str, char_index: usize) -> usize; /// Deletes a range of text `char_range` from this buffer. /// /// # Notes /// `char_range` is a *character range*, not a byte range. fn delete_char_range(&mut self, char_range: Range<usize>); /// Reads the given character range. fn char_range(&self, char_range: Range<usize>) -> &str { slice_char_range(self.as_str(), char_range) } fn byte_index_from_char_index(&self, char_index: usize) -> usize { byte_index_from_char_index(self.as_str(), char_index) } fn char_index_from_byte_index(&self, char_index: usize) -> usize { char_index_from_byte_index(self.as_str(), char_index) } /// Clears all characters in this buffer fn clear(&mut self) { self.delete_char_range(0..self.as_str().len()); } /// Replaces all contents of this string with `text` fn replace_with(&mut self, text: &str) { self.clear(); self.insert_text(text, 0); } /// Clears all characters in this buffer and returns a string of the contents. fn take(&mut self) -> String { let s = self.as_str().to_owned(); self.clear(); s } fn insert_text_at(&mut self, ccursor: &mut CCursor, text_to_insert: &str, char_limit: usize) { if char_limit < usize::MAX { let mut new_string = text_to_insert; // Avoid subtract with overflow panic let cutoff = char_limit.saturating_sub(self.as_str().chars().count()); new_string = match new_string.char_indices().nth(cutoff) { None => new_string, Some((idx, _)) => &new_string[..idx], }; ccursor.index += self.insert_text(new_string, ccursor.index); } else { ccursor.index += self.insert_text(text_to_insert, ccursor.index); } } fn decrease_indentation(&mut self, ccursor: &mut CCursor) { let line_start = find_line_start(self.as_str(), *ccursor); let remove_len = if self.as_str().chars().nth(line_start.index) == Some('\t') { Some(1) } else if self .as_str() .chars() .skip(line_start.index) .take(TAB_SIZE) .all(|c| c == ' ') { Some(TAB_SIZE) } else { None }; if let Some(len) = remove_len { self.delete_char_range(line_start.index..(line_start.index + len)); if *ccursor != line_start { *ccursor -= len; } } } fn delete_selected(&mut self, cursor_range: &CCursorRange) -> CCursor { let [min, max] = cursor_range.sorted_cursors(); self.delete_selected_ccursor_range([min, max]) } fn delete_selected_ccursor_range(&mut self, [min, max]: [CCursor; 2]) -> CCursor { self.delete_char_range(min.index..max.index); CCursor { index: min.index, prefer_next_row: true, } } fn delete_previous_char(&mut self, ccursor: CCursor) -> CCursor { if ccursor.index > 0 { let max_ccursor = ccursor; let min_ccursor = max_ccursor - 1; self.delete_selected_ccursor_range([min_ccursor, max_ccursor]) } else { ccursor } } fn delete_next_char(&mut self, ccursor: CCursor) -> CCursor { self.delete_selected_ccursor_range([ccursor, ccursor + 1]) } fn delete_previous_word(&mut self, max_ccursor: CCursor) -> CCursor { let min_ccursor = ccursor_previous_word(self.as_str(), max_ccursor); self.delete_selected_ccursor_range([min_ccursor, max_ccursor]) } fn delete_next_word(&mut self, min_ccursor: CCursor) -> CCursor { let max_ccursor = ccursor_next_word(self.as_str(), min_ccursor); self.delete_selected_ccursor_range([min_ccursor, max_ccursor]) } fn delete_paragraph_before_cursor( &mut self, galley: &Galley, cursor_range: &CCursorRange, ) -> CCursor { let [min, max] = cursor_range.sorted_cursors(); let min = galley.cursor_begin_of_paragraph(&min); if min == max { self.delete_previous_char(min) } else { self.delete_selected(&CCursorRange::two(min, max)) } } fn delete_paragraph_after_cursor( &mut self, galley: &Galley, cursor_range: &CCursorRange, ) -> CCursor { let [min, max] = cursor_range.sorted_cursors(); let max = galley.cursor_end_of_paragraph(&max); if min == max { self.delete_next_char(min) } else { self.delete_selected(&CCursorRange::two(min, max)) } } /// Returns a unique identifier for the implementing type. /// /// This is useful for downcasting from this trait to the implementing type. /// Here is an example usage: /// ``` /// use egui::TextBuffer; /// use std::any::TypeId; /// /// struct ExampleBuffer {} /// /// impl TextBuffer for ExampleBuffer { /// fn is_mutable(&self) -> bool { unimplemented!() } /// fn as_str(&self) -> &str { unimplemented!() } /// fn insert_text(&mut self, text: &str, char_index: usize) -> usize { unimplemented!() } /// fn delete_char_range(&mut self, char_range: std::ops::Range<usize>) { unimplemented!() } /// /// // Implement it like the following: /// fn type_id(&self) -> TypeId { /// TypeId::of::<Self>() /// } /// } /// /// // Example downcast: /// pub fn downcast_example(buffer: &dyn TextBuffer) -> Option<&ExampleBuffer> { /// if buffer.type_id() == TypeId::of::<ExampleBuffer>() { /// unsafe { Some(&*(buffer as *const dyn TextBuffer as *const ExampleBuffer)) } /// } else { /// None /// } /// } /// ``` fn type_id(&self) -> std::any::TypeId; } impl TextBuffer for String { fn is_mutable(&self) -> bool { true } fn as_str(&self) -> &str { self.as_ref() } fn insert_text(&mut self, text: &str, char_index: usize) -> usize { // Get the byte index from the character index let byte_idx = byte_index_from_char_index(self.as_str(), char_index); // Then insert the string self.insert_str(byte_idx, text); text.chars().count() } fn delete_char_range(&mut self, char_range: Range<usize>) { assert!( char_range.start <= char_range.end, "start must be <= end, but got {char_range:?}" ); // Get both byte indices let byte_start = byte_index_from_char_index(self.as_str(), char_range.start); let byte_end = byte_index_from_char_index(self.as_str(), char_range.end); // Then drain all characters within this range self.drain(byte_start..byte_end); } fn clear(&mut self) { self.clear(); } fn replace_with(&mut self, text: &str) { text.clone_into(self); } fn take(&mut self) -> String { std::mem::take(self) } fn type_id(&self) -> std::any::TypeId { std::any::TypeId::of::<Self>() } } impl TextBuffer for Cow<'_, str> { fn is_mutable(&self) -> bool { true } fn as_str(&self) -> &str { self.as_ref() } fn insert_text(&mut self, text: &str, char_index: usize) -> usize { <String as TextBuffer>::insert_text(self.to_mut(), text, char_index) } fn delete_char_range(&mut self, char_range: Range<usize>) { <String as TextBuffer>::delete_char_range(self.to_mut(), char_range); } fn clear(&mut self) { <String as TextBuffer>::clear(self.to_mut()); } fn replace_with(&mut self, text: &str) { *self = Cow::Owned(text.to_owned()); } fn take(&mut self) -> String { std::mem::take(self).into_owned() } fn type_id(&self) -> std::any::TypeId { std::any::TypeId::of::<Cow<'_, str>>() } } /// Immutable view of a `&str`! impl TextBuffer for &str { fn is_mutable(&self) -> bool { false } fn as_str(&self) -> &str { self } fn insert_text(&mut self, _text: &str, _ch_idx: usize) -> usize { 0 } fn delete_char_range(&mut self, _ch_range: Range<usize>) {} fn type_id(&self) -> std::any::TypeId { std::any::TypeId::of::<&str>() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/widgets/text_edit/output.rs
crates/egui/src/widgets/text_edit/output.rs
use std::sync::Arc; use crate::text::CCursorRange; /// The output from a [`TextEdit`](crate::TextEdit). pub struct TextEditOutput { /// The interaction response. pub response: crate::Response, /// How the text was displayed. pub galley: Arc<crate::Galley>, /// Where the text in [`Self::galley`] ended up on the screen. pub galley_pos: crate::Pos2, /// The text was clipped to this rectangle when painted. pub text_clip_rect: crate::Rect, /// The state we stored after the run. pub state: super::TextEditState, /// Where the text cursor is. pub cursor_range: Option<CCursorRange>, } // TODO(emilk): add `output.paint` and `output.store` and split out that code from `TextEdit::show`.
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/old_popup.rs
crates/egui/src/containers/old_popup.rs
//! Old and deprecated API for popups. Use [`Popup`] instead. #![expect(deprecated)] use crate::containers::tooltip::Tooltip; use crate::{ Align, Context, Id, LayerId, Layout, Popup, PopupAnchor, PopupCloseBehavior, Pos2, Rect, Response, Ui, Widget as _, WidgetText, }; use emath::RectAlign; // ---------------------------------------------------------------------------- /// Show a tooltip at the current pointer position (if any). /// /// Most of the time it is easier to use [`Response::on_hover_ui`]. /// /// See also [`show_tooltip_text`]. /// /// Returns `None` if the tooltip could not be placed. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # #[expect(deprecated)] /// if ui.ui_contains_pointer() { /// egui::show_tooltip(ui.ctx(), ui.layer_id(), egui::Id::new("my_tooltip"), |ui| { /// ui.label("Helpful text"); /// }); /// } /// # }); /// ``` #[deprecated = "Use `egui::Tooltip` instead"] pub fn show_tooltip<R>( ctx: &Context, parent_layer: LayerId, widget_id: Id, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { show_tooltip_at_pointer(ctx, parent_layer, widget_id, add_contents) } /// Show a tooltip at the current pointer position (if any). /// /// Most of the time it is easier to use [`Response::on_hover_ui`]. /// /// See also [`show_tooltip_text`]. /// /// Returns `None` if the tooltip could not be placed. /// /// ``` /// # egui::__run_test_ui(|ui| { /// if ui.ui_contains_pointer() { /// egui::show_tooltip_at_pointer(ui.ctx(), ui.layer_id(), egui::Id::new("my_tooltip"), |ui| { /// ui.label("Helpful text"); /// }); /// } /// # }); /// ``` #[deprecated = "Use `egui::Tooltip` instead"] pub fn show_tooltip_at_pointer<R>( ctx: &Context, parent_layer: LayerId, widget_id: Id, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { Tooltip::always_open(ctx.clone(), parent_layer, widget_id, PopupAnchor::Pointer) .gap(12.0) .show(add_contents) .map(|response| response.inner) } /// Show a tooltip under the given area. /// /// If the tooltip does not fit under the area, it tries to place it above it instead. #[deprecated = "Use `egui::Tooltip` instead"] pub fn show_tooltip_for<R>( ctx: &Context, parent_layer: LayerId, widget_id: Id, widget_rect: &Rect, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { Tooltip::always_open(ctx.clone(), parent_layer, widget_id, *widget_rect) .show(add_contents) .map(|response| response.inner) } /// Show a tooltip at the given position. /// /// Returns `None` if the tooltip could not be placed. #[deprecated = "Use `egui::Tooltip` instead"] pub fn show_tooltip_at<R>( ctx: &Context, parent_layer: LayerId, widget_id: Id, suggested_position: Pos2, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { Tooltip::always_open(ctx.clone(), parent_layer, widget_id, suggested_position) .show(add_contents) .map(|response| response.inner) } /// Show some text at the current pointer position (if any). /// /// Most of the time it is easier to use [`Response::on_hover_text`]. /// /// See also [`show_tooltip`]. /// /// Returns `None` if the tooltip could not be placed. /// /// ``` /// # egui::__run_test_ui(|ui| { /// if ui.ui_contains_pointer() { /// egui::show_tooltip_text(ui.ctx(), ui.layer_id(), egui::Id::new("my_tooltip"), "Helpful text"); /// } /// # }); /// ``` #[deprecated = "Use `egui::Tooltip` instead"] pub fn show_tooltip_text( ctx: &Context, parent_layer: LayerId, widget_id: Id, text: impl Into<WidgetText>, ) -> Option<()> { show_tooltip(ctx, parent_layer, widget_id, |ui| { crate::widgets::Label::new(text).ui(ui); }) } /// Was this tooltip visible last frame? #[deprecated = "Use `Tooltip::was_tooltip_open_last_frame` instead"] pub fn was_tooltip_open_last_frame(ctx: &Context, widget_id: Id) -> bool { Tooltip::was_tooltip_open_last_frame(ctx, widget_id) } /// Indicate whether a popup will be shown above or below the box. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AboveOrBelow { Above, Below, } /// Helper for [`popup_above_or_below_widget`]. #[deprecated = "Use `egui::Popup` instead"] pub fn popup_below_widget<R>( ui: &Ui, popup_id: Id, widget_response: &Response, close_behavior: PopupCloseBehavior, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { popup_above_or_below_widget( ui, popup_id, widget_response, AboveOrBelow::Below, close_behavior, add_contents, ) } /// Shows a popup above or below another widget. /// /// Useful for drop-down menus (combo boxes) or suggestion menus under text fields. /// /// The opened popup will have a minimum width matching its parent. /// /// You must open the popup with [`crate::Memory::open_popup`] or [`crate::Memory::toggle_popup`]. /// /// Returns `None` if the popup is not open. /// /// ``` /// # egui::__run_test_ui(|ui| { /// let response = ui.button("Open popup"); /// let popup_id = ui.make_persistent_id("my_unique_id"); /// if response.clicked() { /// ui.memory_mut(|mem| mem.toggle_popup(popup_id)); /// } /// let below = egui::AboveOrBelow::Below; /// let close_on_click_outside = egui::PopupCloseBehavior::CloseOnClickOutside; /// # #[expect(deprecated)] /// egui::popup_above_or_below_widget(ui, popup_id, &response, below, close_on_click_outside, |ui| { /// ui.set_min_width(200.0); // if you want to control the size /// ui.label("Some more info, or things you can select:"); /// ui.label("…"); /// }); /// # }); /// ``` #[deprecated = "Use `egui::Popup` instead"] pub fn popup_above_or_below_widget<R>( _parent_ui: &Ui, popup_id: Id, widget_response: &Response, above_or_below: AboveOrBelow, close_behavior: PopupCloseBehavior, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { let response = Popup::from_response(widget_response) .layout(Layout::top_down_justified(Align::LEFT)) .open_memory(None) .close_behavior(close_behavior) .id(popup_id) .align(match above_or_below { AboveOrBelow::Above => RectAlign::TOP_START, AboveOrBelow::Below => RectAlign::BOTTOM_START, }) .width(widget_response.rect.width()) .show(|ui| { ui.set_min_width(ui.available_width()); add_contents(ui) })?; Some(response.inner) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/tooltip.rs
crates/egui/src/containers/tooltip.rs
use crate::pass_state::PerWidgetTooltipState; use crate::{ AreaState, Context, Id, InnerResponse, LayerId, Layout, Order, Popup, PopupAnchor, PopupKind, Response, Sense, }; use emath::Vec2; pub struct Tooltip<'a> { pub popup: Popup<'a>, /// The layer of the parent widget. parent_layer: LayerId, /// The id of the widget that owns this tooltip. parent_widget: Id, } impl Tooltip<'_> { /// Show a tooltip that is always open. #[deprecated = "Use `Tooltip::always_open` instead."] pub fn new( parent_widget: Id, ctx: Context, anchor: impl Into<PopupAnchor>, parent_layer: LayerId, ) -> Self { Self { popup: Popup::new(parent_widget, ctx, anchor.into(), parent_layer) .kind(PopupKind::Tooltip) .gap(4.0) .sense(Sense::hover()), parent_layer, parent_widget, } } /// Show a tooltip that is always open. pub fn always_open( ctx: Context, parent_layer: LayerId, parent_widget: Id, anchor: impl Into<PopupAnchor>, ) -> Self { let width = ctx.global_style().spacing.tooltip_width; Self { popup: Popup::new(parent_widget, ctx, anchor.into(), parent_layer) .kind(PopupKind::Tooltip) .gap(4.0) .width(width) .sense(Sense::hover()), parent_layer, parent_widget, } } /// Show a tooltip for a widget. Always open (as long as this function is called). pub fn for_widget(response: &Response) -> Self { let popup = Popup::from_response(response) .kind(PopupKind::Tooltip) .gap(4.0) .width(response.ctx.global_style().spacing.tooltip_width) .sense(Sense::hover()); Self { popup, parent_layer: response.layer_id, parent_widget: response.id, } } /// Show a tooltip when hovering an enabled widget. pub fn for_enabled(response: &Response) -> Self { let mut tooltip = Self::for_widget(response); tooltip.popup = tooltip .popup .open(response.enabled() && Self::should_show_tooltip(response, true)); tooltip } /// Show a tooltip when hovering a disabled widget. pub fn for_disabled(response: &Response) -> Self { let mut tooltip = Self::for_widget(response); tooltip.popup = tooltip .popup .open(!response.enabled() && Self::should_show_tooltip(response, true)); tooltip } /// Show the tooltip at the pointer position. #[inline] pub fn at_pointer(mut self) -> Self { self.popup = self.popup.at_pointer(); self } /// Set the gap between the tooltip and the anchor /// /// Default: 5.0 #[inline] pub fn gap(mut self, gap: f32) -> Self { self.popup = self.popup.gap(gap); self } /// Set the layout of the tooltip #[inline] pub fn layout(mut self, layout: Layout) -> Self { self.popup = self.popup.layout(layout); self } /// Set the width of the tooltip #[inline] pub fn width(mut self, width: f32) -> Self { self.popup = self.popup.width(width); self } /// Show the tooltip pub fn show<R>(self, content: impl FnOnce(&mut crate::Ui) -> R) -> Option<InnerResponse<R>> { let Self { mut popup, parent_layer, parent_widget, } = self; if !popup.is_open() { return None; } let rect = popup.get_anchor_rect()?; let mut state = popup.ctx().pass_state_mut(|fs| { // Remember that this is the widget showing the tooltip: fs.layers .entry(parent_layer) .or_default() .widget_with_tooltip = Some(parent_widget); fs.tooltips .widget_tooltips .get(&parent_widget) .copied() .unwrap_or(PerWidgetTooltipState { bounding_rect: rect, tooltip_count: 0, }) }); let tooltip_area_id = Self::tooltip_id(parent_widget, state.tooltip_count); popup = popup.anchor(state.bounding_rect).id(tooltip_area_id); let response = popup.show(|ui| { // By default, the text in tooltips aren't selectable. // This means that most tooltips aren't interactable, // which also mean they won't stick around so you can click them. // Only tooltips that have actual interactive stuff (buttons, links, …) // will stick around when you try to click them. ui.style_mut().interaction.selectable_labels = false; content(ui) }); // The popup might not be shown on at_pointer if there is no pointer. if let Some(response) = &response { state.tooltip_count += 1; state.bounding_rect |= response.response.rect; response .response .ctx .pass_state_mut(|fs| fs.tooltips.widget_tooltips.insert(parent_widget, state)); Self::remember_that_tooltip_was_shown(&response.response.ctx); } response } fn when_was_a_toolip_last_shown_id() -> Id { Id::new("when_was_a_toolip_last_shown") } pub fn seconds_since_last_tooltip(ctx: &Context) -> f32 { let when_was_a_toolip_last_shown = ctx.data(|d| d.get_temp::<f64>(Self::when_was_a_toolip_last_shown_id())); if let Some(when_was_a_toolip_last_shown) = when_was_a_toolip_last_shown { let now = ctx.input(|i| i.time); (now - when_was_a_toolip_last_shown) as f32 } else { f32::INFINITY } } fn remember_that_tooltip_was_shown(ctx: &Context) { let now = ctx.input(|i| i.time); ctx.data_mut(|data| data.insert_temp::<f64>(Self::when_was_a_toolip_last_shown_id(), now)); } /// What is the id of the next tooltip for this widget? pub fn next_tooltip_id(ctx: &Context, widget_id: Id) -> Id { let tooltip_count = ctx.pass_state(|fs| { fs.tooltips .widget_tooltips .get(&widget_id) .map_or(0, |state| state.tooltip_count) }); Self::tooltip_id(widget_id, tooltip_count) } pub fn tooltip_id(widget_id: Id, tooltip_count: usize) -> Id { widget_id.with(tooltip_count) } /// Should we show a tooltip for this response? /// /// Argument `allow_interactive_tooltip` controls whether mouse can interact with tooltip that /// contains interactive widgets pub fn should_show_tooltip(response: &Response, allow_interactive_tooltip: bool) -> bool { if response.ctx.memory(|mem| mem.everything_is_visible()) { return true; } let any_open_popups = response.ctx.prev_pass_state(|fs| { fs.layers .get(&response.layer_id) .is_some_and(|layer| !layer.open_popups.is_empty()) }); if any_open_popups { // Hide tooltips if the user opens a popup (menu, combo-box, etc.) in the same layer. return false; } let style = response.ctx.global_style(); let tooltip_delay = style.interaction.tooltip_delay; let tooltip_grace_time = style.interaction.tooltip_grace_time; let ( time_since_last_scroll, time_since_last_click, time_since_last_pointer_movement, pointer_pos, pointer_dir, ) = response.ctx.input(|i| { ( i.time_since_last_scroll(), i.pointer.time_since_last_click(), i.pointer.time_since_last_movement(), i.pointer.hover_pos(), i.pointer.direction(), ) }); if time_since_last_scroll < tooltip_delay { // See https://github.com/emilk/egui/issues/4781 // Note that this means we cannot have `ScrollArea`s in a tooltip. response .ctx .request_repaint_after_secs(tooltip_delay - time_since_last_scroll); return false; } let is_our_tooltip_open = response.is_tooltip_open(); if is_our_tooltip_open { // Check if we should automatically stay open: let tooltip_id = Self::next_tooltip_id(&response.ctx, response.id); let tooltip_layer_id = LayerId::new(Order::Tooltip, tooltip_id); let tooltip_has_interactive_widget = allow_interactive_tooltip && response.ctx.viewport(|vp| { vp.prev_pass .widgets .get_layer(tooltip_layer_id) .any(|w| w.enabled && w.sense.interactive()) }); if tooltip_has_interactive_widget { // We keep the tooltip open if hovered, // or if the pointer is on its way to it, // so that the user can interact with the tooltip // (i.e. click links that are in it). if let Some(area) = AreaState::load(&response.ctx, tooltip_id) { let rect = area.rect(); if let Some(pos) = pointer_pos { if rect.contains(pos) { return true; // hovering interactive tooltip } if pointer_dir != Vec2::ZERO && rect.intersects_ray(pos, pointer_dir.normalized()) { return true; // on the way to interactive tooltip } } } } } let clicked_more_recently_than_moved = time_since_last_click < time_since_last_pointer_movement + 0.1; if clicked_more_recently_than_moved { // It is common to click a widget and then rest the mouse there. // It would be annoying to then see a tooltip for it immediately. // Similarly, clicking should hide the existing tooltip. // Only hovering should lead to a tooltip, not clicking. // The offset is only to allow small movement just right after the click. return false; } if is_our_tooltip_open { // Check if we should automatically stay open: if pointer_pos.is_some_and(|pointer_pos| response.rect.contains(pointer_pos)) { // Handle the case of a big tooltip that covers the widget: return true; } } let is_other_tooltip_open = response.ctx.prev_pass_state(|fs| { if let Some(already_open_tooltip) = fs .layers .get(&response.layer_id) .and_then(|layer| layer.widget_with_tooltip) { already_open_tooltip != response.id } else { false } }); if is_other_tooltip_open { // We only allow one tooltip per layer. First one wins. It is up to that tooltip to close itself. return false; } // Fast early-outs: if response.enabled() { if !response.hovered() || !response.ctx.input(|i| i.pointer.has_pointer()) { return false; } } else if !response .ctx .rect_contains_pointer(response.layer_id, response.rect) { return false; } // There is a tooltip_delay before showing the first tooltip, // but once one tooltip is show, moving the mouse cursor to // another widget should show the tooltip for that widget right away. // Let the user quickly move over some dead space to hover the next thing let tooltip_was_recently_shown = Self::seconds_since_last_tooltip(&response.ctx) < tooltip_grace_time; if !tooltip_was_recently_shown && !is_our_tooltip_open { if style.interaction.show_tooltips_only_when_still { // We only show the tooltip when the mouse pointer is still. if !response .ctx .input(|i| i.pointer.is_still() && !i.is_scrolling()) { // wait for mouse to stop response.ctx.request_repaint(); return false; } } let time_since_last_interaction = time_since_last_scroll .min(time_since_last_pointer_movement) .min(time_since_last_click); let time_til_tooltip = tooltip_delay - time_since_last_interaction; if 0.0 < time_til_tooltip { // Wait until the mouse has been still for a while response.ctx.request_repaint_after_secs(time_til_tooltip); return false; } } // We don't want tooltips of things while we are dragging them, // but we do want tooltips while holding down on an item on a touch screen. if response .ctx .input(|i| i.pointer.any_down() && i.pointer.has_moved_too_much_for_a_click) { return false; } // All checks passed: show the tooltip! true } /// Was this tooltip visible last frame? pub fn was_tooltip_open_last_frame(ctx: &Context, widget_id: Id) -> bool { let primary_tooltip_area_id = Self::tooltip_id(widget_id, 0); ctx.memory(|mem| { mem.areas() .visible_last_frame(&LayerId::new(Order::Tooltip, primary_tooltip_area_id)) }) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/menu.rs
crates/egui/src/containers/menu.rs
//! Popup menus, context menus and menu bars. //! //! Show menus via //! - [`Popup::menu`] and [`Popup::context_menu`] //! - [`Ui::menu_button`], [`MenuButton`] and [`SubMenuButton`] //! - [`MenuBar`] //! - [`Response::context_menu`] //! //! See [`MenuBar`] for an example. use crate::style::StyleModifier; use crate::{ Button, Color32, Context, Frame, Id, InnerResponse, IntoAtoms, Layout, Popup, PopupCloseBehavior, Response, Style, Ui, UiBuilder, UiKind, UiStack, UiStackInfo, Widget as _, }; use emath::{Align, RectAlign, Vec2, vec2}; use epaint::Stroke; /// Apply a menu style to the [`Style`]. /// /// Mainly removes the background stroke and the inactive background fill. pub fn menu_style(style: &mut Style) { style.spacing.button_padding = vec2(2.0, 0.0); style.visuals.widgets.active.bg_stroke = Stroke::NONE; style.visuals.widgets.open.bg_stroke = Stroke::NONE; style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; style.visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; } /// Find the root [`UiStack`] of the menu. pub fn find_menu_root(ui: &Ui) -> &UiStack { ui.stack() .iter() .find(|stack| { stack.is_root_ui() || [Some(UiKind::Popup), Some(UiKind::Menu)].contains(&stack.kind()) || stack.info.tags.contains(MenuConfig::MENU_CONFIG_TAG) }) .expect("We should always find the root") } /// Is this Ui part of a menu? /// /// Returns `false` if this is a menu bar. /// Should be used to determine if we should show a menu button or submenu button. pub fn is_in_menu(ui: &Ui) -> bool { for stack in ui.stack().iter() { if let Some(config) = stack .info .tags .get_downcast::<MenuConfig>(MenuConfig::MENU_CONFIG_TAG) { return !config.bar; } if [Some(UiKind::Popup), Some(UiKind::Menu)].contains(&stack.kind()) { return true; } } false } /// Configuration and style for menus. #[derive(Clone, Debug)] pub struct MenuConfig { /// Is this a menu bar? bar: bool, /// If the user clicks, should we close the menu? pub close_behavior: PopupCloseBehavior, /// Override the menu style. /// /// Default is [`menu_style`]. pub style: StyleModifier, } impl Default for MenuConfig { fn default() -> Self { Self { close_behavior: PopupCloseBehavior::default(), bar: false, style: menu_style.into(), } } } impl MenuConfig { /// The tag used to store the menu config in the [`UiStack`]. pub const MENU_CONFIG_TAG: &'static str = "egui_menu_config"; pub fn new() -> Self { Self::default() } /// If the user clicks, should we close the menu? #[inline] pub fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self { self.close_behavior = close_behavior; self } /// Override the menu style. /// /// Default is [`menu_style`]. #[inline] pub fn style(mut self, style: impl Into<StyleModifier>) -> Self { self.style = style.into(); self } fn from_stack(stack: &UiStack) -> Self { stack .info .tags .get_downcast(Self::MENU_CONFIG_TAG) .cloned() .unwrap_or_default() } /// Find the config for the current menu. /// /// Returns the default config if no config is found. pub fn find(ui: &Ui) -> Self { find_menu_root(ui) .info .tags .get_downcast(Self::MENU_CONFIG_TAG) .cloned() .unwrap_or_default() } } /// Holds the state of the menu. #[derive(Clone)] pub struct MenuState { /// The currently open sub menu in this menu. pub open_item: Option<Id>, last_visible_pass: u64, } impl MenuState { pub const ID: &'static str = "menu_state"; /// Find the root of the menu and get the state pub fn from_ui<R>(ui: &Ui, f: impl FnOnce(&mut Self, &UiStack) -> R) -> R { let stack = find_menu_root(ui); Self::from_id(ui.ctx(), stack.id, |state| f(state, stack)) } /// Get the state via the menus root [`Ui`] id pub fn from_id<R>(ctx: &Context, id: Id, f: impl FnOnce(&mut Self) -> R) -> R { let pass_nr = ctx.cumulative_pass_nr(); ctx.data_mut(|data| { let state_id = id.with(Self::ID); let mut state = data.get_temp(state_id).unwrap_or(Self { open_item: None, last_visible_pass: pass_nr, }); // If the menu was closed for at least a frame, reset the open item if state.last_visible_pass + 1 < pass_nr { state.open_item = None; } if let Some(item) = state.open_item && data .get_temp(item.with(Self::ID)) .is_none_or(|item: Self| item.last_visible_pass + 1 < pass_nr) { // If the open item wasn't shown for at least a frame, reset the open item state.open_item = None; } let r = f(&mut state); data.insert_temp(state_id, state); r }) } pub fn mark_shown(ctx: &Context, id: Id) { let pass_nr = ctx.cumulative_pass_nr(); Self::from_id(ctx, id, |state| { state.last_visible_pass = pass_nr; }); } /// Is the menu with this id the deepest sub menu? (-> no child sub menu is open) /// /// Note: This only returns correct results if called after the menu contents were shown. pub fn is_deepest_open_sub_menu(ctx: &Context, id: Id) -> bool { let pass_nr = ctx.cumulative_pass_nr(); let open_item = Self::from_id(ctx, id, |state| state.open_item); // If we have some open item, check if that was actually shown this frame open_item.is_none_or(|submenu_id| { Self::from_id(ctx, submenu_id, |state| state.last_visible_pass != pass_nr) }) } } /// Horizontal menu bar where you can add [`MenuButton`]s. /// /// The menu bar goes well in a [`crate::TopBottomPanel::top`], /// but can also be placed in a [`crate::Window`]. /// In the latter case you may want to wrap it in [`Frame`]. /// /// ### Example: /// ``` /// # egui::__run_test_ui(|ui| { /// egui::MenuBar::new().ui(ui, |ui| { /// ui.menu_button("File", |ui| { /// if ui.button("Quit").clicked() { /// ui.send_viewport_cmd(egui::ViewportCommand::Close); /// } /// }); /// }); /// # }); /// ``` #[derive(Clone, Debug)] pub struct MenuBar { config: MenuConfig, style: StyleModifier, } #[deprecated = "Renamed to `egui::MenuBar`"] pub type Bar = MenuBar; impl Default for MenuBar { fn default() -> Self { Self { config: MenuConfig::default(), style: menu_style.into(), } } } impl MenuBar { pub fn new() -> Self { Self::default() } /// Set the style for buttons in the menu bar. /// /// Doesn't affect the style of submenus, use [`MenuConfig::style`] for that. /// Default is [`menu_style`]. #[inline] pub fn style(mut self, style: impl Into<StyleModifier>) -> Self { self.style = style.into(); self } /// Set the config for submenus. /// /// Note: The config will only be passed when using [`MenuButton`], not via [`Popup::menu`]. #[inline] pub fn config(mut self, config: MenuConfig) -> Self { self.config = config; self } /// Show the menu bar. #[inline] pub fn ui<R>(self, ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { let Self { mut config, style } = self; config.bar = true; // TODO(lucasmerlin): It'd be nice if we had a ui.horizontal_builder or something // So we don't need the nested scope here ui.horizontal(|ui| { ui.scope_builder( UiBuilder::new() .layout(Layout::left_to_right(Align::Center)) .ui_stack_info( UiStackInfo::new(UiKind::Menu) .with_tag_value(MenuConfig::MENU_CONFIG_TAG, config), ), |ui| { style.apply(ui.style_mut()); // Take full width and fixed height: let height = ui.spacing().interact_size.y; ui.set_min_size(vec2(ui.available_width(), height)); content(ui) }, ) .inner }) } } /// A thin wrapper around a [`Button`] that shows a [`Popup::menu`] when clicked. /// /// The only thing this does is search for the current menu config (if set via [`MenuBar`]). /// If your menu button is not in a [`MenuBar`] it's fine to use [`Ui::button`] and [`Popup::menu`] /// directly. pub struct MenuButton<'a> { pub button: Button<'a>, pub config: Option<MenuConfig>, } impl<'a> MenuButton<'a> { pub fn new(atoms: impl IntoAtoms<'a>) -> Self { Self::from_button(Button::new(atoms.into_atoms())) } /// Set the config for the menu. #[inline] pub fn config(mut self, config: MenuConfig) -> Self { self.config = Some(config); self } /// Create a new menu button from a [`Button`]. #[inline] pub fn from_button(button: Button<'a>) -> Self { Self { button, config: None, } } /// Show the menu button. pub fn ui<R>( self, ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R, ) -> (Response, Option<InnerResponse<R>>) { let response = self.button.ui(ui); let mut config = self.config.unwrap_or_else(|| MenuConfig::find(ui)); config.bar = false; let inner = Popup::menu(&response) .close_behavior(config.close_behavior) .style(config.style.clone()) .info( UiStackInfo::new(UiKind::Menu).with_tag_value(MenuConfig::MENU_CONFIG_TAG, config), ) .show(content); (response, inner) } } /// A submenu button that shows a [`SubMenu`] if a [`Button`] is hovered. pub struct SubMenuButton<'a> { pub button: Button<'a>, pub sub_menu: SubMenu, } impl<'a> SubMenuButton<'a> { /// The default right arrow symbol: `"⏵"` pub const RIGHT_ARROW: &'static str = "⏵"; pub fn new(atoms: impl IntoAtoms<'a>) -> Self { Self::from_button(Button::new(atoms.into_atoms()).right_text("⏵")) } /// Create a new submenu button from a [`Button`]. /// /// Use [`Button::right_text`] and [`SubMenuButton::RIGHT_ARROW`] to add the default right /// arrow symbol. pub fn from_button(button: Button<'a>) -> Self { Self { button, sub_menu: SubMenu::default(), } } /// Set the config for the submenu. /// /// The close behavior will not affect the current button, but the buttons in the submenu. #[inline] pub fn config(mut self, config: MenuConfig) -> Self { self.sub_menu.config = Some(config); self } /// Show the submenu button. pub fn ui<R>( self, ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R, ) -> (Response, Option<InnerResponse<R>>) { let my_id = ui.next_auto_id(); let open = MenuState::from_ui(ui, |state, _| { state.open_item == Some(SubMenu::id_from_widget_id(my_id)) }); let inactive = ui.style().visuals.widgets.inactive; // TODO(lucasmerlin) add `open` function to `Button` if open { ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open; } let response = self.button.ui(ui); ui.style_mut().visuals.widgets.inactive = inactive; let popup_response = self.sub_menu.show(ui, &response, content); (response, popup_response) } } /// Show a submenu in a menu. /// /// Useful if you want to make custom menu buttons. /// Usually, just use [`MenuButton`] or [`SubMenuButton`] instead. #[derive(Clone, Debug, Default)] pub struct SubMenu { config: Option<MenuConfig>, } impl SubMenu { pub fn new() -> Self { Self::default() } /// Set the config for the submenu. /// /// The close behavior will not affect the current button, but the buttons in the submenu. #[inline] pub fn config(mut self, config: MenuConfig) -> Self { self.config = Some(config); self } /// Get the id for the submenu from the widget/response id. pub fn id_from_widget_id(widget_id: Id) -> Id { widget_id.with("submenu") } /// Show the submenu. /// /// This does some heuristics to check if the `button_response` was the last thing in the /// menu that was hovered/clicked, and if so, shows the submenu. pub fn show<R>( self, ui: &Ui, button_response: &Response, content: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { let frame = Frame::menu(ui.style()); let id = Self::id_from_widget_id(button_response.id); // Get the state from the parent menu let (open_item, menu_id, parent_config) = MenuState::from_ui(ui, |state, stack| { (state.open_item, stack.id, MenuConfig::from_stack(stack)) }); let mut menu_config = self.config.unwrap_or_else(|| parent_config.clone()); menu_config.bar = false; #[expect(clippy::unwrap_used)] // Since we are a child of that ui, this should always exist let menu_root_response = ui.ctx().read_response(menu_id).unwrap(); let hover_pos = ui.ctx().pointer_hover_pos(); // We don't care if the user is hovering over the border let menu_rect = menu_root_response.rect - frame.total_margin(); let is_hovering_menu = hover_pos.is_some_and(|pos| { ui.ctx().layer_id_at(pos) == Some(menu_root_response.layer_id) && menu_rect.contains(pos) }); let is_any_open = open_item.is_some(); let mut is_open = open_item == Some(id); let mut set_open = None; // We expand the button rect so there is no empty space where no menu is shown // TODO(lucasmerlin): Instead, maybe make item_spacing.y 0.0? let button_rect = button_response .rect .expand2(ui.style().spacing.item_spacing / 2.0); // In theory some other widget could cover the button and this check would still pass // But since we check if no other menu is open, nothing should be able to cover the button let is_hovered = hover_pos.is_some_and(|pos| button_rect.contains(pos)); // The clicked handler is there for accessibility (keyboard navigation) let should_open = ui.is_enabled() && (button_response.clicked() || (is_hovered && !is_any_open)); if should_open { set_open = Some(true); is_open = true; // Ensure that all other sub menus are closed when we open the menu MenuState::from_id(ui.ctx(), menu_id, |state| { state.open_item = None; }); } let gap = frame.total_margin().sum().x / 2.0 + 2.0; let mut response = button_response.clone(); // Expand the button rect so that the button and the first item in the submenu are aligned let expand = Vec2::new(0.0, frame.total_margin().sum().y / 2.0); response.interact_rect = response.interact_rect.expand2(expand); let popup_response = Popup::from_response(&response) .id(id) .open(is_open) .align(RectAlign::RIGHT_START) .layout(Layout::top_down_justified(Align::Min)) .gap(gap) .style(menu_config.style.clone()) .frame(frame) // The close behavior is handled by the menu (see below) .close_behavior(PopupCloseBehavior::IgnoreClicks) .info( UiStackInfo::new(UiKind::Menu) .with_tag_value(MenuConfig::MENU_CONFIG_TAG, menu_config.clone()), ) .show(|ui| { // Ensure our layer stays on top when the button is clicked if button_response.clicked() || button_response.is_pointer_button_down_on() { ui.ctx().move_to_top(ui.layer_id()); } content(ui) }); if let Some(popup_response) = &popup_response { // If no child sub menu is open means we must be the deepest child sub menu. let is_deepest_submenu = MenuState::is_deepest_open_sub_menu(ui.ctx(), id); // If the user clicks and the cursor is not hovering over our menu rect, it's // safe to assume they clicked outside the menu, so we close everything. // If they were to hover some other parent submenu we wouldn't be open. // Only edge case is the user hovering this submenu's button, so we also check // if we clicked outside the parent menu (which we luckily have access to here). let clicked_outside = is_deepest_submenu && popup_response.response.clicked_elsewhere() && menu_root_response.clicked_elsewhere(); // We never automatically close when a submenu button is clicked, (so menus work // on touch devices) // Luckily we will always be the deepest submenu when a submenu button is clicked, // so the following check is enough. let submenu_button_clicked = button_response.clicked(); let clicked_inside = is_deepest_submenu && !submenu_button_clicked && response.ctx.input(|i| i.pointer.any_click()) && hover_pos.is_some_and(|pos| popup_response.response.interact_rect.contains(pos)); let click_close = match menu_config.close_behavior { PopupCloseBehavior::CloseOnClick => clicked_outside || clicked_inside, PopupCloseBehavior::CloseOnClickOutside => clicked_outside, PopupCloseBehavior::IgnoreClicks => false, }; if click_close { set_open = Some(false); ui.close(); } let is_moving_towards_rect = ui.input(|i| { i.pointer .is_moving_towards_rect(&popup_response.response.rect) }); if is_moving_towards_rect { // We need to repaint while this is true, so we can detect when // the pointer is no longer moving towards the rect ui.request_repaint(); } let hovering_other_menu_entry = is_open && !is_hovered && !popup_response.response.contains_pointer() && !is_moving_towards_rect && is_hovering_menu; let close_called = popup_response.response.should_close(); // Close the parent ui to e.g. close the popup from where the submenu was opened if close_called { ui.close(); } if hovering_other_menu_entry { set_open = Some(false); } if ui.will_parent_close() { ui.data_mut(|data| data.remove_by_type::<MenuState>()); } } if let Some(set_open) = set_open { MenuState::from_id(ui.ctx(), menu_id, |state| { state.open_item = set_open.then_some(id); }); } popup_response } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/scene.rs
crates/egui/src/containers/scene.rs
use core::f32; use emath::{GuiRounding as _, Pos2}; use crate::{ InnerResponse, LayerId, PointerButton, Rangef, Rect, Response, Sense, Ui, UiBuilder, Vec2, emath::TSTransform, }; /// Creates a transformation that fits a given scene rectangle into the available screen size. /// /// The resulting visual scene bounds can be larger, due to letterboxing. /// /// Returns the transformation from `scene` to `global` coordinates. fn fit_to_rect_in_scene( rect_in_global: Rect, rect_in_scene: Rect, zoom_range: Rangef, ) -> TSTransform { // Compute the scale factor to fit the bounding rectangle into the available screen size: let scale = rect_in_global.size() / rect_in_scene.size(); // Use the smaller of the two scales to ensure the whole rectangle fits on the screen: let scale = scale.min_elem(); // Clamp scale to what is allowed let scale = zoom_range.clamp(scale); // Compute the translation to center the bounding rect in the screen: let center_in_global = rect_in_global.center().to_vec2(); let center_scene = rect_in_scene.center().to_vec2(); // Set the transformation to scale and then translate to center. TSTransform::from_translation(center_in_global - scale * center_scene) * TSTransform::from_scaling(scale) } /// A container that allows you to zoom and pan. /// /// This is similar to [`crate::ScrollArea`] but: /// * Supports zooming /// * Has no scroll bars /// * Has no limits on the scrolling #[derive(Clone, Debug)] #[must_use = "You should call .show()"] pub struct Scene { zoom_range: Rangef, sense: Sense, max_inner_size: Vec2, drag_pan_buttons: DragPanButtons, } /// Specifies which pointer buttons can be used to pan the scene by dragging. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct DragPanButtons(u8); bitflags::bitflags! { impl DragPanButtons: u8 { /// [PointerButton::Primary] const PRIMARY = 1 << 0; /// [PointerButton::Secondary] const SECONDARY = 1 << 1; /// [PointerButton::Middle] const MIDDLE = 1 << 2; /// [PointerButton::Extra1] const EXTRA_1 = 1 << 3; /// [PointerButton::Extra2] const EXTRA_2 = 1 << 4; } } impl Default for Scene { fn default() -> Self { Self { zoom_range: Rangef::new(f32::EPSILON, 1.0), sense: Sense::click_and_drag(), max_inner_size: Vec2::splat(1000.0), drag_pan_buttons: DragPanButtons::all(), } } } impl Scene { #[inline] pub fn new() -> Self { Default::default() } /// Specify what type of input the scene should respond to. /// /// The default is `Sense::click_and_drag()`. /// /// Set this to `Sense::hover()` to disable panning via clicking and dragging. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = sense; self } /// Set the allowed zoom range. /// /// The default zoom range is `0.0..=1.0`, /// which mean you zan make things arbitrarily small, but you cannot zoom in past a `1:1` ratio. /// /// If you want to allow zooming in, you can set the zoom range to `0.0..=f32::INFINITY`. /// Note that text rendering becomes blurry when you zoom in: <https://github.com/emilk/egui/issues/4813>. #[inline] pub fn zoom_range(mut self, zoom_range: impl Into<Rangef>) -> Self { self.zoom_range = zoom_range.into(); self } /// Set the maximum size of the inner [`Ui`] that will be created. #[inline] pub fn max_inner_size(mut self, max_inner_size: impl Into<Vec2>) -> Self { self.max_inner_size = max_inner_size.into(); self } /// Specify which pointer buttons can be used to pan by clicking and dragging. /// /// By default, this is `DragPanButtons::all()`. #[inline] pub fn drag_pan_buttons(mut self, flags: DragPanButtons) -> Self { self.drag_pan_buttons = flags; self } /// `scene_rect` contains the view bounds of the inner [`Ui`]. /// /// `scene_rect` will be mutated by any panning/zooming done by the user. /// If `scene_rect` is somehow invalid (e.g. `Rect::ZERO`), /// then it will be reset to the inner rect of the inner ui. /// /// You need to store the `scene_rect` in your state between frames. pub fn show<R>( &self, parent_ui: &mut Ui, scene_rect: &mut Rect, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<R> { let (outer_rect, _outer_response) = parent_ui.allocate_exact_size(parent_ui.available_size_before_wrap(), Sense::hover()); let mut to_global = fit_to_rect_in_scene(outer_rect, *scene_rect, self.zoom_range); let scene_rect_was_good = to_global.is_valid() && scene_rect.is_finite() && scene_rect.size() != Vec2::ZERO; let mut inner_rect = *scene_rect; let ret = self.show_global_transform(parent_ui, outer_rect, &mut to_global, |ui| { let r = add_contents(ui); inner_rect = ui.min_rect(); r }); if ret.response.changed() { // Only update if changed, both to avoid numeric drift, // and to avoid expanding the scene rect unnecessarily. *scene_rect = to_global.inverse() * outer_rect; } if !scene_rect_was_good { // Auto-reset if the transformation goes bad somehow (or started bad). // Recalculates transform based on inner_rect, resulting in a rect that's the full size of outer_rect but centered on inner_rect. let to_global = fit_to_rect_in_scene(outer_rect, inner_rect, self.zoom_range); *scene_rect = to_global.inverse() * outer_rect; } ret } fn show_global_transform<R>( &self, parent_ui: &mut Ui, outer_rect: Rect, to_global: &mut TSTransform, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<R> { // Create a new egui paint layer, where we can draw our contents: let scene_layer_id = LayerId::new( parent_ui.layer_id().order, parent_ui.id().with("scene_area"), ); // Put the layer directly on-top of the main layer of the ui: parent_ui .ctx() .set_sublayer(parent_ui.layer_id(), scene_layer_id); let mut local_ui = parent_ui.new_child( UiBuilder::new() .layer_id(scene_layer_id) .max_rect(Rect::from_min_size(Pos2::ZERO, self.max_inner_size)) .sense(self.sense), ); let mut pan_response = local_ui.response(); // Update the `to_global` transform based on use interaction: self.register_pan_and_zoom(&local_ui, &mut pan_response, to_global); // Set a correct global clip rect: local_ui.set_clip_rect(to_global.inverse() * outer_rect); // Tell egui to apply the transform on the layer: local_ui .ctx() .set_transform_layer(scene_layer_id, *to_global); // Add the actual contents to the area: let ret = add_contents(&mut local_ui); // This ensures we catch clicks/drags/pans anywhere on the background. local_ui.force_set_min_rect((to_global.inverse() * outer_rect).round_ui()); InnerResponse { response: pan_response, inner: ret, } } /// Helper function to handle pan and zoom interactions on a response. pub fn register_pan_and_zoom(&self, ui: &Ui, resp: &mut Response, to_global: &mut TSTransform) { let dragged = self.drag_pan_buttons.iter().any(|button| match button { DragPanButtons::PRIMARY => resp.dragged_by(PointerButton::Primary), DragPanButtons::SECONDARY => resp.dragged_by(PointerButton::Secondary), DragPanButtons::MIDDLE => resp.dragged_by(PointerButton::Middle), DragPanButtons::EXTRA_1 => resp.dragged_by(PointerButton::Extra1), DragPanButtons::EXTRA_2 => resp.dragged_by(PointerButton::Extra2), _ => false, }); if dragged { to_global.translation += to_global.scaling * resp.drag_delta(); resp.mark_changed(); } if let Some(mouse_pos) = ui.input(|i| i.pointer.latest_pos()) && resp.contains_pointer() { let pointer_in_scene = to_global.inverse() * mouse_pos; let zoom_delta = ui.input(|i| i.zoom_delta()); let pan_delta = ui.input(|i| i.smooth_scroll_delta()); // Most of the time we can return early. This is also important to // avoid `ui_from_scene` to change slightly due to floating point errors. if zoom_delta == 1.0 && pan_delta == Vec2::ZERO { return; } if zoom_delta != 1.0 { // Zoom in on pointer, but only if we are not zoomed in or out too far. let zoom_delta = zoom_delta.clamp( self.zoom_range.min / to_global.scaling, self.zoom_range.max / to_global.scaling, ); *to_global = *to_global * TSTransform::from_translation(pointer_in_scene.to_vec2()) * TSTransform::from_scaling(zoom_delta) * TSTransform::from_translation(-pointer_in_scene.to_vec2()); // Clamp to exact zoom range. to_global.scaling = self.zoom_range.clamp(to_global.scaling); } // Pan: *to_global = TSTransform::from_translation(pan_delta) * *to_global; resp.mark_changed(); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/combo_box.rs
crates/egui/src/containers/combo_box.rs
use epaint::Shape; use crate::{ Align2, Context, Id, InnerResponse, NumExt as _, Painter, Popup, PopupCloseBehavior, Rect, Response, ScrollArea, Sense, Stroke, TextStyle, TextWrapMode, Ui, UiBuilder, Vec2, WidgetInfo, WidgetText, WidgetType, epaint, style::StyleModifier, style::WidgetVisuals, vec2, }; #[expect(unused_imports)] // Documentation use crate::style::Spacing; /// A function that paints the [`ComboBox`] icon pub type IconPainter = Box<dyn FnOnce(&Ui, Rect, &WidgetVisuals, bool)>; /// A drop-down selection menu with a descriptive label. /// /// ``` /// # egui::__run_test_ui(|ui| { /// # #[derive(Debug, PartialEq, Copy, Clone)] /// # enum Enum { First, Second, Third } /// # let mut selected = Enum::First; /// let before = selected; /// egui::ComboBox::from_label("Select one!") /// .selected_text(format!("{:?}", selected)) /// .show_ui(ui, |ui| { /// ui.selectable_value(&mut selected, Enum::First, "First"); /// ui.selectable_value(&mut selected, Enum::Second, "Second"); /// ui.selectable_value(&mut selected, Enum::Third, "Third"); /// } /// ); /// /// if selected != before { /// // Handle selection change /// } /// # }); /// ``` #[must_use = "You should call .show*"] pub struct ComboBox { id_salt: Id, label: Option<WidgetText>, selected_text: WidgetText, width: Option<f32>, height: Option<f32>, icon: Option<IconPainter>, wrap_mode: Option<TextWrapMode>, close_behavior: Option<PopupCloseBehavior>, popup_style: StyleModifier, } impl ComboBox { /// Create new [`ComboBox`] with id and label pub fn new(id_salt: impl std::hash::Hash, label: impl Into<WidgetText>) -> Self { Self { id_salt: Id::new(id_salt), label: Some(label.into()), selected_text: Default::default(), width: None, height: None, icon: None, wrap_mode: None, close_behavior: None, popup_style: StyleModifier::default(), } } /// Label shown next to the combo box pub fn from_label(label: impl Into<WidgetText>) -> Self { let label = label.into(); Self { id_salt: Id::new(label.text()), label: Some(label), selected_text: Default::default(), width: None, height: None, icon: None, wrap_mode: None, close_behavior: None, popup_style: StyleModifier::default(), } } /// Without label. pub fn from_id_salt(id_salt: impl std::hash::Hash) -> Self { Self { id_salt: Id::new(id_salt), label: Default::default(), selected_text: Default::default(), width: None, height: None, icon: None, wrap_mode: None, close_behavior: None, popup_style: StyleModifier::default(), } } /// Without label. #[deprecated = "Renamed from_id_salt"] pub fn from_id_source(id_salt: impl std::hash::Hash) -> Self { Self::from_id_salt(id_salt) } /// Set the outer width of the button and menu. /// /// Default is [`Spacing::combo_width`]. #[inline] pub fn width(mut self, width: f32) -> Self { self.width = Some(width); self } /// Set the maximum outer height of the menu. /// /// Default is [`Spacing::combo_height`]. #[inline] pub fn height(mut self, height: f32) -> Self { self.height = Some(height); self } /// What we show as the currently selected value #[inline] pub fn selected_text(mut self, selected_text: impl Into<WidgetText>) -> Self { self.selected_text = selected_text.into(); self } /// Use the provided function to render a different [`ComboBox`] icon. /// Defaults to a triangle that expands when the cursor is hovering over the [`ComboBox`]. /// /// For example: /// ``` /// # egui::__run_test_ui(|ui| { /// # let text = "Selected text"; /// pub fn filled_triangle( /// ui: &egui::Ui, /// rect: egui::Rect, /// visuals: &egui::style::WidgetVisuals, /// _is_open: bool, /// ) { /// let rect = egui::Rect::from_center_size( /// rect.center(), /// egui::vec2(rect.width() * 0.6, rect.height() * 0.4), /// ); /// ui.painter().add(egui::Shape::convex_polygon( /// vec![rect.left_top(), rect.right_top(), rect.center_bottom()], /// visuals.fg_stroke.color, /// visuals.fg_stroke, /// )); /// } /// /// egui::ComboBox::from_id_salt("my-combobox") /// .selected_text(text) /// .icon(filled_triangle) /// .show_ui(ui, |_ui| {}); /// # }); /// ``` #[inline] pub fn icon(mut self, icon_fn: impl FnOnce(&Ui, Rect, &WidgetVisuals, bool) + 'static) -> Self { self.icon = Some(Box::new(icon_fn)); self } /// Controls the wrap mode used for the selected text. /// /// By default, [`Ui::wrap_mode`] will be used, which can be overridden with [`crate::Style::wrap_mode`]. /// /// Note that any `\n` in the text will always produce a new line. #[inline] pub fn wrap_mode(mut self, wrap_mode: TextWrapMode) -> Self { self.wrap_mode = Some(wrap_mode); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Wrap`]. #[inline] pub fn wrap(mut self) -> Self { self.wrap_mode = Some(TextWrapMode::Wrap); self } /// Set [`Self::wrap_mode`] to [`TextWrapMode::Truncate`]. #[inline] pub fn truncate(mut self) -> Self { self.wrap_mode = Some(TextWrapMode::Truncate); self } /// Controls the close behavior for the popup. /// /// By default, `PopupCloseBehavior::CloseOnClick` will be used. #[inline] pub fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self { self.close_behavior = Some(close_behavior); self } /// Set the style of the popup menu. /// /// Could for example be used with [`crate::containers::menu::menu_style`] to get the frame-less /// menu button style. #[inline] pub fn popup_style(mut self, popup_style: StyleModifier) -> Self { self.popup_style = popup_style; self } /// Show the combo box, with the given ui code for the menu contents. /// /// Returns `InnerResponse { inner: None }` if the combo box is closed. pub fn show_ui<R>( self, ui: &mut Ui, menu_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<Option<R>> { self.show_ui_dyn(ui, Box::new(menu_contents)) } fn show_ui_dyn<'c, R>( self, ui: &mut Ui, menu_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<Option<R>> { let Self { id_salt, label, selected_text, width, height, icon, wrap_mode, close_behavior, popup_style, } = self; let button_id = ui.make_persistent_id(id_salt); ui.horizontal(|ui| { let mut ir = combo_box_dyn( ui, button_id, selected_text.clone(), menu_contents, icon, wrap_mode, close_behavior, popup_style, (width, height), ); ir.response.widget_info(|| { let mut info = WidgetInfo::new(WidgetType::ComboBox); info.enabled = ui.is_enabled(); info.current_text_value = Some(selected_text.text().to_owned()); info }); if let Some(label) = label { let label_response = ui.label(label); ir.response = ir.response.labelled_by(label_response.id); ir.response |= label_response; } ir }) .inner } /// Show a list of items with the given selected index. /// /// /// ``` /// # #[derive(Debug, PartialEq)] /// # enum Enum { First, Second, Third } /// # let mut selected = Enum::First; /// # egui::__run_test_ui(|ui| { /// let alternatives = ["a", "b", "c", "d"]; /// let mut selected = 2; /// egui::ComboBox::from_label("Select one!").show_index( /// ui, /// &mut selected, /// alternatives.len(), /// |i| alternatives[i] /// ); /// # }); /// ``` pub fn show_index<Text: Into<WidgetText>>( self, ui: &mut Ui, selected: &mut usize, len: usize, get: impl Fn(usize) -> Text, ) -> Response { let slf = self.selected_text(get(*selected)); let mut changed = false; let mut response = slf .show_ui(ui, |ui| { for i in 0..len { if ui.selectable_label(i == *selected, get(i)).clicked() { *selected = i; changed = true; } } }) .response; if changed { response.mark_changed(); } response } /// Check if the [`ComboBox`] with the given id has its popup menu currently opened. pub fn is_open(ctx: &Context, id: Id) -> bool { Popup::is_id_open(ctx, Self::widget_to_popup_id(id)) } /// Convert a [`ComboBox`] id to the id used to store it's popup state. fn widget_to_popup_id(widget_id: Id) -> Id { widget_id.with("popup") } } #[expect(clippy::too_many_arguments)] fn combo_box_dyn<'c, R>( ui: &mut Ui, button_id: Id, selected_text: WidgetText, menu_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, icon: Option<IconPainter>, wrap_mode: Option<TextWrapMode>, close_behavior: Option<PopupCloseBehavior>, popup_style: StyleModifier, (width, height): (Option<f32>, Option<f32>), ) -> InnerResponse<Option<R>> { let popup_id = ComboBox::widget_to_popup_id(button_id); let is_popup_open = Popup::is_id_open(ui.ctx(), popup_id); let wrap_mode = wrap_mode.unwrap_or_else(|| ui.wrap_mode()); let close_behavior = close_behavior.unwrap_or(PopupCloseBehavior::CloseOnClick); let margin = ui.spacing().button_padding; let button_response = button_frame(ui, button_id, is_popup_open, Sense::click(), |ui| { let icon_spacing = ui.spacing().icon_spacing; let icon_size = Vec2::splat(ui.spacing().icon_width); // The combo box selected text will always have this minimum width. // Note: the `ComboBox::width()` if set or `Spacing::combo_width` are considered as the // minimum overall width, regardless of the wrap mode. let minimum_width = width.unwrap_or_else(|| ui.spacing().combo_width) - 2.0 * margin.x; // width against which to lay out the selected text let wrap_width = if wrap_mode == TextWrapMode::Extend { // Use all the width necessary to display the currently selected value's text. f32::INFINITY } else { // Use the available width, currently selected value's text will be wrapped if exceeds this value. ui.available_width() - icon_spacing - icon_size.x }; let galley = selected_text.into_galley(ui, Some(wrap_mode), wrap_width, TextStyle::Button); let actual_width = (galley.size().x + icon_spacing + icon_size.x).at_least(minimum_width); let actual_height = galley.size().y.max(icon_size.y); let (_, rect) = ui.allocate_space(Vec2::new(actual_width, actual_height)); let button_rect = ui.min_rect().expand2(ui.spacing().button_padding); let response = ui.interact(button_rect, button_id, Sense::click()); // response.active |= is_popup_open; if ui.is_rect_visible(rect) { let icon_rect = Align2::RIGHT_CENTER.align_size_within_rect(icon_size, rect); let visuals = if is_popup_open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; if let Some(icon) = icon { icon( ui, icon_rect.expand(visuals.expansion), visuals, is_popup_open, ); } else { paint_default_icon(ui.painter(), icon_rect.expand(visuals.expansion), visuals); } let text_rect = Align2::LEFT_CENTER.align_size_within_rect(galley.size(), rect); ui.painter() .galley(text_rect.min, galley, visuals.text_color()); } }); let height = height.unwrap_or_else(|| ui.spacing().combo_height); let inner = Popup::menu(&button_response) .id(popup_id) .width(button_response.rect.width()) .close_behavior(close_behavior) .style(popup_style) .show(|ui| { ui.set_min_width(ui.available_width()); ScrollArea::vertical() .max_height(height) .show(ui, |ui| { // Often the button is very narrow, which means this popup // is also very narrow. Having wrapping on would therefore // result in labels that wrap very early. // Instead, we turn it off by default so that the labels // expand the width of the menu. ui.style_mut().wrap_mode = Some(TextWrapMode::Extend); menu_contents(ui) }) .inner }) .map(|r| r.inner); InnerResponse { inner, response: button_response, } } fn button_frame( ui: &mut Ui, id: Id, is_popup_open: bool, sense: Sense, add_contents: impl FnOnce(&mut Ui), ) -> Response { let where_to_put_background = ui.painter().add(Shape::Noop); let margin = ui.spacing().button_padding; let interact_size = ui.spacing().interact_size; let mut outer_rect = ui.available_rect_before_wrap(); outer_rect.set_height(outer_rect.height().at_least(interact_size.y)); let inner_rect = outer_rect.shrink2(margin); let mut content_ui = ui.new_child(UiBuilder::new().max_rect(inner_rect)); add_contents(&mut content_ui); let mut outer_rect = content_ui.min_rect().expand2(margin); outer_rect.set_height(outer_rect.height().at_least(interact_size.y)); let response = ui.interact(outer_rect, id, sense); if ui.is_rect_visible(outer_rect) { let visuals = if is_popup_open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; ui.painter().set( where_to_put_background, epaint::RectShape::new( outer_rect.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, epaint::StrokeKind::Inside, ), ); } ui.advance_cursor_after_rect(outer_rect); response } fn paint_default_icon(painter: &Painter, rect: Rect, visuals: &WidgetVisuals) { let rect = Rect::from_center_size( rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45), ); // Downward pointing triangle // Previously, we would show an up arrow when we expected the popup to open upwards // (due to lack of space below the button), but this could look weird in edge cases, so this // feature was removed. (See https://github.com/emilk/egui/pull/5713#issuecomment-2654420245) painter.add(Shape::convex_polygon( vec![rect.left_top(), rect.right_top(), rect.center_bottom()], visuals.fg_stroke.color, Stroke::NONE, )); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/mod.rs
crates/egui/src/containers/mod.rs
//! Containers are pieces of the UI which wraps other pieces of UI. Examples: [`Window`], [`ScrollArea`], [`Resize`], [`Panel`], etc. //! //! For instance, a [`Frame`] adds a frame and background to some contained UI. pub(crate) mod area; mod close_tag; pub mod collapsing_header; mod combo_box; pub mod frame; pub mod menu; pub mod modal; pub mod old_popup; pub mod panel; mod popup; pub(crate) mod resize; mod scene; pub mod scroll_area; mod sides; mod tooltip; pub(crate) mod window; pub use { area::{Area, AreaState}, close_tag::ClosableTag, collapsing_header::{CollapsingHeader, CollapsingResponse}, combo_box::*, frame::Frame, modal::{Modal, ModalResponse}, old_popup::*, panel::*, popup::*, resize::Resize, scene::{DragPanButtons, Scene}, scroll_area::ScrollArea, sides::Sides, tooltip::*, window::Window, };
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/area.rs
crates/egui/src/containers/area.rs
//! Area is a [`Ui`] that has no parent, it floats on the background. //! It has no frame or own size. It is potentially movable. //! It is the foundation for windows and popups. use emath::GuiRounding as _; use crate::{ Align2, Context, Id, InnerResponse, LayerId, Layout, NumExt as _, Order, Pos2, Rect, Response, Sense, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, WidgetRect, WidgetWithState, emath, pos2, }; /// State of an [`Area`] that is persisted between frames. /// /// Areas back [`crate::Window`]s and other floating containers, /// like tooltips and the popups of [`crate::ComboBox`]. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct AreaState { /// Last known position of the pivot. pub pivot_pos: Option<Pos2>, /// The anchor point of the area, i.e. where on the area the [`Self::pivot_pos`] refers to. pub pivot: Align2, /// Last known size. /// /// Area size is intentionally NOT persisted between sessions, /// so that a bad tooltip or menu size won't be remembered forever. /// A resizable [`crate::Window`] remembers the size the user picked using /// the state in the [`crate::Resize`] container. #[cfg_attr(feature = "serde", serde(skip))] pub size: Option<Vec2>, /// If false, clicks goes straight through to what is behind us. Useful for tooltips etc. pub interactable: bool, /// At what time was this area first shown? /// /// Used to fade in the area. #[cfg_attr(feature = "serde", serde(skip))] pub last_became_visible_at: Option<f64>, } impl Default for AreaState { fn default() -> Self { Self { pivot_pos: None, pivot: Align2::LEFT_TOP, size: None, interactable: true, last_became_visible_at: None, } } } impl AreaState { /// Load the state of an [`Area`] from memory. pub fn load(ctx: &Context, id: Id) -> Option<Self> { // TODO(emilk): Area state is not currently stored in `Memory::data`, but maybe it should be? ctx.memory(|mem| mem.areas().get(id).copied()) } /// The left top positions of the area. pub fn left_top_pos(&self) -> Pos2 { let pivot_pos = self.pivot_pos.unwrap_or_default(); let size = self.size.unwrap_or_default(); pos2( pivot_pos.x - self.pivot.x().to_factor() * size.x, pivot_pos.y - self.pivot.y().to_factor() * size.y, ) .round_ui() } /// Move the left top positions of the area. pub fn set_left_top_pos(&mut self, pos: Pos2) { let size = self.size.unwrap_or_default(); self.pivot_pos = Some(pos2( pos.x + self.pivot.x().to_factor() * size.x, pos.y + self.pivot.y().to_factor() * size.y, )); } /// Where the area is on screen. pub fn rect(&self) -> Rect { let size = self.size.unwrap_or_default(); Rect::from_min_size(self.left_top_pos(), size).round_ui() } } /// An area on the screen that can be moved by dragging. /// /// This forms the base of the [`crate::Window`] container. /// /// ``` /// # egui::__run_test_ctx(|ctx| { /// egui::Area::new(egui::Id::new("my_area")) /// .fixed_pos(egui::pos2(32.0, 32.0)) /// .show(ctx, |ui| { /// ui.label("Floating text!"); /// }); /// # }); /// ``` /// /// The previous rectangle used by this area can be obtained through [`crate::Memory::area_rect()`]. #[must_use = "You should call .show()"] #[derive(Clone, Debug)] pub struct Area { pub(crate) id: Id, info: UiStackInfo, sense: Option<Sense>, movable: bool, interactable: bool, enabled: bool, constrain: bool, constrain_rect: Option<Rect>, order: Order, default_pos: Option<Pos2>, default_size: Vec2, pivot: Align2, anchor: Option<(Align2, Vec2)>, new_pos: Option<Pos2>, fade_in: bool, layout: Layout, sizing_pass: bool, } impl WidgetWithState for Area { type State = AreaState; } impl Area { /// The `id` must be globally unique. pub fn new(id: Id) -> Self { Self { id, info: UiStackInfo::new(UiKind::GenericArea), sense: None, movable: true, interactable: true, constrain: true, constrain_rect: None, enabled: true, order: Order::Middle, default_pos: None, default_size: Vec2::NAN, new_pos: None, pivot: Align2::LEFT_TOP, anchor: None, fade_in: true, layout: Layout::default(), sizing_pass: false, } } /// Let's you change the `id` that you assigned in [`Self::new`]. /// /// The `id` must be globally unique. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = id; self } /// Change the [`UiKind`] of the arena. /// /// Default to [`UiKind::GenericArea`]. #[inline] pub fn kind(mut self, kind: UiKind) -> Self { self.info = UiStackInfo::new(kind); self } /// Set the [`UiStackInfo`] of the area's [`Ui`]. /// /// Default to [`UiStackInfo`] with kind [`UiKind::GenericArea`]. #[inline] pub fn info(mut self, info: UiStackInfo) -> Self { self.info = info; self } pub fn layer(&self) -> LayerId { LayerId::new(self.order, self.id) } /// If false, no content responds to click /// and widgets will be shown grayed out. /// You won't be able to move the window. /// Default: `true`. #[inline] pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; self } /// Moveable by dragging the area? #[inline] pub fn movable(mut self, movable: bool) -> Self { self.movable = movable; self.interactable |= movable; self } pub fn is_enabled(&self) -> bool { self.enabled } pub fn is_movable(&self) -> bool { self.movable && self.enabled } /// If false, clicks goes straight through to what is behind us. /// /// Can be used for semi-invisible areas that the user should be able to click through. /// /// Default: `true`. #[inline] pub fn interactable(mut self, interactable: bool) -> Self { self.interactable = interactable; self.movable &= interactable; self } /// Explicitly set a sense. /// /// If not set, this will default to `Sense::drag()` if movable, `Sense::click()` if interactable, and `Sense::hover()` otherwise. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = Some(sense); self } /// `order(Order::Foreground)` for an Area that should always be on top #[inline] pub fn order(mut self, order: Order) -> Self { self.order = order; self } #[inline] pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self { self.default_pos = Some(default_pos.into()); self } /// The size used for the [`Ui::max_rect`] the first frame. /// /// Text will wrap at this width, and images that expand to fill the available space /// will expand to this size. /// /// If the contents are smaller than this size, the area will shrink to fit the contents. /// If the contents overflow, the area will grow. /// /// If not set, [`crate::style::Spacing::default_area_size`] will be used. #[inline] pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self { self.default_size = default_size.into(); self } /// See [`Self::default_size`]. #[inline] pub fn default_width(mut self, default_width: f32) -> Self { self.default_size.x = default_width; self } /// See [`Self::default_size`]. #[inline] pub fn default_height(mut self, default_height: f32) -> Self { self.default_size.y = default_height; self } /// Positions the window and prevents it from being moved #[inline] pub fn fixed_pos(mut self, fixed_pos: impl Into<Pos2>) -> Self { self.new_pos = Some(fixed_pos.into()); self.movable = false; self } /// Constrains this area to [`Context::screen_rect`]? /// /// Default: `true`. #[inline] pub fn constrain(mut self, constrain: bool) -> Self { self.constrain = constrain; self } /// Constrain the movement of the window to the given rectangle. /// /// For instance: `.constrain_to(ctx.screen_rect())`. #[inline] pub fn constrain_to(mut self, constrain_rect: Rect) -> Self { self.constrain = true; self.constrain_rect = Some(constrain_rect); self } /// Where the "root" of the area is. /// /// For instance, if you set this to [`Align2::RIGHT_TOP`] /// then [`Self::fixed_pos`] will set the position of the right-top /// corner of the area. /// /// Default: [`Align2::LEFT_TOP`]. #[inline] pub fn pivot(mut self, pivot: Align2) -> Self { self.pivot = pivot; self } /// Positions the window but you can still move it. #[inline] pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self { self.new_pos = Some(current_pos.into()); self } /// Set anchor and distance. /// /// An anchor of `Align2::RIGHT_TOP` means "put the right-top corner of the window /// in the right-top corner of the screen". /// /// The offset is added to the position, so e.g. an offset of `[-5.0, 5.0]` /// would move the window left and down from the given anchor. /// /// Anchoring also makes the window immovable. /// /// It is an error to set both an anchor and a position. #[inline] pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self { self.anchor = Some((align, offset.into())); self.movable(false) } pub(crate) fn get_pivot(&self) -> Align2 { if let Some((pivot, _)) = self.anchor { pivot } else { Align2::LEFT_TOP } } /// If `true`, quickly fade in the area. /// /// Default: `true`. #[inline] pub fn fade_in(mut self, fade_in: bool) -> Self { self.fade_in = fade_in; self } /// Set the layout for the child Ui. #[inline] pub fn layout(mut self, layout: Layout) -> Self { self.layout = layout; self } /// While true, a sizing pass will be done. This means the area will be invisible /// and the contents will be laid out to estimate the proper containing size of the area. /// If false, there will be no change to the default area behavior. This is useful if the /// area contents area dynamic and you need to need to make sure the area adjusts its size /// accordingly. /// /// This should only be set to true during the specific frames you want force a sizing pass. /// Do NOT hard-code this as `.sizing_pass(true)`, as it will cause the area to never be /// visible. /// /// # Arguments /// - resize: If true, the area will be resized to fit its contents. False will keep the /// default area resizing behavior. /// /// Default: `false`. #[inline] pub fn sizing_pass(mut self, resize: bool) -> Self { self.sizing_pass = resize; self } } pub(crate) struct Prepared { info: Option<UiStackInfo>, layer_id: LayerId, state: AreaState, move_response: Response, enabled: bool, constrain: bool, constrain_rect: Rect, /// We always make windows invisible the first frame to hide "first-frame-jitters". /// /// This is so that we use the first frame to calculate the window size, /// and then can correctly position the window and its contents the next frame, /// without having one frame where the window is wrongly positioned or sized. sizing_pass: bool, fade_in: bool, layout: Layout, } impl Area { pub fn show<R>( self, ctx: &Context, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<R> { let mut prepared = self.begin(ctx); let mut content_ui = prepared.content_ui(ctx); let inner = add_contents(&mut content_ui); let response = prepared.end(ctx, content_ui); InnerResponse { inner, response } } pub(crate) fn begin(self, ctx: &Context) -> Prepared { let Self { id, info, sense, movable, order, interactable, enabled, default_pos, default_size, new_pos, pivot, anchor, constrain, constrain_rect, fade_in, layout, sizing_pass: force_sizing_pass, } = self; let constrain_rect = constrain_rect.unwrap_or_else(|| ctx.content_rect()); let layer_id = LayerId::new(order, id); let state = AreaState::load(ctx, id); let mut sizing_pass = state.is_none(); let mut state = state.unwrap_or(AreaState { pivot_pos: None, pivot, size: None, interactable, last_became_visible_at: None, }); if force_sizing_pass { sizing_pass = true; state.size = None; } state.pivot = pivot; state.interactable = interactable; if let Some(new_pos) = new_pos { state.pivot_pos = Some(new_pos); } state.pivot_pos.get_or_insert_with(|| { default_pos.unwrap_or_else(|| automatic_area_position(ctx, constrain_rect, layer_id)) }); state.interactable = interactable; let size = *state.size.get_or_insert_with(|| { sizing_pass = true; // during the sizing pass we will use this as the max size let mut size = default_size; let default_area_size = ctx.global_style().spacing.default_area_size; if size.x.is_nan() { size.x = default_area_size.x; } if size.y.is_nan() { size.y = default_area_size.y; } if constrain { size = size.at_most(constrain_rect.size()); } size }); // TODO(emilk): if last frame was sizing pass, it should be considered invisible for smoother fade-in let visible_last_frame = ctx.memory(|mem| mem.areas().visible_last_frame(&layer_id)); if !visible_last_frame || state.last_became_visible_at.is_none() { state.last_became_visible_at = Some(ctx.input(|i| i.time)); } if let Some((anchor, offset)) = anchor { state.set_left_top_pos( anchor .align_size_within_rect(size, constrain_rect) .left_top() + offset, ); } // interact right away to prevent frame-delay let mut move_response = { let interact_id = layer_id.id.with("move"); let sense = sense.unwrap_or_else(|| { if movable { Sense::drag() } else if interactable { Sense::click() // allow clicks to bring to front } else { Sense::hover() } }); let move_response = ctx.create_widget( WidgetRect { id: interact_id, layer_id, rect: state.rect(), interact_rect: state.rect().intersect(constrain_rect), sense, enabled, }, true, Default::default(), ); // Used to prevent drift let pivot_at_start_of_drag_id = id.with("pivot_at_drag_start"); if movable && move_response.dragged() && let Some(pivot_pos) = &mut state.pivot_pos { let pivot_at_start_of_drag = ctx.data_mut(|data| { *data.get_temp_mut_or::<Pos2>(pivot_at_start_of_drag_id, *pivot_pos) }); *pivot_pos = pivot_at_start_of_drag + move_response.total_drag_delta().unwrap_or_default(); } else { ctx.data_mut(|data| data.remove::<Pos2>(pivot_at_start_of_drag_id)); } if (move_response.dragged() || move_response.clicked()) || pointer_pressed_on_area(ctx, layer_id) || !ctx.memory(|m| m.areas().visible_last_frame(&layer_id)) { ctx.memory_mut(|m| m.areas_mut().move_to_top(layer_id)); ctx.request_repaint(); } move_response }; state.set_left_top_pos(round_area_position( ctx, if constrain { Context::constrain_window_rect_to_area(state.rect(), constrain_rect).min } else { state.left_top_pos() }, )); // Update response with possibly moved/constrained rect: move_response.rect = state.rect(); move_response.interact_rect = state.rect(); Prepared { info: Some(info), layer_id, state, move_response, enabled, constrain, constrain_rect, sizing_pass, fade_in, layout, } } } fn round_area_position(ctx: &Context, pos: Pos2) -> Pos2 { // We round a lot of rendering to pixels, so we round the whole // area positions to pixels too, so avoid widgets appearing to float // around independently of each other when the area is dragged. // But just in case pixels_per_point is irrational, // we then also round to ui coordinates: pos.round_to_pixels(ctx.pixels_per_point()).round_ui() } impl Prepared { pub(crate) fn state(&self) -> &AreaState { &self.state } pub(crate) fn state_mut(&mut self) -> &mut AreaState { &mut self.state } pub(crate) fn constrain(&self) -> bool { self.constrain } pub(crate) fn constrain_rect(&self) -> Rect { self.constrain_rect } pub(crate) fn content_ui(&mut self, ctx: &Context) -> Ui { let max_rect = self.state.rect(); let mut ui_builder = UiBuilder::new() .ui_stack_info(self.info.take().unwrap_or_default()) .layer_id(self.layer_id) .max_rect(max_rect) .layout(self.layout) .accessibility_parent(self.move_response.id) .closable(); if !self.enabled { ui_builder = ui_builder.disabled(); } if self.sizing_pass { ui_builder = ui_builder.sizing_pass().invisible(); } let mut ui = Ui::new(ctx.clone(), self.layer_id.id, ui_builder); ui.set_clip_rect(self.constrain_rect); // Don't paint outside our bounds if self.fade_in && let Some(last_became_visible_at) = self.state.last_became_visible_at { let age = ctx.input(|i| (i.time - last_became_visible_at) as f32 + i.predicted_dt / 2.0); let opacity = crate::remap_clamp(age, 0.0..=ctx.global_style().animation_time, 0.0..=1.0); let opacity = emath::easing::quadratic_out(opacity); // slow fade-out = quick fade-in ui.multiply_opacity(opacity); if opacity < 1.0 { ctx.request_repaint(); } } ui } pub(crate) fn with_widget_info(&self, make_info: impl Fn() -> crate::WidgetInfo) { self.move_response.widget_info(make_info); } pub(crate) fn id(&self) -> Id { self.move_response.id } #[expect(clippy::needless_pass_by_value)] // intentional to swallow up `content_ui`. pub(crate) fn end(self, ctx: &Context, content_ui: Ui) -> Response { let Self { info: _, layer_id, mut state, move_response: mut response, sizing_pass, .. } = self; state.size = Some(content_ui.min_size()); // Make sure we report back the correct size. // Very important after the initial sizing pass, when the initial estimate of the size is way off. let final_rect = state.rect(); response.rect = final_rect; response.interact_rect = final_rect; // TODO(lucasmerlin): Can the area response be based on Ui::response? Then this won't be needed // Bubble up the close event if content_ui.should_close() { response.set_close(); } ctx.memory_mut(|m| m.areas_mut().set_state(layer_id, state)); if sizing_pass { // If we didn't know the size, we were likely drawing the area in the wrong place. ctx.request_repaint(); } response } } fn pointer_pressed_on_area(ctx: &Context, layer_id: LayerId) -> bool { if let Some(pointer_pos) = ctx.pointer_interact_pos() { let any_pressed = ctx.input(|i| i.pointer.any_pressed()); any_pressed && ctx.layer_id_at(pointer_pos) == Some(layer_id) } else { false } } fn automatic_area_position(ctx: &Context, constrain_rect: Rect, layer_id: LayerId) -> Pos2 { let mut existing: Vec<Rect> = ctx.memory(|mem| { mem.areas() .visible_windows() .filter(|(id, _)| id != &layer_id) // ignore ourselves .filter(|(_, state)| state.pivot_pos.is_some() && state.size.is_some()) .map(|(_, state)| state.rect()) .collect() }); existing.sort_by_key(|r| r.left().round() as i32); let spacing = 16.0; let left = constrain_rect.left() + spacing; let top = constrain_rect.top() + spacing; if existing.is_empty() { return pos2(left, top); } // Separate existing rectangles into columns: let mut column_bbs = vec![existing[0]]; for &rect in &existing { #[expect(clippy::unwrap_used)] let current_column_bb = column_bbs.last_mut().unwrap(); if rect.left() < current_column_bb.right() { // same column *current_column_bb |= rect; } else { // new column column_bbs.push(rect); } } { // Look for large spaces between columns (empty columns): let mut x = left; for col_bb in &column_bbs { let available = col_bb.left() - x; if available >= 300.0 { return pos2(x, top); } x = col_bb.right() + spacing; } } // Find first column with some available space at the bottom of it: for col_bb in &column_bbs { if col_bb.bottom() < constrain_rect.center().y { return pos2(col_bb.left(), col_bb.bottom() + spacing); } } // Maybe we can fit a new column? #[expect(clippy::unwrap_used)] let rightmost = column_bbs.last().unwrap().right(); if rightmost + 200.0 < constrain_rect.right() { return pos2(rightmost + spacing, top); } // Ok, just put us in the column with the most space at the bottom: let mut best_pos = pos2(left, column_bbs[0].bottom() + spacing); for col_bb in &column_bbs { let col_pos = pos2(col_bb.left(), col_bb.bottom() + spacing); if col_pos.y < best_pos.y { best_pos = col_pos; } } best_pos }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/window.rs
crates/egui/src/containers/window.rs
// WARNING: the code in here is horrible. It is a behemoth that needs breaking up into simpler parts. use std::sync::Arc; use emath::GuiRounding as _; use epaint::{CornerRadiusF32, RectShape}; use crate::collapsing_header::CollapsingState; use crate::*; use super::scroll_area::{ScrollBarVisibility, ScrollSource}; use super::{Area, Frame, Resize, ScrollArea, area, resize}; /// Builder for a floating window which can be dragged, closed, collapsed, resized and scrolled (off by default). /// /// You can customize: /// * title /// * default, minimum, maximum and/or fixed size, collapsed/expanded /// * if the window has a scroll area (off by default) /// * if the window can be collapsed (minimized) to just the title bar (yes, by default) /// * if there should be a close button (none by default) /// /// ``` /// # egui::__run_test_ctx(|ctx| { /// egui::Window::new("My Window").show(ctx, |ui| { /// ui.label("Hello World!"); /// }); /// # }); /// ``` /// /// The previous rectangle used by this window can be obtained through [`crate::Memory::area_rect()`]. /// /// Note that this is NOT a native OS window. /// To create a new native OS window, use [`crate::Context::show_viewport_deferred`]. #[must_use = "You should call .show()"] pub struct Window<'open> { title: WidgetText, open: Option<&'open mut bool>, area: Area, frame: Option<Frame>, resize: Resize, scroll: ScrollArea, collapsible: bool, default_open: bool, with_title_bar: bool, fade_out: bool, } impl<'open> Window<'open> { /// The window title is used as a unique [`Id`] and must be unique, and should not change. /// This is true even if you disable the title bar with `.title_bar(false)`. /// If you need a changing title, you must call `window.id(…)` with a fixed id. pub fn new(title: impl Into<WidgetText>) -> Self { let title = title.into().fallback_text_style(TextStyle::Heading); let area = Area::new(Id::new(title.text())).kind(UiKind::Window); Self { title, open: None, area, frame: None, resize: Resize::default() .with_stroke(false) .min_size([96.0, 32.0]) .default_size([340.0, 420.0]), // Default inner size of a window scroll: ScrollArea::neither().auto_shrink(false), collapsible: true, default_open: true, with_title_bar: true, fade_out: true, } } /// Construct a [`Window`] that follows the given viewport. pub fn from_viewport(id: ViewportId, viewport: ViewportBuilder) -> Self { let ViewportBuilder { title, app_id, inner_size, min_inner_size, max_inner_size, resizable, decorations, title_shown, minimize_button, .. // A lot of things not implemented yet } = viewport; let mut window = Self::new(title.or(app_id).unwrap_or_else(String::new)).id(Id::new(id)); if let Some(inner_size) = inner_size { window = window.default_size(inner_size); } if let Some(min_inner_size) = min_inner_size { window = window.min_size(min_inner_size); } if let Some(max_inner_size) = max_inner_size { window = window.max_size(max_inner_size); } if let Some(resizable) = resizable { window = window.resizable(resizable); } window = window.title_bar(decorations.unwrap_or(true) && title_shown.unwrap_or(true)); window = window.collapsible(minimize_button.unwrap_or(true)); window } /// Assign a unique id to the Window. Required if the title changes, or is shared with another window. #[inline] pub fn id(mut self, id: Id) -> Self { self.area = self.area.id(id); self } /// Call this to add a close-button to the window title bar. /// /// * If `*open == false`, the window will not be visible. /// * If `*open == true`, the window will have a close button. /// * If the close button is pressed, `*open` will be set to `false`. #[inline] pub fn open(mut self, open: &'open mut bool) -> Self { self.open = Some(open); self } /// If `false` the window will be grayed out and non-interactive. #[inline] pub fn enabled(mut self, enabled: bool) -> Self { self.area = self.area.enabled(enabled); self } /// If false, clicks goes straight through to what is behind us. /// /// Can be used for semi-invisible areas that the user should be able to click through. /// /// Default: `true`. #[inline] pub fn interactable(mut self, interactable: bool) -> Self { self.area = self.area.interactable(interactable); self } /// If `false` the window will be immovable. #[inline] pub fn movable(mut self, movable: bool) -> Self { self.area = self.area.movable(movable); self } /// `order(Order::Foreground)` for a Window that should always be on top #[inline] pub fn order(mut self, order: Order) -> Self { self.area = self.area.order(order); self } /// If `true`, quickly fade in the `Window` when it first appears. /// /// Default: `true`. #[inline] pub fn fade_in(mut self, fade_in: bool) -> Self { self.area = self.area.fade_in(fade_in); self } /// If `true`, quickly fade out the `Window` when it closes. /// /// This only works if you use [`Self::open`] to close the window. /// /// Default: `true`. #[inline] pub fn fade_out(mut self, fade_out: bool) -> Self { self.fade_out = fade_out; self } /// Usage: `Window::new(…).mutate(|w| w.resize = w.resize.auto_expand_width(true))` // TODO(emilk): I'm not sure this is a good interface for this. #[inline] pub fn mutate(mut self, mutate: impl Fn(&mut Self)) -> Self { mutate(&mut self); self } /// Usage: `Window::new(…).resize(|r| r.auto_expand_width(true))` // TODO(emilk): I'm not sure this is a good interface for this. #[inline] pub fn resize(mut self, mutate: impl Fn(Resize) -> Resize) -> Self { self.resize = mutate(self.resize); self } /// Change the background color, margins, etc. #[inline] pub fn frame(mut self, frame: Frame) -> Self { self.frame = Some(frame); self } /// Set minimum width of the window. #[inline] pub fn min_width(mut self, min_width: f32) -> Self { self.resize = self.resize.min_width(min_width); self } /// Set minimum height of the window. #[inline] pub fn min_height(mut self, min_height: f32) -> Self { self.resize = self.resize.min_height(min_height); self } /// Set minimum size of the window, equivalent to calling both `min_width` and `min_height`. #[inline] pub fn min_size(mut self, min_size: impl Into<Vec2>) -> Self { self.resize = self.resize.min_size(min_size); self } /// Set maximum width of the window. #[inline] pub fn max_width(mut self, max_width: f32) -> Self { self.resize = self.resize.max_width(max_width); self } /// Set maximum height of the window. #[inline] pub fn max_height(mut self, max_height: f32) -> Self { self.resize = self.resize.max_height(max_height); self } /// Set maximum size of the window, equivalent to calling both `max_width` and `max_height`. #[inline] pub fn max_size(mut self, max_size: impl Into<Vec2>) -> Self { self.resize = self.resize.max_size(max_size); self } /// Set current position of the window. /// If the window is movable it is up to you to keep track of where it moved to! #[inline] pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self { self.area = self.area.current_pos(current_pos); self } /// Set initial position of the window. #[inline] pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self { self.area = self.area.default_pos(default_pos); self } /// Sets the window position and prevents it from being dragged around. #[inline] pub fn fixed_pos(mut self, pos: impl Into<Pos2>) -> Self { self.area = self.area.fixed_pos(pos); self } /// Constrains this window to [`Context::screen_rect`]. /// /// To change the area to constrain to, use [`Self::constrain_to`]. /// /// Default: `true`. #[inline] pub fn constrain(mut self, constrain: bool) -> Self { self.area = self.area.constrain(constrain); self } /// Constrain the movement of the window to the given rectangle. /// /// For instance: `.constrain_to(ctx.screen_rect())`. #[inline] pub fn constrain_to(mut self, constrain_rect: Rect) -> Self { self.area = self.area.constrain_to(constrain_rect); self } /// Where the "root" of the window is. /// /// For instance, if you set this to [`Align2::RIGHT_TOP`] /// then [`Self::fixed_pos`] will set the position of the right-top /// corner of the window. /// /// Default: [`Align2::LEFT_TOP`]. #[inline] pub fn pivot(mut self, pivot: Align2) -> Self { self.area = self.area.pivot(pivot); self } /// Set anchor and distance. /// /// An anchor of `Align2::RIGHT_TOP` means "put the right-top corner of the window /// in the right-top corner of the screen". /// /// The offset is added to the position, so e.g. an offset of `[-5.0, 5.0]` /// would move the window left and down from the given anchor. /// /// Anchoring also makes the window immovable. /// /// It is an error to set both an anchor and a position. #[inline] pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self { self.area = self.area.anchor(align, offset); self } /// Set initial collapsed state of the window #[inline] pub fn default_open(mut self, default_open: bool) -> Self { self.default_open = default_open; self } /// Set initial size of the window. #[inline] pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self { let default_size: Vec2 = default_size.into(); self.resize = self.resize.default_size(default_size); self.area = self.area.default_size(default_size); self } /// Set initial width of the window. #[inline] pub fn default_width(mut self, default_width: f32) -> Self { self.resize = self.resize.default_width(default_width); self.area = self.area.default_width(default_width); self } /// Set initial height of the window. #[inline] pub fn default_height(mut self, default_height: f32) -> Self { self.resize = self.resize.default_height(default_height); self.area = self.area.default_height(default_height); self } /// Sets the window size and prevents it from being resized by dragging its edges. #[inline] pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self { self.resize = self.resize.fixed_size(size); self } /// Set initial position and size of the window. pub fn default_rect(self, rect: Rect) -> Self { self.default_pos(rect.min).default_size(rect.size()) } /// Sets the window pos and size and prevents it from being moved and resized by dragging its edges. pub fn fixed_rect(self, rect: Rect) -> Self { self.fixed_pos(rect.min).fixed_size(rect.size()) } /// Can the user resize the window by dragging its edges? /// /// Note that even if you set this to `false` the window may still auto-resize. /// /// You can set the window to only be resizable in one direction by using /// e.g. `[true, false]` as the argument, /// making the window only resizable in the x-direction. /// /// Default is `true`. #[inline] pub fn resizable(mut self, resizable: impl Into<Vec2b>) -> Self { let resizable = resizable.into(); self.resize = self.resize.resizable(resizable); self } /// Can the window be collapsed by clicking on its title? #[inline] pub fn collapsible(mut self, collapsible: bool) -> Self { self.collapsible = collapsible; self } /// Show title bar on top of the window? /// If `false`, the window will not be collapsible nor have a close-button. #[inline] pub fn title_bar(mut self, title_bar: bool) -> Self { self.with_title_bar = title_bar; self } /// Not resizable, just takes the size of its contents. /// Also disabled scrolling. /// Text will not wrap, but will instead make your window width expand. #[inline] pub fn auto_sized(mut self) -> Self { self.resize = self.resize.auto_sized(); self.scroll = ScrollArea::neither(); self } /// Enable/disable horizontal/vertical scrolling. `false` by default. /// /// You can pass in `false`, `true`, `[false, true]` etc. #[inline] pub fn scroll(mut self, scroll: impl Into<Vec2b>) -> Self { self.scroll = self.scroll.scroll(scroll); self } /// Enable/disable horizontal scrolling. `false` by default. #[inline] pub fn hscroll(mut self, hscroll: bool) -> Self { self.scroll = self.scroll.hscroll(hscroll); self } /// Enable/disable vertical scrolling. `false` by default. #[inline] pub fn vscroll(mut self, vscroll: bool) -> Self { self.scroll = self.scroll.vscroll(vscroll); self } /// Enable/disable scrolling on the window by dragging with the pointer. `true` by default. /// /// See [`ScrollArea::drag_to_scroll`] for more. #[inline] pub fn drag_to_scroll(mut self, drag_to_scroll: bool) -> Self { self.scroll = self.scroll.scroll_source(ScrollSource { drag: drag_to_scroll, ..Default::default() }); self } /// Sets the [`ScrollBarVisibility`] of the window. #[inline] pub fn scroll_bar_visibility(mut self, visibility: ScrollBarVisibility) -> Self { self.scroll = self.scroll.scroll_bar_visibility(visibility); self } } impl Window<'_> { /// Returns `None` if the window is not open (if [`Window::open`] was called with `&mut false`). /// Returns `Some(InnerResponse { inner: None })` if the window is collapsed. #[inline] pub fn show<R>( self, ctx: &Context, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<Option<R>>> { self.show_dyn(ctx, Box::new(add_contents)) } fn show_dyn<'c, R>( self, ctx: &Context, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> Option<InnerResponse<Option<R>>> { let Window { title, mut open, area, frame, resize, scroll, collapsible, default_open, with_title_bar, fade_out, } = self; let style = ctx.global_style(); let header_color = frame.map_or_else(|| style.visuals.widgets.open.weak_bg_fill, |f| f.fill); let mut window_frame = frame.unwrap_or_else(|| Frame::window(&style)); let is_explicitly_closed = matches!(open, Some(false)); let is_open = !is_explicitly_closed || ctx.memory(|mem| mem.everything_is_visible()); let opacity = ctx.animate_bool_with_easing( area.id.with("fade-out"), is_open, emath::easing::cubic_out, ); if opacity <= 0.0 { return None; } let area_id = area.id; let area_layer_id = area.layer(); let resize_id = area_id.with("resize"); let mut collapsing = CollapsingState::load_with_default_open(ctx, area_id.with("collapsing"), default_open); let is_collapsed = with_title_bar && !collapsing.is_open(); let possible = PossibleInteractions::new(&area, &resize, is_collapsed); let resize = resize.resizable(false); // We resize it manually let mut resize = resize.id(resize_id); let on_top = Some(area_layer_id) == ctx.top_layer_id(); let mut area = area.begin(ctx); area.with_widget_info(|| WidgetInfo::labeled(WidgetType::Window, true, title.text())); // Calculate roughly how much larger the full window inner size is compared to the content rect let (title_bar_height_with_margin, title_content_spacing) = if with_title_bar { let title_bar_inner_height = ctx .fonts_mut(|fonts| title.font_height(fonts, &style)) .at_least(style.spacing.interact_size.y); let title_bar_inner_height = title_bar_inner_height + window_frame.inner_margin.sum().y; let half_height = (title_bar_inner_height / 2.0).round() as _; window_frame.corner_radius.ne = window_frame.corner_radius.ne.clamp(0, half_height); window_frame.corner_radius.nw = window_frame.corner_radius.nw.clamp(0, half_height); let title_content_spacing = if is_collapsed { 0.0 } else { window_frame.stroke.width }; (title_bar_inner_height, title_content_spacing) } else { (0.0, 0.0) }; { // Prevent window from becoming larger than the constrain rect. let constrain_rect = area.constrain_rect(); let max_width = constrain_rect.width(); let max_height = constrain_rect.height() - title_bar_height_with_margin - title_content_spacing; resize.max_size.x = resize.max_size.x.min(max_width); resize.max_size.y = resize.max_size.y.min(max_height); } // First check for resize to avoid frame delay: let last_frame_outer_rect = area.state().rect(); let resize_interaction = do_resize_interaction( ctx, possible, area.id(), area_layer_id, last_frame_outer_rect, window_frame, ); { let margins = window_frame.total_margin().sum() + vec2(0.0, title_bar_height_with_margin + title_content_spacing); resize_response( resize_interaction, ctx, margins, area_layer_id, &mut area, resize_id, ); } let mut area_content_ui = area.content_ui(ctx); if is_open { // `Area` already takes care of fade-in animations, // so we only need to handle fade-out animations here. } else if fade_out { area_content_ui.multiply_opacity(opacity); } let content_inner = { // BEGIN FRAME -------------------------------- let mut frame = window_frame.begin(&mut area_content_ui); let show_close_button = open.is_some(); let where_to_put_header_background = &area_content_ui.painter().add(Shape::Noop); let title_bar = if with_title_bar { let title_bar = TitleBar::new( &frame.content_ui, title, show_close_button, collapsible, window_frame, title_bar_height_with_margin, ); resize.min_size.x = resize.min_size.x.at_least(title_bar.inner_rect.width()); // Prevent making window smaller than title bar width frame.content_ui.set_min_size(title_bar.inner_rect.size()); // Skip the title bar (and separator): if is_collapsed { frame.content_ui.add_space(title_bar.inner_rect.height()); } else { frame.content_ui.add_space( title_bar.inner_rect.height() + title_content_spacing + window_frame.inner_margin.sum().y, ); } Some(title_bar) } else { None }; let (content_inner, content_response) = collapsing .show_body_unindented(&mut frame.content_ui, |ui| { resize.show(ui, |ui| { if scroll.is_any_scroll_enabled() { scroll.show(ui, add_contents).inner } else { add_contents(ui) } }) }) .map_or((None, None), |ir| (Some(ir.inner), Some(ir.response))); let outer_rect = frame.end(&mut area_content_ui).rect; // Do resize interaction _again_, to move their widget rectangles on TOP of the rest of the window. let resize_interaction = do_resize_interaction( ctx, possible, area.id(), area_layer_id, last_frame_outer_rect, window_frame, ); paint_resize_corner( &area_content_ui, &possible, outer_rect, &window_frame, resize_interaction, ); // END FRAME -------------------------------- if let Some(mut title_bar) = title_bar { title_bar.inner_rect = outer_rect.shrink(window_frame.stroke.width); title_bar.inner_rect.max.y = title_bar.inner_rect.min.y + title_bar_height_with_margin; if on_top && area_content_ui.visuals().window_highlight_topmost { let mut round = window_frame.corner_radius - window_frame.stroke.width.round() as u8; if !is_collapsed { round.se = 0; round.sw = 0; } area_content_ui.painter().set( *where_to_put_header_background, RectShape::filled(title_bar.inner_rect, round, header_color), ); } if false { ctx.debug_painter().debug_rect( title_bar.inner_rect, Color32::LIGHT_BLUE, "title_bar.rect", ); } title_bar.ui( &mut area_content_ui, &content_response, open.as_deref_mut(), &mut collapsing, collapsible, ); } collapsing.store(ctx); paint_frame_interaction(&area_content_ui, outer_rect, resize_interaction); content_inner }; let full_response = area.end(ctx, area_content_ui); if full_response.should_close() && let Some(open) = open { *open = false; } let inner_response = InnerResponse { inner: content_inner, response: full_response, }; Some(inner_response) } } fn paint_resize_corner( ui: &Ui, possible: &PossibleInteractions, outer_rect: Rect, window_frame: &Frame, i: ResizeInteraction, ) { let cr = window_frame.corner_radius; let (corner, radius, corner_response) = if possible.resize_right && possible.resize_bottom { (Align2::RIGHT_BOTTOM, cr.se, i.right & i.bottom) } else if possible.resize_left && possible.resize_bottom { (Align2::LEFT_BOTTOM, cr.sw, i.left & i.bottom) } else if possible.resize_left && possible.resize_top { (Align2::LEFT_TOP, cr.nw, i.left & i.top) } else if possible.resize_right && possible.resize_top { (Align2::RIGHT_TOP, cr.ne, i.right & i.top) } else { // We're not in two directions, but it is still nice to tell the user // we're resizable by painting the resize corner in the expected place // (i.e. for windows only resizable in one direction): if possible.resize_right || possible.resize_bottom { (Align2::RIGHT_BOTTOM, cr.se, i.right & i.bottom) } else if possible.resize_left || possible.resize_bottom { (Align2::LEFT_BOTTOM, cr.sw, i.left & i.bottom) } else if possible.resize_left || possible.resize_top { (Align2::LEFT_TOP, cr.nw, i.left & i.top) } else if possible.resize_right || possible.resize_top { (Align2::RIGHT_TOP, cr.ne, i.right & i.top) } else { return; } }; // Adjust the corner offset to accommodate for window rounding let radius = radius as f32; let offset = ((2.0_f32.sqrt() * (1.0 + radius) - radius) * 45.0_f32.to_radians().cos()).max(2.0); let stroke = if corner_response.drag { ui.visuals().widgets.active.fg_stroke } else if corner_response.hover { ui.visuals().widgets.hovered.fg_stroke } else { window_frame.stroke }; let fill_rect = outer_rect.shrink(window_frame.stroke.width); let corner_size = Vec2::splat(ui.visuals().resize_corner_size); let corner_rect = corner.align_size_within_rect(corner_size, fill_rect); let corner_rect = corner_rect.translate(-offset * corner.to_sign()); // move away from corner crate::resize::paint_resize_corner_with_style(ui, &corner_rect, stroke.color, corner); } // ---------------------------------------------------------------------------- /// Which sides can be resized? #[derive(Clone, Copy, Debug)] struct PossibleInteractions { // Which sides can we drag to resize or move? resize_left: bool, resize_right: bool, resize_top: bool, resize_bottom: bool, } impl PossibleInteractions { fn new(area: &Area, resize: &Resize, is_collapsed: bool) -> Self { let movable = area.is_enabled() && area.is_movable(); let resizable = resize .is_resizable() .and(area.is_enabled() && !is_collapsed); let pivot = area.get_pivot(); Self { resize_left: resizable.x && (movable || pivot.x() != Align::LEFT), resize_right: resizable.x && (movable || pivot.x() != Align::RIGHT), resize_top: resizable.y && (movable || pivot.y() != Align::TOP), resize_bottom: resizable.y && (movable || pivot.y() != Align::BOTTOM), } } pub fn resizable(&self) -> bool { self.resize_left || self.resize_right || self.resize_top || self.resize_bottom } } /// Resizing the window edges. #[derive(Clone, Copy, Debug)] struct ResizeInteraction { /// Outer rect (outside the stroke) outer_rect: Rect, window_frame: Frame, left: SideResponse, right: SideResponse, top: SideResponse, bottom: SideResponse, } /// A miniature version of `Response`, for each side of the window. #[derive(Clone, Copy, Debug, Default)] struct SideResponse { hover: bool, drag: bool, } impl SideResponse { pub fn any(&self) -> bool { self.hover || self.drag } } impl std::ops::BitAnd for SideResponse { type Output = Self; fn bitand(self, rhs: Self) -> Self::Output { Self { hover: self.hover && rhs.hover, drag: self.drag && rhs.drag, } } } impl std::ops::BitOrAssign for SideResponse { fn bitor_assign(&mut self, rhs: Self) { *self = Self { hover: self.hover || rhs.hover, drag: self.drag || rhs.drag, }; } } impl ResizeInteraction { pub fn set_cursor(&self, ctx: &Context) { let left = self.left.any(); let right = self.right.any(); let top = self.top.any(); let bottom = self.bottom.any(); // TODO(emilk): use one-sided cursors for when we reached the min/max size. if (left && top) || (right && bottom) { ctx.set_cursor_icon(CursorIcon::ResizeNwSe); } else if (right && top) || (left && bottom) { ctx.set_cursor_icon(CursorIcon::ResizeNeSw); } else if left || right { ctx.set_cursor_icon(CursorIcon::ResizeHorizontal); } else if bottom || top { ctx.set_cursor_icon(CursorIcon::ResizeVertical); } } pub fn any_hovered(&self) -> bool { self.left.hover || self.right.hover || self.top.hover || self.bottom.hover } pub fn any_dragged(&self) -> bool { self.left.drag || self.right.drag || self.top.drag || self.bottom.drag } } fn resize_response( resize_interaction: ResizeInteraction, ctx: &Context, margins: Vec2, area_layer_id: LayerId, area: &mut area::Prepared, resize_id: Id, ) { let Some(mut new_rect) = move_and_resize_window(ctx, resize_id, &resize_interaction) else { return; }; if area.constrain() { new_rect = Context::constrain_window_rect_to_area(new_rect, area.constrain_rect()); } // TODO(emilk): add this to a Window state instead as a command "move here next frame" area.state_mut().set_left_top_pos(new_rect.left_top()); if resize_interaction.any_dragged() && let Some(mut state) = resize::State::load(ctx, resize_id) { state.requested_size = Some(new_rect.size() - margins); state.store(ctx, resize_id); } ctx.memory_mut(|mem| mem.areas_mut().move_to_top(area_layer_id)); } /// Acts on outer rect (outside the stroke) fn move_and_resize_window(ctx: &Context, id: Id, interaction: &ResizeInteraction) -> Option<Rect> { // Used to prevent drift let rect_at_start_of_drag_id = id.with("window_rect_at_drag_start"); if !interaction.any_dragged() { ctx.data_mut(|data| { data.remove::<Rect>(rect_at_start_of_drag_id); }); return None; } let total_drag_delta = ctx.input(|i| i.pointer.total_drag_delta())?; let rect_at_start_of_drag = ctx.data_mut(|data| { *data.get_temp_mut_or::<Rect>(rect_at_start_of_drag_id, interaction.outer_rect) }); let mut rect = rect_at_start_of_drag; // prevent drift // Put the rect in the center of the stroke: rect = rect.shrink(interaction.window_frame.stroke.width / 2.0); if interaction.left.drag { rect.min.x += total_drag_delta.x; } else if interaction.right.drag { rect.max.x += total_drag_delta.x; } if interaction.top.drag { rect.min.y += total_drag_delta.y; } else if interaction.bottom.drag { rect.max.y += total_drag_delta.y; } // Return to having the rect outside the stroke: rect = rect.expand(interaction.window_frame.stroke.width / 2.0); Some(rect.round_ui()) } fn do_resize_interaction( ctx: &Context, possible: PossibleInteractions, _accessibility_parent: Id, layer_id: LayerId, outer_rect: Rect, window_frame: Frame, ) -> ResizeInteraction { if !possible.resizable() { return ResizeInteraction { outer_rect, window_frame, left: Default::default(), right: Default::default(), top: Default::default(), bottom: Default::default(), }; } // The rect that is in the middle of the stroke: let rect = outer_rect.shrink(window_frame.stroke.width / 2.0); let side_response = |rect, id| { ctx.register_accesskit_parent(id, _accessibility_parent); let response = ctx.create_widget( WidgetRect { layer_id, id, rect, interact_rect: rect, sense: Sense::drag(), enabled: true, }, true, InteractOptions { // We call this multiple times. // First to read the result (to avoid frame delay) // and the second time to move it to the top, above the window contents. move_to_top: true, }, ); response.widget_info(|| WidgetInfo::new(crate::WidgetType::ResizeHandle)); SideResponse { hover: response.hovered(),
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/scroll_area.rs
crates/egui/src/containers/scroll_area.rs
//! See [`ScrollArea`] for docs. #![expect(clippy::needless_range_loop)] use std::ops::{Add, AddAssign, BitOr, BitOrAssign}; use emath::GuiRounding as _; use epaint::Margin; use crate::{ Context, CursorIcon, Id, NumExt as _, Pos2, Rangef, Rect, Response, Sense, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, Vec2b, WidgetInfo, emath, epaint, lerp, pass_state, pos2, remap, remap_clamp, }; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct ScrollingToTarget { animation_time_span: (f64, f64), target_offset: f32, } #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct State { /// Positive offset means scrolling down/right pub offset: Vec2, /// If set, quickly but smoothly scroll to this target offset. offset_target: [Option<ScrollingToTarget>; 2], /// Were the scroll bars visible last frame? show_scroll: Vec2b, /// The content were to large to fit large frame. content_is_too_large: Vec2b, /// Did the user interact (hover or drag) the scroll bars last frame? scroll_bar_interaction: Vec2b, /// Momentum, used for kinetic scrolling #[cfg_attr(feature = "serde", serde(skip))] vel: Vec2, /// Mouse offset relative to the top of the handle when started moving the handle. scroll_start_offset_from_top_left: [Option<f32>; 2], /// Is the scroll sticky. This is true while scroll handle is in the end position /// and remains that way until the user moves the `scroll_handle`. Once unstuck (false) /// it remains false until the scroll touches the end position, which reenables stickiness. scroll_stuck_to_end: Vec2b, /// Area that can be dragged. This is the size of the content from the last frame. interact_rect: Option<Rect>, } impl Default for State { fn default() -> Self { Self { offset: Vec2::ZERO, offset_target: Default::default(), show_scroll: Vec2b::FALSE, content_is_too_large: Vec2b::FALSE, scroll_bar_interaction: Vec2b::FALSE, vel: Vec2::ZERO, scroll_start_offset_from_top_left: [None; 2], scroll_stuck_to_end: Vec2b::TRUE, interact_rect: None, } } } impl State { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_persisted(id)) } pub fn store(self, ctx: &Context, id: Id) { ctx.data_mut(|d| d.insert_persisted(id, self)); } /// Get the current kinetic scrolling velocity. pub fn velocity(&self) -> Vec2 { self.vel } } pub struct ScrollAreaOutput<R> { /// What the user closure returned. pub inner: R, /// [`Id`] of the [`ScrollArea`]. pub id: Id, /// The current state of the scroll area. pub state: State, /// The size of the content. If this is larger than [`Self::inner_rect`], /// then there was need for scrolling. pub content_size: Vec2, /// Where on the screen the content is (excludes scroll bars). pub inner_rect: Rect, } /// Indicate whether the horizontal and vertical scroll bars must be always visible, hidden or visible when needed. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ScrollBarVisibility { /// Hide scroll bar even if they are needed. /// /// You can still scroll, with the scroll-wheel /// and by dragging the contents, but there is no /// visual indication of how far you have scrolled. AlwaysHidden, /// Show scroll bars only when the content size exceeds the container, /// i.e. when there is any need to scroll. /// /// This is the default. VisibleWhenNeeded, /// Always show the scroll bar, even if the contents fit in the container /// and there is no need to scroll. AlwaysVisible, } impl Default for ScrollBarVisibility { #[inline] fn default() -> Self { Self::VisibleWhenNeeded } } impl ScrollBarVisibility { pub const ALL: [Self; 3] = [ Self::AlwaysHidden, Self::VisibleWhenNeeded, Self::AlwaysVisible, ]; } /// What is the source of scrolling for a [`ScrollArea`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ScrollSource { /// Scroll the area by dragging a scroll bar. /// /// By default the scroll bars remain visible to show current position. /// To hide them use [`ScrollArea::scroll_bar_visibility()`]. pub scroll_bar: bool, /// Scroll the area by dragging the contents. pub drag: bool, /// Scroll the area by scrolling (or shift scrolling) the mouse wheel with /// the mouse cursor over the [`ScrollArea`]. pub mouse_wheel: bool, } impl Default for ScrollSource { fn default() -> Self { Self::ALL } } impl ScrollSource { pub const NONE: Self = Self { scroll_bar: false, drag: false, mouse_wheel: false, }; pub const ALL: Self = Self { scroll_bar: true, drag: true, mouse_wheel: true, }; pub const SCROLL_BAR: Self = Self { scroll_bar: true, drag: false, mouse_wheel: false, }; pub const DRAG: Self = Self { scroll_bar: false, drag: true, mouse_wheel: false, }; pub const MOUSE_WHEEL: Self = Self { scroll_bar: false, drag: false, mouse_wheel: true, }; /// Is everything disabled? #[inline] pub fn is_none(&self) -> bool { self == &Self::NONE } /// Is anything enabled? #[inline] pub fn any(&self) -> bool { self.scroll_bar | self.drag | self.mouse_wheel } /// Is everything enabled? #[inline] pub fn is_all(&self) -> bool { self.scroll_bar & self.drag & self.mouse_wheel } } impl BitOr for ScrollSource { type Output = Self; #[inline] fn bitor(self, rhs: Self) -> Self::Output { Self { scroll_bar: self.scroll_bar | rhs.scroll_bar, drag: self.drag | rhs.drag, mouse_wheel: self.mouse_wheel | rhs.mouse_wheel, } } } #[expect(clippy::suspicious_arithmetic_impl)] impl Add for ScrollSource { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self::Output { self | rhs } } impl BitOrAssign for ScrollSource { #[inline] fn bitor_assign(&mut self, rhs: Self) { *self = *self | rhs; } } impl AddAssign for ScrollSource { #[inline] fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } /// Add vertical and/or horizontal scrolling to a contained [`Ui`]. /// /// By default, scroll bars only show up when needed, i.e. when the contents /// is larger than the container. /// This is controlled by [`Self::scroll_bar_visibility`]. /// /// There are two flavors of scroll areas: solid and floating. /// Solid scroll bars use up space, reducing the amount of space available /// to the contents. Floating scroll bars float on top of the contents, covering it. /// You can change the scroll style by changing the [`crate::style::Spacing::scroll`]. /// /// ### Coordinate system /// * content: size of contents (generally large; that's why we want scroll bars) /// * outer: size of scroll area including scroll bar(s) /// * inner: excluding scroll bar(s). The area we clip the contents to. Includes `content_margin`. /// /// If the floating scroll bars settings is turned on then `inner == outer`. /// /// ## Example /// ``` /// # egui::__run_test_ui(|ui| { /// egui::ScrollArea::vertical().show(ui, |ui| { /// // Add a lot of widgets here. /// }); /// # }); /// ``` /// /// You can scroll to an element using [`crate::Response::scroll_to_me`], [`Ui::scroll_to_cursor`] and [`Ui::scroll_to_rect`]. /// /// ## See also /// If you want to allow zooming, use [`crate::Scene`]. #[derive(Clone, Debug)] #[must_use = "You should call .show()"] pub struct ScrollArea { /// Do we have horizontal/vertical scrolling enabled? direction_enabled: Vec2b, auto_shrink: Vec2b, max_size: Vec2, min_scrolled_size: Vec2, scroll_bar_visibility: ScrollBarVisibility, scroll_bar_rect: Option<Rect>, id_salt: Option<Id>, offset_x: Option<f32>, offset_y: Option<f32>, on_hover_cursor: Option<CursorIcon>, on_drag_cursor: Option<CursorIcon>, scroll_source: ScrollSource, wheel_scroll_multiplier: Vec2, content_margin: Option<Margin>, /// If true for vertical or horizontal the scroll wheel will stick to the /// end position until user manually changes position. It will become true /// again once scroll handle makes contact with end. stick_to_end: Vec2b, /// If false, `scroll_to_*` functions will not be animated animated: bool, } impl ScrollArea { /// Create a horizontal scroll area. #[inline] pub fn horizontal() -> Self { Self::new([true, false]) } /// Create a vertical scroll area. #[inline] pub fn vertical() -> Self { Self::new([false, true]) } /// Create a bi-directional (horizontal and vertical) scroll area. #[inline] pub fn both() -> Self { Self::new([true, true]) } /// Create a scroll area where both direction of scrolling is disabled. /// It's unclear why you would want to do this. #[inline] pub fn neither() -> Self { Self::new([false, false]) } /// Create a scroll area where you decide which axis has scrolling enabled. /// For instance, `ScrollArea::new([true, false])` enables horizontal scrolling. pub fn new(direction_enabled: impl Into<Vec2b>) -> Self { Self { direction_enabled: direction_enabled.into(), auto_shrink: Vec2b::TRUE, max_size: Vec2::INFINITY, min_scrolled_size: Vec2::splat(64.0), scroll_bar_visibility: Default::default(), scroll_bar_rect: None, id_salt: None, offset_x: None, offset_y: None, on_hover_cursor: None, on_drag_cursor: None, scroll_source: ScrollSource::default(), wheel_scroll_multiplier: Vec2::splat(1.0), content_margin: None, stick_to_end: Vec2b::FALSE, animated: true, } } /// The maximum width of the outer frame of the scroll area. /// /// Use `f32::INFINITY` if you want the scroll area to expand to fit the surrounding [`Ui`] (default). /// /// See also [`Self::auto_shrink`]. #[inline] pub fn max_width(mut self, max_width: f32) -> Self { self.max_size.x = max_width; self } /// The maximum height of the outer frame of the scroll area. /// /// Use `f32::INFINITY` if you want the scroll area to expand to fit the surrounding [`Ui`] (default). /// /// See also [`Self::auto_shrink`]. #[inline] pub fn max_height(mut self, max_height: f32) -> Self { self.max_size.y = max_height; self } /// The minimum width of a horizontal scroll area which requires scroll bars. /// /// The [`ScrollArea`] will only become smaller than this if the content is smaller than this /// (and so we don't require scroll bars). /// /// Default: `64.0`. #[inline] pub fn min_scrolled_width(mut self, min_scrolled_width: f32) -> Self { self.min_scrolled_size.x = min_scrolled_width; self } /// The minimum height of a vertical scroll area which requires scroll bars. /// /// The [`ScrollArea`] will only become smaller than this if the content is smaller than this /// (and so we don't require scroll bars). /// /// Default: `64.0`. #[inline] pub fn min_scrolled_height(mut self, min_scrolled_height: f32) -> Self { self.min_scrolled_size.y = min_scrolled_height; self } /// Set the visibility of both horizontal and vertical scroll bars. /// /// With `ScrollBarVisibility::VisibleWhenNeeded` (default), the scroll bar will be visible only when needed. #[inline] pub fn scroll_bar_visibility(mut self, scroll_bar_visibility: ScrollBarVisibility) -> Self { self.scroll_bar_visibility = scroll_bar_visibility; self } /// Specify within which screen-space rectangle to show the scroll bars. /// /// This can be used to move the scroll bars to a smaller region of the `ScrollArea`, /// for instance if you are painting a sticky header on top of it. #[inline] pub fn scroll_bar_rect(mut self, scroll_bar_rect: Rect) -> Self { self.scroll_bar_rect = Some(scroll_bar_rect); self } /// A source for the unique [`Id`], e.g. `.id_source("second_scroll_area")` or `.id_source(loop_index)`. #[inline] #[deprecated = "Renamed id_salt"] pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self { self.id_salt(id_salt) } /// A source for the unique [`Id`], e.g. `.id_salt("second_scroll_area")` or `.id_salt(loop_index)`. #[inline] pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self { self.id_salt = Some(Id::new(id_salt)); self } /// Set the horizontal and vertical scroll offset position. /// /// Positive offset means scrolling down/right. /// /// See also: [`Self::vertical_scroll_offset`], [`Self::horizontal_scroll_offset`], /// [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and /// [`Response::scroll_to_me`](crate::Response::scroll_to_me) #[inline] pub fn scroll_offset(mut self, offset: Vec2) -> Self { self.offset_x = Some(offset.x); self.offset_y = Some(offset.y); self } /// Set the vertical scroll offset position. /// /// Positive offset means scrolling down. /// /// See also: [`Self::scroll_offset`], [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and /// [`Response::scroll_to_me`](crate::Response::scroll_to_me) #[inline] pub fn vertical_scroll_offset(mut self, offset: f32) -> Self { self.offset_y = Some(offset); self } /// Set the horizontal scroll offset position. /// /// Positive offset means scrolling right. /// /// See also: [`Self::scroll_offset`], [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and /// [`Response::scroll_to_me`](crate::Response::scroll_to_me) #[inline] pub fn horizontal_scroll_offset(mut self, offset: f32) -> Self { self.offset_x = Some(offset); self } /// Set the cursor used when the mouse pointer is hovering over the [`ScrollArea`]. /// /// Only applies if [`Self::scroll_source()`] has set [`ScrollSource::drag`] to `true`. /// /// Any changes to the mouse cursor made within the contents of the [`ScrollArea`] will /// override this setting. #[inline] pub fn on_hover_cursor(mut self, cursor: CursorIcon) -> Self { self.on_hover_cursor = Some(cursor); self } /// Set the cursor used when the [`ScrollArea`] is being dragged. /// /// Only applies if [`Self::scroll_source()`] has set [`ScrollSource::drag`] to `true`. /// /// Any changes to the mouse cursor made within the contents of the [`ScrollArea`] will /// override this setting. #[inline] pub fn on_drag_cursor(mut self, cursor: CursorIcon) -> Self { self.on_drag_cursor = Some(cursor); self } /// Turn on/off scrolling on the horizontal axis. #[inline] pub fn hscroll(mut self, hscroll: bool) -> Self { self.direction_enabled[0] = hscroll; self } /// Turn on/off scrolling on the vertical axis. #[inline] pub fn vscroll(mut self, vscroll: bool) -> Self { self.direction_enabled[1] = vscroll; self } /// Turn on/off scrolling on the horizontal/vertical axes. /// /// You can pass in `false`, `true`, `[false, true]` etc. #[inline] pub fn scroll(mut self, direction_enabled: impl Into<Vec2b>) -> Self { self.direction_enabled = direction_enabled.into(); self } /// Control the scrolling behavior. /// /// * If `true` (default), the scroll area will respond to user scrolling. /// * If `false`, the scroll area will not respond to user scrolling. /// /// This can be used, for example, to optionally freeze scrolling while the user /// is typing text in a [`crate::TextEdit`] widget contained within the scroll area. /// /// This controls both scrolling directions. #[deprecated = "Use `ScrollArea::scroll_source()"] #[inline] pub fn enable_scrolling(mut self, enable: bool) -> Self { self.scroll_source = if enable { ScrollSource::ALL } else { ScrollSource::NONE }; self } /// Can the user drag the scroll area to scroll? /// /// This is useful for touch screens. /// /// If `true`, the [`ScrollArea`] will sense drags. /// /// Default: `true`. #[deprecated = "Use `ScrollArea::scroll_source()"] #[inline] pub fn drag_to_scroll(mut self, drag_to_scroll: bool) -> Self { self.scroll_source.drag = drag_to_scroll; self } /// What sources does the [`ScrollArea`] use for scrolling the contents. #[inline] pub fn scroll_source(mut self, scroll_source: ScrollSource) -> Self { self.scroll_source = scroll_source; self } /// The scroll amount caused by a mouse wheel scroll is multiplied by this amount. /// /// Independent for each scroll direction. Defaults to `Vec2{x: 1.0, y: 1.0}`. /// /// This can invert or effectively disable mouse scrolling. #[inline] pub fn wheel_scroll_multiplier(mut self, multiplier: Vec2) -> Self { self.wheel_scroll_multiplier = multiplier; self } /// For each axis, should the containing area shrink if the content is small? /// /// * If `true`, egui will add blank space outside the scroll area. /// * If `false`, egui will add blank space inside the scroll area. /// /// Default: `true`. #[inline] pub fn auto_shrink(mut self, auto_shrink: impl Into<Vec2b>) -> Self { self.auto_shrink = auto_shrink.into(); self } /// Should the scroll area animate `scroll_to_*` functions? /// /// Default: `true`. #[inline] pub fn animated(mut self, animated: bool) -> Self { self.animated = animated; self } /// Is any scrolling enabled? pub(crate) fn is_any_scroll_enabled(&self) -> bool { self.direction_enabled[0] || self.direction_enabled[1] } /// Extra margin added around the contents. /// /// The scroll bars will be either on top of this margin, or outside of it, /// depending on the value of [`crate::style::ScrollStyle::floating`]. /// /// Default: [`crate::style::ScrollStyle::content_margin`]. #[inline] pub fn content_margin(mut self, margin: impl Into<Margin>) -> Self { self.content_margin = Some(margin.into()); self } /// The scroll handle will stick to the rightmost position even while the content size /// changes dynamically. This can be useful to simulate text scrollers coming in from right /// hand side. The scroll handle remains stuck until user manually changes position. Once "unstuck" /// it will remain focused on whatever content viewport the user left it on. If the scroll /// handle is dragged all the way to the right it will again become stuck and remain there /// until manually pulled from the end position. #[inline] pub fn stick_to_right(mut self, stick: bool) -> Self { self.stick_to_end[0] = stick; self } /// The scroll handle will stick to the bottom position even while the content size /// changes dynamically. This can be useful to simulate terminal UIs or log/info scrollers. /// The scroll handle remains stuck until user manually changes position. Once "unstuck" /// it will remain focused on whatever content viewport the user left it on. If the scroll /// handle is dragged to the bottom it will again become stuck and remain there until manually /// pulled from the end position. #[inline] pub fn stick_to_bottom(mut self, stick: bool) -> Self { self.stick_to_end[1] = stick; self } } struct Prepared { id: Id, state: State, auto_shrink: Vec2b, /// Does this `ScrollArea` have horizontal/vertical scrolling enabled? direction_enabled: Vec2b, /// Smoothly interpolated boolean of whether or not to show the scroll bars. show_bars_factor: Vec2, /// How much horizontal and vertical space are used up by the /// width of the vertical bar, and the height of the horizontal bar? /// /// This is always zero for floating scroll bars. /// /// Note that this is a `yx` swizzling of [`Self::show_bars_factor`] /// times the maximum bar with. /// That's because horizontal scroll uses up vertical space, /// and vice versa. current_bar_use: Vec2, scroll_bar_visibility: ScrollBarVisibility, scroll_bar_rect: Option<Rect>, /// Where on the screen the content is (excludes scroll bars; includes `content_margin`). inner_rect: Rect, content_ui: Ui, /// Relative coordinates: the offset and size of the view of the inner UI. /// `viewport.min == ZERO` means we scrolled to the top. viewport: Rect, scroll_source: ScrollSource, wheel_scroll_multiplier: Vec2, stick_to_end: Vec2b, /// If there was a scroll target before the [`ScrollArea`] was added this frame, it's /// not for us to handle so we save it and restore it after this [`ScrollArea`] is done. saved_scroll_target: [Option<pass_state::ScrollTarget>; 2], /// The response from dragging the background (if enabled) background_drag_response: Option<Response>, animated: bool, } impl ScrollArea { fn begin(self, ui: &mut Ui) -> Prepared { let Self { direction_enabled, auto_shrink, max_size, min_scrolled_size, scroll_bar_visibility, scroll_bar_rect, id_salt, offset_x, offset_y, on_hover_cursor, on_drag_cursor, scroll_source, wheel_scroll_multiplier, content_margin: _, // Used elsewhere stick_to_end, animated, } = self; let ctx = ui.ctx().clone(); let id_salt = id_salt.unwrap_or_else(|| Id::new("scroll_area")); let id = ui.make_persistent_id(id_salt); ctx.check_for_id_clash( id, Rect::from_min_size(ui.available_rect_before_wrap().min, Vec2::ZERO), "ScrollArea", ); let mut state = State::load(&ctx, id).unwrap_or_default(); state.offset.x = offset_x.unwrap_or(state.offset.x); state.offset.y = offset_y.unwrap_or(state.offset.y); let show_bars: Vec2b = match scroll_bar_visibility { ScrollBarVisibility::AlwaysHidden => Vec2b::FALSE, ScrollBarVisibility::VisibleWhenNeeded => state.show_scroll, ScrollBarVisibility::AlwaysVisible => direction_enabled, }; let show_bars_factor = Vec2::new( ctx.animate_bool_responsive(id.with("h"), show_bars[0]), ctx.animate_bool_responsive(id.with("v"), show_bars[1]), ); let current_bar_use = show_bars_factor.yx() * ui.spacing().scroll.allocated_width(); let available_outer = ui.available_rect_before_wrap(); let outer_size = available_outer.size().at_most(max_size); let inner_size = { let mut inner_size = outer_size - current_bar_use; // Don't go so far that we shrink to zero. // In particular, if we put a [`ScrollArea`] inside of a [`ScrollArea`], the inner // one shouldn't collapse into nothingness. // See https://github.com/emilk/egui/issues/1097 for d in 0..2 { if direction_enabled[d] { inner_size[d] = inner_size[d].max(min_scrolled_size[d]); } } inner_size }; let inner_rect = Rect::from_min_size(available_outer.min, inner_size); let mut content_max_size = inner_size; if true { // Tell the inner Ui to *try* to fit the content without needing to scroll, // i.e. better to wrap text and shrink images than showing a horizontal scrollbar! } else { // Tell the inner Ui to use as much space as possible, we can scroll to see it! for d in 0..2 { if direction_enabled[d] { content_max_size[d] = f32::INFINITY; } } } let content_max_rect = Rect::from_min_size(inner_rect.min - state.offset, content_max_size); // Round to pixels to avoid widgets appearing to "float" when scrolling fractional amounts: let content_max_rect = content_max_rect .round_to_pixels(ui.pixels_per_point()) .round_ui(); let mut content_ui = ui.new_child( UiBuilder::new() .ui_stack_info(UiStackInfo::new(UiKind::ScrollArea)) .max_rect(content_max_rect), ); { // Clip the content, but only when we really need to: let clip_rect_margin = ui.visuals().clip_rect_margin; let mut content_clip_rect = ui.clip_rect(); for d in 0..2 { if direction_enabled[d] { content_clip_rect.min[d] = inner_rect.min[d] - clip_rect_margin; content_clip_rect.max[d] = inner_rect.max[d] + clip_rect_margin; } else { // Nice handling of forced resizing beyond the possible: content_clip_rect.max[d] = ui.clip_rect().max[d] - current_bar_use[d]; } } // Make sure we didn't accidentally expand the clip rect content_clip_rect = content_clip_rect.intersect(ui.clip_rect()); content_ui.set_clip_rect(content_clip_rect); } let viewport = Rect::from_min_size(Pos2::ZERO + state.offset, inner_size); let dt = ui.input(|i| i.stable_dt).at_most(0.1); let background_drag_response = if scroll_source.drag && ui.is_enabled() && state.content_is_too_large.any() { // Drag contents to scroll (for touch screens mostly). // We must do this BEFORE adding content to the `ScrollArea`, // or we will steal input from the widgets we contain. let content_response_option = state .interact_rect .map(|rect| ui.interact(rect, id.with("area"), Sense::drag())); if content_response_option .as_ref() .is_some_and(|response| response.dragged()) { for d in 0..2 { if direction_enabled[d] { ui.input(|input| { state.offset[d] -= input.pointer.delta()[d]; }); state.scroll_stuck_to_end[d] = false; state.offset_target[d] = None; } } } else { // Apply the cursor velocity to the scroll area when the user releases the drag. if content_response_option .as_ref() .is_some_and(|response| response.drag_stopped()) { state.vel = direction_enabled.to_vec2() * ui.input(|input| input.pointer.velocity()); } for d in 0..2 { // Kinetic scrolling let stop_speed = 20.0; // Pixels per second. let friction_coeff = 1000.0; // Pixels per second squared. let friction = friction_coeff * dt; if friction > state.vel[d].abs() || state.vel[d].abs() < stop_speed { state.vel[d] = 0.0; } else { state.vel[d] -= friction * state.vel[d].signum(); // Offset has an inverted coordinate system compared to // the velocity, so we subtract it instead of adding it state.offset[d] -= state.vel[d] * dt; ctx.request_repaint(); } } } // Set the desired mouse cursors. if let Some(response) = &content_response_option { if response.dragged() && let Some(cursor) = on_drag_cursor { ui.set_cursor_icon(cursor); } else if response.hovered() && let Some(cursor) = on_hover_cursor { ui.set_cursor_icon(cursor); } } content_response_option } else { None }; // Scroll with an animation if we have a target offset (that hasn't been cleared by the code // above). for d in 0..2 { if let Some(scroll_target) = state.offset_target[d] { state.vel[d] = 0.0; if (state.offset[d] - scroll_target.target_offset).abs() < 1.0 { // Arrived state.offset[d] = scroll_target.target_offset; state.offset_target[d] = None; } else { // Move towards target let t = emath::interpolation_factor( scroll_target.animation_time_span, ui.input(|i| i.time), dt, emath::ease_in_ease_out, ); if t < 1.0 { state.offset[d] = emath::lerp(state.offset[d]..=scroll_target.target_offset, t); ctx.request_repaint(); } else { // Arrived state.offset[d] = scroll_target.target_offset; state.offset_target[d] = None; } } } } let saved_scroll_target = content_ui .ctx() .pass_state_mut(|state| std::mem::take(&mut state.scroll_target)); Prepared { id, state, auto_shrink, direction_enabled, show_bars_factor, current_bar_use, scroll_bar_visibility, scroll_bar_rect, inner_rect, content_ui, viewport, scroll_source, wheel_scroll_multiplier, stick_to_end, saved_scroll_target, background_drag_response, animated, } } /// Show the [`ScrollArea`], and add the contents to the viewport. /// /// If the inner area can be very long, consider using [`Self::show_rows`] instead. pub fn show<R>( self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R, ) -> ScrollAreaOutput<R> { self.show_viewport_dyn(ui, Box::new(|ui, _viewport| add_contents(ui))) } /// Efficiently show only the visible part of a large number of rows. /// /// ``` /// # egui::__run_test_ui(|ui| { /// let text_style = egui::TextStyle::Body; /// let row_height = ui.text_style_height(&text_style); /// // let row_height = ui.spacing().interact_size.y; // if you are adding buttons instead of labels. /// let total_rows = 10_000; /// egui::ScrollArea::vertical().show_rows(ui, row_height, total_rows, |ui, row_range| { /// for row in row_range {
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/modal.rs
crates/egui/src/containers/modal.rs
use emath::{Align2, Vec2}; use crate::{ Area, Color32, Context, Frame, Id, InnerResponse, Order, Response, Sense, Ui, UiBuilder, UiKind, }; /// A modal dialog. /// /// Similar to a [`crate::Window`] but centered and with a backdrop that /// blocks input to the rest of the UI. /// /// You can show multiple modals on top of each other. The topmost modal will always be /// the most recently shown one. /// If multiple modals are newly shown in the same frame, the order of the modals is undefined /// (either first or second could be top). pub struct Modal { pub area: Area, pub backdrop_color: Color32, pub frame: Option<Frame>, } impl Modal { /// Create a new Modal. /// /// The id is passed to the area. pub fn new(id: Id) -> Self { Self { area: Self::default_area(id), backdrop_color: Color32::from_black_alpha(100), frame: None, } } /// Returns an area customized for a modal. /// /// Makes these changes to the default area: /// - sense: hover /// - anchor: center /// - order: foreground pub fn default_area(id: Id) -> Area { Area::new(id) .kind(UiKind::Modal) .sense(Sense::hover()) .anchor(Align2::CENTER_CENTER, Vec2::ZERO) .order(Order::Foreground) .interactable(true) } /// Set the frame of the modal. /// /// Default is [`Frame::popup`]. #[inline] pub fn frame(mut self, frame: Frame) -> Self { self.frame = Some(frame); self } /// Set the backdrop color of the modal. /// /// Default is `Color32::from_black_alpha(100)`. #[inline] pub fn backdrop_color(mut self, color: Color32) -> Self { self.backdrop_color = color; self } /// Set the area of the modal. /// /// Default is [`Modal::default_area`]. #[inline] pub fn area(mut self, area: Area) -> Self { self.area = area; self } /// Show the modal. pub fn show<T>(self, ctx: &Context, content: impl FnOnce(&mut Ui) -> T) -> ModalResponse<T> { let Self { area, backdrop_color, frame, } = self; let is_top_modal = ctx.memory_mut(|mem| { mem.set_modal_layer(area.layer()); mem.top_modal_layer() == Some(area.layer()) }); let any_popup_open = crate::Popup::is_any_open(ctx); let InnerResponse { inner: (inner, backdrop_response), response, } = area.show(ctx, |ui| { let bg_rect = ui.ctx().content_rect(); let bg_sense = Sense::CLICK | Sense::DRAG; let mut backdrop = ui.new_child(UiBuilder::new().sense(bg_sense).max_rect(bg_rect)); backdrop.set_min_size(bg_rect.size()); ui.painter().rect_filled(bg_rect, 0.0, backdrop_color); let backdrop_response = backdrop.response(); let frame = frame.unwrap_or_else(|| Frame::popup(ui.style())); // We need the extra scope with the sense since frame can't have a sense and since we // need to prevent the clicks from passing through to the backdrop. let inner = ui .scope_builder(UiBuilder::new().sense(Sense::CLICK | Sense::DRAG), |ui| { frame.show(ui, content).inner }) .inner; (inner, backdrop_response) }); ModalResponse { response, backdrop_response, inner, is_top_modal, any_popup_open, } } } /// The response of a modal dialog. pub struct ModalResponse<T> { /// The response of the modal contents pub response: Response, /// The response of the modal backdrop. /// /// A click on this means the user clicked outside the modal, /// in which case you might want to close the modal. pub backdrop_response: Response, /// The inner response from the content closure pub inner: T, /// Is this the topmost modal? pub is_top_modal: bool, /// Is there any popup open? /// We need to check this before the modal contents are shown, so we can know if any popup /// was open when checking if the escape key was clicked. pub any_popup_open: bool, } impl<T> ModalResponse<T> { /// Should the modal be closed? /// Returns true if: /// - the backdrop was clicked /// - this is the topmost modal, no popup is open and the escape key was pressed pub fn should_close(&self) -> bool { let ctx = &self.response.ctx; // this is a closure so that `Esc` is consumed only if the modal is topmost let escape_clicked = || ctx.input_mut(|i| i.consume_key(crate::Modifiers::NONE, crate::Key::Escape)); let ui_close_called = self.response.should_close(); self.backdrop_response.clicked() || ui_close_called || (self.is_top_modal && !self.any_popup_open && escape_clicked()) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/frame.rs
crates/egui/src/containers/frame.rs
//! Frame container use crate::{ InnerResponse, Response, Sense, Style, Ui, UiBuilder, UiKind, UiStackInfo, epaint, layers::ShapeIdx, }; use epaint::{Color32, CornerRadius, Margin, MarginF32, Rect, Shadow, Shape, Stroke}; /// A frame around some content, including margin, colors, etc. /// /// ## Definitions /// The total (outer) size of a frame is /// `content_size + inner_margin + 2 * stroke.width + outer_margin`. /// /// Everything within the stroke is filled with the fill color (if any). /// /// ```text /// +-----------------^-------------------------------------- -+ /// | | outer_margin | /// | +------------v----^------------------------------+ | /// | | | stroke width | | /// | | +------------v---^---------------------+ | | /// | | | | inner_margin | | | /// | | | +-----------v----------------+ | | | /// | | | | ^ | | | | /// | | | | | | | | | /// | | | |<------ content_size ------>| | | | /// | | | | | | | | | /// | | | | v | | | | /// | | | +------- content_rect -------+ | | | /// | | | | | | /// | | +-------------fill_rect ---------------+ | | /// | | | | /// | +----------------- widget_rect ------------------+ | /// | | /// +---------------------- outer_rect ------------------------+ /// ``` /// /// The four rectangles, from inside to outside, are: /// * `content_rect`: the rectangle that is made available to the inner [`Ui`] or widget. /// * `fill_rect`: the rectangle that is filled with the fill color (inside the stroke, if any). /// * `widget_rect`: is the interactive part of the widget (what sense clicks etc). /// * `outer_rect`: what is allocated in the outer [`Ui`], and is what is returned by [`Response::rect`]. /// /// ## Usage /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::Frame::NONE /// .fill(egui::Color32::RED) /// .show(ui, |ui| { /// ui.label("Label with red background"); /// }); /// # }); /// ``` /// /// ## Dynamic color /// If you want to change the color of the frame based on the response of /// the widget, you need to break it up into multiple steps: /// /// ``` /// # egui::__run_test_ui(|ui| { /// let mut frame = egui::Frame::default().inner_margin(4.0).begin(ui); /// { /// let response = frame.content_ui.label("Inside the frame"); /// if response.hovered() { /// frame.frame.fill = egui::Color32::RED; /// } /// } /// frame.end(ui); // Will "close" the frame. /// # }); /// ``` /// /// You can also respond to the hovering of the frame itself: /// /// ``` /// # egui::__run_test_ui(|ui| { /// let mut frame = egui::Frame::default().inner_margin(4.0).begin(ui); /// { /// frame.content_ui.label("Inside the frame"); /// frame.content_ui.label("This too"); /// } /// let response = frame.allocate_space(ui); /// if response.hovered() { /// frame.frame.fill = egui::Color32::RED; /// } /// frame.paint(ui); /// # }); /// ``` /// /// Note that you cannot change the margins after calling `begin`. #[doc(alias = "border")] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[must_use = "You should call .show()"] pub struct Frame { // Fields are ordered inside-out. // TODO(emilk): add `min_content_size: Vec2` // /// Margin within the painted frame. /// /// Known as `padding` in CSS. #[doc(alias = "padding")] pub inner_margin: Margin, /// The background fill color of the frame, within the [`Self::stroke`]. /// /// Known as `background` in CSS. #[doc(alias = "background")] pub fill: Color32, /// The width and color of the outline around the frame. /// /// The width of the stroke is part of the total margin/padding of the frame. #[doc(alias = "border")] pub stroke: Stroke, /// The rounding of the _outer_ corner of the [`Self::stroke`] /// (or, if there is no stroke, the outer corner of [`Self::fill`]). /// /// In other words, this is the corner radius of the _widget rect_. pub corner_radius: CornerRadius, /// Margin outside the painted frame. /// /// Similar to what is called `margin` in CSS. /// However, egui does NOT do "Margin Collapse" like in CSS, /// i.e. when placing two frames next to each other, /// the distance between their borders is the SUM /// of their other margins. /// In CSS the distance would be the MAX of their outer margins. /// Supporting margin collapse is difficult, and would /// requires complicating the already complicated egui layout code. /// /// Consider using [`crate::Spacing::item_spacing`] /// for adding space between widgets. pub outer_margin: Margin, /// Optional drop-shadow behind the frame. pub shadow: Shadow, } #[test] fn frame_size() { assert_eq!( std::mem::size_of::<Frame>(), 32, "Frame changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it." ); assert!( std::mem::size_of::<Frame>() <= 64, "Frame is getting way too big!" ); } /// ## Constructors impl Frame { /// No colors, no margins, no border. /// /// This is also the default. pub const NONE: Self = Self { inner_margin: Margin::ZERO, stroke: Stroke::NONE, fill: Color32::TRANSPARENT, corner_radius: CornerRadius::ZERO, outer_margin: Margin::ZERO, shadow: Shadow::NONE, }; /// No colors, no margins, no border. /// /// Same as [`Frame::NONE`]. pub const fn new() -> Self { Self::NONE } #[deprecated = "Use `Frame::NONE` or `Frame::new()` instead."] pub const fn none() -> Self { Self::NONE } /// For when you want to group a few widgets together within a frame. pub fn group(style: &Style) -> Self { Self::new() .inner_margin(6) .corner_radius(style.visuals.widgets.noninteractive.corner_radius) .stroke(style.visuals.widgets.noninteractive.bg_stroke) } pub fn side_top_panel(style: &Style) -> Self { Self::new() .inner_margin(Margin::symmetric(8, 2)) .fill(style.visuals.panel_fill) } pub fn central_panel(style: &Style) -> Self { Self::new().inner_margin(8).fill(style.visuals.panel_fill) } pub fn window(style: &Style) -> Self { Self::new() .inner_margin(style.spacing.window_margin) .corner_radius(style.visuals.window_corner_radius) .shadow(style.visuals.window_shadow) .fill(style.visuals.window_fill()) .stroke(style.visuals.window_stroke()) } pub fn menu(style: &Style) -> Self { Self::new() .inner_margin(style.spacing.menu_margin) .corner_radius(style.visuals.menu_corner_radius) .shadow(style.visuals.popup_shadow) .fill(style.visuals.window_fill()) .stroke(style.visuals.window_stroke()) } pub fn popup(style: &Style) -> Self { Self::new() .inner_margin(style.spacing.menu_margin) .corner_radius(style.visuals.menu_corner_radius) .shadow(style.visuals.popup_shadow) .fill(style.visuals.window_fill()) .stroke(style.visuals.window_stroke()) } /// A canvas to draw on. /// /// In bright mode this will be very bright, /// and in dark mode this will be very dark. pub fn canvas(style: &Style) -> Self { Self::new() .inner_margin(2) .corner_radius(style.visuals.widgets.noninteractive.corner_radius) .fill(style.visuals.extreme_bg_color) .stroke(style.visuals.window_stroke()) } /// A dark canvas to draw on. pub fn dark_canvas(style: &Style) -> Self { Self::canvas(style).fill(Color32::from_black_alpha(250)) } } /// ## Builders impl Frame { /// Margin within the painted frame. /// /// Known as `padding` in CSS. #[doc(alias = "padding")] #[inline] pub fn inner_margin(mut self, inner_margin: impl Into<Margin>) -> Self { self.inner_margin = inner_margin.into(); self } /// The background fill color of the frame, within the [`Self::stroke`]. /// /// Known as `background` in CSS. #[doc(alias = "background")] #[inline] pub fn fill(mut self, fill: Color32) -> Self { self.fill = fill; self } /// The width and color of the outline around the frame. /// /// The width of the stroke is part of the total margin/padding of the frame. #[inline] pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self { self.stroke = stroke.into(); self } /// The rounding of the _outer_ corner of the [`Self::stroke`] /// (or, if there is no stroke, the outer corner of [`Self::fill`]). /// /// In other words, this is the corner radius of the _widget rect_. #[inline] pub fn corner_radius(mut self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius = corner_radius.into(); self } /// The rounding of the _outer_ corner of the [`Self::stroke`] /// (or, if there is no stroke, the outer corner of [`Self::fill`]). /// /// In other words, this is the corner radius of the _widget rect_. #[inline] #[deprecated = "Renamed to `corner_radius`"] pub fn rounding(self, corner_radius: impl Into<CornerRadius>) -> Self { self.corner_radius(corner_radius) } /// Margin outside the painted frame. /// /// Similar to what is called `margin` in CSS. /// However, egui does NOT do "Margin Collapse" like in CSS, /// i.e. when placing two frames next to each other, /// the distance between their borders is the SUM /// of their other margins. /// In CSS the distance would be the MAX of their outer margins. /// Supporting margin collapse is difficult, and would /// requires complicating the already complicated egui layout code. /// /// Consider using [`crate::Spacing::item_spacing`] /// for adding space between widgets. #[inline] pub fn outer_margin(mut self, outer_margin: impl Into<Margin>) -> Self { self.outer_margin = outer_margin.into(); self } /// Optional drop-shadow behind the frame. #[inline] pub fn shadow(mut self, shadow: Shadow) -> Self { self.shadow = shadow; self } /// Opacity multiplier in gamma space. /// /// For instance, multiplying with `0.5` /// will make the frame half transparent. #[inline] pub fn multiply_with_opacity(mut self, opacity: f32) -> Self { self.fill = self.fill.gamma_multiply(opacity); self.stroke.color = self.stroke.color.gamma_multiply(opacity); self.shadow.color = self.shadow.color.gamma_multiply(opacity); self } } /// ## Inspectors impl Frame { /// How much extra space the frame uses up compared to the content. /// /// [`Self::inner_margin`] + [`Self::stroke`]`.width` + [`Self::outer_margin`]. #[inline] pub fn total_margin(&self) -> MarginF32 { MarginF32::from(self.inner_margin) + MarginF32::from(self.stroke.width) + MarginF32::from(self.outer_margin) } /// Calculate the `fill_rect` from the `content_rect`. /// /// This is the rectangle that is filled with the fill color (inside the stroke, if any). pub fn fill_rect(&self, content_rect: Rect) -> Rect { content_rect + self.inner_margin } /// Calculate the `widget_rect` from the `content_rect`. /// /// This is the visible and interactive rectangle. pub fn widget_rect(&self, content_rect: Rect) -> Rect { content_rect + self.inner_margin + MarginF32::from(self.stroke.width) } /// Calculate the `outer_rect` from the `content_rect`. /// /// This is what is allocated in the outer [`Ui`], and is what is returned by [`Response::rect`]. pub fn outer_rect(&self, content_rect: Rect) -> Rect { content_rect + self.inner_margin + MarginF32::from(self.stroke.width) + self.outer_margin } } // ---------------------------------------------------------------------------- pub struct Prepared { /// The frame that was prepared. /// /// The margin has already been read and used, /// but the rest of the fields may be modified. pub frame: Frame, /// This is where we will insert the frame shape so it ends up behind the content. where_to_put_background: ShapeIdx, /// Add your widgets to this UI so it ends up within the frame. pub content_ui: Ui, } impl Frame { /// Begin a dynamically colored frame. /// /// This is a more advanced API. /// Usually you want to use [`Self::show`] instead. /// /// See docs for [`Frame`] for an example. pub fn begin(self, ui: &mut Ui) -> Prepared { let where_to_put_background = ui.painter().add(Shape::Noop); let outer_rect_bounds = ui.available_rect_before_wrap(); let mut max_content_rect = outer_rect_bounds - self.total_margin(); // Make sure we don't shrink to the negative: max_content_rect.max.x = max_content_rect.max.x.max(max_content_rect.min.x); max_content_rect.max.y = max_content_rect.max.y.max(max_content_rect.min.y); let content_ui = ui.new_child( UiBuilder::new() .ui_stack_info(UiStackInfo::new(UiKind::Frame).with_frame(self)) .max_rect(max_content_rect), ); Prepared { frame: self, where_to_put_background, content_ui, } } /// Show the given ui surrounded by this frame. pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> { self.show_dyn(ui, Box::new(add_contents)) } /// Show using dynamic dispatch. pub fn show_dyn<'c, R>( self, ui: &mut Ui, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<R> { let mut prepared = self.begin(ui); let ret = add_contents(&mut prepared.content_ui); let response = prepared.end(ui); InnerResponse::new(ret, response) } /// Paint this frame as a shape. pub fn paint(&self, content_rect: Rect) -> Shape { let Self { inner_margin: _, fill, stroke, corner_radius, outer_margin: _, shadow, } = *self; let widget_rect = self.widget_rect(content_rect); let frame_shape = Shape::Rect(epaint::RectShape::new( widget_rect, corner_radius, fill, stroke, epaint::StrokeKind::Inside, )); if shadow == Default::default() { frame_shape } else { let shadow = shadow.as_shape(widget_rect, corner_radius); Shape::Vec(vec![Shape::from(shadow), frame_shape]) } } } impl Prepared { fn outer_rect(&self) -> Rect { let content_rect = self.content_ui.min_rect(); content_rect + self.frame.inner_margin + MarginF32::from(self.frame.stroke.width) + self.frame.outer_margin } /// Allocate the space that was used by [`Self::content_ui`]. /// /// This MUST be called, or the parent ui will not know how much space this widget used. /// /// This can be called before or after [`Self::paint`]. pub fn allocate_space(&self, ui: &mut Ui) -> Response { ui.allocate_rect(self.outer_rect(), Sense::hover()) } /// Paint the frame. /// /// This can be called before or after [`Self::allocate_space`]. pub fn paint(&self, ui: &Ui) { let content_rect = self.content_ui.min_rect(); let widget_rect = self.frame.widget_rect(content_rect); if ui.is_rect_visible(widget_rect) { let shape = self.frame.paint(content_rect); ui.painter().set(self.where_to_put_background, shape); } } /// Convenience for calling [`Self::allocate_space`] and [`Self::paint`]. /// /// Returns the outer rect, i.e. including the outer margin. pub fn end(self, ui: &mut Ui) -> Response { self.paint(ui); self.allocate_space(ui) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/collapsing_header.rs
crates/egui/src/containers/collapsing_header.rs
use std::hash::Hash; use crate::{ Context, Id, InnerResponse, NumExt as _, Rect, Response, Sense, Stroke, TextStyle, TextWrapMode, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, WidgetInfo, WidgetText, WidgetType, emath, epaint, pos2, remap, remap_clamp, vec2, }; use emath::GuiRounding as _; use epaint::{Shape, StrokeKind}; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct InnerState { open: bool, /// Height of the region when open. Used for animations #[cfg_attr(feature = "serde", serde(default))] open_height: Option<f32>, } /// This is a a building block for building collapsing regions. /// /// It is used by [`CollapsingHeader`] and [`crate::Window`], but can also be used on its own. /// /// See [`CollapsingState::show_header`] for how to show a collapsing header with a custom header. #[derive(Clone, Debug)] pub struct CollapsingState { id: Id, state: InnerState, } impl CollapsingState { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| { d.get_persisted::<InnerState>(id) .map(|state| Self { id, state }) }) } pub fn store(&self, ctx: &Context) { ctx.data_mut(|d| d.insert_persisted(self.id, self.state)); } pub fn remove(&self, ctx: &Context) { ctx.data_mut(|d| d.remove::<InnerState>(self.id)); } pub fn id(&self) -> Id { self.id } pub fn load_with_default_open(ctx: &Context, id: Id, default_open: bool) -> Self { Self::load(ctx, id).unwrap_or(Self { id, state: InnerState { open: default_open, open_height: None, }, }) } pub fn is_open(&self) -> bool { self.state.open } pub fn set_open(&mut self, open: bool) { self.state.open = open; } pub fn toggle(&mut self, ui: &Ui) { self.state.open = !self.state.open; ui.request_repaint(); } /// 0 for closed, 1 for open, with tweening pub fn openness(&self, ctx: &Context) -> f32 { if ctx.memory(|mem| mem.everything_is_visible()) { 1.0 } else { ctx.animate_bool_responsive(self.id, self.state.open) } } /// Will toggle when clicked, etc. pub(crate) fn show_default_button_with_size( &mut self, ui: &mut Ui, button_size: Vec2, ) -> Response { let (_id, rect) = ui.allocate_space(button_size); let response = ui.interact(rect, self.id, Sense::click()); response.widget_info(|| { WidgetInfo::labeled( WidgetType::Button, ui.is_enabled(), if self.is_open() { "Hide" } else { "Show" }, ) }); if response.clicked() { self.toggle(ui); } let openness = self.openness(ui.ctx()); paint_default_icon(ui, openness, &response); response } /// Will toggle when clicked, etc. fn show_default_button_indented(&mut self, ui: &mut Ui) -> Response { self.show_button_indented(ui, paint_default_icon) } /// Will toggle when clicked, etc. fn show_button_indented( &mut self, ui: &mut Ui, icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static, ) -> Response { let size = vec2(ui.spacing().indent, ui.spacing().icon_width); let (_id, rect) = ui.allocate_space(size); let response = ui.interact(rect, self.id, Sense::click()); if response.clicked() { self.toggle(ui); } let (mut icon_rect, _) = ui.spacing().icon_rectangles(response.rect); icon_rect.set_center(pos2( response.rect.left() + ui.spacing().indent / 2.0, response.rect.center().y, )); let openness = self.openness(ui.ctx()); let small_icon_response = response.clone().with_new_rect(icon_rect); icon_fn(ui, openness, &small_icon_response); response } /// Shows header and body (if expanded). /// /// The header will start with the default button in a horizontal layout, followed by whatever you add. /// /// Will also store the state. /// /// Returns the response of the collapsing button, the custom header, and the custom body. /// /// ``` /// # egui::__run_test_ui(|ui| { /// let id = ui.make_persistent_id("my_collapsing_header"); /// egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false) /// .show_header(ui, |ui| { /// ui.label("Header"); // you can put checkboxes or whatever here /// }) /// .body(|ui| ui.label("Body")); /// # }); /// ``` pub fn show_header<HeaderRet>( mut self, ui: &mut Ui, add_header: impl FnOnce(&mut Ui) -> HeaderRet, ) -> HeaderResponse<'_, HeaderRet> { let header_response = ui.horizontal(|ui| { let prev_item_spacing = ui.spacing_mut().item_spacing; ui.spacing_mut().item_spacing.x = 0.0; // the toggler button uses the full indent width let collapser = self.show_default_button_indented(ui); ui.spacing_mut().item_spacing = prev_item_spacing; (collapser, add_header(ui)) }); HeaderResponse { state: self, ui, toggle_button_response: header_response.inner.0, header_response: InnerResponse { response: header_response.response, inner: header_response.inner.1, }, } } /// Show body if we are open, with a nice animation between closed and open. /// Indent the body to show it belongs to the header. /// /// Will also store the state. pub fn show_body_indented<R>( &mut self, header_response: &Response, ui: &mut Ui, add_body: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { let id = self.id; self.show_body_unindented(ui, |ui| { ui.indent(id, |ui| { // make as wide as the header: ui.expand_to_include_x(header_response.rect.right()); add_body(ui) }) .inner }) } /// Show body if we are open, with a nice animation between closed and open. /// Will also store the state. pub fn show_body_unindented<R>( &mut self, ui: &mut Ui, add_body: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { let openness = self.openness(ui.ctx()); let builder = UiBuilder::new() .ui_stack_info(UiStackInfo::new(UiKind::Collapsible)) .closable(); if openness <= 0.0 { self.store(ui.ctx()); // we store any earlier toggling as promised in the docstring None } else if openness < 1.0 { Some(ui.scope_builder(builder, |child_ui| { let max_height = if self.state.open && self.state.open_height.is_none() { // First frame of expansion. // We don't know full height yet, but we will next frame. // Just use a placeholder value that shows some movement: 10.0 } else { let full_height = self.state.open_height.unwrap_or_default(); remap_clamp(openness, 0.0..=1.0, 0.0..=full_height).round_ui() }; let mut clip_rect = child_ui.clip_rect(); clip_rect.max.y = clip_rect.max.y.min(child_ui.max_rect().top() + max_height); child_ui.set_clip_rect(clip_rect); let ret = add_body(child_ui); let mut min_rect = child_ui.min_rect(); self.state.open_height = Some(min_rect.height()); if child_ui.should_close() { self.state.open = false; } self.store(child_ui.ctx()); // remember the height // Pretend children took up at most `max_height` space: min_rect.max.y = min_rect.max.y.at_most(min_rect.top() + max_height); child_ui.force_set_min_rect(min_rect); ret })) } else { let ret_response = ui.scope_builder(builder, add_body); if ret_response.response.should_close() { self.state.open = false; } let full_size = ret_response.response.rect.size(); self.state.open_height = Some(full_size.y); self.store(ui.ctx()); // remember the height Some(ret_response) } } /// Paint this [`CollapsingState`]'s toggle button. Takes an [`IconPainter`] as the icon. /// ``` /// # egui::__run_test_ui(|ui| { /// fn circle_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) { /// let stroke = ui.style().interact(&response).fg_stroke; /// let radius = egui::lerp(2.0..=3.0, openness); /// ui.painter().circle_filled(response.rect.center(), radius, stroke.color); /// } /// /// let mut state = egui::collapsing_header::CollapsingState::load_with_default_open( /// ui.ctx(), /// ui.make_persistent_id("my_collapsing_state"), /// false, /// ); /// /// let header_res = ui.horizontal(|ui| { /// ui.label("Header"); /// state.show_toggle_button(ui, circle_icon); /// }); /// /// state.show_body_indented(&header_res.response, ui, |ui| ui.label("Body")); /// # }); /// ``` pub fn show_toggle_button( &mut self, ui: &mut Ui, icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static, ) -> Response { self.show_button_indented(ui, icon_fn) } } /// From [`CollapsingState::show_header`]. #[must_use = "Remember to show the body"] pub struct HeaderResponse<'ui, HeaderRet> { state: CollapsingState, ui: &'ui mut Ui, toggle_button_response: Response, header_response: InnerResponse<HeaderRet>, } impl<HeaderRet> HeaderResponse<'_, HeaderRet> { pub fn is_open(&self) -> bool { self.state.is_open() } pub fn set_open(&mut self, open: bool) { self.state.set_open(open); } pub fn toggle(&mut self) { self.state.toggle(self.ui); } /// Returns the response of the collapsing button, the custom header, and the custom body. pub fn body<BodyRet>( mut self, add_body: impl FnOnce(&mut Ui) -> BodyRet, ) -> ( Response, InnerResponse<HeaderRet>, Option<InnerResponse<BodyRet>>, ) { let body_response = self.state .show_body_indented(&self.header_response.response, self.ui, add_body); ( self.toggle_button_response, self.header_response, body_response, ) } /// Returns the response of the collapsing button, the custom header, and the custom body, without indentation. pub fn body_unindented<BodyRet>( mut self, add_body: impl FnOnce(&mut Ui) -> BodyRet, ) -> ( Response, InnerResponse<HeaderRet>, Option<InnerResponse<BodyRet>>, ) { let body_response = self.state.show_body_unindented(self.ui, add_body); ( self.toggle_button_response, self.header_response, body_response, ) } } // ---------------------------------------------------------------------------- /// Paint the arrow icon that indicated if the region is open or not pub fn paint_default_icon(ui: &mut Ui, openness: f32, response: &Response) { let visuals = ui.style().interact(response); let rect = response.rect; // Draw a pointy triangle arrow: let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height()) * 0.75); let rect = rect.expand(visuals.expansion); let mut points = vec![rect.left_top(), rect.right_top(), rect.center_bottom()]; use std::f32::consts::TAU; let rotation = emath::Rot2::from_angle(remap(openness, 0.0..=1.0, -TAU / 4.0..=0.0)); for p in &mut points { *p = rect.center() + rotation * (*p - rect.center()); } ui.painter().add(Shape::convex_polygon( points, visuals.fg_stroke.color, Stroke::NONE, )); } /// A function that paints an icon indicating if the region is open or not pub type IconPainter = Box<dyn FnOnce(&mut Ui, f32, &Response)>; /// A header which can be collapsed/expanded, revealing a contained [`Ui`] region. /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::CollapsingHeader::new("Heading") /// .show(ui, |ui| { /// ui.label("Body"); /// }); /// /// // Short version: /// ui.collapsing("Heading", |ui| { ui.label("Body"); }); /// # }); /// ``` /// /// If you want to customize the header contents, see [`CollapsingState::show_header`]. #[must_use = "You should call .show()"] pub struct CollapsingHeader { text: WidgetText, default_open: bool, open: Option<bool>, id_salt: Id, enabled: bool, selectable: bool, selected: bool, show_background: bool, icon: Option<IconPainter>, } impl CollapsingHeader { /// The [`CollapsingHeader`] starts out collapsed unless you call `default_open`. /// /// The label is used as an [`Id`] source. /// If the label is unique and static this is fine, /// but if it changes or there are several [`CollapsingHeader`] with the same title /// you need to provide a unique id source with [`Self::id_salt`]. pub fn new(text: impl Into<WidgetText>) -> Self { let text = text.into(); let id_salt = Id::new(text.text()); Self { text, default_open: false, open: None, id_salt, enabled: true, selectable: false, selected: false, show_background: false, icon: None, } } /// By default, the [`CollapsingHeader`] is collapsed. /// Call `.default_open(true)` to change this. #[inline] pub fn default_open(mut self, open: bool) -> Self { self.default_open = open; self } /// Calling `.open(Some(true))` will make the collapsing header open this frame (or stay open). /// /// Calling `.open(Some(false))` will make the collapsing header close this frame (or stay closed). /// /// Calling `.open(None)` has no effect (default). #[inline] pub fn open(mut self, open: Option<bool>) -> Self { self.open = open; self } /// Explicitly set the source of the [`Id`] of this widget, instead of using title label. /// This is useful if the title label is dynamic or not unique. #[inline] pub fn id_salt(mut self, id_salt: impl Hash) -> Self { self.id_salt = Id::new(id_salt); self } /// Explicitly set the source of the [`Id`] of this widget, instead of using title label. /// This is useful if the title label is dynamic or not unique. #[deprecated = "Renamed id_salt"] #[inline] pub fn id_source(mut self, id_salt: impl Hash) -> Self { self.id_salt = Id::new(id_salt); self } /// If you set this to `false`, the [`CollapsingHeader`] will be grayed out and un-clickable. /// /// This is a convenience for [`Ui::disable`]. #[inline] pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; self } /// Should the [`CollapsingHeader`] show a background behind it? Default: `false`. /// /// To show it behind all [`CollapsingHeader`] you can just use: /// ``` /// # egui::__run_test_ui(|ui| { /// ui.visuals_mut().collapsing_header_frame = true; /// # }); /// ``` #[inline] pub fn show_background(mut self, show_background: bool) -> Self { self.show_background = show_background; self } /// Use the provided function to render a different [`CollapsingHeader`] icon. /// Defaults to a triangle that animates as the [`CollapsingHeader`] opens and closes. /// /// For example: /// ``` /// # egui::__run_test_ui(|ui| { /// fn circle_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) { /// let stroke = ui.style().interact(&response).fg_stroke; /// let radius = egui::lerp(2.0..=3.0, openness); /// ui.painter().circle_filled(response.rect.center(), radius, stroke.color); /// } /// /// egui::CollapsingHeader::new("Circles") /// .icon(circle_icon) /// .show(ui, |ui| { ui.label("Hi!"); }); /// # }); /// ``` #[inline] pub fn icon(mut self, icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static) -> Self { self.icon = Some(Box::new(icon_fn)); self } } struct Prepared { header_response: Response, state: CollapsingState, openness: f32, } impl CollapsingHeader { fn begin(self, ui: &mut Ui) -> Prepared { assert!( ui.layout().main_dir().is_vertical(), "Horizontal collapsing is unimplemented" ); let Self { icon, text, default_open, open, id_salt, enabled: _, selectable, selected, show_background, } = self; // TODO(emilk): horizontal layout, with icon and text as labels. Insert background behind using Frame. let id = ui.make_persistent_id(id_salt); let button_padding = ui.spacing().button_padding; let available = ui.available_rect_before_wrap(); let text_pos = available.min + vec2(ui.spacing().indent, 0.0); let wrap_width = available.right() - text_pos.x; let galley = text.into_galley( ui, Some(TextWrapMode::Extend), wrap_width, TextStyle::Button, ); let text_max_x = text_pos.x + galley.size().x; let mut desired_width = text_max_x + button_padding.x - available.left(); if ui.visuals().collapsing_header_frame { desired_width = desired_width.max(available.width()); // fill full width } let mut desired_size = vec2(desired_width, galley.size().y + 2.0 * button_padding.y); desired_size = desired_size.at_least(ui.spacing().interact_size); let (_, rect) = ui.allocate_space(desired_size); let mut header_response = ui.interact(rect, id, Sense::click()); let text_pos = pos2( text_pos.x, header_response.rect.center().y - galley.size().y / 2.0, ); let mut state = CollapsingState::load_with_default_open(ui.ctx(), id, default_open); if let Some(open) = open { if open != state.is_open() { state.toggle(ui); header_response.mark_changed(); } } else if header_response.clicked() { state.toggle(ui); header_response.mark_changed(); } header_response.widget_info(|| { WidgetInfo::labeled(WidgetType::CollapsingHeader, ui.is_enabled(), galley.text()) }); let openness = state.openness(ui.ctx()); if ui.is_rect_visible(rect) { let visuals = ui.style().interact_selectable(&header_response, selected); if ui.visuals().collapsing_header_frame || show_background { ui.painter().add(epaint::RectShape::new( header_response.rect.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, StrokeKind::Inside, )); } if selected || selectable && (header_response.hovered() || header_response.has_focus()) { let rect = rect.expand(visuals.expansion); ui.painter().rect( rect, visuals.corner_radius, visuals.bg_fill, visuals.bg_stroke, StrokeKind::Inside, ); } { let (mut icon_rect, _) = ui.spacing().icon_rectangles(header_response.rect); icon_rect.set_center(pos2( header_response.rect.left() + ui.spacing().indent / 2.0, header_response.rect.center().y, )); let icon_response = header_response.clone().with_new_rect(icon_rect); if let Some(icon) = icon { icon(ui, openness, &icon_response); } else { paint_default_icon(ui, openness, &icon_response); } } ui.painter().galley(text_pos, galley, visuals.text_color()); } Prepared { header_response, state, openness, } } #[inline] pub fn show<R>( self, ui: &mut Ui, add_body: impl FnOnce(&mut Ui) -> R, ) -> CollapsingResponse<R> { self.show_dyn(ui, Box::new(add_body), true) } #[inline] pub fn show_unindented<R>( self, ui: &mut Ui, add_body: impl FnOnce(&mut Ui) -> R, ) -> CollapsingResponse<R> { self.show_dyn(ui, Box::new(add_body), false) } fn show_dyn<'c, R>( self, ui: &mut Ui, add_body: Box<dyn FnOnce(&mut Ui) -> R + 'c>, indented: bool, ) -> CollapsingResponse<R> { // Make sure body is bellow header, // and make sure it is one unit (necessary for putting a [`CollapsingHeader`] in a grid). ui.vertical(|ui| { if !self.enabled { ui.disable(); } let Prepared { header_response, mut state, openness, } = self.begin(ui); // show the header let ret_response = if indented { state.show_body_indented(&header_response, ui, add_body) } else { state.show_body_unindented(ui, add_body) }; if let Some(ret_response) = ret_response { CollapsingResponse { header_response, body_response: Some(ret_response.response), body_returned: Some(ret_response.inner), openness, } } else { CollapsingResponse { header_response, body_response: None, body_returned: None, openness, } } }) .inner } } /// The response from showing a [`CollapsingHeader`]. pub struct CollapsingResponse<R> { /// Response of the actual clickable header. pub header_response: Response, /// None iff collapsed. pub body_response: Option<Response>, /// None iff collapsed. pub body_returned: Option<R>, /// 0.0 if fully closed, 1.0 if fully open, and something in-between while animating. pub openness: f32, } impl<R> CollapsingResponse<R> { /// Was the [`CollapsingHeader`] fully closed (and not being animated)? pub fn fully_closed(&self) -> bool { self.openness <= 0.0 } /// Was the [`CollapsingHeader`] fully open (and not being animated)? pub fn fully_open(&self) -> bool { self.openness >= 1.0 } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/panel.rs
crates/egui/src/containers/panel.rs
//! Panels are [`Ui`] regions taking up e.g. the left side of a [`Ui`] or screen. //! //! Panels can either be a child of a [`Ui`] (taking up a portion of the parent) //! or be top-level (taking up a portion of the whole screen). //! //! Together with [`crate::Window`] and [`crate::Area`]:s, top-level panels are //! the only places where you can put you widgets. //! //! The order in which you add panels matter! //! The first panel you add will always be the outermost, and the last you add will always be the innermost. //! //! You must never open one top-level panel from within another panel. Add one panel, then the next. //! //! ⚠ Always add any [`CentralPanel`] last. //! //! Add your [`crate::Window`]:s after any top-level panels. use emath::{GuiRounding as _, Pos2}; use crate::{ Align, Context, CursorIcon, Frame, Id, InnerResponse, LayerId, Layout, NumExt as _, Rangef, Rect, Sense, Stroke, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, WidgetInfo, WidgetType, lerp, vec2, }; fn animate_expansion(ctx: &Context, id: Id, is_expanded: bool) -> f32 { ctx.animate_bool_responsive(id, is_expanded) } /// State regarding panels. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct PanelState { pub rect: Rect, } impl PanelState { pub fn load(ctx: &Context, bar_id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_persisted(bar_id)) } /// The size of the panel (from previous frame). pub fn size(&self) -> Vec2 { self.rect.size() } fn store(self, ctx: &Context, bar_id: Id) { ctx.data_mut(|d| d.insert_persisted(bar_id, self)); } } // ---------------------------------------------------------------------------- /// [`Left`](VerticalSide::Left) or [`Right`](VerticalSide::Right) #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum VerticalSide { Left, Right, } impl VerticalSide { pub fn opposite(self) -> Self { match self { Self::Left => Self::Right, Self::Right => Self::Left, } } /// `self` is the _fixed_ side. /// /// * Left panels are resized on their right side /// * Right panels are resized on their left side fn set_rect_width(self, rect: &mut Rect, width: f32) { match self { Self::Left => rect.max.x = rect.min.x + width, Self::Right => rect.min.x = rect.max.x - width, } } fn sign(self) -> f32 { match self { Self::Left => -1.0, Self::Right => 1.0, } } fn side_x(self, rect: Rect) -> f32 { match self { Self::Left => rect.left(), Self::Right => rect.right(), } } } /// [`Top`](HorizontalSide::Top) or [`Bottom`](HorizontalSide::Bottom) #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum HorizontalSide { Top, Bottom, } impl HorizontalSide { pub fn opposite(self) -> Self { match self { Self::Top => Self::Bottom, Self::Bottom => Self::Top, } } /// `self` is the _fixed_ side. /// /// * Top panels are resized on their bottom side /// * Bottom panels are resized upwards fn set_rect_height(self, rect: &mut Rect, height: f32) { match self { Self::Top => rect.max.y = rect.min.y + height, Self::Bottom => rect.min.y = rect.max.y - height, } } fn sign(self) -> f32 { match self { Self::Top => -1.0, Self::Bottom => 1.0, } } fn side_y(self, rect: Rect) -> f32 { match self { Self::Top => rect.top(), Self::Bottom => rect.bottom(), } } } // Intentionally private because I'm not sure of the naming. // TODO(emilk): decide on good names and make public. // "VerticalSide" and "HorizontalSide" feels inverted to me. /// [`Horizontal`](PanelSide::Horizontal) or [`Vertical`](PanelSide::Vertical) #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PanelSide { /// Left or right. Vertical(VerticalSide), /// Top or bottom Horizontal(HorizontalSide), } impl From<HorizontalSide> for PanelSide { fn from(side: HorizontalSide) -> Self { Self::Horizontal(side) } } impl From<VerticalSide> for PanelSide { fn from(side: VerticalSide) -> Self { Self::Vertical(side) } } impl PanelSide { pub const LEFT: Self = Self::Vertical(VerticalSide::Left); pub const RIGHT: Self = Self::Vertical(VerticalSide::Right); pub const TOP: Self = Self::Horizontal(HorizontalSide::Top); pub const BOTTOM: Self = Self::Horizontal(HorizontalSide::Bottom); /// Resize by keeping the [`self`] side fixed, and moving the opposite side. fn set_rect_size(self, rect: &mut Rect, size: f32) { match self { Self::Vertical(side) => side.set_rect_width(rect, size), Self::Horizontal(side) => side.set_rect_height(rect, size), } } fn ui_kind(self) -> UiKind { match self { Self::Vertical(side) => match side { VerticalSide::Left => UiKind::LeftPanel, VerticalSide::Right => UiKind::RightPanel, }, Self::Horizontal(side) => match side { HorizontalSide::Top => UiKind::TopPanel, HorizontalSide::Bottom => UiKind::BottomPanel, }, } } } // ---------------------------------------------------------------------------- /// Intermediate structure to abstract some portion of [`Panel::show_inside`](Panel::show_inside). struct PanelSizer<'a> { panel: &'a Panel, frame: Frame, available_rect: Rect, size: f32, panel_rect: Rect, } impl<'a> PanelSizer<'a> { fn new(panel: &'a Panel, ui: &Ui) -> Self { let frame = panel .frame .unwrap_or_else(|| Frame::side_top_panel(ui.style())); let available_rect = ui.available_rect_before_wrap(); let size = PanelSizer::get_size_from_state_or_default(panel, ui, frame); let panel_rect = PanelSizer::panel_rect(panel, available_rect, size); Self { panel, frame, available_rect, size, panel_rect, } } fn get_size_from_state_or_default(panel: &Panel, ui: &Ui, frame: Frame) -> f32 { if let Some(state) = PanelState::load(ui.ctx(), panel.id) { match panel.side { PanelSide::Vertical(_) => state.rect.width(), PanelSide::Horizontal(_) => state.rect.height(), } } else { match panel.side { PanelSide::Vertical(_) => panel.default_size.unwrap_or_else(|| { ui.style().spacing.interact_size.x + frame.inner_margin.sum().x }), PanelSide::Horizontal(_) => panel.default_size.unwrap_or_else(|| { ui.style().spacing.interact_size.y + frame.inner_margin.sum().y }), } } } fn panel_rect(panel: &Panel, available_rect: Rect, mut size: f32) -> Rect { let side = panel.side; let size_range = panel.size_range; let mut panel_rect = available_rect; match side { PanelSide::Vertical(_) => { size = clamp_to_range(size, size_range).at_most(available_rect.width()); } PanelSide::Horizontal(_) => { size = clamp_to_range(size, size_range).at_most(available_rect.height()); } } side.set_rect_size(&mut panel_rect, size); panel_rect } fn prepare_resizing_response(&mut self, is_resizing: bool, pointer: Option<Pos2>) { let side = self.panel.side; let size_range = self.panel.size_range; if is_resizing && let Some(pointer) = pointer { match side { PanelSide::Vertical(side) => { self.size = (pointer.x - side.side_x(self.panel_rect)).abs(); self.size = clamp_to_range(self.size, size_range).at_most(self.available_rect.width()); } PanelSide::Horizontal(side) => { self.size = (pointer.y - side.side_y(self.panel_rect)).abs(); self.size = clamp_to_range(self.size, size_range).at_most(self.available_rect.height()); } } side.set_rect_size(&mut self.panel_rect, self.size); } } } // ---------------------------------------------------------------------------- /// A panel that covers an entire side /// ([`left`](Panel::left), [`right`](Panel::right), /// [`top`](Panel::top) or [`bottom`](Panel::bottom)) /// of a [`Ui`] or screen. /// /// The order in which you add panels matter! /// The first panel you add will always be the outermost, and the last you add will always be the innermost. /// /// ⚠ Always add any [`CentralPanel`] last. /// /// See the [module level docs](crate::containers::panel) for more details. /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::Panel::left("my_left_panel").show_inside(ui, |ui| { /// ui.label("Hello World!"); /// }); /// # }); /// ``` #[must_use = "You should call .show_inside()"] pub struct Panel { side: PanelSide, id: Id, frame: Option<Frame>, resizable: bool, show_separator_line: bool, /// The size is defined as being either the width for a Vertical Panel /// or the height for a Horizontal Panel. default_size: Option<f32>, /// The size is defined as being either the width for a Vertical Panel /// or the height for a Horizontal Panel. size_range: Rangef, } impl Panel { /// Create a left panel. /// /// The id should be globally unique, e.g. `Id::new("my_left_panel")`. pub fn left(id: impl Into<Id>) -> Self { Self::new(PanelSide::LEFT, id) } /// Create a right panel. /// /// The id should be globally unique, e.g. `Id::new("my_right_panel")`. pub fn right(id: impl Into<Id>) -> Self { Self::new(PanelSide::RIGHT, id) } /// Create a top panel. /// /// The id should be globally unique, e.g. `Id::new("my_top_panel")`. /// /// By default this is NOT resizable. pub fn top(id: impl Into<Id>) -> Self { Self::new(PanelSide::TOP, id).resizable(false) } /// Create a bottom panel. /// /// The id should be globally unique, e.g. `Id::new("my_bottom_panel")`. /// /// By default this is NOT resizable. pub fn bottom(id: impl Into<Id>) -> Self { Self::new(PanelSide::BOTTOM, id).resizable(false) } /// Create a panel. /// /// The id should be globally unique, e.g. `Id::new("my_panel")`. fn new(side: PanelSide, id: impl Into<Id>) -> Self { let default_size: Option<f32> = match side { PanelSide::Vertical(_) => Some(200.0), PanelSide::Horizontal(_) => None, }; let size_range: Rangef = match side { PanelSide::Vertical(_) => Rangef::new(96.0, f32::INFINITY), PanelSide::Horizontal(_) => Rangef::new(20.0, f32::INFINITY), }; Self { side, id: id.into(), frame: None, resizable: true, show_separator_line: true, default_size, size_range, } } /// Can panel be resized by dragging the edge of it? /// /// Default is `true`. /// /// If you want your panel to be resizable you also need to make the ui use /// the available space. /// /// This can be done by using [`Ui::take_available_space`], or using a /// widget in it that takes up more space as you resize it, such as: /// * Wrapping text ([`Ui::horizontal_wrapped`]). /// * A [`crate::ScrollArea`]. /// * A [`crate::Separator`]. /// * A [`crate::TextEdit`]. /// * … #[inline] pub fn resizable(mut self, resizable: bool) -> Self { self.resizable = resizable; self } /// Show a separator line, even when not interacting with it? /// /// Default: `true`. #[inline] pub fn show_separator_line(mut self, show_separator_line: bool) -> Self { self.show_separator_line = show_separator_line; self } /// The initial wrapping width of the [`Panel`], including margins. #[inline] pub fn default_size(mut self, default_size: f32) -> Self { self.default_size = Some(default_size); self.size_range = Rangef::new( self.size_range.min.at_most(default_size), self.size_range.max.at_least(default_size), ); self } /// Minimum size of the panel, including margins. #[inline] pub fn min_size(mut self, min_size: f32) -> Self { self.size_range = Rangef::new(min_size, self.size_range.max.at_least(min_size)); self } /// Maximum size of the panel, including margins. #[inline] pub fn max_size(mut self, max_size: f32) -> Self { self.size_range = Rangef::new(self.size_range.min.at_most(max_size), max_size); self } /// The allowable size range for the panel, including margins. #[inline] pub fn size_range(mut self, size_range: impl Into<Rangef>) -> Self { let size_range = size_range.into(); self.default_size = self .default_size .map(|default_size| clamp_to_range(default_size, size_range)); self.size_range = size_range; self } /// Enforce this exact size, including margins. #[inline] pub fn exact_size(mut self, size: f32) -> Self { self.default_size = Some(size); self.size_range = Rangef::point(size); self } /// Change the background color, margins, etc. #[inline] pub fn frame(mut self, frame: Frame) -> Self { self.frame = Some(frame); self } } // Deprecated impl Panel { #[deprecated = "Renamed default_size"] pub fn default_width(self, default_size: f32) -> Self { self.default_size(default_size) } #[deprecated = "Renamed min_size"] pub fn min_width(self, min_size: f32) -> Self { self.min_size(min_size) } #[deprecated = "Renamed max_size"] pub fn max_width(self, max_size: f32) -> Self { self.max_size(max_size) } #[deprecated = "Renamed size_range"] pub fn width_range(self, size_range: impl Into<Rangef>) -> Self { self.size_range(size_range) } #[deprecated = "Renamed exact_size"] pub fn exact_width(self, size: f32) -> Self { self.exact_size(size) } #[deprecated = "Renamed default_size"] pub fn default_height(self, default_size: f32) -> Self { self.default_size(default_size) } #[deprecated = "Renamed min_size"] pub fn min_height(self, min_size: f32) -> Self { self.min_size(min_size) } #[deprecated = "Renamed max_size"] pub fn max_height(self, max_size: f32) -> Self { self.max_size(max_size) } #[deprecated = "Renamed size_range"] pub fn height_range(self, size_range: impl Into<Rangef>) -> Self { self.size_range(size_range) } #[deprecated = "Renamed exact_size"] pub fn exact_height(self, size: f32) -> Self { self.exact_size(size) } } // Public showing methods impl Panel { /// Show the panel inside a [`Ui`]. pub fn show_inside<R>( self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<R> { self.show_inside_dyn(ui, Box::new(add_contents)) } /// Show the panel at the top level. #[deprecated = "Use show_inside() instead"] pub fn show<R>( self, ctx: &Context, add_contents: impl FnOnce(&mut Ui) -> R, ) -> InnerResponse<R> { self.show_dyn(ctx, Box::new(add_contents)) } /// Show the panel if `is_expanded` is `true`, /// otherwise don't show it, but with a nice animation between collapsed and expanded. #[deprecated = "Use show_animated_inside() instead"] pub fn show_animated<R>( self, ctx: &Context, is_expanded: bool, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { #![expect(deprecated)] let how_expanded = animate_expansion(ctx, self.id.with("animation"), is_expanded); let animated_panel = self.get_animated_panel(ctx, is_expanded)?; if how_expanded < 1.0 { // Show a fake panel in this in-between animation state: animated_panel.show(ctx, |_ui| {}); None } else { // Show the real panel: Some(animated_panel.show(ctx, add_contents)) } } /// Show the panel if `is_expanded` is `true`, /// otherwise don't show it, but with a nice animation between collapsed and expanded. pub fn show_animated_inside<R>( self, ui: &mut Ui, is_expanded: bool, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<InnerResponse<R>> { let how_expanded = animate_expansion(ui.ctx(), self.id.with("animation"), is_expanded); // Get either the fake or the real panel to animate let animated_panel = self.get_animated_panel(ui.ctx(), is_expanded)?; if how_expanded < 1.0 { // Show a fake panel in this in-between animation state: animated_panel.show_inside(ui, |_ui| {}); None } else { // Show the real panel: Some(animated_panel.show_inside(ui, add_contents)) } } /// Show either a collapsed or a expanded panel, with a nice animation between. #[deprecated = "Use show_animated_between_inside() instead"] pub fn show_animated_between<R>( ctx: &Context, is_expanded: bool, collapsed_panel: Self, expanded_panel: Self, add_contents: impl FnOnce(&mut Ui, f32) -> R, ) -> Option<InnerResponse<R>> { #![expect(deprecated)] let how_expanded = animate_expansion(ctx, expanded_panel.id.with("animation"), is_expanded); // Get either the fake or the real panel to animate let animated_between_panel = Self::get_animated_between_panel(ctx, is_expanded, collapsed_panel, expanded_panel); if 0.0 == how_expanded { Some(animated_between_panel.show(ctx, |ui| add_contents(ui, how_expanded))) } else if how_expanded < 1.0 { // Show animation: animated_between_panel.show(ctx, |ui| add_contents(ui, how_expanded)); None } else { Some(animated_between_panel.show(ctx, |ui| add_contents(ui, how_expanded))) } } /// Show either a collapsed or a expanded panel, with a nice animation between. pub fn show_animated_between_inside<R>( ui: &mut Ui, is_expanded: bool, collapsed_panel: Self, expanded_panel: Self, add_contents: impl FnOnce(&mut Ui, f32) -> R, ) -> InnerResponse<R> { let how_expanded = animate_expansion(ui.ctx(), expanded_panel.id.with("animation"), is_expanded); let animated_between_panel = Self::get_animated_between_panel( ui.ctx(), is_expanded, collapsed_panel, expanded_panel, ); if 0.0 == how_expanded { animated_between_panel.show_inside(ui, |ui| add_contents(ui, how_expanded)) } else if how_expanded < 1.0 { // Show animation: animated_between_panel.show_inside(ui, |ui| add_contents(ui, how_expanded)) } else { animated_between_panel.show_inside(ui, |ui| add_contents(ui, how_expanded)) } } } // Private methods to support the various show methods impl Panel { /// Show the panel inside a [`Ui`]. fn show_inside_dyn<'c, R>( self, ui: &mut Ui, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<R> { let side = self.side; let id = self.id; let resizable = self.resizable; let show_separator_line = self.show_separator_line; let size_range = self.size_range; // Define the sizing of the panel. let mut panel_sizer = PanelSizer::new(&self, ui); // Check for duplicate id ui.ctx() .check_for_id_clash(id, panel_sizer.panel_rect, "Panel"); if self.resizable { // Prepare the resizable panel to avoid frame latency in the resize self.prepare_resizable_panel(&mut panel_sizer, ui); } // NOTE(shark98): This must be **after** the resizable preparation, as the size // may change and round_ui() uses the size. panel_sizer.panel_rect = panel_sizer.panel_rect.round_ui(); let mut panel_ui = ui.new_child( UiBuilder::new() .id_salt(id) .ui_stack_info(UiStackInfo::new(side.ui_kind())) .max_rect(panel_sizer.panel_rect) .layout(Layout::top_down(Align::Min)), ); panel_ui.expand_to_include_rect(panel_sizer.panel_rect); panel_ui.set_clip_rect(panel_sizer.panel_rect); // If we overflow, don't do so visibly (#4475) let inner_response = panel_sizer.frame.show(&mut panel_ui, |ui| { match side { PanelSide::Vertical(_) => { ui.set_min_height(ui.max_rect().height()); // Make sure the frame fills the full height ui.set_min_width( (size_range.min - panel_sizer.frame.inner_margin.sum().x).at_least(0.0), ); } PanelSide::Horizontal(_) => { ui.set_min_width(ui.max_rect().width()); // Make the frame fill full width ui.set_min_height( (size_range.min - panel_sizer.frame.inner_margin.sum().y).at_least(0.0), ); } } add_contents(ui) }); let rect = inner_response.response.rect; { let mut cursor = ui.cursor(); match side { PanelSide::Vertical(side) => match side { VerticalSide::Left => cursor.min.x = rect.max.x, VerticalSide::Right => cursor.max.x = rect.min.x, }, PanelSide::Horizontal(side) => match side { HorizontalSide::Top => cursor.min.y = rect.max.y, HorizontalSide::Bottom => cursor.max.y = rect.min.y, }, } ui.set_cursor(cursor); } ui.expand_to_include_rect(rect); let mut resize_hover = false; let mut is_resizing = false; if resizable { // Now we do the actual resize interaction, on top of all the contents, // otherwise its input could be eaten by the contents, e.g. a // `ScrollArea` on either side of the panel boundary. (resize_hover, is_resizing) = self.resize_panel(&panel_sizer, ui); } if resize_hover || is_resizing { ui.set_cursor_icon(self.cursor_icon(&panel_sizer)); } PanelState { rect }.store(ui.ctx(), id); { let stroke = if is_resizing { ui.style().visuals.widgets.active.fg_stroke // highly visible } else if resize_hover { ui.style().visuals.widgets.hovered.fg_stroke // highly visible } else if show_separator_line { // TODO(emilk): distinguish resizable from non-resizable ui.style().visuals.widgets.noninteractive.bg_stroke // dim } else { Stroke::NONE }; // TODO(emilk): draw line on top of all panels in this ui when https://github.com/emilk/egui/issues/1516 is done match side { PanelSide::Vertical(side) => { let x = side.opposite().side_x(rect) + 0.5 * side.sign() * stroke.width; ui.painter() .vline(x, panel_sizer.panel_rect.y_range(), stroke); } PanelSide::Horizontal(side) => { let y = side.opposite().side_y(rect) + 0.5 * side.sign() * stroke.width; ui.painter() .hline(panel_sizer.panel_rect.x_range(), y, stroke); } } } inner_response } /// Show the panel at the top level. fn show_dyn<'c, R>( self, ctx: &Context, add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>, ) -> InnerResponse<R> { #![expect(deprecated)] let side = self.side; let available_rect = ctx.available_rect(); let mut panel_ui = Ui::new( ctx.clone(), self.id, UiBuilder::new() .layer_id(LayerId::background()) .max_rect(available_rect), ); panel_ui.set_clip_rect(ctx.content_rect()); panel_ui .response() .widget_info(|| WidgetInfo::new(WidgetType::Panel)); let inner_response = self.show_inside_dyn(&mut panel_ui, add_contents); let rect = inner_response.response.rect; match side { PanelSide::Vertical(side) => match side { VerticalSide::Left => ctx.pass_state_mut(|state| { state.allocate_left_panel(Rect::from_min_max(available_rect.min, rect.max)); }), VerticalSide::Right => ctx.pass_state_mut(|state| { state.allocate_right_panel(Rect::from_min_max(rect.min, available_rect.max)); }), }, PanelSide::Horizontal(side) => match side { HorizontalSide::Top => { ctx.pass_state_mut(|state| { state.allocate_top_panel(Rect::from_min_max(available_rect.min, rect.max)); }); } HorizontalSide::Bottom => { ctx.pass_state_mut(|state| { state.allocate_bottom_panel(Rect::from_min_max( rect.min, available_rect.max, )); }); } }, } inner_response } fn prepare_resizable_panel(&self, panel_sizer: &mut PanelSizer<'_>, ui: &Ui) { let resize_id = self.id.with("__resize"); let resize_response = ui.ctx().read_response(resize_id); if let Some(resize_response) = resize_response { // NOTE(sharky98): The original code was initializing to // false first, but it doesn't seem necessary. let is_resizing = resize_response.dragged(); let pointer = resize_response.interact_pointer_pos(); panel_sizer.prepare_resizing_response(is_resizing, pointer); } } fn resize_panel(&self, panel_sizer: &PanelSizer<'_>, ui: &Ui) -> (bool, bool) { let (resize_x, resize_y, amount): (Rangef, Rangef, Vec2) = match self.side { PanelSide::Vertical(side) => { let resize_x = side.opposite().side_x(panel_sizer.panel_rect); let resize_y = panel_sizer.panel_rect.y_range(); ( Rangef::from(resize_x..=resize_x), resize_y, vec2(ui.style().interaction.resize_grab_radius_side, 0.0), ) } PanelSide::Horizontal(side) => { let resize_x = panel_sizer.panel_rect.x_range(); let resize_y = side.opposite().side_y(panel_sizer.panel_rect); ( resize_x, Rangef::from(resize_y..=resize_y), vec2(0.0, ui.style().interaction.resize_grab_radius_side), ) } }; let resize_id = self.id.with("__resize"); let resize_rect = Rect::from_x_y_ranges(resize_x, resize_y).expand2(amount); let resize_response = ui.interact(resize_rect, resize_id, Sense::drag()); (resize_response.hovered(), resize_response.dragged()) } fn cursor_icon(&self, panel_sizer: &PanelSizer<'_>) -> CursorIcon { if panel_sizer.size <= self.size_range.min { match self.side { PanelSide::Vertical(side) => match side { VerticalSide::Left => CursorIcon::ResizeEast, VerticalSide::Right => CursorIcon::ResizeWest, }, PanelSide::Horizontal(side) => match side { HorizontalSide::Top => CursorIcon::ResizeSouth, HorizontalSide::Bottom => CursorIcon::ResizeNorth, }, } } else if panel_sizer.size < self.size_range.max { match self.side { PanelSide::Vertical(_) => CursorIcon::ResizeHorizontal, PanelSide::Horizontal(_) => CursorIcon::ResizeVertical, } } else { match self.side { PanelSide::Vertical(side) => match side { VerticalSide::Left => CursorIcon::ResizeWest, VerticalSide::Right => CursorIcon::ResizeEast, }, PanelSide::Horizontal(side) => match side { HorizontalSide::Top => CursorIcon::ResizeNorth, HorizontalSide::Bottom => CursorIcon::ResizeSouth, }, } } } /// Get the real or fake panel to animate if `is_expanded` is `true`. fn get_animated_panel(self, ctx: &Context, is_expanded: bool) -> Option<Self> { let how_expanded = animate_expansion(ctx, self.id.with("animation"), is_expanded); if 0.0 == how_expanded { None } else if how_expanded < 1.0 { // Show a fake panel in this in-between animation state: // TODO(emilk): move the panel out-of-screen instead of changing its width. // Then we can actually paint it as it animates. let expanded_size = Self::animated_size(ctx, &self); let fake_size = how_expanded * expanded_size; Some( Self { id: self.id.with("animating_panel"), ..self } .resizable(false) .exact_size(fake_size), ) } else { // Show the real panel: Some(self) } } /// Get either the collapsed or expended panel to animate. fn get_animated_between_panel( ctx: &Context, is_expanded: bool, collapsed_panel: Self, expanded_panel: Self, ) -> Self { let how_expanded = animate_expansion(ctx, expanded_panel.id.with("animation"), is_expanded); if 0.0 == how_expanded { collapsed_panel } else if how_expanded < 1.0 { let collapsed_size = Self::animated_size(ctx, &collapsed_panel); let expanded_size = Self::animated_size(ctx, &expanded_panel); let fake_size = lerp(collapsed_size..=expanded_size, how_expanded); Self { id: expanded_panel.id.with("animating_panel"), ..expanded_panel } .resizable(false) .exact_size(fake_size) } else { expanded_panel } } fn animated_size(ctx: &Context, panel: &Self) -> f32 { let get_rect_state_size = |state: PanelState| match panel.side { PanelSide::Vertical(_) => state.rect.width(), PanelSide::Horizontal(_) => state.rect.height(), }; let get_spacing_size = || match panel.side { PanelSide::Vertical(_) => ctx.global_style().spacing.interact_size.x, PanelSide::Horizontal(_) => ctx.global_style().spacing.interact_size.y, }; PanelState::load(ctx, panel.id) .map(get_rect_state_size) .or(panel.default_size) .unwrap_or_else(get_spacing_size) } } // ---------------------------------------------------------------------------- /// A panel that covers the remainder of the screen, /// i.e. whatever area is left after adding other panels. /// /// This acts very similar to [`Frame::central_panel`], but always expands
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/resize.rs
crates/egui/src/containers/resize.rs
use crate::{ Align2, Color32, Context, CursorIcon, Id, NumExt as _, Rect, Response, Sense, Shape, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, Vec2b, pos2, vec2, }; #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct State { /// This is the size that the user has picked by dragging the resize handles. /// This may be smaller and/or larger than the actual size. /// For instance, the user may have tried to shrink too much (not fitting the contents). /// Or the user requested a large area, but the content don't need that much space. pub(crate) desired_size: Vec2, /// Actual size of content last frame last_content_size: Vec2, /// Externally requested size (e.g. by Window) for the next frame pub(crate) requested_size: Option<Vec2>, } impl State { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_persisted(id)) } pub fn store(self, ctx: &Context, id: Id) { ctx.data_mut(|d| d.insert_persisted(id, self)); } } /// A region that can be resized by dragging the bottom right corner. #[derive(Clone, Copy, Debug)] #[must_use = "You should call .show()"] pub struct Resize { id: Option<Id>, id_salt: Option<Id>, /// If false, we are no enabled resizable: Vec2b, pub(crate) min_size: Vec2, pub(crate) max_size: Vec2, default_size: Vec2, with_stroke: bool, } impl Default for Resize { fn default() -> Self { Self { id: None, id_salt: None, resizable: Vec2b::TRUE, min_size: Vec2::splat(16.0), max_size: Vec2::splat(f32::INFINITY), default_size: vec2(320.0, 128.0), // TODO(emilk): preferred size of [`Resize`] area. with_stroke: true, } } } impl Resize { /// Assign an explicit and globally unique id. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = Some(id); self } /// A source for the unique [`Id`], e.g. `.id_source("second_resize_area")` or `.id_source(loop_index)`. #[inline] #[deprecated = "Renamed id_salt"] pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self { self.id_salt(id_salt) } /// A source for the unique [`Id`], e.g. `.id_salt("second_resize_area")` or `.id_salt(loop_index)`. #[inline] pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self { self.id_salt = Some(Id::new(id_salt)); self } /// Preferred / suggested width. Actual width will depend on contents. /// /// Examples: /// * if the contents is text, this will decide where we break long lines. /// * if the contents is a canvas, this decides the width of it, /// * if the contents is some buttons, this is ignored and we will auto-size. #[inline] pub fn default_width(mut self, width: f32) -> Self { self.default_size.x = width; self } /// Preferred / suggested height. Actual height will depend on contents. /// /// Examples: /// * if the contents is a [`crate::ScrollArea`] then this decides the maximum size. /// * if the contents is a canvas, this decides the height of it, /// * if the contents is text and buttons, then the `default_height` is ignored /// and the height is picked automatically.. #[inline] pub fn default_height(mut self, height: f32) -> Self { self.default_size.y = height; self } #[inline] pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self { self.default_size = default_size.into(); self } /// Won't shrink to smaller than this #[inline] pub fn min_size(mut self, min_size: impl Into<Vec2>) -> Self { self.min_size = min_size.into(); self } /// Won't shrink to smaller than this #[inline] pub fn min_width(mut self, min_width: f32) -> Self { self.min_size.x = min_width; self } /// Won't shrink to smaller than this #[inline] pub fn min_height(mut self, min_height: f32) -> Self { self.min_size.y = min_height; self } /// Won't expand to larger than this #[inline] pub fn max_size(mut self, max_size: impl Into<Vec2>) -> Self { self.max_size = max_size.into(); self } /// Won't expand to larger than this #[inline] pub fn max_width(mut self, max_width: f32) -> Self { self.max_size.x = max_width; self } /// Won't expand to larger than this #[inline] pub fn max_height(mut self, max_height: f32) -> Self { self.max_size.y = max_height; self } /// Can you resize it with the mouse? /// /// Note that a window can still auto-resize. /// /// Default is `true`. #[inline] pub fn resizable(mut self, resizable: impl Into<Vec2b>) -> Self { self.resizable = resizable.into(); self } #[inline] pub fn is_resizable(&self) -> Vec2b { self.resizable } /// Not manually resizable, just takes the size of its contents. /// Text will not wrap, but will instead make your window width expand. pub fn auto_sized(self) -> Self { self.min_size(Vec2::ZERO) .default_size(Vec2::splat(f32::INFINITY)) .resizable(false) } #[inline] pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self { let size = size.into(); self.default_size = size; self.min_size = size; self.max_size = size; self.resizable = Vec2b::FALSE; self } #[inline] pub fn with_stroke(mut self, with_stroke: bool) -> Self { self.with_stroke = with_stroke; self } } struct Prepared { id: Id, corner_id: Option<Id>, state: State, content_ui: Ui, } impl Resize { fn begin(&self, ui: &mut Ui) -> Prepared { let position = ui.available_rect_before_wrap().min; let id = self.id.unwrap_or_else(|| { let id_salt = self.id_salt.unwrap_or_else(|| Id::new("resize")); ui.make_persistent_id(id_salt) }); let mut state = State::load(ui.ctx(), id).unwrap_or_else(|| { ui.request_repaint(); // counter frame delay let default_size = self .default_size .at_least(self.min_size) .at_most(self.max_size) .at_most( ui.ctx().content_rect().size() - ui.spacing().window_margin.sum(), // hack for windows ) .round_ui(); State { desired_size: default_size, last_content_size: vec2(0.0, 0.0), requested_size: None, } }); state.desired_size = state .desired_size .at_least(self.min_size) .at_most(self.max_size) .round_ui(); let mut user_requested_size = state.requested_size.take(); let corner_id = self.resizable.any().then(|| id.with("__resize_corner")); if let Some(corner_id) = corner_id && let Some(corner_response) = ui.ctx().read_response(corner_id) && let Some(pointer_pos) = corner_response.interact_pointer_pos() { // Respond to the interaction early to avoid frame delay. user_requested_size = Some(pointer_pos - position + 0.5 * corner_response.rect.size()); } if let Some(user_requested_size) = user_requested_size { state.desired_size = user_requested_size; } else { // We are not being actively resized, so auto-expand to include size of last frame. // This prevents auto-shrinking if the contents contain width-filling widgets (separators etc) // but it makes a lot of interactions with [`Window`]s nicer. state.desired_size = state.desired_size.max(state.last_content_size); } state.desired_size = state .desired_size .at_least(self.min_size) .at_most(self.max_size); // ------------------------------ let inner_rect = Rect::from_min_size(position, state.desired_size); let mut content_clip_rect = inner_rect.expand(ui.visuals().clip_rect_margin); // If we pull the resize handle to shrink, we want to TRY to shrink it. // After laying out the contents, we might be much bigger. // In those cases we don't want the clip_rect to be smaller, because // then we will clip the contents of the region even thought the result gets larger. This is simply ugly! // So we use the memory of last_content_size to make the clip rect large enough. content_clip_rect.max = content_clip_rect.max.max( inner_rect.min + state.last_content_size + Vec2::splat(ui.visuals().clip_rect_margin), ); content_clip_rect = content_clip_rect.intersect(ui.clip_rect()); // Respect parent region let mut content_ui = ui.new_child( UiBuilder::new() .ui_stack_info(UiStackInfo::new(UiKind::Resize)) .max_rect(inner_rect), ); content_ui.set_clip_rect(content_clip_rect); Prepared { id, corner_id, state, content_ui, } } pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { let mut prepared = self.begin(ui); let ret = add_contents(&mut prepared.content_ui); self.end(ui, prepared); ret } fn end(self, ui: &mut Ui, prepared: Prepared) { let Prepared { id, corner_id, mut state, content_ui, } = prepared; state.last_content_size = content_ui.min_size(); // ------------------------------ let mut size = state.last_content_size; for d in 0..2 { if self.with_stroke || self.resizable[d] { // We show how large we are, // so we must follow the contents: state.desired_size[d] = state.desired_size[d].max(state.last_content_size[d]); // We are as large as we look size[d] = state.desired_size[d]; } else { // Probably a window. size[d] = state.last_content_size[d]; } } ui.advance_cursor_after_rect(Rect::from_min_size(content_ui.min_rect().min, size)); // ------------------------------ let corner_response = if let Some(corner_id) = corner_id { // We do the corner interaction last to place it on top of the content: let corner_size = Vec2::splat(ui.visuals().resize_corner_size); let corner_rect = Rect::from_min_size( content_ui.min_rect().left_top() + size - corner_size, corner_size, ); Some(ui.interact(corner_rect, corner_id, Sense::drag())) } else { None }; // ------------------------------ if self.with_stroke && corner_response.is_some() { let rect = Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size); let rect = rect.expand(2.0); // breathing room for content ui.painter().add(Shape::rect_stroke( rect, 3.0, ui.visuals().widgets.noninteractive.bg_stroke, epaint::StrokeKind::Inside, )); } if let Some(corner_response) = corner_response { paint_resize_corner(ui, &corner_response); if corner_response.hovered() || corner_response.dragged() { ui.set_cursor_icon(CursorIcon::ResizeNwSe); } } state.store(ui.ctx(), id); #[cfg(debug_assertions)] if ui.global_style().debug.show_resize { ui.debug_painter().debug_rect( Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size), Color32::GREEN, "desired_size", ); ui.debug_painter().debug_rect( Rect::from_min_size(content_ui.min_rect().left_top(), state.last_content_size), Color32::LIGHT_BLUE, "last_content_size", ); } } } use emath::GuiRounding as _; use epaint::Stroke; pub fn paint_resize_corner(ui: &Ui, response: &Response) { let stroke = ui.style().interact(response).fg_stroke; paint_resize_corner_with_style(ui, &response.rect, stroke.color, Align2::RIGHT_BOTTOM); } pub fn paint_resize_corner_with_style( ui: &Ui, rect: &Rect, color: impl Into<Color32>, corner: Align2, ) { let painter = ui.painter(); let cp = corner .pos_in_rect(rect) .round_to_pixels(ui.pixels_per_point()); let mut w = 2.0; let stroke = Stroke { width: 1.0, // Set width to 1.0 to prevent overlapping color: color.into(), }; while w <= rect.width() && w <= rect.height() { painter.line_segment( [ pos2(cp.x - w * corner.x().to_sign(), cp.y), pos2(cp.x, cp.y - w * corner.y().to_sign()), ], stroke, ); w += 4.0; } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/popup.rs
crates/egui/src/containers/popup.rs
#![expect(deprecated)] // This is a new, safe wrapper around the old `Memory::popup` API. use std::iter::once; use emath::{Align, Pos2, Rect, RectAlign, Vec2, vec2}; use crate::{ Area, AreaState, Context, Frame, Id, InnerResponse, Key, LayerId, Layout, Order, Response, Sense, Ui, UiKind, UiStackInfo, containers::menu::{MenuConfig, MenuState, menu_style}, style::StyleModifier, }; /// What should we anchor the popup to? /// /// The final position for the popup will be calculated based on [`RectAlign`] /// and can be customized with [`Popup::align`] and [`Popup::align_alternatives`]. /// [`PopupAnchor`] is the parent rect of [`RectAlign`]. /// /// For [`PopupAnchor::Pointer`], [`PopupAnchor::PointerFixed`] and [`PopupAnchor::Position`], /// the rect will be derived via [`Rect::from_pos`] (so a zero-sized rect at the given position). /// /// The rect should be in global coordinates. `PopupAnchor::from(&response)` will automatically /// do this conversion. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PopupAnchor { /// Show the popup relative to some parent [`Rect`]. ParentRect(Rect), /// Show the popup relative to the mouse pointer. Pointer, /// Remember the mouse position and show the popup relative to that (like a context menu). PointerFixed, /// Show the popup relative to a specific position. Position(Pos2), } impl From<Rect> for PopupAnchor { fn from(rect: Rect) -> Self { Self::ParentRect(rect) } } impl From<Pos2> for PopupAnchor { fn from(pos: Pos2) -> Self { Self::Position(pos) } } impl From<&Response> for PopupAnchor { fn from(response: &Response) -> Self { // We use interact_rect so we don't show the popup relative to some clipped point let mut widget_rect = response.interact_rect; if let Some(to_global) = response.ctx.layer_transform_to_global(response.layer_id) { widget_rect = to_global * widget_rect; } Self::ParentRect(widget_rect) } } impl PopupAnchor { /// Get the rect the popup should be shown relative to. /// Returns `Rect::from_pos` for [`PopupAnchor::Pointer`], [`PopupAnchor::PointerFixed`] /// and [`PopupAnchor::Position`] (so the rect will be zero-sized). pub fn rect(self, popup_id: Id, ctx: &Context) -> Option<Rect> { match self { Self::ParentRect(rect) => Some(rect), Self::Pointer => ctx.pointer_hover_pos().map(Rect::from_pos), Self::PointerFixed => Popup::position_of_id(ctx, popup_id).map(Rect::from_pos), Self::Position(pos) => Some(Rect::from_pos(pos)), } } } /// Determines popup's close behavior #[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] pub enum PopupCloseBehavior { /// Popup will be closed on click anywhere, inside or outside the popup. /// /// It is used in [`crate::ComboBox`] and in [`crate::containers::menu`]s. #[default] CloseOnClick, /// Popup will be closed if the click happened somewhere else /// but in the popup's body CloseOnClickOutside, /// Clicks will be ignored. Popup might be closed manually by calling [`crate::Memory::close_all_popups`] /// or by pressing the escape button IgnoreClicks, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SetOpenCommand { /// Set the open state to the given value Bool(bool), /// Toggle the open state Toggle, } impl From<bool> for SetOpenCommand { fn from(b: bool) -> Self { Self::Bool(b) } } /// How do we determine if the popup should be open or closed enum OpenKind<'a> { /// Always open Open, /// Always closed Closed, /// Open if the bool is true Bool(&'a mut bool), /// Store the open state via [`crate::Memory`] Memory { set: Option<SetOpenCommand> }, } impl OpenKind<'_> { /// Returns `true` if the popup should be open fn is_open(&self, popup_id: Id, ctx: &Context) -> bool { match self { OpenKind::Open => true, OpenKind::Closed => false, OpenKind::Bool(open) => **open, OpenKind::Memory { .. } => Popup::is_id_open(ctx, popup_id), } } } /// Is the popup a popup, tooltip or menu? #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PopupKind { Popup, Tooltip, Menu, } impl PopupKind { /// Returns the order to be used with this kind. pub fn order(self) -> Order { match self { Self::Tooltip => Order::Tooltip, Self::Menu | Self::Popup => Order::Foreground, } } } impl From<PopupKind> for UiKind { fn from(kind: PopupKind) -> Self { match kind { PopupKind::Popup => Self::Popup, PopupKind::Tooltip => Self::Tooltip, PopupKind::Menu => Self::Menu, } } } /// A popup container. #[must_use = "Call `.show()` to actually display the popup"] pub struct Popup<'a> { id: Id, ctx: Context, anchor: PopupAnchor, rect_align: RectAlign, alternative_aligns: Option<&'a [RectAlign]>, layer_id: LayerId, open_kind: OpenKind<'a>, close_behavior: PopupCloseBehavior, info: Option<UiStackInfo>, kind: PopupKind, /// Gap between the anchor and the popup gap: f32, /// Default width passed to the Area width: Option<f32>, sense: Sense, layout: Layout, frame: Option<Frame>, style: StyleModifier, } impl<'a> Popup<'a> { /// Create a new popup pub fn new(id: Id, ctx: Context, anchor: impl Into<PopupAnchor>, layer_id: LayerId) -> Self { Self { id, ctx, anchor: anchor.into(), open_kind: OpenKind::Open, close_behavior: PopupCloseBehavior::default(), info: None, kind: PopupKind::Popup, layer_id, rect_align: RectAlign::BOTTOM_START, alternative_aligns: None, gap: 0.0, width: None, sense: Sense::click(), layout: Layout::default(), frame: None, style: StyleModifier::default(), } } /// Show a popup relative to some widget. /// The popup will be always open. /// /// See [`Self::menu`] and [`Self::context_menu`] for common use cases. pub fn from_response(response: &Response) -> Self { Self::new( Self::default_response_id(response), response.ctx.clone(), response, response.layer_id, ) } /// Show a popup relative to some widget, /// toggling the open state based on the widget's click state. /// /// See [`Self::menu`] and [`Self::context_menu`] for common use cases. pub fn from_toggle_button_response(button_response: &Response) -> Self { Self::from_response(button_response) .open_memory(button_response.clicked().then_some(SetOpenCommand::Toggle)) } /// Show a popup when the widget was clicked. /// Sets the layout to `Layout::top_down_justified(Align::Min)`. pub fn menu(button_response: &Response) -> Self { Self::from_toggle_button_response(button_response) .kind(PopupKind::Menu) .layout(Layout::top_down_justified(Align::Min)) .style(menu_style) .gap(0.0) } /// Show a context menu when the widget was secondary clicked. /// Sets the layout to `Layout::top_down_justified(Align::Min)`. /// In contrast to [`Self::menu`], this will open at the pointer position. pub fn context_menu(response: &Response) -> Self { Self::menu(response) .open_memory(if response.secondary_clicked() { Some(SetOpenCommand::Bool(true)) } else if response.clicked() { // Explicitly close the menu if the widget was clicked // Without this, the context menu would stay open if the user clicks the widget Some(SetOpenCommand::Bool(false)) } else { None }) .at_pointer_fixed() } /// Set the kind of the popup. Used for [`Area::kind`] and [`Area::order`]. #[inline] pub fn kind(mut self, kind: PopupKind) -> Self { self.kind = kind; self } /// Set the [`UiStackInfo`] of the popup's [`Ui`]. #[inline] pub fn info(mut self, info: UiStackInfo) -> Self { self.info = Some(info); self } /// Set the [`RectAlign`] of the popup relative to the [`PopupAnchor`]. /// This is the default position, and will be used if it fits. /// See [`Self::align_alternatives`] for more on this. #[inline] pub fn align(mut self, position_align: RectAlign) -> Self { self.rect_align = position_align; self } /// Set alternative positions to try if the default one doesn't fit. Set to an empty slice to /// always use the position you set with [`Self::align`]. /// By default, this will try [`RectAlign::symmetries`] and then [`RectAlign::MENU_ALIGNS`]. #[inline] pub fn align_alternatives(mut self, alternatives: &'a [RectAlign]) -> Self { self.alternative_aligns = Some(alternatives); self } /// Force the popup to be open or closed. #[inline] pub fn open(mut self, open: bool) -> Self { self.open_kind = if open { OpenKind::Open } else { OpenKind::Closed }; self } /// Store the open state via [`crate::Memory`]. /// You can set the state via the first [`SetOpenCommand`] param. #[inline] pub fn open_memory(mut self, set_state: impl Into<Option<SetOpenCommand>>) -> Self { self.open_kind = OpenKind::Memory { set: set_state.into(), }; self } /// Store the open state via a mutable bool. #[inline] pub fn open_bool(mut self, open: &'a mut bool) -> Self { self.open_kind = OpenKind::Bool(open); self } /// Set the close behavior of the popup. /// /// This will do nothing if [`Popup::open`] was called. #[inline] pub fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self { self.close_behavior = close_behavior; self } /// Show the popup relative to the pointer. #[inline] pub fn at_pointer(mut self) -> Self { self.anchor = PopupAnchor::Pointer; self } /// Remember the pointer position at the time of opening the popup, and show the popup /// relative to that. #[inline] pub fn at_pointer_fixed(mut self) -> Self { self.anchor = PopupAnchor::PointerFixed; self } /// Show the popup relative to a specific position. #[inline] pub fn at_position(mut self, position: Pos2) -> Self { self.anchor = PopupAnchor::Position(position); self } /// Show the popup relative to the given [`PopupAnchor`]. #[inline] pub fn anchor(mut self, anchor: impl Into<PopupAnchor>) -> Self { self.anchor = anchor.into(); self } /// Set the gap between the anchor and the popup. #[inline] pub fn gap(mut self, gap: f32) -> Self { self.gap = gap; self } /// Set the frame of the popup. #[inline] pub fn frame(mut self, frame: Frame) -> Self { self.frame = Some(frame); self } /// Set the sense of the popup. #[inline] pub fn sense(mut self, sense: Sense) -> Self { self.sense = sense; self } /// Set the layout of the popup. #[inline] pub fn layout(mut self, layout: Layout) -> Self { self.layout = layout; self } /// The width that will be passed to [`Area::default_width`]. #[inline] pub fn width(mut self, width: f32) -> Self { self.width = Some(width); self } /// Set the id of the Area. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = id; self } /// Set the style for the popup contents. /// /// Default: /// - is [`menu_style`] for [`Self::menu`] and [`Self::context_menu`] /// - is [`None`] otherwise #[inline] pub fn style(mut self, style: impl Into<StyleModifier>) -> Self { self.style = style.into(); self } /// Get the [`Context`] pub fn ctx(&self) -> &Context { &self.ctx } /// Return the [`PopupAnchor`] of the popup. pub fn get_anchor(&self) -> PopupAnchor { self.anchor } /// Return the anchor rect of the popup. /// /// Returns `None` if the anchor is [`PopupAnchor::Pointer`] and there is no pointer. pub fn get_anchor_rect(&self) -> Option<Rect> { self.anchor.rect(self.id, &self.ctx) } /// Get the expected rect the popup will be shown in. /// /// Returns `None` if the popup wasn't shown before or anchor is `PopupAnchor::Pointer` and /// there is no pointer. pub fn get_popup_rect(&self) -> Option<Rect> { let size = self.get_expected_size(); if let Some(size) = size { self.get_anchor_rect() .map(|anchor| self.get_best_align().align_rect(&anchor, size, self.gap)) } else { None } } /// Get the id of the popup. pub fn get_id(&self) -> Id { self.id } /// Is the popup open? pub fn is_open(&self) -> bool { match &self.open_kind { OpenKind::Open => true, OpenKind::Closed => false, OpenKind::Bool(open) => **open, OpenKind::Memory { .. } => Self::is_id_open(&self.ctx, self.id), } } /// Get the expected size of the popup. pub fn get_expected_size(&self) -> Option<Vec2> { AreaState::load(&self.ctx, self.id)?.size } /// Calculate the best alignment for the popup, based on the last size and screen rect. pub fn get_best_align(&self) -> RectAlign { let expected_popup_size = self .get_expected_size() .unwrap_or_else(|| vec2(self.width.unwrap_or(0.0), 0.0)); let Some(anchor_rect) = self.anchor.rect(self.id, &self.ctx) else { return self.rect_align; }; RectAlign::find_best_align( #[expect(clippy::iter_on_empty_collections)] #[expect(clippy::or_fun_call)] once(self.rect_align).chain( self.alternative_aligns // Need the empty slice so the iters have the same type so we can unwrap_or .map(|a| a.iter().copied().chain([].iter().copied())) .unwrap_or( self.rect_align .symmetries() .iter() .copied() .chain(RectAlign::MENU_ALIGNS.iter().copied()), ), ), self.ctx.content_rect(), anchor_rect, self.gap, expected_popup_size, ) .unwrap_or_default() } /// Show the popup. /// /// Returns `None` if the popup is not open or anchor is `PopupAnchor::Pointer` and there is /// no pointer. pub fn show<R>(self, content: impl FnOnce(&mut Ui) -> R) -> Option<InnerResponse<R>> { let id = self.id; // When the popup was just opened with a click we don't want to immediately close it based // on the `PopupCloseBehavior`, so we need to remember if the popup was already open on // last frame. A convenient way to check this is to see if we have a response for the `Area` // from last frame: let was_open_last_frame = self.ctx.read_response(id).is_some(); let hover_pos = self.ctx.pointer_hover_pos(); if let OpenKind::Memory { set } = self.open_kind { match set { Some(SetOpenCommand::Bool(open)) => { if open { match self.anchor { PopupAnchor::PointerFixed => { self.ctx.memory_mut(|mem| mem.open_popup_at(id, hover_pos)); } _ => Popup::open_id(&self.ctx, id), } } else { Self::close_id(&self.ctx, id); } } Some(SetOpenCommand::Toggle) => { Self::toggle_id(&self.ctx, id); } None => { self.ctx.memory_mut(|mem| mem.keep_popup_open(id)); } } } if !self.open_kind.is_open(self.id, &self.ctx) { return None; } let best_align = self.get_best_align(); let Popup { id, ctx, anchor, open_kind, close_behavior, kind, info, layer_id, rect_align: _, alternative_aligns: _, gap, width, sense, layout, frame, style, } = self; if kind != PopupKind::Tooltip { ctx.pass_state_mut(|fs| { fs.layers .entry(layer_id) .or_default() .open_popups .insert(id) }); } let anchor_rect = anchor.rect(id, &ctx)?; let (pivot, anchor) = best_align.pivot_pos(&anchor_rect, gap); let mut area = Area::new(id) .order(kind.order()) .pivot(pivot) .fixed_pos(anchor) .sense(sense) .layout(layout) .info(info.unwrap_or_else(|| { UiStackInfo::new(kind.into()).with_tag_value( MenuConfig::MENU_CONFIG_TAG, MenuConfig::new() .close_behavior(close_behavior) .style(style.clone()), ) })); if let Some(width) = width { area = area.default_width(width); } let mut response = area.show(&ctx, |ui| { style.apply(ui.style_mut()); let frame = frame.unwrap_or_else(|| Frame::popup(ui.style())); frame.show(ui, content).inner }); // If the popup was just opened with a click, we don't want to immediately close it again. let close_click = was_open_last_frame && ctx.input(|i| i.pointer.any_click()); let closed_by_click = match close_behavior { PopupCloseBehavior::CloseOnClick => close_click, PopupCloseBehavior::CloseOnClickOutside => { close_click && response.response.clicked_elsewhere() } PopupCloseBehavior::IgnoreClicks => false, }; // Mark the menu as shown, so the sub menu open state is not reset MenuState::mark_shown(&ctx, id); // If a submenu is open, the CloseBehavior is handled there let is_any_submenu_open = !MenuState::is_deepest_open_sub_menu(&response.response.ctx, id); let should_close = (!is_any_submenu_open && closed_by_click) || ctx.input(|i| i.key_pressed(Key::Escape)) || response.response.should_close(); if should_close { response.response.set_close(); } match open_kind { OpenKind::Open | OpenKind::Closed => {} OpenKind::Bool(open) => { if should_close { *open = false; } } OpenKind::Memory { .. } => { if should_close { ctx.memory_mut(|mem| mem.close_popup(id)); } } } Some(response) } } /// ## Static methods impl Popup<'_> { /// The default ID when constructing a popup from the [`Response`] of e.g. a button. pub fn default_response_id(response: &Response) -> Id { response.id.with("popup") } /// Is the given popup open? /// /// This assumes the use of either: /// * [`Self::open_memory`] /// * [`Self::from_toggle_button_response`] /// * [`Self::menu`] /// * [`Self::context_menu`] /// /// The popup id should be the same as either you set with [`Self::id`] or the /// default one from [`Self::default_response_id`]. pub fn is_id_open(ctx: &Context, popup_id: Id) -> bool { ctx.memory(|mem| mem.is_popup_open(popup_id)) } /// Is any popup open? /// /// This assumes the egui memory is being used to track the open state of popups. pub fn is_any_open(ctx: &Context) -> bool { ctx.memory(|mem| mem.any_popup_open()) } /// Open the given popup and close all others. /// /// If you are NOT using [`Popup::show`], you must /// also call [`crate::Memory::keep_popup_open`] as long as /// you're showing the popup. pub fn open_id(ctx: &Context, popup_id: Id) { ctx.memory_mut(|mem| mem.open_popup(popup_id)); } /// Toggle the given popup between closed and open. /// /// Note: At most, only one popup can be open at a time. pub fn toggle_id(ctx: &Context, popup_id: Id) { ctx.memory_mut(|mem| mem.toggle_popup(popup_id)); } /// Close all currently open popups. pub fn close_all(ctx: &Context) { ctx.memory_mut(|mem| mem.close_all_popups()); } /// Close the given popup, if it is open. /// /// See also [`Self::close_all`] if you want to close any / all currently open popups. pub fn close_id(ctx: &Context, popup_id: Id) { ctx.memory_mut(|mem| mem.close_popup(popup_id)); } /// Get the position for this popup, if it is open. pub fn position_of_id(ctx: &Context, popup_id: Id) -> Option<Pos2> { ctx.memory(|mem| mem.popup_position(popup_id)) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/sides.rs
crates/egui/src/containers/sides.rs
use emath::{Align, NumExt as _}; use crate::{Layout, Ui, UiBuilder}; /// Put some widgets on the left and right sides of a ui. /// /// The result will look like this: /// ```text /// parent Ui /// ______________________________________________________ /// | | | | ^ /// | -> left widgets -> | gap | <- right widgets <- | | height /// |____________________| |_____________________| v /// | | /// | | /// ``` /// /// The width of the gap is dynamic, based on the max width of the parent [`Ui`]. /// When the parent is being auto-sized ([`Ui::is_sizing_pass`]) the gap will be as small as possible. /// /// If the parent is not wide enough to fit all widgets, the parent will be expanded to the right. /// /// The left widgets are added left-to-right. /// The right widgets are added right-to-left. /// /// Which side is first depends on the configuration: /// - [`Sides::extend`] - left widgets are added first /// - [`Sides::shrink_left`] - right widgets are added first /// - [`Sides::shrink_right`] - left widgets are added first /// /// ``` /// # egui::__run_test_ui(|ui| { /// egui::containers::Sides::new().show(ui, /// |ui| { /// ui.label("Left"); /// }, /// |ui| { /// ui.label("Right"); /// } /// ); /// # }); /// ``` #[must_use = "You should call sides.show()"] #[derive(Clone, Copy, Debug, Default)] pub struct Sides { height: Option<f32>, spacing: Option<f32>, kind: SidesKind, wrap_mode: Option<crate::TextWrapMode>, } #[derive(Clone, Copy, Debug, Default)] enum SidesKind { #[default] Extend, ShrinkLeft, ShrinkRight, } impl Sides { #[inline] pub fn new() -> Self { Default::default() } /// The minimum height of the sides. /// /// The content will be centered vertically within this height. /// The default height is [`crate::Spacing::interact_size`]`.y`. #[inline] pub fn height(mut self, height: f32) -> Self { self.height = Some(height); self } /// The horizontal spacing between the left and right UIs. /// /// This is the minimum gap. /// The default is [`crate::Spacing::item_spacing`]`.x`. #[inline] pub fn spacing(mut self, spacing: f32) -> Self { self.spacing = Some(spacing); self } /// Try to shrink widgets on the left side. /// /// Right widgets will be added first. The left [`Ui`]s max rect will be limited to the /// remaining space. #[inline] pub fn shrink_left(mut self) -> Self { self.kind = SidesKind::ShrinkLeft; self } /// Try to shrink widgets on the right side. /// /// Left widgets will be added first. The right [`Ui`]s max rect will be limited to the /// remaining space. #[inline] pub fn shrink_right(mut self) -> Self { self.kind = SidesKind::ShrinkRight; self } /// Extend the left and right sides to fill the available space. /// /// This is the default behavior. /// The left widgets will be added first, followed by the right widgets. #[inline] pub fn extend(mut self) -> Self { self.kind = SidesKind::Extend; self } /// The text wrap mode for the shrinking side. /// /// Does nothing if [`Self::extend`] is used (the default). #[inline] pub fn wrap_mode(mut self, wrap_mode: crate::TextWrapMode) -> Self { self.wrap_mode = Some(wrap_mode); self } /// Truncate the text on the shrinking side. /// /// This is a shortcut for [`Self::wrap_mode`]. /// Does nothing if [`Self::extend`] is used (the default). #[inline] pub fn truncate(mut self) -> Self { self.wrap_mode = Some(crate::TextWrapMode::Truncate); self } /// Wrap the text on the shrinking side. /// /// This is a shortcut for [`Self::wrap_mode`]. /// Does nothing if [`Self::extend`] is used (the default). #[inline] pub fn wrap(mut self) -> Self { self.wrap_mode = Some(crate::TextWrapMode::Wrap); self } pub fn show<RetL, RetR>( self, ui: &mut Ui, add_left: impl FnOnce(&mut Ui) -> RetL, add_right: impl FnOnce(&mut Ui) -> RetR, ) -> (RetL, RetR) { let Self { height, spacing, mut kind, mut wrap_mode, } = self; let height = height.unwrap_or_else(|| ui.spacing().interact_size.y); let spacing = spacing.unwrap_or_else(|| ui.spacing().item_spacing.x); let mut top_rect = ui.available_rect_before_wrap(); top_rect.max.y = top_rect.min.y + height; if ui.is_sizing_pass() { kind = SidesKind::Extend; wrap_mode = None; } match kind { SidesKind::ShrinkLeft => { let (right_rect, result_right) = Self::create_ui( ui, top_rect, Layout::right_to_left(Align::Center), add_right, None, ); let available_width = top_rect.width() - right_rect.width() - spacing; let left_rect_constraint = top_rect.with_max_x(top_rect.min.x + available_width.at_least(0.0)); let (left_rect, result_left) = Self::create_ui( ui, left_rect_constraint, Layout::left_to_right(Align::Center), add_left, wrap_mode, ); ui.advance_cursor_after_rect(left_rect | right_rect); (result_left, result_right) } SidesKind::ShrinkRight => { let (left_rect, result_left) = Self::create_ui( ui, top_rect, Layout::left_to_right(Align::Center), add_left, None, ); let right_rect_constraint = top_rect.with_min_x(left_rect.max.x + spacing); let (right_rect, result_right) = Self::create_ui( ui, right_rect_constraint, Layout::right_to_left(Align::Center), add_right, wrap_mode, ); ui.advance_cursor_after_rect(left_rect | right_rect); (result_left, result_right) } SidesKind::Extend => { let (left_rect, result_left) = Self::create_ui( ui, top_rect, Layout::left_to_right(Align::Center), add_left, None, ); let right_max_rect = top_rect.with_min_x(left_rect.max.x); let (right_rect, result_right) = Self::create_ui( ui, right_max_rect, Layout::right_to_left(Align::Center), add_right, None, ); let mut final_rect = left_rect | right_rect; let min_width = left_rect.width() + spacing + right_rect.width(); if ui.is_sizing_pass() { final_rect.max.x = left_rect.min.x + min_width; } else { final_rect.max.x = final_rect.max.x.max(left_rect.min.x + min_width); } ui.advance_cursor_after_rect(final_rect); (result_left, result_right) } } } fn create_ui<Ret>( ui: &mut Ui, max_rect: emath::Rect, layout: Layout, add_content: impl FnOnce(&mut Ui) -> Ret, wrap_mode: Option<crate::TextWrapMode>, ) -> (emath::Rect, Ret) { let mut child_ui = ui.new_child(UiBuilder::new().max_rect(max_rect).layout(layout)); if let Some(wrap_mode) = wrap_mode { child_ui.style_mut().wrap_mode = Some(wrap_mode); } let result = add_content(&mut child_ui); (child_ui.min_rect(), result) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/containers/close_tag.rs
crates/egui/src/containers/close_tag.rs
#[expect(unused_imports)] use crate::{Ui, UiBuilder}; use std::sync::atomic::AtomicBool; /// A tag to mark a container as closable. /// /// Usually set via [`UiBuilder::closable`]. /// /// [`Ui::close`] will find the closest parent [`ClosableTag`] and set its `close` field to `true`. /// Use [`Ui::should_close`] to check if close has been called. #[derive(Debug, Default)] pub struct ClosableTag { pub close: AtomicBool, } impl ClosableTag { pub const NAME: &'static str = "egui_close_tag"; /// Set close to `true` pub fn set_close(&self) { self.close.store(true, std::sync::atomic::Ordering::Relaxed); } /// Returns `true` if [`ClosableTag::set_close`] has been called. pub fn should_close(&self) -> bool { self.close.load(std::sync::atomic::Ordering::Relaxed) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/data/key.rs
crates/egui/src/data/key.rs
/// Keyboard keys. /// /// egui usually uses logical keys, i.e. after applying any user keymap.\ // See comment at the end of `Key { … }` on how to add new keys. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Key { // ---------------------------------------------- // Commands: ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Escape, Tab, Backspace, Enter, Space, Insert, Delete, Home, End, PageUp, PageDown, Copy, Cut, Paste, // ---------------------------------------------- // Punctuation: /// `:` Colon, /// `,` Comma, /// `\` Backslash, /// `/` Slash, /// `|`, a vertical bar Pipe, /// `?` Questionmark, // '!' Exclamationmark, // `[` OpenBracket, // `]` CloseBracket, // `{` OpenCurlyBracket, // `}` CloseCurlyBracket, /// Also known as "backquote" or "grave" Backtick, /// `-` Minus, /// `.` Period, /// `+` Plus, /// `=` Equals, /// `;` Semicolon, /// `'` Quote, // ---------------------------------------------- // Digits: /// `0` (from main row or numpad) Num0, /// `1` (from main row or numpad) Num1, /// `2` (from main row or numpad) Num2, /// `3` (from main row or numpad) Num3, /// `4` (from main row or numpad) Num4, /// `5` (from main row or numpad) Num5, /// `6` (from main row or numpad) Num6, /// `7` (from main row or numpad) Num7, /// `8` (from main row or numpad) Num8, /// `9` (from main row or numpad) Num9, // ---------------------------------------------- // Letters: A, // Used for cmd+A (select All) B, C, // |CMD COPY| D, // |CMD BOOKMARK| E, // |CMD SEARCH| F, // |CMD FIND firefox & chrome| G, // |CMD FIND chrome| H, // |CMD History| I, // italics J, // |CMD SEARCH firefox/DOWNLOAD chrome| K, // Used for ctrl+K (delete text after cursor) L, M, N, O, // |CMD OPEN| P, // |CMD PRINT| Q, R, // |CMD REFRESH| S, // |CMD SAVE| T, // |CMD TAB| U, // Used for ctrl+U (delete text before cursor) V, // |CMD PASTE| W, // Used for ctrl+W (delete previous word) X, // |CMD CUT| Y, Z, // |CMD UNDO| // ---------------------------------------------- // Function keys: F1, F2, F3, F4, F5, // |CMD REFRESH| F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25, F26, F27, F28, F29, F30, F31, F32, F33, F34, F35, /// Back navigation key from multimedia keyboard. /// Android sends this key on Back button press. /// Does not work on Web. BrowserBack, // When adding keys, remember to also update: // * crates/egui-winit/src/lib.rs // * Key::ALL // * Key::from_name // You should test that it works using the "Input Event History" window in the egui demo app. // Make sure to test both natively and on web! // Also: don't add keys last; add them to the group they best belong to. } impl Key { /// All egui keys pub const ALL: &'static [Self] = &[ // Commands: Self::ArrowDown, Self::ArrowLeft, Self::ArrowRight, Self::ArrowUp, Self::Escape, Self::Tab, Self::Backspace, Self::Enter, Self::Insert, Self::Delete, Self::Home, Self::End, Self::PageUp, Self::PageDown, Self::Copy, Self::Cut, Self::Paste, // Punctuation: Self::Space, Self::Colon, Self::Comma, Self::Minus, Self::Period, Self::Plus, Self::Equals, Self::Semicolon, Self::OpenBracket, Self::CloseBracket, Self::OpenCurlyBracket, Self::CloseCurlyBracket, Self::Backtick, Self::Backslash, Self::Slash, Self::Pipe, Self::Questionmark, Self::Exclamationmark, Self::Quote, // Digits: Self::Num0, Self::Num1, Self::Num2, Self::Num3, Self::Num4, Self::Num5, Self::Num6, Self::Num7, Self::Num8, Self::Num9, // Letters: Self::A, Self::B, Self::C, Self::D, Self::E, Self::F, Self::G, Self::H, Self::I, Self::J, Self::K, Self::L, Self::M, Self::N, Self::O, Self::P, Self::Q, Self::R, Self::S, Self::T, Self::U, Self::V, Self::W, Self::X, Self::Y, Self::Z, // Function keys: Self::F1, Self::F2, Self::F3, Self::F4, Self::F5, Self::F6, Self::F7, Self::F8, Self::F9, Self::F10, Self::F11, Self::F12, Self::F13, Self::F14, Self::F15, Self::F16, Self::F17, Self::F18, Self::F19, Self::F20, Self::F21, Self::F22, Self::F23, Self::F24, Self::F25, Self::F26, Self::F27, Self::F28, Self::F29, Self::F30, Self::F31, Self::F32, Self::F33, Self::F34, Self::F35, // Navigation keys: Self::BrowserBack, ]; /// Converts `"A"` to `Key::A`, `Space` to `Key::Space`, etc. /// /// Makes sense for logical keys. /// /// This will parse the output of both [`Self::name`] and [`Self::symbol_or_name`], /// but will also parse single characters, so that both `"-"` and `"Minus"` will return `Key::Minus`. /// /// This should support both the names generated in a web browser, /// and by winit. Please test on both with `eframe`. pub fn from_name(key: &str) -> Option<Self> { Some(match key { "⏷" | "ArrowDown" | "Down" => Self::ArrowDown, "⏴" | "ArrowLeft" | "Left" => Self::ArrowLeft, "⏵" | "ArrowRight" | "Right" => Self::ArrowRight, "⏶" | "ArrowUp" | "Up" => Self::ArrowUp, "Escape" | "Esc" => Self::Escape, "Tab" => Self::Tab, "Backspace" => Self::Backspace, "Enter" | "Return" => Self::Enter, "Help" | "Insert" => Self::Insert, "Delete" => Self::Delete, "Home" => Self::Home, "End" => Self::End, "PageUp" => Self::PageUp, "PageDown" => Self::PageDown, "Copy" => Self::Copy, "Cut" => Self::Cut, "Paste" => Self::Paste, " " | "Space" => Self::Space, ":" | "Colon" => Self::Colon, "," | "Comma" => Self::Comma, "-" | "−" | "Minus" => Self::Minus, "." | "Period" => Self::Period, "+" | "Plus" => Self::Plus, "=" | "Equal" | "Equals" | "NumpadEqual" => Self::Equals, ";" | "Semicolon" => Self::Semicolon, "\\" | "Backslash" => Self::Backslash, "/" | "Slash" => Self::Slash, "|" | "Pipe" => Self::Pipe, "?" | "Questionmark" => Self::Questionmark, "!" | "Exclamationmark" => Self::Exclamationmark, "[" | "OpenBracket" => Self::OpenBracket, "]" | "CloseBracket" => Self::CloseBracket, "{" | "OpenCurlyBracket" => Self::OpenCurlyBracket, "}" | "CloseCurlyBracket" => Self::CloseCurlyBracket, "`" | "Backtick" | "Backquote" | "Grave" => Self::Backtick, "'" | "Quote" => Self::Quote, "0" | "Digit0" | "Numpad0" => Self::Num0, "1" | "Digit1" | "Numpad1" => Self::Num1, "2" | "Digit2" | "Numpad2" => Self::Num2, "3" | "Digit3" | "Numpad3" => Self::Num3, "4" | "Digit4" | "Numpad4" => Self::Num4, "5" | "Digit5" | "Numpad5" => Self::Num5, "6" | "Digit6" | "Numpad6" => Self::Num6, "7" | "Digit7" | "Numpad7" => Self::Num7, "8" | "Digit8" | "Numpad8" => Self::Num8, "9" | "Digit9" | "Numpad9" => Self::Num9, "a" | "A" => Self::A, "b" | "B" => Self::B, "c" | "C" => Self::C, "d" | "D" => Self::D, "e" | "E" => Self::E, "f" | "F" => Self::F, "g" | "G" => Self::G, "h" | "H" => Self::H, "i" | "I" => Self::I, "j" | "J" => Self::J, "k" | "K" => Self::K, "l" | "L" => Self::L, "m" | "M" => Self::M, "n" | "N" => Self::N, "o" | "O" => Self::O, "p" | "P" => Self::P, "q" | "Q" => Self::Q, "r" | "R" => Self::R, "s" | "S" => Self::S, "t" | "T" => Self::T, "u" | "U" => Self::U, "v" | "V" => Self::V, "w" | "W" => Self::W, "x" | "X" => Self::X, "y" | "Y" => Self::Y, "z" | "Z" => Self::Z, "F1" => Self::F1, "F2" => Self::F2, "F3" => Self::F3, "F4" => Self::F4, "F5" => Self::F5, "F6" => Self::F6, "F7" => Self::F7, "F8" => Self::F8, "F9" => Self::F9, "F10" => Self::F10, "F11" => Self::F11, "F12" => Self::F12, "F13" => Self::F13, "F14" => Self::F14, "F15" => Self::F15, "F16" => Self::F16, "F17" => Self::F17, "F18" => Self::F18, "F19" => Self::F19, "F20" => Self::F20, "F21" => Self::F21, "F22" => Self::F22, "F23" => Self::F23, "F24" => Self::F24, "F25" => Self::F25, "F26" => Self::F26, "F27" => Self::F27, "F28" => Self::F28, "F29" => Self::F29, "F30" => Self::F30, "F31" => Self::F31, "F32" => Self::F32, "F33" => Self::F33, "F34" => Self::F34, "F35" => Self::F35, "BrowserBack" => Self::BrowserBack, _ => return None, }) } /// Emoji or name representing the key pub fn symbol_or_name(self) -> &'static str { // TODO(emilk): add support for more unicode symbols (see for instance https://wincent.com/wiki/Unicode_representations_of_modifier_keys). // 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. match self { Self::ArrowDown => "⏷", Self::ArrowLeft => "⏴", Self::ArrowRight => "⏵", Self::ArrowUp => "⏶", Self::Colon => ":", Self::Comma => ",", Self::Minus => crate::MINUS_CHAR_STR, Self::Period => ".", Self::Plus => "+", Self::Equals => "=", Self::Semicolon => ";", Self::Backslash => "\\", Self::Slash => "/", Self::Pipe => "|", Self::Questionmark => "?", Self::Exclamationmark => "!", Self::OpenBracket => "[", Self::CloseBracket => "]", Self::OpenCurlyBracket => "{", Self::CloseCurlyBracket => "}", Self::Backtick => "`", _ => self.name(), } } /// Human-readable English name. pub fn name(self) -> &'static str { match self { Self::ArrowDown => "Down", Self::ArrowLeft => "Left", Self::ArrowRight => "Right", Self::ArrowUp => "Up", Self::Escape => "Escape", Self::Tab => "Tab", Self::Backspace => "Backspace", Self::Enter => "Enter", Self::Insert => "Insert", Self::Delete => "Delete", Self::Home => "Home", Self::End => "End", Self::PageUp => "PageUp", Self::PageDown => "PageDown", Self::Copy => "Copy", Self::Cut => "Cut", Self::Paste => "Paste", Self::Space => "Space", Self::Colon => "Colon", Self::Comma => "Comma", Self::Minus => "Minus", Self::Period => "Period", Self::Plus => "Plus", Self::Equals => "Equals", Self::Semicolon => "Semicolon", Self::Backslash => "Backslash", Self::Slash => "Slash", Self::Pipe => "Pipe", Self::Questionmark => "Questionmark", Self::Exclamationmark => "Exclamationmark", Self::OpenBracket => "OpenBracket", Self::CloseBracket => "CloseBracket", Self::OpenCurlyBracket => "OpenCurlyBracket", Self::CloseCurlyBracket => "CloseCurlyBracket", Self::Backtick => "Backtick", Self::Quote => "Quote", Self::Num0 => "0", Self::Num1 => "1", Self::Num2 => "2", Self::Num3 => "3", Self::Num4 => "4", Self::Num5 => "5", Self::Num6 => "6", Self::Num7 => "7", Self::Num8 => "8", Self::Num9 => "9", Self::A => "A", Self::B => "B", Self::C => "C", Self::D => "D", Self::E => "E", Self::F => "F", Self::G => "G", Self::H => "H", Self::I => "I", Self::J => "J", Self::K => "K", Self::L => "L", Self::M => "M", Self::N => "N", Self::O => "O", Self::P => "P", Self::Q => "Q", Self::R => "R", Self::S => "S", Self::T => "T", Self::U => "U", Self::V => "V", Self::W => "W", Self::X => "X", Self::Y => "Y", Self::Z => "Z", Self::F1 => "F1", Self::F2 => "F2", Self::F3 => "F3", Self::F4 => "F4", Self::F5 => "F5", Self::F6 => "F6", Self::F7 => "F7", Self::F8 => "F8", Self::F9 => "F9", Self::F10 => "F10", Self::F11 => "F11", Self::F12 => "F12", Self::F13 => "F13", Self::F14 => "F14", Self::F15 => "F15", Self::F16 => "F16", Self::F17 => "F17", Self::F18 => "F18", Self::F19 => "F19", Self::F20 => "F20", Self::F21 => "F21", Self::F22 => "F22", Self::F23 => "F23", Self::F24 => "F24", Self::F25 => "F25", Self::F26 => "F26", Self::F27 => "F27", Self::F28 => "F28", Self::F29 => "F29", Self::F30 => "F30", Self::F31 => "F31", Self::F32 => "F32", Self::F33 => "F33", Self::F34 => "F34", Self::F35 => "F35", Self::BrowserBack => "BrowserBack", } } } #[test] fn test_key_from_name() { assert_eq!( Key::ALL.len(), Key::BrowserBack as usize + 1, "Some keys are missing in Key::ALL" ); for &key in Key::ALL { let name = key.name(); assert_eq!( Key::from_name(name), Some(key), "Failed to roundtrip {key:?} from name {name:?}" ); let symbol = key.symbol_or_name(); assert_eq!( Key::from_name(symbol), Some(key), "Failed to roundtrip {key:?} from symbol {symbol:?}" ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/data/user_data.rs
crates/egui/src/data/user_data.rs
use std::{any::Any, sync::Arc}; /// A wrapper around `dyn Any`, used for passing custom user data /// to [`crate::ViewportCommand::Screenshot`]. #[derive(Clone, Debug, Default)] pub struct UserData { /// A user value given to the screenshot command, /// that will be returned in [`crate::Event::Screenshot`]. pub data: Option<Arc<dyn Any + Send + Sync>>, } impl UserData { /// You can also use [`Self::default`]. pub fn new(user_info: impl Any + Send + Sync) -> Self { Self { data: Some(Arc::new(user_info)), } } } impl PartialEq for UserData { fn eq(&self, other: &Self) -> bool { match (&self.data, &other.data) { (Some(a), Some(b)) => Arc::ptr_eq(a, b), (None, None) => true, _ => false, } } } impl Eq for UserData {} impl std::hash::Hash for UserData { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.data.as_ref().map(Arc::as_ptr).hash(state); } } #[cfg(feature = "serde")] impl serde::Serialize for UserData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_none() // can't serialize an `Any` } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for UserData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct UserDataVisitor; impl serde::de::Visitor<'_> for UserDataVisitor { type Value = UserData; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("a None value") } fn visit_none<E>(self) -> Result<UserData, E> where E: serde::de::Error, { Ok(UserData::default()) } } deserializer.deserialize_option(UserDataVisitor) } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/data/mod.rs
crates/egui/src/data/mod.rs
//! All the data sent between egui and the backend pub mod input; mod key; pub mod output; mod user_data; pub use key::Key; pub use user_data::UserData;
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/data/output.rs
crates/egui/src/data/output.rs
//! All the data egui returns to the backend at the end of each frame. use crate::{OrderedViewportIdMap, RepaintCause, ViewportOutput, WidgetType}; /// What egui emits each frame from [`crate::Context::run`]. /// /// The backend should use this. #[derive(Clone, Default)] pub struct FullOutput { /// Non-rendering related output. pub platform_output: PlatformOutput, /// Texture changes since last frame (including the font texture). /// /// The backend needs to apply [`crate::TexturesDelta::set`] _before_ painting, /// and free any texture in [`crate::TexturesDelta::free`] _after_ painting. /// /// It is assumed that all egui viewports share the same painter and texture namespace. pub textures_delta: epaint::textures::TexturesDelta, /// What to paint. /// /// You can use [`crate::Context::tessellate`] to turn this into triangles. pub shapes: Vec<epaint::ClippedShape>, /// The number of physical pixels per logical ui point, for the viewport that was updated. /// /// You can pass this to [`crate::Context::tessellate`] together with [`Self::shapes`]. pub pixels_per_point: f32, /// All the active viewports, including the root. /// /// It is up to the integration to spawn a native window for each viewport, /// and to close any window that no longer has a viewport in this map. pub viewport_output: OrderedViewportIdMap<ViewportOutput>, } impl FullOutput { /// Add on new output. pub fn append(&mut self, newer: Self) { use std::collections::btree_map::Entry; let Self { platform_output, textures_delta, shapes, pixels_per_point, viewport_output, } = newer; self.platform_output.append(platform_output); self.textures_delta.append(textures_delta); self.shapes = shapes; // Only paint the latest self.pixels_per_point = pixels_per_point; // Use latest for (id, new_viewport) in viewport_output { match self.viewport_output.entry(id) { Entry::Vacant(entry) => { entry.insert(new_viewport); } Entry::Occupied(mut entry) => { entry.get_mut().append(new_viewport); } } } } } /// Information about text being edited. /// /// Useful for IME. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct IMEOutput { /// Where the [`crate::TextEdit`] is located on screen. pub rect: crate::Rect, /// Where the primary cursor is. /// /// This is a very thin rectangle. pub cursor_rect: crate::Rect, } /// Commands that the egui integration should execute at the end of a frame. /// /// Commands that are specific to a viewport should be put in [`crate::ViewportCommand`] instead. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum OutputCommand { /// Put this text to the system clipboard. /// /// This is often a response to [`crate::Event::Copy`] or [`crate::Event::Cut`]. CopyText(String), /// Put this image to the system clipboard. CopyImage(crate::ColorImage), /// Open this url in a browser. OpenUrl(OpenUrl), } /// The non-rendering part of what egui emits each frame. /// /// You can access (and modify) this with [`crate::Context::output`]. /// /// The backend should use this. #[derive(Default, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct PlatformOutput { /// Commands that the egui integration should execute at the end of a frame. pub commands: Vec<OutputCommand>, /// Set the cursor to this icon. pub cursor_icon: CursorIcon, /// Events that may be useful to e.g. a screen reader. pub events: Vec<OutputEvent>, /// Is there a mutable [`TextEdit`](crate::TextEdit) under the cursor? /// Use by `eframe` web to show/hide mobile keyboard and IME agent. pub mutable_text_under_cursor: bool, /// This is set if, and only if, the user is currently editing text. /// /// Useful for IME. pub ime: Option<IMEOutput>, /// The difference in the widget tree since last frame. /// /// NOTE: this needs to be per-viewport. pub accesskit_update: Option<accesskit::TreeUpdate>, /// How many ui passes is this the sum of? /// /// See [`crate::Context::request_discard`] for details. /// /// This is incremented at the END of each frame, /// so this will be `0` for the first pass. pub num_completed_passes: usize, /// Was [`crate::Context::request_discard`] called during the latest pass? /// /// If so, what was the reason(s) for it? /// /// If empty, there was never any calls. #[cfg_attr(feature = "serde", serde(skip))] pub request_discard_reasons: Vec<RepaintCause>, } impl PlatformOutput { /// This can be used by a text-to-speech system to describe the events (if any). pub fn events_description(&self) -> String { // only describe last event: if let Some(event) = self.events.iter().next_back() { match event { OutputEvent::Clicked(widget_info) | OutputEvent::DoubleClicked(widget_info) | OutputEvent::TripleClicked(widget_info) | OutputEvent::FocusGained(widget_info) | OutputEvent::TextSelectionChanged(widget_info) | OutputEvent::ValueChanged(widget_info) => { return widget_info.description(); } } } Default::default() } /// Add on new output. pub fn append(&mut self, newer: Self) { let Self { mut commands, cursor_icon, mut events, mutable_text_under_cursor, ime, accesskit_update, num_completed_passes, mut request_discard_reasons, } = newer; self.commands.append(&mut commands); self.cursor_icon = cursor_icon; self.events.append(&mut events); self.mutable_text_under_cursor = mutable_text_under_cursor; self.ime = ime.or(self.ime); self.num_completed_passes += num_completed_passes; self.request_discard_reasons .append(&mut request_discard_reasons); // egui produces a complete AccessKit tree for each frame, so overwrite rather than append: self.accesskit_update = accesskit_update; } /// Take everything ephemeral (everything except `cursor_icon` currently) pub fn take(&mut self) -> Self { let taken = std::mem::take(self); self.cursor_icon = taken.cursor_icon; // everything else is ephemeral taken } /// Was [`crate::Context::request_discard`] called? pub fn requested_discard(&self) -> bool { !self.request_discard_reasons.is_empty() } } /// What URL to open, and how. /// /// Use with [`crate::Context::open_url`]. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct OpenUrl { pub url: String, /// If `true`, open the url in a new tab. /// If `false` open it in the same tab. /// Only matters when in a web browser. pub new_tab: bool, } impl OpenUrl { #[expect(clippy::needless_pass_by_value)] pub fn same_tab(url: impl ToString) -> Self { Self { url: url.to_string(), new_tab: false, } } #[expect(clippy::needless_pass_by_value)] pub fn new_tab(url: impl ToString) -> Self { Self { url: url.to_string(), new_tab: true, } } } /// Types of attention to request from a user when a native window is not in focus. /// /// See [winit's documentation][user_attention_type] for platform-specific meaning of the attention types. /// /// [user_attention_type]: https://docs.rs/winit/latest/winit/window/enum.UserAttentionType.html #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum UserAttentionType { /// Request an elevated amount of animations and flair for the window and the task bar or dock icon. Critical, /// Request a standard amount of attention-grabbing actions. Informational, /// Reset the attention request and interrupt related animations and flashes. Reset, } /// A mouse cursor icon. /// /// egui emits a [`CursorIcon`] in [`PlatformOutput`] each frame as a request to the integration. /// /// Loosely based on <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor>. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum CursorIcon { /// Normal cursor icon, whatever that is. #[default] Default, /// Show no cursor None, // ------------------------------------ // Links and status: /// A context menu is available ContextMenu, /// Question mark Help, /// Pointing hand, used for e.g. web links PointingHand, /// Shows that processing is being done, but that the program is still interactive. Progress, /// Not yet ready, try later. Wait, // ------------------------------------ // Selection: /// Hover a cell in a table Cell, /// For precision work Crosshair, /// Text caret, e.g. "Click here to edit text" Text, /// Vertical text caret, e.g. "Click here to edit vertical text" VerticalText, // ------------------------------------ // Drag-and-drop: /// Indicated an alias, e.g. a shortcut Alias, /// Indicate that a copy will be made Copy, /// Omnidirectional move icon (e.g. arrows in all cardinal directions) Move, /// Can't drop here NoDrop, /// Forbidden NotAllowed, /// The thing you are hovering can be grabbed Grab, /// You are grabbing the thing you are hovering Grabbing, // ------------------------------------ /// Something can be scrolled in any direction (panned). AllScroll, // ------------------------------------ // Resizing in two directions: /// Horizontal resize `-` to make something wider or more narrow (left to/from right) ResizeHorizontal, /// Diagonal resize `/` (right-up to/from left-down) ResizeNeSw, /// Diagonal resize `\` (left-up to/from right-down) ResizeNwSe, /// Vertical resize `|` (up-down or down-up) ResizeVertical, // ------------------------------------ // Resizing in one direction: /// Resize something rightwards (e.g. when dragging the right-most edge of something) ResizeEast, /// Resize something down and right (e.g. when dragging the bottom-right corner of something) ResizeSouthEast, /// Resize something downwards (e.g. when dragging the bottom edge of something) ResizeSouth, /// Resize something down and left (e.g. when dragging the bottom-left corner of something) ResizeSouthWest, /// Resize something leftwards (e.g. when dragging the left edge of something) ResizeWest, /// Resize something up and left (e.g. when dragging the top-left corner of something) ResizeNorthWest, /// Resize something up (e.g. when dragging the top edge of something) ResizeNorth, /// Resize something up and right (e.g. when dragging the top-right corner of something) ResizeNorthEast, // ------------------------------------ /// Resize a column ResizeColumn, /// Resize a row ResizeRow, // ------------------------------------ // Zooming: /// Enhance! ZoomIn, /// Let's get a better overview ZoomOut, } impl CursorIcon { pub const ALL: [Self; 35] = [ Self::Default, Self::None, Self::ContextMenu, Self::Help, Self::PointingHand, Self::Progress, Self::Wait, Self::Cell, Self::Crosshair, Self::Text, Self::VerticalText, Self::Alias, Self::Copy, Self::Move, Self::NoDrop, Self::NotAllowed, Self::Grab, Self::Grabbing, Self::AllScroll, Self::ResizeHorizontal, Self::ResizeNeSw, Self::ResizeNwSe, Self::ResizeVertical, Self::ResizeEast, Self::ResizeSouthEast, Self::ResizeSouth, Self::ResizeSouthWest, Self::ResizeWest, Self::ResizeNorthWest, Self::ResizeNorth, Self::ResizeNorthEast, Self::ResizeColumn, Self::ResizeRow, Self::ZoomIn, Self::ZoomOut, ]; } /// Things that happened during this frame that the integration may be interested in. /// /// In particular, these events may be useful for accessibility, i.e. for screen readers. #[derive(Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum OutputEvent { /// A widget was clicked. Clicked(WidgetInfo), /// A widget was double-clicked. DoubleClicked(WidgetInfo), /// A widget was triple-clicked. TripleClicked(WidgetInfo), /// A widget gained keyboard focus (by tab key). FocusGained(WidgetInfo), /// Text selection was updated. TextSelectionChanged(WidgetInfo), /// A widget's value changed. ValueChanged(WidgetInfo), } impl OutputEvent { pub fn widget_info(&self) -> &WidgetInfo { match self { Self::Clicked(info) | Self::DoubleClicked(info) | Self::TripleClicked(info) | Self::FocusGained(info) | Self::TextSelectionChanged(info) | Self::ValueChanged(info) => info, } } } impl std::fmt::Debug for OutputEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Clicked(wi) => write!(f, "Clicked({wi:?})"), Self::DoubleClicked(wi) => write!(f, "DoubleClicked({wi:?})"), Self::TripleClicked(wi) => write!(f, "TripleClicked({wi:?})"), Self::FocusGained(wi) => write!(f, "FocusGained({wi:?})"), Self::TextSelectionChanged(wi) => write!(f, "TextSelectionChanged({wi:?})"), Self::ValueChanged(wi) => write!(f, "ValueChanged({wi:?})"), } } } /// Describes a widget such as a [`crate::Button`] or a [`crate::TextEdit`]. #[derive(Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct WidgetInfo { /// The type of widget this is. pub typ: WidgetType, /// Whether the widget is enabled. pub enabled: bool, /// The text on labels, buttons, checkboxes etc. pub label: Option<String>, /// The contents of some editable text (for [`TextEdit`](crate::TextEdit) fields). pub current_text_value: Option<String>, /// The previous text value. pub prev_text_value: Option<String>, /// The current value of checkboxes and radio buttons. pub selected: Option<bool>, /// The current value of sliders etc. pub value: Option<f64>, /// Selected range of characters in [`Self::current_text_value`]. pub text_selection: Option<std::ops::RangeInclusive<usize>>, /// The hint text for text edit fields. pub hint_text: Option<String>, } impl std::fmt::Debug for WidgetInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { typ, enabled, label, current_text_value: text_value, prev_text_value, selected, value, text_selection, hint_text, } = self; let mut s = f.debug_struct("WidgetInfo"); s.field("typ", typ); if !enabled { s.field("enabled", enabled); } if let Some(label) = label { s.field("label", label); } if let Some(text_value) = text_value { s.field("text_value", text_value); } if let Some(prev_text_value) = prev_text_value { s.field("prev_text_value", prev_text_value); } if let Some(selected) = selected { s.field("selected", selected); } if let Some(value) = value { s.field("value", value); } if let Some(text_selection) = text_selection { s.field("text_selection", text_selection); } if let Some(hint_text) = hint_text { s.field("hint_text", hint_text); } s.finish() } } impl WidgetInfo { pub fn new(typ: WidgetType) -> Self { Self { typ, enabled: true, label: None, current_text_value: None, prev_text_value: None, selected: None, value: None, text_selection: None, hint_text: None, } } #[expect(clippy::needless_pass_by_value)] pub fn labeled(typ: WidgetType, enabled: bool, label: impl ToString) -> Self { Self { enabled, label: Some(label.to_string()), ..Self::new(typ) } } /// checkboxes, radio-buttons etc #[expect(clippy::needless_pass_by_value)] pub fn selected(typ: WidgetType, enabled: bool, selected: bool, label: impl ToString) -> Self { Self { enabled, label: Some(label.to_string()), selected: Some(selected), ..Self::new(typ) } } pub fn drag_value(enabled: bool, value: f64) -> Self { Self { enabled, value: Some(value), ..Self::new(WidgetType::DragValue) } } #[expect(clippy::needless_pass_by_value)] pub fn slider(enabled: bool, value: f64, label: impl ToString) -> Self { let label = label.to_string(); Self { enabled, label: if label.is_empty() { None } else { Some(label) }, value: Some(value), ..Self::new(WidgetType::Slider) } } #[expect(clippy::needless_pass_by_value)] pub fn text_edit( enabled: bool, prev_text_value: impl ToString, text_value: impl ToString, hint_text: impl ToString, ) -> Self { let text_value = text_value.to_string(); let prev_text_value = prev_text_value.to_string(); let hint_text = hint_text.to_string(); let prev_text_value = if text_value == prev_text_value { None } else { Some(prev_text_value) }; Self { enabled, current_text_value: Some(text_value), prev_text_value, hint_text: Some(hint_text), ..Self::new(WidgetType::TextEdit) } } #[expect(clippy::needless_pass_by_value)] pub fn text_selection_changed( enabled: bool, text_selection: std::ops::RangeInclusive<usize>, current_text_value: impl ToString, ) -> Self { Self { enabled, text_selection: Some(text_selection), current_text_value: Some(current_text_value.to_string()), ..Self::new(WidgetType::TextEdit) } } /// This can be used by a text-to-speech system to describe the widget. pub fn description(&self) -> String { let Self { typ, enabled, label, current_text_value: text_value, prev_text_value: _, selected, value, text_selection: _, hint_text: _, } = self; // TODO(emilk): localization let widget_type = match typ { WidgetType::Link => "link", WidgetType::TextEdit => "text edit", WidgetType::Button => "button", WidgetType::Checkbox => "checkbox", WidgetType::RadioButton => "radio", WidgetType::RadioGroup => "radio group", WidgetType::SelectableLabel => "selectable", WidgetType::ComboBox => "combo", WidgetType::Slider => "slider", WidgetType::DragValue => "drag value", WidgetType::ColorButton => "color button", WidgetType::Image => "image", WidgetType::CollapsingHeader => "collapsing header", WidgetType::Panel => "panel", WidgetType::ProgressIndicator => "progress indicator", WidgetType::Window => "window", WidgetType::ScrollBar => "scroll bar", WidgetType::ResizeHandle => "resize handle", WidgetType::Label | WidgetType::Other => "", }; let mut description = widget_type.to_owned(); if let Some(selected) = selected { if *typ == WidgetType::Checkbox { let state = if *selected { "checked" } else { "unchecked" }; description = format!("{state} {description}"); } else { description += if *selected { "selected" } else { "" }; } } if let Some(label) = label { description = format!("{label}: {description}"); } if typ == &WidgetType::TextEdit { let text = if let Some(text_value) = text_value { if text_value.is_empty() { "blank".into() } else { text_value.clone() } } else { "blank".into() }; description = format!("{text}: {description}"); } if let Some(value) = value { description += " "; description += &value.to_string(); } if !enabled { description += ": disabled"; } description.trim().to_owned() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/data/input.rs
crates/egui/src/data/input.rs
//! The input needed by egui. use epaint::{ColorImage, MarginF32}; use crate::{ Key, OrderedViewportIdMap, Theme, ViewportId, ViewportIdMap, emath::{Pos2, Rect, Vec2}, }; /// What the integrations provides to egui at the start of each frame. /// /// Set the values that make sense, leave the rest at their `Default::default()`. /// /// You can check if `egui` is using the inputs using /// [`crate::Context::wants_pointer_input`] and [`crate::Context::wants_keyboard_input`]. /// /// All coordinates are in points (logical pixels) with origin (0, 0) in the top left .corner. /// /// Ii "points" can be calculated from native physical pixels /// using `pixels_per_point` = [`crate::Context::zoom_factor`] * `native_pixels_per_point`; #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct RawInput { /// The id of the active viewport. pub viewport_id: ViewportId, /// Information about all egui viewports. pub viewports: ViewportIdMap<ViewportInfo>, /// The insets used to only render content in a mobile safe area /// /// `None` will be treated as "same as last frame" pub safe_area_insets: Option<SafeAreaInsets>, /// Position and size of the area that egui should use, in points. /// Usually you would set this to /// /// `Some(Rect::from_min_size(Default::default(), screen_size_in_points))`. /// /// but you could also constrain egui to some smaller portion of your window if you like. /// /// `None` will be treated as "same as last frame", with the default being a very big area. pub screen_rect: Option<Rect>, /// Maximum size of one side of the font texture. /// /// Ask your graphics drivers about this. This corresponds to `GL_MAX_TEXTURE_SIZE`. /// /// The default is a very small (but very portable) 2048. pub max_texture_side: Option<usize>, /// Monotonically increasing time, in seconds. Relative to whatever. Used for animations. /// If `None` is provided, egui will assume a time delta of `predicted_dt` (default 1/60 seconds). pub time: Option<f64>, /// Should be set to the expected time between frames when painting at vsync speeds. /// The default for this is 1/60. /// Can safely be left at its default value. pub predicted_dt: f32, /// Which modifier keys are down at the start of the frame? pub modifiers: Modifiers, /// In-order events received this frame. /// /// There is currently no way to know if egui handles a particular event, /// but you can check if egui is using the keyboard with [`crate::Context::wants_keyboard_input`] /// and/or the pointer (mouse/touch) with [`crate::Context::is_using_pointer`]. pub events: Vec<Event>, /// Dragged files hovering over egui. pub hovered_files: Vec<HoveredFile>, /// Dragged files dropped into egui. /// /// Note: when using `eframe` on Windows, this will always be empty if drag-and-drop support has /// been disabled in [`crate::viewport::ViewportBuilder`]. pub dropped_files: Vec<DroppedFile>, /// The native window has the keyboard focus (i.e. is receiving key presses). /// /// False when the user alt-tab away from the application, for instance. pub focused: bool, /// Does the OS use dark or light mode? /// /// `None` means "don't know". pub system_theme: Option<Theme>, } impl Default for RawInput { fn default() -> Self { Self { viewport_id: ViewportId::ROOT, viewports: std::iter::once((ViewportId::ROOT, Default::default())).collect(), screen_rect: None, max_texture_side: None, time: None, predicted_dt: 1.0 / 60.0, modifiers: Modifiers::default(), events: vec![], hovered_files: Default::default(), dropped_files: Default::default(), focused: true, // integrations opt into global focus tracking system_theme: None, safe_area_insets: Default::default(), } } } impl RawInput { /// Info about the active viewport #[inline] pub fn viewport(&self) -> &ViewportInfo { self.viewports.get(&self.viewport_id).expect("Failed to find current viewport in egui RawInput. This is the fault of the egui backend") } /// Helper: move volatile (deltas and events), clone the rest. /// /// * [`Self::hovered_files`] is cloned. /// * [`Self::dropped_files`] is moved. pub fn take(&mut self) -> Self { Self { viewport_id: self.viewport_id, viewports: self .viewports .iter_mut() .map(|(id, info)| (*id, info.take())) .collect(), screen_rect: self.screen_rect.take(), safe_area_insets: self.safe_area_insets.take(), max_texture_side: self.max_texture_side.take(), time: self.time, predicted_dt: self.predicted_dt, modifiers: self.modifiers, events: std::mem::take(&mut self.events), hovered_files: self.hovered_files.clone(), dropped_files: std::mem::take(&mut self.dropped_files), focused: self.focused, system_theme: self.system_theme, } } /// Add on new input. pub fn append(&mut self, newer: Self) { let Self { viewport_id: viewport_ids, viewports, screen_rect, max_texture_side, time, predicted_dt, modifiers, mut events, mut hovered_files, mut dropped_files, focused, system_theme, safe_area_insets: safe_area, } = newer; self.viewport_id = viewport_ids; self.viewports = viewports; self.screen_rect = screen_rect.or(self.screen_rect); self.max_texture_side = max_texture_side.or(self.max_texture_side); self.time = time; // use latest time self.predicted_dt = predicted_dt; // use latest dt self.modifiers = modifiers; // use latest self.events.append(&mut events); self.hovered_files.append(&mut hovered_files); self.dropped_files.append(&mut dropped_files); self.focused = focused; self.system_theme = system_theme; self.safe_area_insets = safe_area; } } /// An input event from the backend into egui, about a specific [viewport](crate::viewport). #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ViewportEvent { /// The user clicked the close-button on the window, or similar. /// /// If this is the root viewport, the application will exit /// after this frame unless you send a /// [`crate::ViewportCommand::CancelClose`] command. /// /// If this is not the root viewport, /// it is up to the user to hide this viewport the next frame. /// /// This even will wake up both the child and parent viewport. Close, } /// Information about the current viewport, given as input each frame. /// /// `None` means "unknown". /// /// All units are in ui "points", which can be calculated from native physical pixels /// using `pixels_per_point` = [`crate::Context::zoom_factor`] * `[Self::native_pixels_per_point`]; #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct ViewportInfo { /// Parent viewport, if known. pub parent: Option<crate::ViewportId>, /// Name of the viewport, if known. pub title: Option<String>, pub events: Vec<ViewportEvent>, /// The OS native pixels-per-point. /// /// This should always be set, if known. /// /// On web this takes browser scaling into account, /// and corresponds to [`window.devicePixelRatio`](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) in JavaScript. pub native_pixels_per_point: Option<f32>, /// Current monitor size in egui points. pub monitor_size: Option<Vec2>, /// The inner rectangle of the native window, in monitor space and ui points scale. /// /// This is the content rectangle of the viewport. /// /// **`eframe` notes**: /// /// On Android / Wayland, this will always be `None` since getting the /// position of the window is not possible. pub inner_rect: Option<Rect>, /// The outer rectangle of the native window, in monitor space and ui points scale. /// /// This is the content rectangle plus decoration chrome. /// /// **`eframe` notes**: /// /// On Android / Wayland, this will always be `None` since getting the /// position of the window is not possible. pub outer_rect: Option<Rect>, /// Are we minimized? pub minimized: Option<bool>, /// Are we maximized? pub maximized: Option<bool>, /// Are we in fullscreen mode? pub fullscreen: Option<bool>, /// Is the window focused and able to receive input? /// /// This should be the same as [`RawInput::focused`]. pub focused: Option<bool>, } impl ViewportInfo { /// This viewport has been told to close. /// /// If this is the root viewport, the application will exit /// after this frame unless you send a /// [`crate::ViewportCommand::CancelClose`] command. /// /// If this is not the root viewport, /// it is up to the user to hide this viewport the next frame. pub fn close_requested(&self) -> bool { self.events.contains(&ViewportEvent::Close) } /// Helper: move [`Self::events`], clone the other fields. pub fn take(&mut self) -> Self { Self { parent: self.parent, title: self.title.clone(), events: std::mem::take(&mut self.events), native_pixels_per_point: self.native_pixels_per_point, monitor_size: self.monitor_size, inner_rect: self.inner_rect, outer_rect: self.outer_rect, minimized: self.minimized, maximized: self.maximized, fullscreen: self.fullscreen, focused: self.focused, } } pub fn ui(&self, ui: &mut crate::Ui) { let Self { parent, title, events, native_pixels_per_point, monitor_size, inner_rect, outer_rect, minimized, maximized, fullscreen, focused, } = self; crate::Grid::new("viewport_info").show(ui, |ui| { ui.label("Parent:"); ui.label(opt_as_str(parent)); ui.end_row(); ui.label("Title:"); ui.label(opt_as_str(title)); ui.end_row(); ui.label("Events:"); ui.label(format!("{events:?}")); ui.end_row(); ui.label("Native pixels-per-point:"); ui.label(opt_as_str(native_pixels_per_point)); ui.end_row(); ui.label("Monitor size:"); ui.label(opt_as_str(monitor_size)); ui.end_row(); ui.label("Inner rect:"); ui.label(opt_rect_as_string(inner_rect)); ui.end_row(); ui.label("Outer rect:"); ui.label(opt_rect_as_string(outer_rect)); ui.end_row(); ui.label("Minimized:"); ui.label(opt_as_str(minimized)); ui.end_row(); ui.label("Maximized:"); ui.label(opt_as_str(maximized)); ui.end_row(); ui.label("Fullscreen:"); ui.label(opt_as_str(fullscreen)); ui.end_row(); ui.label("Focused:"); ui.label(opt_as_str(focused)); ui.end_row(); fn opt_rect_as_string(v: &Option<Rect>) -> String { v.as_ref().map_or(String::new(), |r| { format!("Pos: {:?}, size: {:?}", r.min, r.size()) }) } fn opt_as_str<T: std::fmt::Debug>(v: &Option<T>) -> String { v.as_ref().map_or(String::new(), |v| format!("{v:?}")) } }); } } /// A file about to be dropped into egui. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct HoveredFile { /// Set by the `egui-winit` backend. pub path: Option<std::path::PathBuf>, /// With the `eframe` web backend, this is set to the mime-type of the file (if available). pub mime: String, } /// A file dropped into egui. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct DroppedFile { /// Set by the `egui-winit` backend. pub path: Option<std::path::PathBuf>, /// Name of the file. Set by the `eframe` web backend. pub name: String, /// With the `eframe` web backend, this is set to the mime-type of the file (if available). pub mime: String, /// Set by the `eframe` web backend. pub last_modified: Option<std::time::SystemTime>, /// Set by the `eframe` web backend. pub bytes: Option<std::sync::Arc<[u8]>>, } /// An input event generated by the integration. /// /// This only covers events that egui cares about. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Event { /// The integration detected a "copy" event (e.g. Cmd+C). Copy, /// The integration detected a "cut" event (e.g. Cmd+X). Cut, /// The integration detected a "paste" event (e.g. Cmd+V). Paste(String), /// Text input, e.g. via keyboard. /// /// When the user presses enter/return, do not send a [`Text`](Event::Text) (just [`Key::Enter`]). Text(String), /// A key was pressed or released. Key { /// Most of the time, it's the logical key, heeding the active keymap -- for instance, if the user has Dvorak /// keyboard layout, it will be taken into account. /// /// If it's impossible to determine the logical key on desktop platforms (say, in case of non-Latin letters), /// `key` falls back to the value of the corresponding physical key. This is necessary for proper work of /// standard shortcuts that only respond to Latin-based bindings (such as `Ctrl` + `V`). key: Key, /// The physical key, corresponding to the actual position on the keyboard. /// /// This ignores keymaps, so it is not recommended to use this. /// The only thing it makes sense for is things like games, /// where e.g. the physical location of WSAD on QWERTY should always map to movement, /// even if the user is using Dvorak or AZERTY. /// /// `eframe` does not (yet) implement this on web. physical_key: Option<Key>, /// Was it pressed or released? pressed: bool, /// If this is a `pressed` event, is it a key-repeat? /// /// On many platforms, holding down a key produces many repeated "pressed" events for it, so called key-repeats. /// Sometimes you will want to ignore such events, and this lets you do that. /// /// egui will automatically detect such repeat events and mark them as such here. /// Therefore, if you are writing an egui integration, you do not need to set this (just set it to `false`). repeat: bool, /// The state of the modifier keys at the time of the event. modifiers: Modifiers, }, /// The mouse or touch moved to a new place. PointerMoved(Pos2), /// The mouse moved, the units are unspecified. /// Represents the actual movement of the mouse, without acceleration or clamped by screen edges. /// `PointerMoved` and `MouseMoved` can be sent at the same time. /// This event is optional. If the integration can not determine unfiltered motion it should not send this event. MouseMoved(Vec2), /// A mouse button was pressed or released (or a touch started or stopped). PointerButton { /// Where is the pointer? pos: Pos2, /// What mouse button? For touches, use [`PointerButton::Primary`]. button: PointerButton, /// Was it the button/touch pressed this frame, or released? pressed: bool, /// The state of the modifier keys at the time of the event. modifiers: Modifiers, }, /// The mouse left the screen, or the last/primary touch input disappeared. /// /// This means there is no longer a cursor on the screen for hovering etc. /// /// On touch-up first send `PointerButton{pressed: false, …}` followed by `PointerLeft`. PointerGone, /// Zoom scale factor this frame (e.g. from a pinch gesture). /// /// * `zoom = 1`: no change. /// * `zoom < 1`: pinch together /// * `zoom > 1`: pinch spread /// /// Note that egui also implement zooming by holding `Ctrl` and scrolling the mouse wheel, /// so integration need NOT emit this `Zoom` event in those cases, just [`Self::MouseWheel`]. /// /// As a user, check [`crate::InputState::smooth_scroll_delta`] to see if the user did any zooming this frame. Zoom(f32), /// Rotation in radians this frame, measuring clockwise (e.g. from a rotation gesture). Rotate(f32), /// IME Event Ime(ImeEvent), /// On touch screens, report this *in addition to* /// [`Self::PointerMoved`], [`Self::PointerButton`], [`Self::PointerGone`] Touch { /// Hashed device identifier (if available; may be zero). /// Can be used to separate touches from different devices. device_id: TouchDeviceId, /// Unique identifier of a finger/pen. Value is stable from touch down /// to lift-up id: TouchId, /// One of: start move end cancel. phase: TouchPhase, /// Position of the touch (or where the touch was last detected) pos: Pos2, /// Describes how hard the touch device was pressed. May always be `None` if the platform does /// not support pressure sensitivity. /// The value is in the range from 0.0 (no pressure) to 1.0 (maximum pressure). force: Option<f32>, }, /// A raw mouse wheel event as sent by the backend. /// /// Used for scrolling. MouseWheel { /// The unit of `delta`: points, lines, or pages. unit: MouseWheelUnit, /// The direction of the vector indicates how to move the _content_ that is being viewed. /// So if you get positive values, the content being viewed should move to the right and down, /// revealing new things to the left and up. /// /// A positive X-value indicates the content is being moved right, /// as when swiping right on a touch-screen or track-pad with natural scrolling. /// /// A positive Y-value indicates the content is being moved down, /// as when swiping down on a touch-screen or track-pad with natural scrolling. delta: Vec2, /// The phase of the scroll, useful for trackpads. /// /// If unknown set this to [`TouchPhase::Move`]. phase: TouchPhase, /// The state of the modifier keys at the time of the event. modifiers: Modifiers, }, /// The native window gained or lost focused (e.g. the user clicked alt-tab). WindowFocused(bool), /// An assistive technology (e.g. screen reader) requested an action. AccessKitActionRequest(accesskit::ActionRequest), /// The reply of a screenshot requested with [`crate::ViewportCommand::Screenshot`]. Screenshot { viewport_id: crate::ViewportId, /// Whatever was passed to [`crate::ViewportCommand::Screenshot`]. user_data: crate::UserData, image: std::sync::Arc<ColorImage>, }, } /// IME event. /// /// See <https://docs.rs/winit/latest/winit/event/enum.Ime.html> #[derive(Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum ImeEvent { /// Notifies when the IME was enabled. Enabled, /// A new IME candidate is being suggested. Preedit(String), /// IME composition ended with this final result. Commit(String), /// Notifies when the IME was disabled. Disabled, } /// Mouse button (or similar for touch input) #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum PointerButton { /// The primary mouse button is usually the left one. Primary = 0, /// The secondary mouse button is usually the right one, /// and most often used for context menus or other optional things. Secondary = 1, /// The tertiary mouse button is usually the middle mouse button (e.g. clicking the scroll wheel). Middle = 2, /// The first extra mouse button on some mice. In web typically corresponds to the Browser back button. Extra1 = 3, /// The second extra mouse button on some mice. In web typically corresponds to the Browser forward button. Extra2 = 4, } /// Number of pointer buttons supported by egui, i.e. the number of possible states of [`PointerButton`]. pub const NUM_POINTER_BUTTONS: usize = 5; /// State of the modifier keys. These must be fed to egui. /// /// The best way to compare [`Modifiers`] is by using [`Modifiers::matches_logically`] or [`Modifiers::matches_exact`]. /// /// NOTE: For cross-platform uses, ALT+SHIFT is a bad combination of modifiers /// as on mac that is how you type special characters, /// so those key presses are usually not reported to egui. #[derive(Clone, Copy, Default, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub struct Modifiers { /// Either of the alt keys are down (option ⌥ on Mac). pub alt: bool, /// Either of the control keys are down. /// When checking for keyboard shortcuts, consider using [`Self::command`] instead. pub ctrl: bool, /// Either of the shift keys are down. pub shift: bool, /// The Mac ⌘ Command key. Should always be set to `false` on other platforms. pub mac_cmd: bool, /// On Windows and Linux, set this to the same value as `ctrl`. /// On Mac, this should be set whenever one of the ⌘ Command keys are down (same as `mac_cmd`). /// This is so that egui can, for instance, select all text by checking for `command + A` /// and it will work on both Mac and Windows. pub command: bool, } impl std::fmt::Debug for Modifiers { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.is_none() { return write!(f, "Modifiers::NONE"); } let Self { alt, ctrl, shift, mac_cmd, command, } = *self; let mut debug = f.debug_struct("Modifiers"); if alt { debug.field("alt", &true); } if ctrl { debug.field("ctrl", &true); } if shift { debug.field("shift", &true); } if mac_cmd { debug.field("mac_cmd", &true); } if command { debug.field("command", &true); } debug.finish() } } impl Modifiers { pub const NONE: Self = Self { alt: false, ctrl: false, shift: false, mac_cmd: false, command: false, }; pub const ALT: Self = Self { alt: true, ctrl: false, shift: false, mac_cmd: false, command: false, }; pub const CTRL: Self = Self { alt: false, ctrl: true, shift: false, mac_cmd: false, command: false, }; pub const SHIFT: Self = Self { alt: false, ctrl: false, shift: true, mac_cmd: false, command: false, }; /// The Mac ⌘ Command key pub const MAC_CMD: Self = Self { alt: false, ctrl: false, shift: false, mac_cmd: true, command: false, }; /// On Mac: ⌘ Command key, elsewhere: Ctrl key pub const COMMAND: Self = Self { alt: false, ctrl: false, shift: false, mac_cmd: false, command: true, }; /// ``` /// # use egui::Modifiers; /// assert_eq!( /// Modifiers::CTRL | Modifiers::ALT, /// Modifiers { ctrl: true, alt: true, ..Default::default() } /// ); /// assert_eq!( /// Modifiers::ALT.plus(Modifiers::CTRL), /// Modifiers::CTRL.plus(Modifiers::ALT), /// ); /// assert_eq!( /// Modifiers::CTRL | Modifiers::ALT, /// Modifiers::CTRL.plus(Modifiers::ALT), /// ); /// ``` #[inline] pub const fn plus(self, rhs: Self) -> Self { Self { alt: self.alt | rhs.alt, ctrl: self.ctrl | rhs.ctrl, shift: self.shift | rhs.shift, mac_cmd: self.mac_cmd | rhs.mac_cmd, command: self.command | rhs.command, } } #[inline] pub fn is_none(&self) -> bool { self == &Self::default() } #[inline] pub fn any(&self) -> bool { !self.is_none() } #[inline] pub fn all(&self) -> bool { self.alt && self.ctrl && self.shift && self.command } /// Is shift the only pressed button? #[inline] pub fn shift_only(&self) -> bool { self.shift && !(self.alt || self.command) } /// true if only [`Self::ctrl`] or only [`Self::mac_cmd`] is pressed. #[inline] pub fn command_only(&self) -> bool { !self.alt && !self.shift && self.command } /// Checks that the `ctrl/cmd` matches, and that the `shift/alt` of the argument is a subset /// of the pressed key (`self`). /// /// This means that if the pattern has not set `shift`, then `self` can have `shift` set or not. /// /// The reason is that many logical keys require `shift` or `alt` on some keyboard layouts. /// For instance, in order to press `+` on an English keyboard, you need to press `shift` and `=`, /// but a Swedish keyboard has dedicated `+` key. /// So if you want to make a [`KeyboardShortcut`] looking for `Cmd` + `+`, it makes sense /// to ignore the shift key. /// Similarly, the `Alt` key is sometimes used to type special characters. /// /// However, if the pattern (the argument) explicitly requires the `shift` or `alt` keys /// to be pressed, then they must be pressed. /// /// # Example: /// ``` /// # use egui::Modifiers; /// # let pressed_modifiers = Modifiers::default(); /// if pressed_modifiers.matches_logically(Modifiers::ALT | Modifiers::SHIFT) { /// // Alt and Shift are pressed, but not ctrl/command /// } /// ``` /// /// ## Behavior: /// ``` /// # use egui::Modifiers; /// assert!(Modifiers::CTRL.matches_logically(Modifiers::CTRL)); /// assert!(!Modifiers::CTRL.matches_logically(Modifiers::CTRL | Modifiers::SHIFT)); /// assert!((Modifiers::CTRL | Modifiers::SHIFT).matches_logically(Modifiers::CTRL)); /// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches_logically(Modifiers::CTRL)); /// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches_logically(Modifiers::COMMAND)); /// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches_logically(Modifiers::COMMAND)); /// assert!(!Modifiers::COMMAND.matches_logically(Modifiers::MAC_CMD)); /// ``` pub fn matches_logically(&self, pattern: Self) -> bool { if pattern.alt && !self.alt { return false; } if pattern.shift && !self.shift { return false; } self.cmd_ctrl_matches(pattern) } /// Check for equality but with proper handling of [`Self::command`]. /// /// `self` here are the currently pressed modifiers, /// and the argument the pattern we are testing for. /// /// Note that this will require the `shift` and `alt` keys match, even though /// these modifiers are sometimes required to produce some logical keys. /// For instance, to press `+` on an English keyboard, you need to press `shift` and `=`, /// but on a Swedish keyboard you can press the dedicated `+` key. /// Therefore, you often want to use [`Self::matches_logically`] instead. /// /// # Example: /// ``` /// # use egui::Modifiers; /// # let pressed_modifiers = Modifiers::default(); /// if pressed_modifiers.matches_exact(Modifiers::ALT | Modifiers::SHIFT) { /// // Alt and Shift are pressed, and nothing else /// } /// ``` /// /// ## Behavior: /// ``` /// # use egui::Modifiers; /// assert!(Modifiers::CTRL.matches_exact(Modifiers::CTRL)); /// assert!(!Modifiers::CTRL.matches_exact(Modifiers::CTRL | Modifiers::SHIFT)); /// assert!(!(Modifiers::CTRL | Modifiers::SHIFT).matches_exact(Modifiers::CTRL)); /// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches_exact(Modifiers::CTRL)); /// assert!((Modifiers::CTRL | Modifiers::COMMAND).matches_exact(Modifiers::COMMAND)); /// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches_exact(Modifiers::COMMAND)); /// assert!(!Modifiers::COMMAND.matches_exact(Modifiers::MAC_CMD)); /// ``` pub fn matches_exact(&self, pattern: Self) -> bool { // alt and shift must always match the pattern: if pattern.alt != self.alt || pattern.shift != self.shift { return false; } self.cmd_ctrl_matches(pattern) } /// Check if any of the modifiers match exactly. /// /// Returns true if the same modifier is pressed in `self` as in `pattern`, /// for at least one modifier. /// /// ## Behavior: /// ``` /// # use egui::Modifiers; /// assert!(Modifiers::CTRL.matches_any(Modifiers::CTRL)); /// assert!(Modifiers::CTRL.matches_any(Modifiers::CTRL | Modifiers::SHIFT)); /// assert!((Modifiers::CTRL | Modifiers::SHIFT).matches_any(Modifiers::CTRL)); /// ``` pub fn matches_any(&self, pattern: Self) -> bool { if self.alt && pattern.alt { return true; } if self.shift && pattern.shift { return true; } if self.ctrl && pattern.ctrl { return true; } if self.mac_cmd && pattern.mac_cmd { return true; } if (self.mac_cmd || self.command || self.ctrl) && pattern.command { return true; } false } /// Checks only cmd/ctrl, not alt/shift. /// /// `self` here are the currently pressed modifiers, /// and the argument the pattern we are testing for. /// /// This takes care to properly handle the difference between /// [`Self::ctrl`], [`Self::command`] and [`Self::mac_cmd`]. pub fn cmd_ctrl_matches(&self, pattern: Self) -> bool { if pattern.mac_cmd { // Mac-specific match: if !self.mac_cmd { return false; } if pattern.ctrl != self.ctrl { return false; } return true; } if !pattern.ctrl && !pattern.command { // the pattern explicitly doesn't want any ctrl/command: return !self.ctrl && !self.command; } // if the pattern is looking for command, then `ctrl` may or may not be set depending on platform. // if the pattern is looking for `ctrl`, then `command` may or may not be set depending on platform. if pattern.ctrl && !self.ctrl { return false; } if pattern.command && !self.command { return false; } true } /// Whether another set of modifiers is contained in this set of modifiers with proper handling of [`Self::command`]. /// /// ``` /// # use egui::Modifiers; /// assert!(Modifiers::default().contains(Modifiers::default())); /// assert!(Modifiers::CTRL.contains(Modifiers::default())); /// assert!(Modifiers::CTRL.contains(Modifiers::CTRL)); /// assert!(Modifiers::CTRL.contains(Modifiers::COMMAND)); /// assert!(Modifiers::MAC_CMD.contains(Modifiers::COMMAND)); /// assert!(Modifiers::COMMAND.contains(Modifiers::MAC_CMD));
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
true
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/load/texture_loader.rs
crates/egui/src/load/texture_loader.rs
use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use emath::Vec2; use super::{ BytesLoader as _, Context, HashMap, ImagePoll, Mutex, SizeHint, SizedTexture, TextureHandle, TextureLoadResult, TextureLoader, TextureOptions, TexturePoll, }; #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct PrimaryKey { uri: String, texture_options: TextureOptions, } /// SVG:s might have several different sizes loaded type Bucket = HashMap<Option<SizeHint>, Entry>; struct Entry { last_used: AtomicU64, /// Size of the original SVG, if any, or the texel size of the image if not an SVG. source_size: Vec2, handle: TextureHandle, } #[derive(Default)] pub struct DefaultTextureLoader { pass_index: AtomicU64, cache: Mutex<HashMap<PrimaryKey, Bucket>>, } impl TextureLoader for DefaultTextureLoader { fn id(&self) -> &'static str { crate::generate_loader_id!(DefaultTextureLoader) } fn load( &self, ctx: &Context, uri: &str, texture_options: TextureOptions, size_hint: SizeHint, ) -> TextureLoadResult { let svg_size_hint = if is_svg(uri) { // For SVGs it's important that we render at the desired size, // or we might get a blurry image when we scale it up. // So we make the size hint a part of the cache key. // This might lead to a lot of extra entries for the same SVG file, // which is potentially wasteful of RAM, but better that than blurry images. Some(size_hint) } else { // For other images we just use one cache value, no matter what the size we render at. None }; let mut cache = self.cache.lock(); let bucket = cache .entry(PrimaryKey { uri: uri.to_owned(), texture_options, }) .or_default(); if let Some(texture) = bucket.get(&svg_size_hint) { texture .last_used .store(self.pass_index.load(Relaxed), Relaxed); let texture = SizedTexture::new(texture.handle.id(), texture.source_size); Ok(TexturePoll::Ready { texture }) } else { match ctx.try_load_image(uri, size_hint)? { ImagePoll::Pending { size } => Ok(TexturePoll::Pending { size }), ImagePoll::Ready { image } => { let source_size = image.source_size; let handle = ctx.load_texture(uri, image, texture_options); let texture = SizedTexture::new(handle.id(), source_size); bucket.insert( svg_size_hint, Entry { last_used: AtomicU64::new(self.pass_index.load(Relaxed)), source_size, handle, }, ); let reduce_texture_memory = ctx.options(|o| o.reduce_texture_memory); if reduce_texture_memory { let loaders = ctx.loaders(); loaders.include.forget(uri); for loader in loaders.bytes.lock().iter().rev() { loader.forget(uri); } for loader in loaders.image.lock().iter().rev() { loader.forget(uri); } } Ok(TexturePoll::Ready { texture }) } } } } fn forget(&self, uri: &str) { log::trace!("forget {uri:?}"); self.cache.lock().retain(|key, _value| key.uri != uri); } fn forget_all(&self) { log::trace!("forget all"); self.cache.lock().clear(); } fn end_pass(&self, pass_index: u64) { self.pass_index.store(pass_index, Relaxed); let mut cache = self.cache.lock(); cache.retain(|_key, bucket| { if 2 <= bucket.len() { // There are multiple textures of the same URI (e.g. SVGs of different scales). // This could be because someone has an SVG in a resizable container, // and so we get a lot of different sizes of it. // This could wast VRAM, so we remove the ones that are not used in this frame. bucket.retain(|_, texture| pass_index <= texture.last_used.load(Relaxed) + 1); } !bucket.is_empty() }); } fn byte_size(&self) -> usize { self.cache .lock() .values() .map(|bucket| { bucket .values() .map(|texture| texture.handle.byte_size()) .sum::<usize>() }) .sum() } } fn is_svg(uri: &str) -> bool { uri.ends_with(".svg") }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/egui/src/load/bytes_loader.rs
crates/egui/src/load/bytes_loader.rs
use super::{ Bytes, BytesLoadResult, BytesLoader, BytesPoll, Context, Cow, HashMap, LoadError, Mutex, generate_loader_id, }; /// Maps URI:s to [`Bytes`], e.g. found with `include_bytes!`. /// /// By convention, the URI:s should be prefixed with `bytes://`. #[derive(Default)] pub struct DefaultBytesLoader { cache: Mutex<HashMap<Cow<'static, str>, Bytes>>, } impl DefaultBytesLoader { pub fn insert(&self, uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) { self.cache .lock() .entry(uri.into()) .or_insert_with_key(|_uri| { let bytes: Bytes = bytes.into(); log::trace!("loaded {} bytes for uri {_uri:?}", bytes.len()); bytes }); } } impl BytesLoader for DefaultBytesLoader { fn id(&self) -> &'static str { generate_loader_id!(DefaultBytesLoader) } fn load(&self, _: &Context, uri: &str) -> BytesLoadResult { // We accept uri:s that don't start with `bytes://` too… for now. match self.cache.lock().get(uri).cloned() { Some(bytes) => Ok(BytesPoll::Ready { size: None, bytes, mime: None, }), None => { if uri.starts_with("bytes://") { Err(LoadError::Loading( "Bytes not found. Did you forget to call Context::include_bytes?".into(), )) } else { Err(LoadError::NotSupported) } } } } fn forget(&self, uri: &str) { log::trace!("forget {uri:?}"); self.cache.lock().remove(uri); } fn forget_all(&self) { log::trace!("forget all"); self.cache.lock().clear(); } fn byte_size(&self) -> usize { self.cache.lock().values().map(|bytes| bytes.len()).sum() } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/lib.rs
crates/ecolor/src/lib.rs
//! Color conversions and types. //! //! This crate is built for the wants and needs of [`egui`](https://github.com/emilk/egui/). //! //! If you want an actual _good_ color crate, use [`color`](https://crates.io/crates/color) instead. //! //! If you want a compact color representation, use [`Color32`]. //! If you want to manipulate RGBA colors in linear space use [`Rgba`]. //! If you want to manipulate colors in a way closer to how humans think about colors, use [`HsvaGamma`]. //! //! ## Conventions //! The word "gamma" or "srgb" is used to refer to values in the non-linear space defined by //! [the sRGB transfer function](https://en.wikipedia.org/wiki/SRGB). //! We use `u8` for anything in the "gamma" space. //! //! We use `f32` in 0-1 range for anything in the linear space. //! //! ## Feature flags #![cfg_attr(feature = "document-features", doc = document_features::document_features!())] //! #![expect(clippy::wrong_self_convention)] #[cfg(feature = "cint")] mod cint_impl; mod color32; pub use color32::*; mod hsva_gamma; pub use hsva_gamma::*; mod hsva; pub use hsva::*; #[cfg(feature = "color-hex")] mod hex_color_macro; #[cfg(feature = "color-hex")] #[doc(hidden)] pub use color_hex; mod rgba; pub use rgba::*; mod hex_color_runtime; pub use hex_color_runtime::*; // ---------------------------------------------------------------------------- // Color conversion: impl From<Color32> for Rgba { fn from(srgba: Color32) -> Self { let [r, g, b, a] = srgba.to_array(); if a == 0 { // Additive, or completely transparent Self([ linear_f32_from_gamma_u8(r), linear_f32_from_gamma_u8(g), linear_f32_from_gamma_u8(b), 0.0, ]) } else { let a = linear_f32_from_linear_u8(a); Self([ linear_from_gamma(r as f32 / (255.0 * a)) * a, linear_from_gamma(g as f32 / (255.0 * a)) * a, linear_from_gamma(b as f32 / (255.0 * a)) * a, a, ]) } } } impl From<Rgba> for Color32 { fn from(rgba: Rgba) -> Self { let [r, g, b, a] = rgba.to_array(); if a == 0.0 { // Additive, or completely transparent Self([ gamma_u8_from_linear_f32(r), gamma_u8_from_linear_f32(g), gamma_u8_from_linear_f32(b), 0, ]) } else { Self([ fast_round(gamma_u8_from_linear_f32(r / a) as f32 * a), fast_round(gamma_u8_from_linear_f32(g / a) as f32 * a), fast_round(gamma_u8_from_linear_f32(b / a) as f32 * a), linear_u8_from_linear_f32(a), ]) } } } /// gamma [0, 255] -> linear [0, 1]. pub fn linear_f32_from_gamma_u8(s: u8) -> f32 { if s <= 10 { s as f32 / 3294.6 } else { ((s as f32 + 14.025) / 269.025).powf(2.4) } } /// linear [0, 255] -> linear [0, 1]. /// Useful for alpha-channel. #[inline(always)] pub const fn linear_f32_from_linear_u8(a: u8) -> f32 { a as f32 / 255.0 } /// linear [0, 1] -> gamma [0, 255] (clamped). /// Values outside this range will be clamped to the range. pub fn gamma_u8_from_linear_f32(l: f32) -> u8 { if l <= 0.0 { 0 } else if l <= 0.0031308 { fast_round(3294.6 * l) } else if l <= 1.0 { fast_round(269.025 * l.powf(1.0 / 2.4) - 14.025) } else { 255 } } /// linear [0, 1] -> linear [0, 255] (clamped). /// Useful for alpha-channel. #[inline(always)] pub fn linear_u8_from_linear_f32(a: f32) -> u8 { fast_round(a * 255.0) } const fn fast_round(r: f32) -> u8 { (r + 0.5) as _ // rust does a saturating cast since 1.45 } #[test] pub fn test_srgba_conversion() { for b in 0..=255 { let l = linear_f32_from_gamma_u8(b); assert!(0.0 <= l && l <= 1.0); assert_eq!(gamma_u8_from_linear_f32(l), b); } } /// gamma [0, 1] -> linear [0, 1] (not clamped). /// Works for numbers outside this range (e.g. negative numbers). pub fn linear_from_gamma(gamma: f32) -> f32 { if gamma < 0.0 { -linear_from_gamma(-gamma) } else if gamma <= 0.04045 { gamma / 12.92 } else { ((gamma + 0.055) / 1.055).powf(2.4) } } /// linear [0, 1] -> gamma [0, 1] (not clamped). /// Works for numbers outside this range (e.g. negative numbers). pub fn gamma_from_linear(linear: f32) -> f32 { if linear < 0.0 { -gamma_from_linear(-linear) } else if linear <= 0.0031308 { 12.92 * linear } else { 1.055 * linear.powf(1.0 / 2.4) - 0.055 } } // ---------------------------------------------------------------------------- /// Cheap and ugly. /// Made for graying out disabled `Ui`s. pub fn tint_color_towards(color: Color32, target: Color32) -> Color32 { let [mut r, mut g, mut b, mut a] = color.to_array(); if a == 0 { r /= 2; g /= 2; b /= 2; } else if a < 170 { // Cheapish and looks ok. // Works for e.g. grid stripes. let div = (2 * 255 / a as i32) as u8; r = r / 2 + target.r() / div; g = g / 2 + target.g() / div; b = b / 2 + target.b() / div; a /= 2; } else { r = r / 2 + target.r() / 2; g = g / 2 + target.g() / 2; b = b / 2 + target.b() / 2; } Color32::from_rgba_premultiplied(r, g, b, a) }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/cint_impl.rs
crates/ecolor/src/cint_impl.rs
use super::{Color32, Hsva, HsvaGamma, Rgba, linear_f32_from_linear_u8, linear_u8_from_linear_f32}; use cint::{Alpha, ColorInterop, EncodedSrgb, Hsv, LinearSrgb, PremultipliedAlpha}; // ---- Color32 ---- impl From<Alpha<EncodedSrgb<u8>>> for Color32 { fn from(srgba: Alpha<EncodedSrgb<u8>>) -> Self { let Alpha { color: EncodedSrgb { r, g, b }, alpha: a, } = srgba; Self::from_rgba_unmultiplied(r, g, b, a) } } // No From<Color32> for Alpha<_> because Color32 is premultiplied impl From<PremultipliedAlpha<EncodedSrgb<u8>>> for Color32 { fn from(srgba: PremultipliedAlpha<EncodedSrgb<u8>>) -> Self { let PremultipliedAlpha { color: EncodedSrgb { r, g, b }, alpha: a, } = srgba; Self::from_rgba_premultiplied(r, g, b, a) } } impl From<Color32> for PremultipliedAlpha<EncodedSrgb<u8>> { fn from(col: Color32) -> Self { let (r, g, b, a) = col.to_tuple(); Self { color: EncodedSrgb { r, g, b }, alpha: a, } } } impl From<PremultipliedAlpha<EncodedSrgb<f32>>> for Color32 { fn from(srgba: PremultipliedAlpha<EncodedSrgb<f32>>) -> Self { let PremultipliedAlpha { color: EncodedSrgb { r, g, b }, alpha: a, } = srgba; // This is a bit of an abuse of the function name but it does what we want. let r = linear_u8_from_linear_f32(r); let g = linear_u8_from_linear_f32(g); let b = linear_u8_from_linear_f32(b); let a = linear_u8_from_linear_f32(a); Self::from_rgba_premultiplied(r, g, b, a) } } impl From<Color32> for PremultipliedAlpha<EncodedSrgb<f32>> { fn from(col: Color32) -> Self { let (r, g, b, a) = col.to_tuple(); // This is a bit of an abuse of the function name but it does what we want. let r = linear_f32_from_linear_u8(r); let g = linear_f32_from_linear_u8(g); let b = linear_f32_from_linear_u8(b); let a = linear_f32_from_linear_u8(a); Self { color: EncodedSrgb { r, g, b }, alpha: a, } } } impl ColorInterop for Color32 { type CintTy = PremultipliedAlpha<EncodedSrgb<u8>>; } // ---- Rgba ---- impl From<PremultipliedAlpha<LinearSrgb<f32>>> for Rgba { fn from(srgba: PremultipliedAlpha<LinearSrgb<f32>>) -> Self { let PremultipliedAlpha { color: LinearSrgb { r, g, b }, alpha: a, } = srgba; Self([r, g, b, a]) } } impl From<Rgba> for PremultipliedAlpha<LinearSrgb<f32>> { fn from(col: Rgba) -> Self { let (r, g, b, a) = col.to_tuple(); Self { color: LinearSrgb { r, g, b }, alpha: a, } } } impl ColorInterop for Rgba { type CintTy = PremultipliedAlpha<LinearSrgb<f32>>; } // ---- Hsva ---- impl From<Alpha<Hsv<f32>>> for Hsva { fn from(srgba: Alpha<Hsv<f32>>) -> Self { let Alpha { color: Hsv { h, s, v }, alpha: a, } = srgba; Self::new(h, s, v, a) } } impl From<Hsva> for Alpha<Hsv<f32>> { fn from(col: Hsva) -> Self { let Hsva { h, s, v, a } = col; Self { color: Hsv { h, s, v }, alpha: a, } } } impl ColorInterop for Hsva { type CintTy = Alpha<Hsv<f32>>; } // ---- HsvaGamma ---- impl ColorInterop for HsvaGamma { type CintTy = Alpha<Hsv<f32>>; } impl From<Alpha<Hsv<f32>>> for HsvaGamma { fn from(srgba: Alpha<Hsv<f32>>) -> Self { let Alpha { color: Hsv { h, s, v }, alpha: a, } = srgba; Hsva::new(h, s, v, a).into() } } impl From<HsvaGamma> for Alpha<Hsv<f32>> { fn from(col: HsvaGamma) -> Self { let Hsva { h, s, v, a } = col.into(); Self { color: Hsv { h, s, v }, alpha: a, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/hex_color_macro.rs
crates/ecolor/src/hex_color_macro.rs
/// Construct a [`crate::Color32`] from a hex RGB or RGBA string literal. /// /// Requires the "color-hex" feature. /// /// The string is checked at compile time. If the format is invalid, compilation fails. The valid /// format is the one described in <https://drafts.csswg.org/css-color-4/#hex-color>. Only 6 (RGB) or 8 (RGBA) /// digits are supported, and the leading `#` character is optional. /// /// Note that despite being checked at compile-time, this macro is not usable in `const` contexts /// because creating the [`crate::Color32`] instance requires floating-point arithmetic. /// /// See also [`crate::Color32::from_hex`] and [`crate::Color32::to_hex`]. /// /// # Examples /// /// ``` /// # use ecolor::{hex_color, Color32}; /// assert_eq!(hex_color!("#202122"), Color32::from_hex("#202122").unwrap()); /// assert_eq!(hex_color!("#202122"), Color32::from_rgb(0x20, 0x21, 0x22)); /// assert_eq!(hex_color!("#202122"), hex_color!("202122")); /// assert_eq!(hex_color!("#abcdef12"), Color32::from_rgba_unmultiplied(0xab, 0xcd, 0xef, 0x12)); /// ``` /// /// If the literal string has the wrong format, the code does not compile. /// /// ```compile_fail /// let _ = ecolor::hex_color!("#abc"); /// ``` /// /// ```compile_fail /// let _ = ecolor::hex_color!("#20212x"); /// ``` /// /// The macro can be used in a `const` context. /// /// ``` /// const COLOR: ecolor::Color32 = ecolor::hex_color!("#202122"); /// assert_eq!(COLOR, ecolor::Color32::from_rgb(0x20, 0x21, 0x22)); /// ``` #[macro_export] macro_rules! hex_color { ($s:literal) => {{ let array = $crate::color_hex::color_from_hex!($s); match array.as_slice() { [r, g, b] => $crate::Color32::from_rgb(*r, *g, *b), [r, g, b, a] => $crate::Color32::from_rgba_unmultiplied_const(*r, *g, *b, *a), _ => panic!("Invalid hex color length: expected 3 (RGB) or 4 (RGBA) bytes"), } }}; } #[test] fn test_from_rgb_hex() { assert_eq!( crate::Color32::from_rgb(0x20, 0x21, 0x22), hex_color!("#202122") ); assert_eq!( crate::Color32::from_rgb_additive(0x20, 0x21, 0x22), hex_color!("#202122").additive() ); } #[test] fn test_from_rgba_hex() { assert_eq!( crate::Color32::from_rgba_unmultiplied(0x20, 0x21, 0x22, 0x50), hex_color!("20212250") ); }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/hex_color_runtime.rs
crates/ecolor/src/hex_color_runtime.rs
//! Convert colors to and from the hex-color string format at runtime //! //! Supports the 3, 4, 6, and 8-digit formats, according to the specification in //! <https://drafts.csswg.org/css-color-4/#hex-color> use std::{fmt::Display, str::FromStr}; use crate::Color32; #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] /// A wrapper around Color32 that converts to and from a hex-color string /// /// Implements [`Display`] and [`FromStr`] to convert to and from the hex string. pub enum HexColor { /// 3 hexadecimal digits, one for each of the r, g, b channels Hex3(Color32), /// 4 hexadecimal digits, one for each of the r, g, b, a channels Hex4(Color32), /// 6 hexadecimal digits, two for each of the r, g, b channels Hex6(Color32), /// 8 hexadecimal digits, one for each of the r, g, b, a channels Hex8(Color32), } #[derive(Clone, Debug, Eq, PartialEq)] pub enum ParseHexColorError { MissingHash, InvalidLength, InvalidInt(std::num::ParseIntError), } impl FromStr for HexColor { type Err = ParseHexColorError; fn from_str(s: &str) -> Result<Self, Self::Err> { s.strip_prefix('#') .ok_or(ParseHexColorError::MissingHash) .and_then(Self::from_str_without_hash) } } impl Display for HexColor { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Hex3(color) => { let [r, g, b, _] = color.to_srgba_unmultiplied().map(|u| u >> 4); f.write_fmt(format_args!("#{r:x}{g:x}{b:x}")) } Self::Hex4(color) => { 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}")) } Self::Hex6(color) => { let [r, g, b, _] = color.to_srgba_unmultiplied(); let u = u32::from_be_bytes([0, r, g, b]); f.write_fmt(format_args!("#{u:06x}")) } Self::Hex8(color) => { let [r, g, b, a] = color.to_srgba_unmultiplied(); let u = u32::from_be_bytes([r, g, b, a]); f.write_fmt(format_args!("#{u:08x}")) } } } } impl HexColor { /// Retrieves the inner [`Color32`] #[inline] pub fn color(&self) -> Color32 { match self { Self::Hex3(color) | Self::Hex4(color) | Self::Hex6(color) | Self::Hex8(color) => *color, } } /// Parses a string as a hex color without the leading `#` character /// /// # Errors /// Returns an error if the length of the string does not correspond to one of the standard /// formats (3, 4, 6, or 8), or if it contains non-hex characters. #[inline] pub fn from_str_without_hash(s: &str) -> Result<Self, ParseHexColorError> { match s.len() { 3 => { let [r, gb] = u16::from_str_radix(s, 16) .map_err(ParseHexColorError::InvalidInt)? .to_be_bytes(); let [r, g, b] = [r, gb >> 4, gb & 0x0f].map(|u| (u << 4) | u); Ok(Self::Hex3(Color32::from_rgb(r, g, b))) } 4 => { let [r_g, b_a] = u16::from_str_radix(s, 16) .map_err(ParseHexColorError::InvalidInt)? .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); Ok(Self::Hex4(Color32::from_rgba_unmultiplied(r, g, b, a))) } 6 => { let [_, r, g, b] = u32::from_str_radix(s, 16) .map_err(ParseHexColorError::InvalidInt)? .to_be_bytes(); Ok(Self::Hex6(Color32::from_rgb(r, g, b))) } 8 => { let [r, g, b, a] = u32::from_str_radix(s, 16) .map_err(ParseHexColorError::InvalidInt)? .to_be_bytes(); Ok(Self::Hex8(Color32::from_rgba_unmultiplied(r, g, b, a))) } _ => Err(ParseHexColorError::InvalidLength)?, } } } impl Color32 { /// Parses a color from a hex string. /// /// Supports the 3, 4, 6, and 8-digit formats, according to the specification in /// <https://drafts.csswg.org/css-color-4/#hex-color> /// /// To parse hex colors from string literals with compile-time checking, use the macro /// [`crate::hex_color!`] instead. /// /// # Example /// ```rust /// use ecolor::Color32; /// assert_eq!(Ok(Color32::RED), Color32::from_hex("#ff0000")); /// assert_eq!(Ok(Color32::GREEN), Color32::from_hex("#00ff00ff")); /// assert_eq!(Ok(Color32::BLUE), Color32::from_hex("#00f")); /// assert_eq!(Ok(Color32::TRANSPARENT), Color32::from_hex("#0000")); /// ``` /// /// # Errors /// Returns an error if the string doesn't start with the hash `#` character, if the remaining /// length does not correspond to one of the standard formats (3, 4, 6, or 8), if it contains /// non-hex characters. pub fn from_hex(hex: &str) -> Result<Self, ParseHexColorError> { HexColor::from_str(hex).map(|h| h.color()) } /// Formats the color as a hex string. /// /// # Example /// ```rust /// use ecolor::Color32; /// assert_eq!(Color32::RED.to_hex(), "#ff0000ff"); /// assert_eq!(Color32::GREEN.to_hex(), "#00ff00ff"); /// assert_eq!(Color32::BLUE.to_hex(), "#0000ffff"); /// assert_eq!(Color32::TRANSPARENT.to_hex(), "#00000000"); /// ``` /// /// Uses the 8-digit format described in <https://drafts.csswg.org/css-color-4/#hex-color>, /// as that is the only format that is lossless. /// For other formats, see [`HexColor`]. #[inline] pub fn to_hex(&self) -> String { HexColor::Hex8(*self).to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn hex_string_formats() { use Color32 as C; use HexColor as H; let cases = [ (H::Hex3(C::RED), "#f00"), (H::Hex4(C::RED), "#f00f"), (H::Hex6(C::RED), "#ff0000"), (H::Hex8(C::RED), "#ff0000ff"), (H::Hex3(C::GREEN), "#0f0"), (H::Hex4(C::GREEN), "#0f0f"), (H::Hex6(C::GREEN), "#00ff00"), (H::Hex8(C::GREEN), "#00ff00ff"), (H::Hex3(C::BLUE), "#00f"), (H::Hex4(C::BLUE), "#00ff"), (H::Hex6(C::BLUE), "#0000ff"), (H::Hex8(C::BLUE), "#0000ffff"), (H::Hex3(C::WHITE), "#fff"), (H::Hex4(C::WHITE), "#ffff"), (H::Hex6(C::WHITE), "#ffffff"), (H::Hex8(C::WHITE), "#ffffffff"), (H::Hex3(C::BLACK), "#000"), (H::Hex4(C::BLACK), "#000f"), (H::Hex6(C::BLACK), "#000000"), (H::Hex8(C::BLACK), "#000000ff"), (H::Hex4(C::TRANSPARENT), "#0000"), (H::Hex8(C::TRANSPARENT), "#00000000"), ]; for (color, string) in cases { assert_eq!(color.to_string(), string, "{color:?} <=> {string}"); assert_eq!( H::from_str(string).unwrap(), color, "{color:?} <=> {string}" ); } } #[test] fn hex_string_round_trip() { let cases = [ [0, 20, 30, 0], [10, 0, 30, 40], [10, 100, 200, 0], [10, 100, 200, 100], [10, 100, 200, 200], [10, 100, 200, 255], [10, 100, 200, 40], [10, 20, 0, 255], [10, 20, 30, 0], [10, 20, 30, 255], [10, 20, 30, 40], ]; for [r, g, b, a] in cases { let color = Color32::from_rgba_unmultiplied(r, g, b, a); assert_eq!(Color32::from_hex(color.to_hex().as_str()), Ok(color)); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/hsva.rs
crates/ecolor/src/hsva.rs
use crate::{ Color32, Rgba, gamma_u8_from_linear_f32, linear_f32_from_gamma_u8, linear_u8_from_linear_f32, }; /// Hue, saturation, value, alpha. All in the range [0, 1]. /// No premultiplied alpha. #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Hsva { /// hue 0-1 pub h: f32, /// saturation 0-1 pub s: f32, /// value 0-1 pub v: f32, /// alpha 0-1. A negative value signifies an additive color (and alpha is ignored). pub a: f32, } impl Hsva { #[inline] pub fn new(h: f32, s: f32, v: f32, a: f32) -> Self { Self { h, s, v, a } } /// From `sRGBA` with premultiplied alpha #[inline] pub fn from_srgba_premultiplied([r, g, b, a]: [u8; 4]) -> Self { Self::from(Color32::from_rgba_premultiplied(r, g, b, a)) } /// From `sRGBA` without premultiplied alpha #[inline] pub fn from_srgba_unmultiplied([r, g, b, a]: [u8; 4]) -> Self { Self::from(Color32::from_rgba_unmultiplied(r, g, b, a)) } /// From linear RGBA with premultiplied alpha #[inline] pub fn from_rgba_premultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { #![expect(clippy::many_single_char_names)] if a <= 0.0 { if r == 0.0 && b == 0.0 && a == 0.0 { Self::default() } else { Self::from_additive_rgb([r, g, b]) } } else { let (h, s, v) = hsv_from_rgb([r / a, g / a, b / a]); Self { h, s, v, a } } } /// From linear RGBA without premultiplied alpha #[inline] pub fn from_rgba_unmultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { #![expect(clippy::many_single_char_names)] let (h, s, v) = hsv_from_rgb([r, g, b]); Self { h, s, v, a } } #[inline] pub fn from_additive_rgb(rgb: [f32; 3]) -> Self { let (h, s, v) = hsv_from_rgb(rgb); Self { h, s, v, a: -0.5, // anything negative is treated as additive } } #[inline] pub fn from_additive_srgb([r, g, b]: [u8; 3]) -> Self { Self::from_additive_rgb([ linear_f32_from_gamma_u8(r), linear_f32_from_gamma_u8(g), linear_f32_from_gamma_u8(b), ]) } #[inline] pub fn from_rgb(rgb: [f32; 3]) -> Self { let (h, s, v) = hsv_from_rgb(rgb); Self { h, s, v, a: 1.0 } } #[inline] pub fn from_srgb([r, g, b]: [u8; 3]) -> Self { Self::from_rgb([ linear_f32_from_gamma_u8(r), linear_f32_from_gamma_u8(g), linear_f32_from_gamma_u8(b), ]) } // ------------------------------------------------------------------------ #[inline] pub fn to_opaque(self) -> Self { Self { a: 1.0, ..self } } #[inline] pub fn to_rgb(&self) -> [f32; 3] { rgb_from_hsv((self.h, self.s, self.v)) } #[inline] pub fn to_srgb(&self) -> [u8; 3] { let [r, g, b] = self.to_rgb(); [ gamma_u8_from_linear_f32(r), gamma_u8_from_linear_f32(g), gamma_u8_from_linear_f32(b), ] } #[inline] pub fn to_rgba_premultiplied(&self) -> [f32; 4] { let [r, g, b, a] = self.to_rgba_unmultiplied(); let additive = a < 0.0; if additive { [r, g, b, 0.0] } else { [a * r, a * g, a * b, a] } } /// To linear space rgba in 0-1 range. /// /// Represents additive colors using a negative alpha. #[inline] pub fn to_rgba_unmultiplied(&self) -> [f32; 4] { let Self { h, s, v, a } = *self; let [r, g, b] = rgb_from_hsv((h, s, v)); [r, g, b, a] } #[inline] pub fn to_srgba_premultiplied(&self) -> [u8; 4] { Color32::from(*self).to_array() } /// To gamma-space 0-255. #[inline] pub fn to_srgba_unmultiplied(&self) -> [u8; 4] { let [r, g, b, a] = self.to_rgba_unmultiplied(); [ gamma_u8_from_linear_f32(r), gamma_u8_from_linear_f32(g), gamma_u8_from_linear_f32(b), linear_u8_from_linear_f32(a.abs()), ] } } impl From<Hsva> for Rgba { #[inline] fn from(hsva: Hsva) -> Self { Self(hsva.to_rgba_premultiplied()) } } impl From<Rgba> for Hsva { #[inline] fn from(rgba: Rgba) -> Self { Self::from_rgba_premultiplied(rgba.0[0], rgba.0[1], rgba.0[2], rgba.0[3]) } } impl From<Hsva> for Color32 { #[inline] fn from(hsva: Hsva) -> Self { Self::from(Rgba::from(hsva)) } } impl From<Color32> for Hsva { #[inline] fn from(srgba: Color32) -> Self { Self::from(Rgba::from(srgba)) } } /// All ranges in 0-1, rgb is linear. #[inline] pub fn hsv_from_rgb([r, g, b]: [f32; 3]) -> (f32, f32, f32) { #![expect(clippy::many_single_char_names)] let min = r.min(g.min(b)); let max = r.max(g.max(b)); // value let range = max - min; let h = if max == min { 0.0 // hue is undefined } else if max == r { (g - b) / (6.0 * range) } else if max == g { (b - r) / (6.0 * range) + 1.0 / 3.0 } else { // max == b (r - g) / (6.0 * range) + 2.0 / 3.0 }; let h = (h + 1.0).fract(); // wrap let s = if max == 0.0 { 0.0 } else { 1.0 - min / max }; (h, s, max) } /// All ranges in 0-1, rgb is linear. #[inline] pub fn rgb_from_hsv((h, s, v): (f32, f32, f32)) -> [f32; 3] { #![expect(clippy::many_single_char_names)] let h = (h.fract() + 1.0).fract(); // wrap let s = s.clamp(0.0, 1.0); let f = h * 6.0 - (h * 6.0).floor(); let p = v * (1.0 - s); let q = v * (1.0 - f * s); let t = v * (1.0 - (1.0 - f) * s); match (h * 6.0).floor() as i32 % 6 { 0 => [v, t, p], 1 => [q, v, p], 2 => [p, v, t], 3 => [p, q, v], 4 => [t, p, v], 5 => [v, p, q], _ => unreachable!(), } } #[test] #[ignore = "too expensive"] fn test_hsv_roundtrip() { for r in 0..=255 { for g in 0..=255 { for b in 0..=255 { let srgba = Color32::from_rgb(r, g, b); let hsva = Hsva::from(srgba); assert_eq!(srgba, Color32::from(hsva)); } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/rgba.rs
crates/ecolor/src/rgba.rs
use crate::Color32; /// 0-1 linear space `RGBA` color with premultiplied alpha. /// /// See [`crate::Color32`] for explanation of what "premultiplied alpha" means. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))] pub struct Rgba(pub(crate) [f32; 4]); impl std::ops::Index<usize> for Rgba { type Output = f32; #[inline] fn index(&self, index: usize) -> &f32 { &self.0[index] } } impl std::ops::IndexMut<usize> for Rgba { #[inline] fn index_mut(&mut self, index: usize) -> &mut f32 { &mut self.0[index] } } /// Deterministically hash an `f32`, treating all NANs as equal, and ignoring the sign of zero. #[inline] pub(crate) fn f32_hash<H: std::hash::Hasher>(state: &mut H, f: f32) { if f == 0.0 { state.write_u8(0); } else if f.is_nan() { state.write_u8(1); } else { use std::hash::Hash as _; f.to_bits().hash(state); } } impl std::hash::Hash for Rgba { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { crate::f32_hash(state, self.0[0]); crate::f32_hash(state, self.0[1]); crate::f32_hash(state, self.0[2]); crate::f32_hash(state, self.0[3]); } } impl Rgba { pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0.0, 0.0, 0.0, 0.0); pub const BLACK: Self = Self::from_rgb(0.0, 0.0, 0.0); pub const WHITE: Self = Self::from_rgb(1.0, 1.0, 1.0); pub const RED: Self = Self::from_rgb(1.0, 0.0, 0.0); pub const GREEN: Self = Self::from_rgb(0.0, 1.0, 0.0); pub const BLUE: Self = Self::from_rgb(0.0, 0.0, 1.0); #[inline] pub const fn from_rgba_premultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { Self([r, g, b, a]) } #[inline] pub fn from_rgba_unmultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { Self([r * a, g * a, b * a, a]) } #[inline] pub fn from_srgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self { Self::from(Color32::from_rgba_premultiplied(r, g, b, a)) } #[inline] pub fn from_srgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self { Self::from(Color32::from_rgba_unmultiplied(r, g, b, a)) } #[inline] pub const fn from_rgb(r: f32, g: f32, b: f32) -> Self { Self([r, g, b, 1.0]) } #[doc(alias = "from_grey")] #[inline] pub const fn from_gray(l: f32) -> Self { Self([l, l, l, 1.0]) } #[inline] pub fn from_luminance_alpha(l: f32, a: f32) -> Self { debug_assert!( 0.0 <= l && l <= 1.0, "l should be in the range [0, 1], but was {l}" ); debug_assert!( 0.0 <= a && a <= 1.0, "a should be in the range [0, 1], but was {a}" ); Self([l * a, l * a, l * a, a]) } /// Transparent black #[inline] pub fn from_black_alpha(a: f32) -> Self { debug_assert!( 0.0 <= a && a <= 1.0, "a should be in the range [0, 1], but was {a}" ); Self([0.0, 0.0, 0.0, a]) } /// Transparent white #[inline] pub fn from_white_alpha(a: f32) -> Self { debug_assert!(0.0 <= a && a <= 1.0, "a: {a}"); Self([a, a, a, a]) } /// Return an additive version of this color (alpha = 0) #[inline] pub fn additive(self) -> Self { let [r, g, b, _] = self.0; Self([r, g, b, 0.0]) } /// Is the alpha=0 ? #[inline] pub fn is_additive(self) -> bool { self.a() == 0.0 } /// Multiply with e.g. 0.5 to make us half transparent #[inline] pub fn multiply(self, alpha: f32) -> Self { Self([ alpha * self[0], alpha * self[1], alpha * self[2], alpha * self[3], ]) } #[inline] pub fn r(&self) -> f32 { self.0[0] } #[inline] pub fn g(&self) -> f32 { self.0[1] } #[inline] pub fn b(&self) -> f32 { self.0[2] } #[inline] pub fn a(&self) -> f32 { self.0[3] } /// How perceptually intense (bright) is the color? #[inline] pub fn intensity(&self) -> f32 { 0.3 * self.r() + 0.59 * self.g() + 0.11 * self.b() } /// Returns an opaque version of self #[inline] pub fn to_opaque(&self) -> Self { if self.a() == 0.0 { // Additive or fully transparent black. Self::from_rgb(self.r(), self.g(), self.b()) } else { // un-multiply alpha: Self::from_rgb( self.r() / self.a(), self.g() / self.a(), self.b() / self.a(), ) } } /// Premultiplied RGBA #[inline] pub fn to_array(&self) -> [f32; 4] { [self.r(), self.g(), self.b(), self.a()] } /// Premultiplied RGBA #[inline] pub fn to_tuple(&self) -> (f32, f32, f32, f32) { (self.r(), self.g(), self.b(), self.a()) } /// unmultiply the alpha #[inline] pub fn to_rgba_unmultiplied(&self) -> [f32; 4] { let a = self.a(); if a == 0.0 { // Additive, let's assume we are black self.0 } else { [self.r() / a, self.g() / a, self.b() / a, a] } } /// unmultiply the alpha #[inline] pub fn to_srgba_unmultiplied(&self) -> [u8; 4] { crate::Color32::from(*self).to_srgba_unmultiplied() } /// Blend two colors in linear space, so that `self` is behind the argument. pub fn blend(self, on_top: Self) -> Self { self.multiply(1.0 - on_top.a()) + on_top } } impl std::ops::Add for Rgba { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Self([ self[0] + rhs[0], self[1] + rhs[1], self[2] + rhs[2], self[3] + rhs[3], ]) } } impl std::ops::Mul for Rgba { type Output = Self; #[inline] fn mul(self, other: Self) -> Self { Self([ self[0] * other[0], self[1] * other[1], self[2] * other[2], self[3] * other[3], ]) } } impl std::ops::Mul<f32> for Rgba { type Output = Self; #[inline] fn mul(self, factor: f32) -> Self { Self([ self[0] * factor, self[1] * factor, self[2] * factor, self[3] * factor, ]) } } impl std::ops::Mul<Rgba> for f32 { type Output = Rgba; #[inline] fn mul(self, rgba: Rgba) -> Rgba { Rgba([ self * rgba[0], self * rgba[1], self * rgba[2], self * rgba[3], ]) } } #[cfg(test)] mod test { use super::*; fn test_rgba() -> impl Iterator<Item = [u8; 4]> { [ [0, 0, 0, 0], [0, 0, 0, 255], [10, 0, 30, 0], [10, 0, 30, 40], [10, 100, 200, 0], [10, 100, 200, 100], [10, 100, 200, 200], [10, 100, 200, 255], [10, 100, 200, 40], [10, 20, 0, 0], [10, 20, 0, 255], [10, 20, 30, 255], [10, 20, 30, 40], [255, 255, 255, 0], [255, 255, 255, 255], ] .into_iter() } #[test] fn test_rgba_blend() { let opaque = Rgba::from_rgb(0.4, 0.5, 0.6); let transparent = Rgba::from_rgb(1.0, 0.5, 0.0).multiply(0.3); assert_eq!( transparent.blend(opaque), opaque, "Opaque on top of transparent" ); assert_eq!( opaque.blend(transparent), Rgba::from_rgb( 0.7 * 0.4 + 0.3 * 1.0, 0.7 * 0.5 + 0.3 * 0.5, 0.7 * 0.6 + 0.3 * 0.0 ), "Transparent on top of opaque" ); } #[test] fn test_rgba_roundtrip() { for in_rgba in test_rgba() { let [r, g, b, a] = in_rgba; if a == 0 { continue; } let rgba = Rgba::from_srgba_unmultiplied(r, g, b, a); let out_rgba = rgba.to_srgba_unmultiplied(); if a == 255 { assert_eq!(in_rgba, out_rgba); } else { // There will be small rounding errors whenever the alpha is not 0 or 255, // because we multiply and then unmultiply the alpha. for (&a, &b) in in_rgba.iter().zip(out_rgba.iter()) { assert!(a.abs_diff(b) <= 3, "{in_rgba:?} != {out_rgba:?}"); } } } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/hsva_gamma.rs
crates/ecolor/src/hsva_gamma.rs
use crate::{Color32, Hsva, Rgba, gamma_from_linear, linear_from_gamma}; /// Like Hsva but with the `v` value (brightness) being gamma corrected /// so that it is somewhat perceptually even. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct HsvaGamma { /// hue 0-1 pub h: f32, /// saturation 0-1 pub s: f32, /// value 0-1, in gamma-space (~perceptually even) pub v: f32, /// alpha 0-1. A negative value signifies an additive color (and alpha is ignored). pub a: f32, } impl From<HsvaGamma> for Rgba { fn from(hsvag: HsvaGamma) -> Self { Hsva::from(hsvag).into() } } impl From<HsvaGamma> for Color32 { fn from(hsvag: HsvaGamma) -> Self { Rgba::from(hsvag).into() } } impl From<HsvaGamma> for Hsva { fn from(hsvag: HsvaGamma) -> Self { let HsvaGamma { h, s, v, a } = hsvag; Self { h, s, v: linear_from_gamma(v), a, } } } impl From<Rgba> for HsvaGamma { fn from(rgba: Rgba) -> Self { Hsva::from(rgba).into() } } impl From<Color32> for HsvaGamma { fn from(srgba: Color32) -> Self { Hsva::from(srgba).into() } } impl From<Hsva> for HsvaGamma { fn from(hsva: Hsva) -> Self { let Hsva { h, s, v, a } = hsva; Self { h, s, v: gamma_from_linear(v), a, } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/ecolor/src/color32.rs
crates/ecolor/src/color32.rs
use crate::{Rgba, fast_round, linear_f32_from_linear_u8}; /// This format is used for space-efficient color representation (32 bits). /// /// Instead of manipulating this directly it is often better /// to first convert it to either [`Rgba`] or [`crate::Hsva`]. /// /// Internally this uses 0-255 gamma space `sRGBA` color with _premultiplied alpha_. /// /// It's the non-linear ("gamma") values that are multiplied with the alpha. /// /// Premultiplied alpha means that the color values have been pre-multiplied with the alpha (opacity). /// This is in contrast with "normal" RGBA, where the alpha is _separate_ (or "unmultiplied"). /// Using premultiplied alpha has some advantages: /// * It allows encoding additive colors /// * It is the better way to blend colors, e.g. when filtering texture colors /// * Because the above, it is the better way to encode colors in a GPU texture /// /// The color space is assumed to be [sRGB](https://en.wikipedia.org/wiki/SRGB). /// /// All operations on `Color32` are done in "gamma space" (see <https://en.wikipedia.org/wiki/SRGB>). /// This is not physically correct, but it is fast and sometimes more perceptually even than linear space. /// If you instead want to perform these operations in linear-space color, use [`Rgba`]. /// /// An `alpha=0` means the color is to be treated as an additive color. #[repr(C)] #[repr(align(4))] #[derive(Clone, Copy, Default, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))] pub struct Color32(pub(crate) [u8; 4]); impl std::fmt::Debug for Color32 { /// Prints the contents with premultiplied alpha! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let [r, g, b, a] = self.0; write!(f, "#{r:02X}_{g:02X}_{b:02X}_{a:02X}") } } impl std::ops::Index<usize> for Color32 { type Output = u8; #[inline] fn index(&self, index: usize) -> &u8 { &self.0[index] } } impl std::ops::IndexMut<usize> for Color32 { #[inline] fn index_mut(&mut self, index: usize) -> &mut u8 { &mut self.0[index] } } impl Color32 { // Mostly follows CSS names: pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0); pub const BLACK: Self = Self::from_rgb(0, 0, 0); #[doc(alias = "DARK_GREY")] pub const DARK_GRAY: Self = Self::from_rgb(96, 96, 96); #[doc(alias = "GREY")] pub const GRAY: Self = Self::from_rgb(160, 160, 160); #[doc(alias = "LIGHT_GREY")] pub const LIGHT_GRAY: Self = Self::from_rgb(220, 220, 220); pub const WHITE: Self = Self::from_rgb(255, 255, 255); pub const BROWN: Self = Self::from_rgb(165, 42, 42); pub const DARK_RED: Self = Self::from_rgb(0x8B, 0, 0); pub const RED: Self = Self::from_rgb(255, 0, 0); pub const LIGHT_RED: Self = Self::from_rgb(255, 128, 128); pub const CYAN: Self = Self::from_rgb(0, 255, 255); pub const MAGENTA: Self = Self::from_rgb(255, 0, 255); pub const YELLOW: Self = Self::from_rgb(255, 255, 0); pub const ORANGE: Self = Self::from_rgb(255, 165, 0); pub const LIGHT_YELLOW: Self = Self::from_rgb(255, 255, 0xE0); pub const KHAKI: Self = Self::from_rgb(240, 230, 140); pub const DARK_GREEN: Self = Self::from_rgb(0, 0x64, 0); pub const GREEN: Self = Self::from_rgb(0, 255, 0); pub const LIGHT_GREEN: Self = Self::from_rgb(0x90, 0xEE, 0x90); pub const DARK_BLUE: Self = Self::from_rgb(0, 0, 0x8B); pub const BLUE: Self = Self::from_rgb(0, 0, 255); pub const LIGHT_BLUE: Self = Self::from_rgb(0xAD, 0xD8, 0xE6); pub const PURPLE: Self = Self::from_rgb(0x80, 0, 0x80); pub const GOLD: Self = Self::from_rgb(255, 215, 0); 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. /// /// This is an invalid color, in that it does not correspond to a valid multiplied color, /// nor to an additive color. /// /// This is used as a special color key, /// i.e. often taken to mean "no color". pub const PLACEHOLDER: Self = Self::from_rgba_premultiplied(64, 254, 0, 128); /// From RGB with alpha of 255 (opaque). #[inline] pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self { Self([r, g, b, 255]) } /// From RGB into an additive color (will make everything it blend with brighter). #[inline] pub const fn from_rgb_additive(r: u8, g: u8, b: u8) -> Self { Self([r, g, b, 0]) } /// From `sRGBA` with premultiplied alpha. /// /// You likely want to use [`Self::from_rgba_unmultiplied`] instead. #[inline] pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self { Self([r, g, b, a]) } /// From `sRGBA` with separate alpha. /// /// This is a "normal" RGBA value that you would find in a color picker or a table somewhere. /// /// You can use [`Self::to_srgba_unmultiplied`] to get back these values, /// but for transparent colors what you get back might be slightly different (rounding errors). #[inline] pub fn from_rgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self { use std::sync::OnceLock; match a { // common-case optimization: 0 => Self::TRANSPARENT, // common-case optimization: 255 => Self::from_rgb(r, g, b), a => { static LOOKUP_TABLE: OnceLock<Box<[u8]>> = OnceLock::new(); let lut = LOOKUP_TABLE.get_or_init(|| { (0..=u16::MAX) .map(|i| { let [value, alpha] = i.to_ne_bytes(); fast_round(value as f32 * linear_f32_from_linear_u8(alpha)) }) .collect() }); let [r, g, b] = [r, g, b].map(|value| lut[usize::from(u16::from_ne_bytes([value, a]))]); Self::from_rgba_premultiplied(r, g, b, a) } } } /// Same as [`Self::from_rgba_unmultiplied`], but can be used in a const context. /// /// It is slightly slower when operating on non-const data. #[inline] pub const fn from_rgba_unmultiplied_const(r: u8, g: u8, b: u8, a: u8) -> Self { match a { // common-case optimization: 0 => Self::TRANSPARENT, // common-case optimization: 255 => Self::from_rgb(r, g, b), a => { let r = fast_round(r as f32 * linear_f32_from_linear_u8(a)); let g = fast_round(g as f32 * linear_f32_from_linear_u8(a)); let b = fast_round(b as f32 * linear_f32_from_linear_u8(a)); Self::from_rgba_premultiplied(r, g, b, a) } } } /// Opaque gray. #[doc(alias = "from_grey")] #[inline] pub const fn from_gray(l: u8) -> Self { Self([l, l, l, 255]) } /// Black with the given opacity. #[inline] pub const fn from_black_alpha(a: u8) -> Self { Self([0, 0, 0, a]) } /// White with the given opacity. #[inline] pub fn from_white_alpha(a: u8) -> Self { Self([a, a, a, a]) } /// Additive white. #[inline] pub const fn from_additive_luminance(l: u8) -> Self { Self([l, l, l, 0]) } #[inline] pub const fn is_opaque(&self) -> bool { self.a() == 255 } /// Red component multiplied by alpha. #[inline] pub const fn r(&self) -> u8 { self.0[0] } /// Green component multiplied by alpha. #[inline] pub const fn g(&self) -> u8 { self.0[1] } /// Blue component multiplied by alpha. #[inline] pub const fn b(&self) -> u8 { self.0[2] } /// Alpha (opacity). #[inline] pub const fn a(&self) -> u8 { self.0[3] } /// Returns an opaque version of self #[inline] pub fn to_opaque(self) -> Self { Rgba::from(self).to_opaque().into() } /// Returns an additive version of self #[inline] pub const fn additive(self) -> Self { let [r, g, b, _] = self.to_array(); Self([r, g, b, 0]) } /// Is the alpha=0 ? #[inline] pub fn is_additive(self) -> bool { self.a() == 0 } /// Premultiplied RGBA #[inline] pub const fn to_array(&self) -> [u8; 4] { [self.r(), self.g(), self.b(), self.a()] } /// Premultiplied RGBA #[inline] pub const fn to_tuple(&self) -> (u8, u8, u8, u8) { (self.r(), self.g(), self.b(), self.a()) } /// Convert to a normal "unmultiplied" RGBA color (i.e. with separate alpha). /// /// This will unmultiply the alpha. /// /// This is the inverse of [`Self::from_rgba_unmultiplied`], /// but due to precision problems it may return slightly different values for transparent colors. #[inline] pub fn to_srgba_unmultiplied(&self) -> [u8; 4] { let [r, g, b, a] = self.to_array(); match a { // Common-case optimization. 0 | 255 => self.to_array(), a => { let factor = 255.0 / a as f32; let r = fast_round(factor * r as f32); let g = fast_round(factor * g as f32); let b = fast_round(factor * b as f32); [r, g, b, a] } } } /// Multiply with 0.5 to make color half as opaque, perceptually. /// /// Fast multiplication in gamma-space. /// /// This is perceptually even, and faster that [`Self::linear_multiply`]. #[inline] pub fn gamma_multiply(self, factor: f32) -> Self { debug_assert!( 0.0 <= factor && factor.is_finite(), "factor should be finite, but was {factor}" ); let Self([r, g, b, a]) = self; Self([ (r as f32 * factor + 0.5) as u8, (g as f32 * factor + 0.5) as u8, (b as f32 * factor + 0.5) as u8, (a as f32 * factor + 0.5) as u8, ]) } /// Multiply with 127 to make color half as opaque, perceptually. /// /// Fast multiplication in gamma-space. /// /// This is perceptually even, and faster that [`Self::linear_multiply`]. #[inline] pub fn gamma_multiply_u8(self, factor: u8) -> Self { let Self([r, g, b, a]) = self; let factor = factor as u32; Self([ ((r as u32 * factor + 127) / 255) as u8, ((g as u32 * factor + 127) / 255) as u8, ((b as u32 * factor + 127) / 255) as u8, ((a as u32 * factor + 127) / 255) as u8, ]) } /// Multiply with 0.5 to make color half as opaque in linear space. /// /// This is using linear space, which is not perceptually even. /// You likely want to use [`Self::gamma_multiply`] instead. #[inline] pub fn linear_multiply(self, factor: f32) -> Self { debug_assert!( 0.0 <= factor && factor.is_finite(), "factor should be finite, but was {factor}" ); // As an unfortunate side-effect of using premultiplied alpha // we need a somewhat expensive conversion to linear space and back. Rgba::from(self).multiply(factor).into() } /// Converts to floating point values in the range 0-1 without any gamma space conversion. /// /// Use this with great care! In almost all cases, you want to convert to [`crate::Rgba`] instead /// in order to obtain linear space color values. #[inline] pub fn to_normalized_gamma_f32(self) -> [f32; 4] { let Self([r, g, b, a]) = self; [ r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a as f32 / 255.0, ] } /// Lerp this color towards `other` by `t` in gamma space. pub fn lerp_to_gamma(&self, other: Self, t: f32) -> Self { use emath::lerp; Self::from_rgba_premultiplied( fast_round(lerp((self[0] as f32)..=(other[0] as f32), t)), fast_round(lerp((self[1] as f32)..=(other[1] as f32), t)), fast_round(lerp((self[2] as f32)..=(other[2] as f32), t)), fast_round(lerp((self[3] as f32)..=(other[3] as f32), t)), ) } /// Blend two colors in gamma space, so that `self` is behind the argument. pub fn blend(self, on_top: Self) -> Self { self.gamma_multiply_u8(255 - on_top.a()) + on_top } /// Intensity of the color. /// /// Returns a value in the range 0-1. /// The brighter the color, the closer to 1. pub fn intensity(&self) -> f32 { (self.r() as f32 * 0.299 + self.g() as f32 * 0.587 + self.b() as f32 * 0.114) / 255.0 } } impl std::ops::Mul for Color32 { type Output = Self; /// Fast gamma-space multiplication. #[inline] fn mul(self, other: Self) -> Self { Self([ fast_round(self[0] as f32 * other[0] as f32 / 255.0), fast_round(self[1] as f32 * other[1] as f32 / 255.0), fast_round(self[2] as f32 * other[2] as f32 / 255.0), fast_round(self[3] as f32 * other[3] as f32 / 255.0), ]) } } impl std::ops::Add for Color32 { type Output = Self; #[inline] fn add(self, other: Self) -> Self { Self([ self[0].saturating_add(other[0]), self[1].saturating_add(other[1]), self[2].saturating_add(other[2]), self[3].saturating_add(other[3]), ]) } } #[cfg(test)] mod test { use super::*; fn test_rgba() -> impl Iterator<Item = [u8; 4]> { [ [0, 0, 0, 0], [0, 0, 0, 255], [10, 0, 30, 0], [10, 0, 30, 40], [10, 100, 200, 0], [10, 100, 200, 100], [10, 100, 200, 200], [10, 100, 200, 255], [10, 100, 200, 40], [10, 20, 0, 0], [10, 20, 0, 255], [10, 20, 30, 255], [10, 20, 30, 40], [255, 255, 255, 0], [255, 255, 255, 255], ] .into_iter() } #[test] fn test_color32_additive() { let opaque = Color32::from_rgb(40, 50, 60); let additive = Color32::from_rgb(255, 127, 10).additive(); assert_eq!(additive.blend(opaque), opaque, "opaque on top of additive"); assert_eq!( opaque.blend(additive), Color32::from_rgb(255, 177, 70), "additive on top of opaque" ); } #[test] fn test_color32_blend_vs_gamma_blend() { let opaque = Color32::from_rgb(0x60, 0x60, 0x60); let transparent = Color32::from_rgba_unmultiplied(168, 65, 65, 79); assert_eq!( transparent.blend(opaque), opaque, "Opaque on top of transparent" ); // Blending in gamma-space is the de-facto standard almost everywhere. // Browsers and most image editors do it, and so it is what users expect. assert_eq!( opaque.blend(transparent), Color32::from_rgb( blend(0x60, 168, 79), blend(0x60, 65, 79), blend(0x60, 65, 79) ), "Transparent on top of opaque" ); fn blend(dest: u8, src: u8, alpha: u8) -> u8 { let src = src as f32 / 255.0; let dest = dest as f32 / 255.0; let alpha = alpha as f32 / 255.0; fast_round((src * alpha + dest * (1.0 - alpha)) * 255.0) } } #[test] fn color32_unmultiplied_round_trip() { for in_rgba in test_rgba() { let [r, g, b, a] = in_rgba; if a == 0 { continue; } let c = Color32::from_rgba_unmultiplied(r, g, b, a); let out_rgba = c.to_srgba_unmultiplied(); if a == 255 { assert_eq!(in_rgba, out_rgba); } else { // There will be small rounding errors whenever the alpha is not 0 or 255, // because we multiply and then unmultiply the alpha. for (&a, &b) in in_rgba.iter().zip(out_rgba.iter()) { assert!(a.abs_diff(b) <= 3, "{in_rgba:?} != {out_rgba:?}"); } } } } #[test] fn from_black_white_alpha() { for a in 0..=255 { assert_eq!( Color32::from_white_alpha(a), Color32::from_rgba_unmultiplied(255, 255, 255, a) ); assert_eq!( Color32::from_white_alpha(a), Color32::WHITE.gamma_multiply_u8(a) ); assert_eq!( Color32::from_black_alpha(a), Color32::from_rgba_unmultiplied(0, 0, 0, a) ); assert_eq!( Color32::from_black_alpha(a), Color32::BLACK.gamma_multiply_u8(a) ); } } #[test] fn to_from_rgba() { for [r, g, b, a] in test_rgba() { let original = Color32::from_rgba_unmultiplied(r, g, b, a); let constfn = Color32::from_rgba_unmultiplied_const(r, g, b, a); let rgba = Rgba::from(original); let back = Color32::from(rgba); assert_eq!(back, original); assert_eq!(constfn, original); } assert_eq!( Color32::from(Rgba::from_rgba_unmultiplied(1.0, 0.0, 0.0, 0.5)), Color32::from_rgba_unmultiplied(255, 0, 0, 128) ); } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/emath/src/easing.rs
crates/emath/src/easing.rs
//! Easing functions for animations. //! //! Contains most easing functions from <https://easings.net/>. //! //! All functions take a value in `[0, 1]` and return a value in `[0, 1]`. //! //! Derived from <https://github.com/warrenm/AHEasing/blob/master/AHEasing/easing.c>. use std::f32::consts::PI; #[inline] fn powf(base: f32, exp: f32) -> f32 { base.powf(exp) } /// No easing, just `y = x` #[inline] pub fn linear(t: f32) -> f32 { t } /// <https://easings.net/#easeInQuad> /// /// Modeled after the parabola `y = x^2` #[inline] pub fn quadratic_in(t: f32) -> f32 { t * t } /// <https://easings.net/#easeOutQuad> /// /// Same as `1.0 - quadratic_in(1.0 - t)`. #[inline] pub fn quadratic_out(t: f32) -> f32 { -(t * (t - 2.)) } /// <https://easings.net/#easeInOutQuad> #[inline] pub fn quadratic_in_out(t: f32) -> f32 { if t < 0.5 { 2. * t * t } else { (-2. * t * t) + (4. * t) - 1. } } /// <https://easings.net/#easeInCubic> /// /// Modeled after the parabola `y = x^3` #[inline] pub fn cubic_in(t: f32) -> f32 { t * t * t } /// <https://easings.net/#easeOutCubic> #[inline] pub fn cubic_out(t: f32) -> f32 { let f = t - 1.; f * f * f + 1. } /// <https://easings.net/#easeInOutCubic> #[inline] pub fn cubic_in_out(t: f32) -> f32 { if t < 0.5 { 4. * t * t * t } else { let f = (2. * t) - 2.; 0.5 * f * f * f + 1. } } /// <https://easings.net/#easeInSine> /// /// Modeled after quarter-cycle of sine wave #[inline] pub fn sin_in(t: f32) -> f32 { ((t - 1.) * 2. * PI).sin() + 1. } /// <https://easings.net/#easeOuSine> /// /// Modeled after quarter-cycle of sine wave (different phase) #[inline] pub fn sin_out(t: f32) -> f32 { (t * 2. * PI).sin() } /// <https://easings.net/#easeInOutSine> /// /// Modeled after half sine wave #[inline] pub fn sin_in_out(t: f32) -> f32 { 0.5 * (1. - (t * PI).cos()) } /// <https://easings.net/#easeInCirc> /// /// Modeled after shifted quadrant IV of unit circle #[inline] pub fn circular_in(t: f32) -> f32 { 1. - (1. - t * t).sqrt() } /// <https://easings.net/#easeOutCirc> /// /// Modeled after shifted quadrant II of unit circle #[inline] pub fn circular_out(t: f32) -> f32 { (2. - t).sqrt() * t } /// <https://easings.net/#easeInOutCirc> #[inline] pub fn circular_in_out(t: f32) -> f32 { if t < 0.5 { 0.5 * (1. - (1. - 4. * t * t).sqrt()) } else { 0.5 * ((-(2. * t - 3.) * (2. * t - 1.)).sqrt() + 1.) } } /// <https://easings.net/#easeInExpo> /// /// There is a small discontinuity at 0. #[inline] pub fn exponential_in(t: f32) -> f32 { if t == 0. { t } else { powf(2.0, 10. * (t - 1.)) } } /// <https://easings.net/#easeOutExpo> /// /// There is a small discontinuity at 1. #[inline] pub fn exponential_out(t: f32) -> f32 { if t == 1. { t } else { 1. - powf(2.0, -10. * t) } } /// <https://easings.net/#easeInOutExpo> /// /// There is a small discontinuity at 0 and 1. #[inline] pub fn exponential_in_out(t: f32) -> f32 { if t == 0. || t == 1. { t } else if t < 0.5 { 0.5 * powf(2.0, 20. * t - 10.) } else { 0.5 * powf(2.0, -20. * t + 10.) + 1. } } /// <https://easings.net/#easeInBack> #[inline] pub fn back_in(t: f32) -> f32 { t * t * t - t * (t * PI).sin() } /// <https://easings.net/#easeOutBack> #[inline] pub fn back_out(t: f32) -> f32 { let f = 1. - t; 1. - (f * f * f - f * (f * PI).sin()) } /// <https://easings.net/#easeInOutBack> #[inline] pub fn back_in_out(t: f32) -> f32 { if t < 0.5 { let f = 2. * t; 0.5 * (f * f * f - f * (f * PI).sin()) } else { let f = 1. - (2. * t - 1.); 0.5 * (1. - (f * f * f - f * (f * PI).sin())) + 0.5 } } /// <https://easings.net/#easeInBounce> /// /// Each bounce is modelled as a parabola. #[inline] pub fn bounce_in(t: f32) -> f32 { 1. - bounce_out(1. - t) } /// <https://easings.net/#easeOutBounce> /// /// Each bounce is modelled as a parabola. #[inline] pub fn bounce_out(t: f32) -> f32 { if t < 4. / 11. { const T2: f32 = 121. / 16.; T2 * t * t } else if t < 8. / 11. { const T2: f32 = 363. / 40.; const T1: f32 = -99. / 10.; const T0: f32 = 17. / 5.; T2 * t * t + T1 * t + T0 } else if t < 9. / 10. { const T2: f32 = 4356. / 361.; const T1: f32 = -35442. / 1805.; const T0: f32 = 16061. / 1805.; T2 * t * t + T1 * t + T0 } else { const T2: f32 = 54. / 5.; const T1: f32 = -513. / 25.; const T0: f32 = 268. / 25.; T2 * t * t + T1 * t + T0 } } /// <https://easings.net/#easeInOutBounce> /// /// Each bounce is modelled as a parabola. #[inline] pub fn bounce_in_out(t: f32) -> f32 { if t < 0.5 { 0.5 * bounce_in(t * 2.) } else { 0.5 * bounce_out(t * 2. - 1.) + 0.5 } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false
emilk/egui
https://github.com/emilk/egui/blob/9e95b9ca50c224077617434707f7bd29bd70938b/crates/emath/src/ordered_float.rs
crates/emath/src/ordered_float.rs
//! Total order on floating point types. //! Can be used for sorting, min/max computation, and other collection algorithms. use std::cmp::Ordering; use std::hash::{Hash, Hasher}; /// Wraps a floating-point value to add total order and hash. /// Possible types for `T` are `f32` and `f64`. /// /// All NaNs are considered equal to each other. /// The size of zero is ignored. /// /// See also [`Float`]. #[derive(Clone, Copy)] pub struct OrderedFloat<T>(pub T); impl<T: Float + Copy> OrderedFloat<T> { #[inline] pub fn into_inner(self) -> T { self.0 } } impl<T: std::fmt::Debug> std::fmt::Debug for OrderedFloat<T> { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl<T: Float> Eq for OrderedFloat<T> {} impl<T: Float> PartialEq<Self> for OrderedFloat<T> { #[inline] fn eq(&self, other: &Self) -> bool { // NaNs are considered equal (equivalent) when it comes to ordering if self.0.is_nan() { other.0.is_nan() } else { self.0 == other.0 } } } impl<T: Float> PartialOrd<Self> for OrderedFloat<T> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T: Float> Ord for OrderedFloat<T> { #[inline] fn cmp(&self, other: &Self) -> Ordering { match self.0.partial_cmp(&other.0) { Some(ord) => ord, None => self.0.is_nan().cmp(&other.0.is_nan()), } } } impl<T: Float> Hash for OrderedFloat<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl<T> From<T> for OrderedFloat<T> { #[inline] fn from(val: T) -> Self { Self(val) } } // ---------------------------------------------------------------------------- /// Extension trait to provide `ord()` method. /// /// Example with `f64`: /// ``` /// use emath::Float as _; /// /// let array = [1.0, 2.5, 2.0]; /// let max = array.iter().max_by_key(|val| val.ord()); /// /// assert_eq!(max, Some(&2.5)); /// ``` pub trait Float: PartialOrd + PartialEq + private::FloatImpl { /// Type to provide total order, useful as key in sorted contexts. fn ord(self) -> OrderedFloat<Self> where Self: Sized; } impl Float for f32 { #[inline] fn ord(self) -> OrderedFloat<Self> { OrderedFloat(self) } } impl Float for f64 { #[inline] fn ord(self) -> OrderedFloat<Self> { OrderedFloat(self) } } // Keep this trait in private module, to avoid exposing its methods as extensions in user code mod private { use super::{Hash as _, Hasher}; pub trait FloatImpl { fn is_nan(&self) -> bool; fn hash<H: Hasher>(&self, state: &mut H); } impl FloatImpl for f32 { #[inline] fn is_nan(&self) -> bool { Self::is_nan(*self) } #[inline] fn hash<H: Hasher>(&self, state: &mut H) { let bits = if self.is_nan() { // "Canonical" NaN. 0x7fc00000 } else { // A trick taken from the `ordered-float` crate: -0.0 + 0.0 == +0.0. // https://github.com/reem/rust-ordered-float/blob/1841f0541ea0e56779cbac03de2705149e020675/src/lib.rs#L2178-L2181 (self + 0.0).to_bits() }; bits.hash(state); } } impl FloatImpl for f64 { #[inline] fn is_nan(&self) -> bool { Self::is_nan(*self) } #[inline] fn hash<H: Hasher>(&self, state: &mut H) { let bits = if self.is_nan() { // "Canonical" NaN. 0x7ff8000000000000 } else { (self + 0.0).to_bits() }; bits.hash(state); } } }
rust
Apache-2.0
9e95b9ca50c224077617434707f7bd29bd70938b
2026-01-04T15:36:36.351731Z
false