mirror of
https://github.com/storytold/egui.git
synced 2026-11-30 10:16:24 +01:00
Deprecate Id::new and From<&str> for Id (#8534)
`Id::new` and `From<&str> for Id` etc are foot-guns: they hide the fact that an `Id` MUST be globally unique (well, at least unique within your app). So this PR removes both and replaces them with `Id::unique`, which is very explicit. In places where non-uniqueness is desired, you can use `IdSalt`, which has the convenient `From<&str>`. Most changes are in tests. --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Lucas Meurer <hi@lucasmerlin.me>
This commit is contained in:
52 files changed
+342
-248
No files matched your search
@@ -121,7 +121,7 @@ mod tests {
|
||||
fn zero_duration_value_animation_reaches_target_immediately() {
|
||||
let mut animations = AnimationManager::default();
|
||||
let input = InputState::default();
|
||||
let id = Id::new("value_animation");
|
||||
let id = Id::unique("value_animation");
|
||||
|
||||
assert_eq!(animations.animate_value(&input, 0.0, id, 0.0), 0.0);
|
||||
assert_eq!(animations.animate_value(&input, 0.0, id, 1.0), 1.0);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
AtomKind, AtomLayout, AtomPaintArgs, FontSelection, Id, IntoSizedArgs, IntoSizedResult,
|
||||
AtomKind, AtomLayout, AtomPaintArgs, FontSelection, IdSalt, IntoSizedArgs, IntoSizedResult,
|
||||
SizedAtom, Ui,
|
||||
};
|
||||
use emath::{Align2, NumExt as _, Vec2};
|
||||
@@ -32,7 +32,7 @@ use epaint::text::TextWrapMode;
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Atom<'a> {
|
||||
/// See [`crate::AtomExt::atom_id`]
|
||||
pub id: Option<Id>,
|
||||
pub id: Option<IdSalt>,
|
||||
|
||||
/// See [`crate::AtomExt::atom_size`]
|
||||
pub size: Option<Vec2>,
|
||||
@@ -83,10 +83,10 @@ impl<'a> Atom<'a> {
|
||||
///
|
||||
/// Example:
|
||||
/// ```
|
||||
/// # use egui::{AtomExt, AtomKind, Atom, Button, Id, __run_test_ui};
|
||||
/// # use egui::{AtomExt, AtomKind, Atom, Button, IdSalt, __run_test_ui};
|
||||
/// # use emath::Vec2;
|
||||
/// # __run_test_ui(|ui| {
|
||||
/// let id = Id::new("my_button");
|
||||
/// let id = IdSalt::new("my_button");
|
||||
/// let response = Button::new(("Hi!", Atom::custom(id, Vec2::splat(18.0)))).atom_ui(ui);
|
||||
///
|
||||
/// let rect = response.rect(id);
|
||||
@@ -95,7 +95,7 @@ impl<'a> Atom<'a> {
|
||||
/// }
|
||||
/// # });
|
||||
/// ```
|
||||
pub fn custom(id: Id, size: impl Into<Vec2>) -> Self {
|
||||
pub fn custom(id: IdSalt, size: impl Into<Vec2>) -> Self {
|
||||
Atom {
|
||||
size: Some(size.into()),
|
||||
kind: AtomKind::Empty,
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
use crate::{Atom, FontSelection, Id, Ui};
|
||||
use crate::{Atom, FontSelection, IdSalt, 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 [`Id`] for custom rendering.
|
||||
/// Set the [`IdSalt`] for custom rendering.
|
||||
///
|
||||
/// You can get the [`crate::Rect`] with the [`Id`] from [`crate::AtomLayoutResponse`] and use a
|
||||
/// The salt only needs to be unique among the atoms of the same widget.
|
||||
///
|
||||
/// You can get the [`crate::Rect`] with the [`IdSalt`] from [`crate::AtomLayoutResponse`] and use a
|
||||
/// [`crate::Painter`] or [`Ui::place`] to add/draw some custom content.
|
||||
fn atom_id(self, id: Id) -> Atom<'a>;
|
||||
fn atom_id(self, id: IdSalt) -> Atom<'a>;
|
||||
|
||||
/// Set the atom to a fixed size.
|
||||
///
|
||||
@@ -80,7 +82,7 @@ impl<'a, T> AtomExt<'a> for T
|
||||
where
|
||||
T: Into<Atom<'a>> + Sized,
|
||||
{
|
||||
fn atom_id(self, id: Id) -> Atom<'a> {
|
||||
fn atom_id(self, id: IdSalt) -> Atom<'a> {
|
||||
let mut atom = self.into();
|
||||
atom.id = Some(id);
|
||||
atom
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
AtomKind, AtomPaintArgs, Atoms, Direction, FontSelection, Frame, Id, Image, IntoAtoms,
|
||||
AtomKind, AtomPaintArgs, Atoms, Direction, FontSelection, Frame, Id, IdSalt, Image, IntoAtoms,
|
||||
Response, Sense, SizedAtom, SizedAtomKind, Stroke, Ui, Widget,
|
||||
text_selection::LabelSelectionState,
|
||||
};
|
||||
@@ -716,7 +716,7 @@ impl AllocatedAtomLayout<'_> {
|
||||
pub struct AtomLayoutResponse {
|
||||
pub response: Response,
|
||||
// There should rarely be more than one custom rect.
|
||||
custom_rects: SmallVec<[(Id, Rect); 1]>,
|
||||
custom_rects: SmallVec<[(IdSalt, Rect); 1]>,
|
||||
}
|
||||
|
||||
impl AtomLayoutResponse {
|
||||
@@ -727,14 +727,14 @@ impl AtomLayoutResponse {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn custom_rects(&self) -> impl Iterator<Item = (Id, Rect)> + '_ {
|
||||
pub fn custom_rects(&self) -> impl Iterator<Item = (IdSalt, Rect)> + '_ {
|
||||
self.custom_rects.iter().copied()
|
||||
}
|
||||
|
||||
/// Use this together with [`crate::Atom::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> {
|
||||
pub fn rect(&self, id: IdSalt) -> Option<Rect> {
|
||||
self.custom_rects
|
||||
.iter()
|
||||
.find_map(|(i, r)| if *i == id { Some(*r) } else { None })
|
||||
|
||||
@@ -4,7 +4,7 @@ use emath::Vec2;
|
||||
/// A [`crate::Atom`] which has been sized.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SizedAtom<'a> {
|
||||
pub id: Option<crate::Id>,
|
||||
pub id: Option<crate::IdSalt>,
|
||||
|
||||
pub(crate) grow: bool,
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ impl AreaState {
|
||||
///
|
||||
/// ```
|
||||
/// # egui::__run_test_ctx(|ctx| {
|
||||
/// egui::Area::new(egui::Id::new("my_area"))
|
||||
/// egui::Area::new(egui::Id::unique("my_area"))
|
||||
/// .fixed_pos(egui::pos2(32.0, 32.0))
|
||||
/// .show(ctx, |ui| {
|
||||
/// ui.label("Floating text!");
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
use emath::GuiRounding as _;
|
||||
|
||||
use crate::{
|
||||
Align, Context, CursorIcon, Frame, Id, InnerResponse, LayerId, Layout, Margin, NumExt as _,
|
||||
Order, Rangef, Rect, Response, Sense, Stroke, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, lerp,
|
||||
Align, Context, CursorIcon, Frame, Id, IdSalt, InnerResponse, LayerId, Layout, Margin,
|
||||
NumExt as _, Order, Rangef, Rect, Response, Sense, Stroke, Ui, UiBuilder, UiKind, UiStackInfo,
|
||||
Vec2, lerp,
|
||||
};
|
||||
|
||||
fn animate_expansion(ctx: &Context, id: Id, is_expanded: bool) -> f32 {
|
||||
@@ -205,7 +206,9 @@ impl PanelSide {
|
||||
#[must_use = "You should call .show()"]
|
||||
pub struct Panel {
|
||||
side: PanelSide,
|
||||
id: Id,
|
||||
|
||||
/// Combined with the parent [`Ui::id`] to form the [`Id`] of the panel.
|
||||
id_salt: IdSalt,
|
||||
frame: Option<Frame>,
|
||||
resizable: bool,
|
||||
drag_to_open: bool,
|
||||
@@ -245,40 +248,40 @@ pub struct Panel {
|
||||
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)
|
||||
/// The `id_salt` only needs to be unique among the panels of the same parent [`Ui`], e.g. `"my_left_panel"`.
|
||||
pub fn left(id_salt: impl Into<IdSalt>) -> Self {
|
||||
Self::new(PanelSide::Left, id_salt)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
/// The `id_salt` only needs to be unique among the panels of the same parent [`Ui`], e.g. `"my_right_panel"`.
|
||||
pub fn right(id_salt: impl Into<IdSalt>) -> Self {
|
||||
Self::new(PanelSide::Right, id_salt)
|
||||
}
|
||||
|
||||
/// Create a top panel.
|
||||
///
|
||||
/// The id should be globally unique, e.g. `Id::new("my_top_panel")`.
|
||||
/// The `id_salt` only needs to be unique among the panels of the same parent [`Ui`], e.g. `"my_top_panel"`.
|
||||
///
|
||||
/// By default this is NOT resizable.
|
||||
pub fn top(id: impl Into<Id>) -> Self {
|
||||
Self::new(PanelSide::Top, id).resizable(false)
|
||||
pub fn top(id_salt: impl Into<IdSalt>) -> Self {
|
||||
Self::new(PanelSide::Top, id_salt).resizable(false)
|
||||
}
|
||||
|
||||
/// Create a bottom panel.
|
||||
///
|
||||
/// The id should be globally unique, e.g. `Id::new("my_bottom_panel")`.
|
||||
/// The `id_salt` only needs to be unique among the panels of the same parent [`Ui`], e.g. `"my_bottom_panel"`.
|
||||
///
|
||||
/// By default this is NOT resizable.
|
||||
pub fn bottom(id: impl Into<Id>) -> Self {
|
||||
Self::new(PanelSide::Bottom, id).resizable(false)
|
||||
pub fn bottom(id_salt: impl Into<IdSalt>) -> Self {
|
||||
Self::new(PanelSide::Bottom, id_salt).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 {
|
||||
/// The `id_salt` only needs to be unique among the panels of the same parent [`Ui`], e.g. `"my_panel"`.
|
||||
fn new(side: PanelSide, id_salt: impl Into<IdSalt>) -> Self {
|
||||
let default_outer_size: Option<f32> = match side {
|
||||
PanelSide::Left | PanelSide::Right => Some(200.0),
|
||||
PanelSide::Top | PanelSide::Bottom => None,
|
||||
@@ -291,7 +294,7 @@ impl Panel {
|
||||
|
||||
Self {
|
||||
side,
|
||||
id: id.into(),
|
||||
id_salt: id_salt.into(),
|
||||
frame: None,
|
||||
resizable: true,
|
||||
drag_to_open: true,
|
||||
@@ -454,7 +457,7 @@ impl Panel {
|
||||
is_expanded: &mut bool,
|
||||
add_contents: impl FnOnce(&mut Ui) -> R,
|
||||
) -> Option<InnerResponse<R>> {
|
||||
let how_expanded = animate_expansion(ui, self.id.with("animation"), *is_expanded);
|
||||
let how_expanded = animate_expansion(ui, self.id(ui).with("animation"), *is_expanded);
|
||||
|
||||
if how_expanded == 0.0 {
|
||||
// Panel is fully closed, but we still leave a grab handle at its fixed
|
||||
@@ -470,7 +473,7 @@ impl Panel {
|
||||
|
||||
// Don't lose the drag during the slide-back-open animation:
|
||||
let drag_in_progress = ui
|
||||
.read_response(self.resize_id())
|
||||
.read_response(self.resize_id(ui))
|
||||
.is_some_and(|r| r.dragged());
|
||||
|
||||
let panel = if how_expanded < 1.0 {
|
||||
@@ -568,7 +571,7 @@ impl Panel {
|
||||
add_contents: impl FnOnce(&mut Ui, bool) -> R,
|
||||
) -> InnerResponse<R> {
|
||||
debug_assert!(
|
||||
collapsed_panel.id != expanded_panel.id,
|
||||
collapsed_panel.id_salt != expanded_panel.id_salt,
|
||||
"show_switched: the collapsed and expanded panels must have distinct ids \
|
||||
(their persisted sizes are stored per-id, and sharing one id would let the collapsed \
|
||||
size overwrite the expanded size)."
|
||||
@@ -576,7 +579,7 @@ impl Panel {
|
||||
// Share one resize-handle widget across the collapsed and expanded panels
|
||||
// by routing both through the expanded panel's id. A drag that starts on
|
||||
// either panel survives the swap to the other view.
|
||||
let resize_id_source = expanded_panel.id;
|
||||
let resize_id_source = expanded_panel.id(ui);
|
||||
// Drag-to-collapse fires when the drag crosses the collapsed panel's
|
||||
// size, so the swap lines up with the visual size at that moment.
|
||||
let collapse_threshold = collapsed_panel.outer_size(ui);
|
||||
@@ -586,7 +589,7 @@ impl Panel {
|
||||
.read_response(resize_widget_id(resize_id_source))
|
||||
.is_some_and(|r| r.dragged());
|
||||
|
||||
let animation_id = expanded_panel.id.with("animation");
|
||||
let animation_id = expanded_panel.id(ui).with("animation");
|
||||
let how_expanded = animate_expansion(ui, animation_id, *is_expanded);
|
||||
|
||||
// When expanding, the user sees the expanded content the moment animation starts.
|
||||
@@ -690,7 +693,7 @@ impl Panel {
|
||||
add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
|
||||
) -> InnerResponse<R> {
|
||||
let side = self.side;
|
||||
let id = self.id;
|
||||
let id = self.id(parent_ui);
|
||||
let resizable = self.resizable;
|
||||
let show_separator_line = self.show_separator_line;
|
||||
|
||||
@@ -739,7 +742,7 @@ impl Panel {
|
||||
// released size gets persisted into [`PanelState`] — without this the
|
||||
// store-skipped-during-drag rule would leave the stored size at the
|
||||
// pre-drag value.
|
||||
let resize_id = self.resize_id();
|
||||
let resize_id = self.resize_id(parent_ui);
|
||||
let resize_response = parent_ui.read_response(resize_id);
|
||||
|
||||
// Double-click on the resize edge toggles `*is_expanded` for the
|
||||
@@ -939,8 +942,15 @@ impl Panel {
|
||||
/// [`Id`] of this panel's resize-handle widget.
|
||||
///
|
||||
/// See [`resize_widget_id`] for why open and collapsed panels must share it.
|
||||
fn resize_id(&self) -> Id {
|
||||
resize_widget_id(self.resize_id_source.unwrap_or(self.id))
|
||||
fn resize_id(&self, parent_ui: &Ui) -> Id {
|
||||
resize_widget_id(self.resize_id_source.unwrap_or_else(|| self.id(parent_ui)))
|
||||
}
|
||||
|
||||
/// The [`Id`] of this panel, given the [`Ui`] it is shown in.
|
||||
///
|
||||
/// Used as the key for the persisted [`PanelState`].
|
||||
fn id(&self, parent_ui: &Ui) -> Id {
|
||||
parent_ui.id().with_salt(self.id_salt)
|
||||
}
|
||||
|
||||
/// The configured [`Frame`], or the default side/top panel frame for this [`Ui`].
|
||||
@@ -995,7 +1005,7 @@ impl Panel {
|
||||
ui.style().interaction.resize_grab_radius_side,
|
||||
);
|
||||
|
||||
let resize_id = self.resize_id();
|
||||
let resize_id = self.resize_id(ui);
|
||||
let response = ui.interact(resize_rect, resize_id, Sense::click_and_drag());
|
||||
|
||||
if response.double_clicked() {
|
||||
@@ -1063,7 +1073,7 @@ impl Panel {
|
||||
/// previous build with a different range.
|
||||
fn outer_size(&self, ui: &Ui) -> f32 {
|
||||
let axis = self.side.axis();
|
||||
let raw = if let Some(state) = PanelState::load(ui, self.id) {
|
||||
let raw = if let Some(state) = PanelState::load(ui, self.id(ui)) {
|
||||
state.outer_rect.size_along(axis)
|
||||
} else if let Some(default_outer_size) = self.default_outer_size {
|
||||
default_outer_size
|
||||
@@ -1087,7 +1097,7 @@ impl Panel {
|
||||
|
||||
// Use `resize_id_source` so collapsed/expanded panels in
|
||||
// `show_switched` share one resize widget.
|
||||
let resize_id = self.resize_id();
|
||||
let resize_id = self.resize_id(ui);
|
||||
let resize_rect = Rect::from_x_y_ranges(resize_x, resize_y).expand2(amount);
|
||||
ui.interact(resize_rect, resize_id, Sense::click_and_drag())
|
||||
}
|
||||
@@ -1137,7 +1147,7 @@ impl Panel {
|
||||
self
|
||||
}
|
||||
|
||||
/// Register the resize-handle widget under this `Id` instead of `self.id`.
|
||||
/// Register the resize-handle widget under this `Id` instead of [`Self::id`].
|
||||
///
|
||||
/// Used by [`Self::show_switched`] to share one widget across
|
||||
/// the collapsed and expanded panels.
|
||||
|
||||
@@ -165,7 +165,7 @@ impl Tooltip<'_> {
|
||||
}
|
||||
|
||||
fn when_was_a_toolip_last_shown_id() -> Id {
|
||||
Id::new("when_was_a_toolip_last_shown")
|
||||
Id::unique("when_was_a_toolip_last_shown")
|
||||
}
|
||||
|
||||
pub fn seconds_since_last_tooltip(ctx: &Context) -> f32 {
|
||||
|
||||
@@ -101,7 +101,7 @@ impl<'a> Window<'a> {
|
||||
/// If you need a changing title, you must call `window.id(…)` with a fixed id.
|
||||
pub fn new(title: impl IntoAtoms<'a>) -> Self {
|
||||
let title: Atoms<'_> = title.into_atoms();
|
||||
let area = Area::new(Id::new(title.text())).kind(UiKind::Window);
|
||||
let area = Area::new(Id::unique(title.text())).kind(UiKind::Window);
|
||||
Self {
|
||||
title,
|
||||
open: None,
|
||||
@@ -137,7 +137,7 @@ impl<'a> Window<'a> {
|
||||
.. // 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));
|
||||
let mut window = Self::new(title.or(app_id).unwrap_or_else(String::new)).id(Id::unique(id));
|
||||
|
||||
if let Some(inner_size) = inner_size {
|
||||
window = window.default_size(inner_size);
|
||||
@@ -1090,7 +1090,7 @@ fn do_resize_interaction(
|
||||
}
|
||||
};
|
||||
|
||||
let id = Id::new(layer_id).with("edge_drag");
|
||||
let id = Id::unique(layer_id).with("edge_drag");
|
||||
|
||||
let style = ctx.global_style();
|
||||
|
||||
@@ -1314,8 +1314,8 @@ fn title_ui(
|
||||
let button_allocation_size = Vec2::splat(heading_font_height);
|
||||
let button_shrink = (button_allocation_size - button_size) / 2.0;
|
||||
|
||||
let collapse_atom_id = Id::new("__window_collapse_button");
|
||||
let close_atom_id = Id::new("__window_close_button");
|
||||
let collapse_atom_id = IdSalt::new("__window_collapse_button");
|
||||
let close_atom_id = IdSalt::new("__window_close_button");
|
||||
|
||||
let expanded = collapsing.openness(ui.ctx()) > 0.0;
|
||||
|
||||
|
||||
@@ -851,7 +851,7 @@ impl Context {
|
||||
self.run_dyn(new_input, &mut |ctx| {
|
||||
let mut root_ui = Ui::new(
|
||||
ctx.clone(),
|
||||
Id::new((ctx.viewport_id(), "__top_ui")),
|
||||
ctx.viewport_id().root_ui_id(),
|
||||
UiBuilder::new()
|
||||
.layer_id(LayerId::background())
|
||||
.max_rect(ctx.viewport_rect()),
|
||||
|
||||
+21
-21
@@ -463,17 +463,17 @@ mod tests {
|
||||
fn buttons_on_window() {
|
||||
let widgets = vec![
|
||||
wr(
|
||||
Id::new("bg-area"),
|
||||
Id::unique("bg-area"),
|
||||
Sense::drag(),
|
||||
Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0)),
|
||||
),
|
||||
wr(
|
||||
Id::new("click"),
|
||||
Id::unique("click"),
|
||||
Sense::click(),
|
||||
Rect::from_min_size(pos2(10.0, 10.0), vec2(10.0, 10.0)),
|
||||
),
|
||||
wr(
|
||||
Id::new("click-and-drag"),
|
||||
Id::unique("click-and-drag"),
|
||||
Sense::click_and_drag(),
|
||||
Rect::from_min_size(pos2(100.0, 10.0), vec2(10.0, 10.0)),
|
||||
),
|
||||
@@ -481,45 +481,45 @@ mod tests {
|
||||
|
||||
// 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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("click"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("click"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("click-and-drag"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("click-and-drag"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("click-and-drag"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thin_resize_handle_next_to_label() {
|
||||
let widgets = vec![
|
||||
wr(
|
||||
Id::new("bg-area"),
|
||||
Id::unique("bg-area"),
|
||||
Sense::drag(),
|
||||
Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0)),
|
||||
),
|
||||
wr(
|
||||
Id::new("bg-left-label"),
|
||||
Id::unique("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"),
|
||||
Id::unique("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"),
|
||||
Id::unique("fg-right-label"),
|
||||
Sense::click_and_drag(),
|
||||
Rect::from_min_size(pos2(60.0, 0.0), vec2(50.0, 100.0)),
|
||||
),
|
||||
@@ -531,22 +531,22 @@ mod tests {
|
||||
|
||||
// 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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("bg-left-label"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("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"));
|
||||
assert_eq!(hits.click.unwrap().id, Id::unique("fg-right-label"));
|
||||
assert_eq!(hits.drag.unwrap().id, Id::unique("fg-right-label"));
|
||||
}
|
||||
}
|
||||
+62
-42
@@ -12,6 +12,8 @@ pub trait AsId: core::hash::Hash + core::fmt::Debug {}
|
||||
|
||||
impl<T: core::hash::Hash + core::fmt::Debug> AsId for T {}
|
||||
|
||||
/// A (hopefully) unique identity within this application.
|
||||
///
|
||||
/// egui tracks widgets frame-to-frame using [`Id`]s.
|
||||
///
|
||||
/// For instance, if you start dragging a slider one frame, egui stores
|
||||
@@ -22,7 +24,7 @@ impl<T: core::hash::Hash + core::fmt::Debug> AsId for T {}
|
||||
/// For some widgets [`Id`]s are also used to persist some state about the
|
||||
/// widgets, such as Window position or whether not a collapsing header region is open.
|
||||
///
|
||||
/// This implies that the [`Id`]s must be unique.
|
||||
/// This implies that the [`Id`]s must be "globally" unique (unique within the running app).
|
||||
///
|
||||
/// For simple things like sliders and buttons that don't have any memory and
|
||||
/// doesn't move we can use the location of the widget as a source of identity.
|
||||
@@ -60,7 +62,7 @@ impl Id {
|
||||
/// though obviously it will lead to a lot of collisions if you do use it!
|
||||
pub const NULL: Self = Self(NonZeroU64::MAX);
|
||||
|
||||
/// Create a new root [`Id`] from a high-entropy hash.
|
||||
/// Create a new, globally unique, root [`Id`] from a high-entropy hash.
|
||||
#[inline]
|
||||
const fn from_hash(hash: u64) -> Self {
|
||||
if let Some(nonzero) = NonZeroU64::new(hash) {
|
||||
@@ -70,8 +72,13 @@ impl Id {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a new root [`Id`] by hashing some source (e.g. a string or integer).
|
||||
pub fn new(source: impl AsId) -> Self {
|
||||
/// Creates a new root [`Id`] from a globally unique source (e.g. a string or integer) by hashing it.
|
||||
///
|
||||
/// The source must be unique within the whole application,
|
||||
/// or else you risk [`Id`] clashes with other widgets.
|
||||
///
|
||||
/// If you only need something unique within a parent widget, use [`IdSalt`] instead.
|
||||
pub fn unique(source: impl AsId) -> Self {
|
||||
let id = Self::from_hash(ahash::RandomState::with_seeds(1, 2, 3, 4).hash_one(&source));
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -80,13 +87,17 @@ impl Id {
|
||||
id
|
||||
}
|
||||
|
||||
/// Generate a new, globally unique, root [`Id`] by hashing some source (e.g. a string or integer).
|
||||
#[deprecated = "Use `Id::unique` (for a globally unique id) or `IdSalt::new` (for a locally unique salt) instead"]
|
||||
pub fn new(source: impl AsId) -> Self {
|
||||
Self::unique(source)
|
||||
}
|
||||
|
||||
/// Generate a child [`Id`] by salting the parent [`Id`] with the given argument.
|
||||
///
|
||||
/// `id.with(salt)` is the same as `id.with_salt(IdSalt::new(salt))`.
|
||||
pub fn with(self, salt: impl AsIdSalt) -> Self {
|
||||
use core::hash::{BuildHasher as _, Hasher as _};
|
||||
let mut hasher = ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher();
|
||||
hasher.write_u64(self.value());
|
||||
hasher.write_u64(IdSalt::new(&salt).value());
|
||||
let id = Self::from_hash(hasher.finish());
|
||||
let id = self.hash_with_salt(IdSalt::new(&salt));
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
id_source::insert_child(id, self, &salt);
|
||||
@@ -94,6 +105,26 @@ impl Id {
|
||||
id
|
||||
}
|
||||
|
||||
/// Generate a child [`Id`] by salting the parent [`Id`] with the given [`IdSalt`].
|
||||
///
|
||||
/// `id.with_salt(IdSalt::new(salt))` is the same as `id.with(salt)`.
|
||||
pub fn with_salt(self, salt: IdSalt) -> Self {
|
||||
let id = self.hash_with_salt(salt);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
id_source::insert_child(id, self, &salt);
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
fn hash_with_salt(self, salt: IdSalt) -> Self {
|
||||
use core::hash::{BuildHasher as _, Hasher as _};
|
||||
let mut hasher = ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher();
|
||||
hasher.write_u64(self.value());
|
||||
hasher.write_u64(salt.value());
|
||||
Self::from_hash(hasher.finish())
|
||||
}
|
||||
|
||||
/// Short and readable summary
|
||||
pub fn short_debug_format(&self) -> String {
|
||||
format!("{:04X}", self.value() as u16)
|
||||
@@ -146,23 +177,6 @@ impl core::fmt::Debug for Id {
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Convenience
|
||||
impl From<&'static str> for Id {
|
||||
#[inline]
|
||||
fn from(string: &'static str) -> Self {
|
||||
Self::new(string)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Id {
|
||||
#[inline]
|
||||
fn from(string: String) -> Self {
|
||||
Self::new(string)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// `IdSet` is a `HashSet<Id>` optimized by knowing that [`Id`] has good entropy, and doesn't need more hashing.
|
||||
pub type IdSet = nohash_hasher::IntSet<Id>;
|
||||
|
||||
@@ -173,8 +187,8 @@ pub type IdMap<V> = nohash_hasher::IntMap<Id, V>;
|
||||
|
||||
/// In debug builds, remember the `Debug`-formatted call chain that produced each [`Id`].
|
||||
///
|
||||
/// Used by [`Id`]'s `Debug` impl so that `Id::new("foo")` prints as `Id::new("foo")`,
|
||||
/// and `Id::new("foo").with("bar")` prints as `Id::new("foo").with("bar")`, etc.
|
||||
/// Used by [`Id`]'s `Debug` impl so that `Id::unique("foo")` prints as `Id::unique("foo")`,
|
||||
/// and `Id::unique("foo").with("bar")` prints as `Id::unique("foo").with("bar")`, etc.
|
||||
#[cfg(debug_assertions)]
|
||||
mod id_source {
|
||||
use super::{AsId, AsIdSalt, Id, IdMap};
|
||||
@@ -188,7 +202,7 @@ mod id_source {
|
||||
return;
|
||||
}
|
||||
// Format outside the lock since `{source:?}` may itself recurse into [`Id`]'s `Debug` impl.
|
||||
let formatted = format!("Id::new({source:?})");
|
||||
let formatted = format!("Id::unique({source:?})");
|
||||
SOURCE_MAP.write().insert(id, formatted);
|
||||
}
|
||||
|
||||
@@ -224,42 +238,48 @@ mod debug_format_tests {
|
||||
|
||||
#[test]
|
||||
fn root_string() {
|
||||
let id = Id::new("foo");
|
||||
assert_eq!(format!("{id:?}"), r#"Id::new("foo")"#);
|
||||
let id = Id::unique("foo");
|
||||
assert_eq!(format!("{id:?}"), r#"Id::unique("foo")"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_integer() {
|
||||
let id = Id::new(42_i32);
|
||||
assert_eq!(format!("{id:?}"), "Id::new(42)");
|
||||
let id = Id::unique(42_i32);
|
||||
assert_eq!(format!("{id:?}"), "Id::unique(42)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_id_salt() {
|
||||
let id = Id::new(IdSalt::new("foo"));
|
||||
assert_eq!(format!("{id:?}"), r#"Id::new(IdSalt::new("foo"))"#);
|
||||
let id = Id::unique(IdSalt::new("foo"));
|
||||
assert_eq!(format!("{id:?}"), r#"Id::unique(IdSalt::new("foo"))"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_salt_matches_with() {
|
||||
let parent = Id::unique("parent");
|
||||
assert_eq!(parent.with_salt(IdSalt::new("child")), parent.with("child"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_one_child() {
|
||||
let id = Id::new("parent").with("child");
|
||||
assert_eq!(format!("{id:?}"), r#"Id::new("parent").with("child")"#);
|
||||
let id = Id::unique("parent").with("child");
|
||||
assert_eq!(format!("{id:?}"), r#"Id::unique("parent").with("child")"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_chain() {
|
||||
let id = Id::new("a").with("b").with("c").with(7_i32);
|
||||
let id = Id::unique("a").with("b").with("c").with(7_i32);
|
||||
assert_eq!(
|
||||
format!("{id:?}"),
|
||||
r#"Id::new("a").with("b").with("c").with(7)"#
|
||||
r#"Id::unique("a").with("b").with("c").with(7)"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_id_as_source() {
|
||||
let inner = Id::new("foo");
|
||||
let outer = Id::new(inner);
|
||||
assert_eq!(format!("{outer:?}"), r#"Id::new(Id::new("foo"))"#);
|
||||
let inner = Id::unique("foo");
|
||||
let outer = Id::unique(inner);
|
||||
assert_eq!(format!("{outer:?}"), r#"Id::unique(Id::unique("foo"))"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,7 +8,7 @@ pub trait AsIdSalt: core::hash::Hash + core::fmt::Debug {}
|
||||
|
||||
impl<T: core::hash::Hash + core::fmt::Debug> AsIdSalt for T {}
|
||||
|
||||
/// Uniquely identifies a child widget within a parent widget.
|
||||
/// A "locally unique" identifier, e.g. to identify a child widget within a parent widget.
|
||||
///
|
||||
/// An [`IdSalt`] is only unique within a parent [`crate::Id`].
|
||||
/// An [`IdSalt`] is NOT globally unique.
|
||||
@@ -57,6 +57,21 @@ impl IdSalt {
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience
|
||||
impl From<&'static str> for IdSalt {
|
||||
#[inline]
|
||||
fn from(string: &'static str) -> Self {
|
||||
Self::new(string)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for IdSalt {
|
||||
#[inline]
|
||||
fn from(string: String) -> Self {
|
||||
Self::new(string)
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for IdSalt {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
#[cfg(debug_assertions)]
|
||||
|
||||
@@ -75,14 +75,14 @@ impl LayerId {
|
||||
pub fn debug() -> Self {
|
||||
Self {
|
||||
order: Order::Debug,
|
||||
id: Id::new("debug"),
|
||||
id: Id::unique("debug"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn background() -> Self {
|
||||
Self {
|
||||
order: Order::Background,
|
||||
id: Id::new("background"),
|
||||
id: Id::unique("background"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -663,5 +663,5 @@ pub fn __run_test_ui(mut add_contents: impl FnMut(&mut Ui)) {
|
||||
}
|
||||
|
||||
pub fn accesskit_root_id() -> Id {
|
||||
Id::new("accesskit_root")
|
||||
Id::unique("accesskit_root")
|
||||
}
|
||||
@@ -1016,8 +1016,8 @@ impl Memory {
|
||||
}
|
||||
|
||||
/// Obtain the previous rectangle of an area.
|
||||
pub fn area_rect(&self, id: impl Into<Id>) -> Option<Rect> {
|
||||
self.areas().get(id.into()).map(|state| state.rect())
|
||||
pub fn area_rect(&self, id: Id) -> Option<Rect> {
|
||||
self.areas().get(id).map(|state| state.rect())
|
||||
}
|
||||
|
||||
pub(crate) fn interaction(&self) -> &InteractionState {
|
||||
@@ -1416,8 +1416,8 @@ fn memory_impl_send_sync() {
|
||||
#[test]
|
||||
fn lost_focus_fires_after_mid_frame_focus_transfer() {
|
||||
use crate::data::input::RawInput;
|
||||
let a = Id::new("A");
|
||||
let b = Id::new("B");
|
||||
let a = Id::unique("A");
|
||||
let b = Id::unique("B");
|
||||
let mut focus = Focus::default();
|
||||
let raw = RawInput::default();
|
||||
|
||||
@@ -1463,13 +1463,13 @@ fn lost_focus_fires_after_mid_frame_focus_transfer() {
|
||||
#[test]
|
||||
fn order_map_total_ordering() {
|
||||
let mut layers = [
|
||||
LayerId::new(Order::Tooltip, Id::new("a")),
|
||||
LayerId::new(Order::Background, Id::new("b")),
|
||||
LayerId::new(Order::Background, Id::new("c")),
|
||||
LayerId::new(Order::Tooltip, Id::new("d")),
|
||||
LayerId::new(Order::Background, Id::new("e")),
|
||||
LayerId::new(Order::Background, Id::new("f")),
|
||||
LayerId::new(Order::Tooltip, Id::new("g")),
|
||||
LayerId::new(Order::Tooltip, Id::unique("a")),
|
||||
LayerId::new(Order::Background, Id::unique("b")),
|
||||
LayerId::new(Order::Background, Id::unique("c")),
|
||||
LayerId::new(Order::Tooltip, Id::unique("d")),
|
||||
LayerId::new(Order::Background, Id::unique("e")),
|
||||
LayerId::new(Order::Background, Id::unique("f")),
|
||||
LayerId::new(Order::Tooltip, Id::unique("g")),
|
||||
];
|
||||
let mut areas = Areas::default();
|
||||
|
||||
|
||||
@@ -750,7 +750,7 @@ mod tests {
|
||||
|
||||
fn test_selection() -> CurrentSelection {
|
||||
let cursor = WidgetTextCursor {
|
||||
widget_id: Id::new("selected_label"),
|
||||
widget_id: Id::unique("selected_label"),
|
||||
ccursor: CCursor::default(),
|
||||
pos: Pos2::ZERO,
|
||||
};
|
||||
|
||||
@@ -887,12 +887,12 @@ impl Ui {
|
||||
|
||||
/// This is the `Id` that will be assigned to the next widget added to this `Ui`.
|
||||
pub fn next_auto_id(&self) -> Id {
|
||||
Id::new(self.next_auto_id_salt)
|
||||
Id::unique(self.next_auto_id_salt)
|
||||
}
|
||||
|
||||
/// Same as `ui.next_auto_id().with(id_salt)`
|
||||
pub fn auto_id_with(&self, id_salt: impl AsIdSalt) -> Id {
|
||||
Id::new(self.next_auto_id_salt).with(id_salt)
|
||||
Id::unique(self.next_auto_id_salt).with(id_salt)
|
||||
}
|
||||
|
||||
/// Pretend like `count` widgets have been allocated.
|
||||
@@ -1228,7 +1228,7 @@ impl Ui {
|
||||
}
|
||||
}
|
||||
|
||||
let id = Id::new(self.next_auto_id_salt);
|
||||
let id = Id::unique(self.next_auto_id_salt);
|
||||
self.next_auto_id_salt = self.next_auto_id_salt.wrapping_add(1);
|
||||
|
||||
(id, rect)
|
||||
@@ -1269,7 +1269,7 @@ impl Ui {
|
||||
self.placer.advance_after_rects(rect, rect, item_spacing);
|
||||
register_rect(self, rect);
|
||||
|
||||
let id = Id::new(self.next_auto_id_salt);
|
||||
let id = Id::unique(self.next_auto_id_salt);
|
||||
self.next_auto_id_salt = self.next_auto_id_salt.wrapping_add(1);
|
||||
id
|
||||
}
|
||||
|
||||
@@ -378,8 +378,8 @@ impl RawKey {
|
||||
///
|
||||
/// ```
|
||||
/// # use egui::{Id, util::IdTypeMap};
|
||||
/// let a = Id::new("a");
|
||||
/// let b = Id::new("b");
|
||||
/// let a = Id::unique("a");
|
||||
/// let b = Id::unique("b");
|
||||
/// let mut map: IdTypeMap = Default::default();
|
||||
///
|
||||
/// // `a` associated with an f64 and an i32
|
||||
@@ -806,8 +806,8 @@ impl<'de> serde::Deserialize<'de> for IdTypeMap {
|
||||
|
||||
#[test]
|
||||
fn test_two_id_two_type() {
|
||||
let a = Id::new("a");
|
||||
let b = Id::new("b");
|
||||
let a = Id::unique("a");
|
||||
let b = Id::unique("b");
|
||||
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
map.insert_persisted(a, 13.37);
|
||||
@@ -822,8 +822,8 @@ fn test_two_id_two_type() {
|
||||
fn test_two_id_x_two_types() {
|
||||
#![expect(clippy::approx_constant)]
|
||||
|
||||
let a = Id::new("a");
|
||||
let b = Id::new("b");
|
||||
let a = Id::unique("a");
|
||||
let b = Id::unique("b");
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
|
||||
// `a` associated with an f64 and an i32
|
||||
@@ -849,7 +849,7 @@ fn test_two_id_x_two_types() {
|
||||
|
||||
#[test]
|
||||
fn test_one_id_two_types() {
|
||||
let id = Id::new("a");
|
||||
let id = Id::unique("a");
|
||||
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
map.insert_persisted(id, 13.37);
|
||||
@@ -885,7 +885,7 @@ fn test_mix() {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Bar(f32);
|
||||
|
||||
let id = Id::new("a");
|
||||
let id = Id::unique("a");
|
||||
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
map.insert_persisted(id, Foo(555));
|
||||
@@ -923,7 +923,7 @@ fn test_mix_serialize() {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct NonSerializable(f32);
|
||||
|
||||
let id = Id::new("a");
|
||||
let id = Id::unique("a");
|
||||
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
map.insert_persisted(id, Serializable(555));
|
||||
@@ -989,10 +989,10 @@ fn test_serialize_generations() {
|
||||
|
||||
let mut map: IdTypeMap = Default::default();
|
||||
for i in 0..3 {
|
||||
map.insert_persisted(Id::new(i), A(i));
|
||||
map.insert_persisted(Id::unique(i), A(i));
|
||||
}
|
||||
for i in 0..3 {
|
||||
assert_eq!(map.get_generation::<A>(Id::new(i)), Some(0));
|
||||
assert_eq!(map.get_generation::<A>(Id::unique(i)), Some(0));
|
||||
}
|
||||
|
||||
map = serialize_and_deserialize(&map);
|
||||
@@ -1002,17 +1002,17 @@ fn test_serialize_generations() {
|
||||
// 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));
|
||||
assert_eq!(map.get_generation::<A>(Id::unique(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));
|
||||
assert_eq!(map.get_persisted::<A>(Id::unique(0)), Some(A(0)));
|
||||
assert_eq!(map.get_generation::<A>(Id::unique(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));
|
||||
assert_eq!(map.get_generation::<A>(Id::unique(0)), Some(2));
|
||||
assert_eq!(map.get_generation::<A>(Id::unique(1)), Some(3));
|
||||
}
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
@@ -1038,10 +1038,10 @@ fn test_serialize_gc() {
|
||||
let num_b = 10;
|
||||
|
||||
for i in 0..num_a {
|
||||
map.insert_persisted(Id::new(i), A(i));
|
||||
map.insert_persisted(Id::unique(i), A(i));
|
||||
}
|
||||
for i in 0..num_b {
|
||||
map.insert_persisted(Id::new(i), B(i));
|
||||
map.insert_persisted(Id::unique(i), B(i));
|
||||
}
|
||||
|
||||
map = serialize_and_deserialize(map, 100);
|
||||
@@ -1051,15 +1051,15 @@ fn test_serialize_gc() {
|
||||
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));
|
||||
map.insert_persisted(Id::unique(1_000_000), A(1_000_000));
|
||||
map.insert_persisted(Id::unique(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)));
|
||||
assert_eq!(map.get_persisted::<A>(Id::unique(0)), Some(A(0)));
|
||||
assert_eq!(map.get_persisted::<B>(Id::unique(0)), Some(B(0)));
|
||||
|
||||
map = serialize_and_deserialize(map, 100);
|
||||
|
||||
@@ -1075,8 +1075,8 @@ fn test_serialize_gc() {
|
||||
);
|
||||
|
||||
// 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.insert_persisted(Id::unique(2_000_000), A(2_000_000));
|
||||
map.insert_persisted(Id::unique(2_000_000), B(2_000_000));
|
||||
|
||||
map = serialize_and_deserialize(map, 100);
|
||||
|
||||
@@ -1091,11 +1091,11 @@ fn test_serialize_gc() {
|
||||
assert_eq!(map.count::<B>(), 1);
|
||||
|
||||
assert_eq!(
|
||||
map.get_persisted::<A>(Id::new(2_000_000)),
|
||||
map.get_persisted::<A>(Id::unique(2_000_000)),
|
||||
Some(A(2_000_000))
|
||||
);
|
||||
assert_eq!(
|
||||
map.get_persisted::<B>(Id::new(2_000_000)),
|
||||
map.get_persisted::<B>(Id::unique(2_000_000)),
|
||||
Some(B(2_000_000))
|
||||
);
|
||||
}
|
||||
@@ -150,7 +150,13 @@ impl ViewportId {
|
||||
|
||||
#[inline]
|
||||
pub fn from_hash_of(source: impl AsId) -> Self {
|
||||
Self(Id::new(source))
|
||||
Self(Id::unique(source))
|
||||
}
|
||||
|
||||
/// The [`Id`] of the root [`crate::Ui`] of this viewport,
|
||||
/// i.e. the `Ui` passed to the closure of [`crate::Context::run_ui`].
|
||||
pub fn root_ui_id(&self) -> Id {
|
||||
Id::unique((*self, "__top_ui"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use emath::Rect;
|
||||
|
||||
use crate::{
|
||||
Atom, AtomLayout, Atoms, Id, IntoAtoms, NumExt as _, Response, Sense, Shape, Ui, Vec2, Widget,
|
||||
WidgetInfo, WidgetType,
|
||||
Atom, AtomLayout, Atoms, IdSalt, IntoAtoms, NumExt as _, Response, Sense, Shape, Ui, Vec2,
|
||||
Widget, WidgetInfo, WidgetType,
|
||||
class::{Classes, HasClasses},
|
||||
epaint, pos2,
|
||||
widget_style::CheckboxStyle,
|
||||
@@ -85,7 +85,7 @@ impl Widget for Checkbox<'_> {
|
||||
// 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");
|
||||
let rect_id = IdSalt::new("checkbox_icon");
|
||||
atoms.push_left(Atom::custom(rect_id, icon_size));
|
||||
|
||||
let text = atoms.text().map(String::from);
|
||||
|
||||
@@ -47,7 +47,7 @@ fn background_checkers(painter: &Painter, bounds: RoundedRect) {
|
||||
);
|
||||
let texture = painter.ctx().load_texture_cached(
|
||||
"color_picker_checkers",
|
||||
Id::new("color_picker_checkers"),
|
||||
Id::unique("color_picker_checkers"),
|
||||
image,
|
||||
TextureOptions::NEAREST_REPEAT,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
Atom, AtomExt as _, AtomKind, Atoms, Button, CursorIcon, Id, IntoAtoms, Key, MINUS_CHAR_STR,
|
||||
Modifiers, NumExt as _, Response, RichText, Sense, TextEdit, TextWrapMode, Ui, Widget,
|
||||
WidgetInfo,
|
||||
Atom, AtomExt as _, AtomKind, Atoms, Button, CursorIcon, Id, IdSalt, IntoAtoms, Key,
|
||||
MINUS_CHAR_STR, Modifiers, NumExt as _, Response, RichText, Sense, TextEdit, TextWrapMode, Ui,
|
||||
Widget, WidgetInfo,
|
||||
class::{ClassName, Classes, HasClasses},
|
||||
emath, text,
|
||||
};
|
||||
@@ -91,7 +91,8 @@ impl<'a> DragValue<'a> {
|
||||
}
|
||||
|
||||
pub fn from_get_set(get_set_value: impl 'a + FnMut(Option<f64>) -> f64) -> Self {
|
||||
let atoms = Atoms::new(Atom::custom(Id::new(Self::ATOM_ID), Vec2::ZERO).atom_grow(true));
|
||||
let atoms =
|
||||
Atoms::new(Atom::custom(IdSalt::new(Self::ATOM_ID), Vec2::ZERO).atom_grow(true));
|
||||
|
||||
Self {
|
||||
get_set_value: Box::new(get_set_value),
|
||||
@@ -474,7 +475,7 @@ impl Widget for DragValue<'_> {
|
||||
let mut prefix_text = String::new();
|
||||
let mut suffix_text = String::new();
|
||||
let mut past_value = false;
|
||||
let atom_id = Id::new(Self::ATOM_ID);
|
||||
let atom_id = IdSalt::new(Self::ATOM_ID);
|
||||
for atom in atoms.iter() {
|
||||
if atom.id == Some(atom_id) {
|
||||
past_value = true;
|
||||
|
||||
@@ -910,7 +910,7 @@ pub fn decode_animated_image_uri(uri: &str) -> Result<(&str, usize), String> {
|
||||
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)));
|
||||
let durations: Option<FrameDurations> = ctx.data(|data| data.get_temp(Id::unique(uri)));
|
||||
|
||||
if let Some(durations) = durations {
|
||||
let frames: Duration = durations.all().sum();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
Atom, AtomLayout, Atoms, Id, IntoAtoms, NumExt as _, Response, Sense, Ui, Vec2, Widget,
|
||||
Atom, AtomLayout, Atoms, IdSalt, IntoAtoms, NumExt as _, Response, Sense, Ui, Vec2, Widget,
|
||||
WidgetInfo, WidgetType, epaint,
|
||||
};
|
||||
|
||||
@@ -57,7 +57,7 @@ impl Widget for RadioButton<'_> {
|
||||
// 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");
|
||||
let rect_id = IdSalt::new("radio_button_icon");
|
||||
atoms.push_left(Atom::custom(rect_id, icon_size));
|
||||
|
||||
let text = atoms.text().map(String::from);
|
||||
|
||||
@@ -663,7 +663,7 @@ impl TextEdit<'_> {
|
||||
let frame = atom_layout_style.frame;
|
||||
|
||||
let mut get_galley = None;
|
||||
let inner_rect_id = Id::new("text_edit_rect");
|
||||
let inner_rect_id = IdSalt::new("text_edit_rect");
|
||||
let mut response = {
|
||||
let any_shrink = hint_text.any_shrink();
|
||||
// Ideally we could just do `let mut atoms = prefix` here, but that won't compile
|
||||
|
||||
@@ -87,10 +87,10 @@ impl egui::Plugin for AccessibilityInspectorPlugin {
|
||||
|
||||
ui.enable_accesskit();
|
||||
|
||||
Panel::right(Self::id()).show(ui, |ui| {
|
||||
Panel::right("accessibility_inspector").show(ui, |ui| {
|
||||
ui.heading("🔎 AccessKit Inspector");
|
||||
if let Some(selected_node) = self.selected_node {
|
||||
Panel::bottom(Self::id().with("details_panel"))
|
||||
Panel::bottom("details_panel")
|
||||
.frame(Frame::new())
|
||||
.show_separator_line(false)
|
||||
.show(ui, |ui| {
|
||||
@@ -110,7 +110,7 @@ impl egui::Plugin for AccessibilityInspectorPlugin {
|
||||
|
||||
impl AccessibilityInspectorPlugin {
|
||||
fn id() -> Id {
|
||||
Id::new("Accessibility Inspector")
|
||||
Id::unique("Accessibility Inspector")
|
||||
}
|
||||
|
||||
fn selection_ui(&mut self, ui: &mut Ui, selected_node: NodeId) {
|
||||
|
||||
@@ -492,8 +492,10 @@ impl WrapApp {
|
||||
text
|
||||
});
|
||||
|
||||
let painter =
|
||||
ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target")));
|
||||
let painter = ctx.layer_painter(LayerId::new(
|
||||
Order::Foreground,
|
||||
Id::unique("file_drop_target"),
|
||||
));
|
||||
|
||||
let content_rect = ctx.content_rect();
|
||||
painter.rect_filled(content_rect, 0.0, Color32::from_black_alpha(192));
|
||||
|
||||
@@ -15,7 +15,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; // Much faster allocator
|
||||
/// to prevent the Context from building a massive map of `WidgetRects` (which would slow the test,
|
||||
/// causing unreliable results).
|
||||
fn create_benchmark_ui(ctx: &egui::Context) -> Ui {
|
||||
Ui::new(ctx.clone(), Id::new("clashing_id"), UiBuilder::new())
|
||||
Ui::new(ctx.clone(), Id::unique("clashing_id"), UiBuilder::new())
|
||||
}
|
||||
|
||||
pub fn criterion_benchmark(c: &mut Criterion) {
|
||||
|
||||
@@ -64,7 +64,7 @@ impl crate::View for DragAndDropDemo {
|
||||
let (_, dropped_payload) = ui.dnd_drop_zone::<Location, ()>(frame, |ui| {
|
||||
ui.set_min_size(vec2(64.0, 100.0));
|
||||
for (row_idx, item) in column.iter().enumerate() {
|
||||
let item_id = Id::new(("my_drag_and_drop_demo", col_idx, row_idx));
|
||||
let item_id = Id::unique(("my_drag_and_drop_demo", col_idx, row_idx));
|
||||
let item_location = Location {
|
||||
col: col_idx,
|
||||
row: row_idx,
|
||||
|
||||
@@ -15,7 +15,7 @@ impl crate::Demo for ExtraViewport {
|
||||
return;
|
||||
}
|
||||
|
||||
let id = egui::Id::new(self.name());
|
||||
let id = egui::Id::unique(self.name());
|
||||
|
||||
ui.show_viewport_immediate(
|
||||
egui::ViewportId(id),
|
||||
|
||||
@@ -71,7 +71,7 @@ impl crate::View for Modals {
|
||||
);
|
||||
|
||||
if *user_modal_open {
|
||||
let modal = Modal::new(Id::new("Modal A")).show(ui.ctx(), |ui| {
|
||||
let modal = Modal::new(Id::unique("Modal A")).show(ui.ctx(), |ui| {
|
||||
ui.set_width(250.0);
|
||||
|
||||
ui.heading("Edit User");
|
||||
@@ -111,7 +111,7 @@ impl crate::View for Modals {
|
||||
}
|
||||
|
||||
if *save_modal_open {
|
||||
let modal = Modal::new(Id::new("Modal B")).show(ui.ctx(), |ui| {
|
||||
let modal = Modal::new(Id::unique("Modal B")).show(ui.ctx(), |ui| {
|
||||
ui.set_width(200.0);
|
||||
ui.heading("Save? Are you sure?");
|
||||
|
||||
@@ -138,7 +138,7 @@ impl crate::View for Modals {
|
||||
}
|
||||
|
||||
if let Some(progress) = *save_progress {
|
||||
Modal::new(Id::new("Modal C")).show(ui.ctx(), |ui| {
|
||||
Modal::new(Id::unique("Modal C")).show(ui.ctx(), |ui| {
|
||||
ui.set_width(70.0);
|
||||
ui.heading("Saving…");
|
||||
|
||||
|
||||
@@ -152,14 +152,14 @@ impl crate::View for PopupsDemo {
|
||||
})
|
||||
.inner;
|
||||
|
||||
self.apply_options(Popup::menu(&response).id(Id::new("menu")))
|
||||
self.apply_options(Popup::menu(&response).id(Id::unique("menu")))
|
||||
.show(|ui| self.nested_menus(ui));
|
||||
|
||||
self.apply_options(Popup::context_menu(&response).id(Id::new("context_menu")))
|
||||
self.apply_options(Popup::context_menu(&response).id(Id::unique("context_menu")))
|
||||
.show(|ui| self.nested_menus(ui));
|
||||
|
||||
if self.popup_open {
|
||||
self.apply_options(Popup::from_response(&response).id(Id::new("popup")))
|
||||
self.apply_options(Popup::from_response(&response).id(Id::unique("popup")))
|
||||
.show(|ui| {
|
||||
ui.label("Popup contents");
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ impl crate::View for TextEditDemo {
|
||||
ui.selectable_value(valign, egui::Align::BOTTOM, "Bottom");
|
||||
});
|
||||
|
||||
let clear_id = egui::Id::new("clear_button");
|
||||
let clear_id = egui::IdSalt::new("clear_button");
|
||||
let clear_size = egui::Vec2::splat(ui.spacing().interact_size.y);
|
||||
|
||||
let output = egui::TextEdit::multiline(text)
|
||||
|
||||
@@ -69,7 +69,7 @@ impl crate::Demo for WindowOptions {
|
||||
|
||||
use crate::View as _;
|
||||
let mut window = egui::Window::new(title)
|
||||
.id(egui::Id::new("demo_window_options")) // required since we change the title
|
||||
.id(egui::Id::unique("demo_window_options")) // required since we change the title
|
||||
.resizable(resizable)
|
||||
.constrain_to(ui.available_rect_before_wrap())
|
||||
.constrain(constrain)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use egui::{Id, Pos2, Rect, Response, Sense, Ui, UiBuilder, emath::GuiRounding as _};
|
||||
use egui::{IdSalt, Pos2, Rect, Response, Sense, Ui, UiBuilder, emath::GuiRounding as _};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum CellSize {
|
||||
@@ -117,7 +117,7 @@ impl<'l> StripLayout<'l> {
|
||||
flags: StripLayoutFlags,
|
||||
width: CellSize,
|
||||
height: CellSize,
|
||||
child_ui_id_salt: Id,
|
||||
child_ui_id_salt: IdSalt,
|
||||
add_cell_contents: impl FnOnce(&mut Ui),
|
||||
) -> (Rect, Response) {
|
||||
let max_rect = self.cell_rect(&width, &height);
|
||||
@@ -201,7 +201,7 @@ impl<'l> StripLayout<'l> {
|
||||
&mut self,
|
||||
flags: StripLayoutFlags,
|
||||
max_rect: Rect,
|
||||
child_ui_id_salt: egui::Id,
|
||||
child_ui_id_salt: IdSalt,
|
||||
add_cell_contents: impl FnOnce(&mut Ui),
|
||||
) -> Ui {
|
||||
let mut ui_builder = UiBuilder::new()
|
||||
|
||||
@@ -94,7 +94,7 @@ impl ImageLoader for GifLoader {
|
||||
let result = AnimatedImage::load_gif(&bytes).map(Arc::new);
|
||||
if let Ok(v) = &result {
|
||||
ctx.data_mut(|data| {
|
||||
*data.get_temp_mut_or_default(Id::new(image_uri)) =
|
||||
*data.get_temp_mut_or_default(Id::unique(image_uri)) =
|
||||
v.frame_durations.clone();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ impl ImageLoader for WebPLoader {
|
||||
|
||||
if let Ok(WebP::Animated(animated_image)) = &result {
|
||||
ctx.data_mut(|data| {
|
||||
*data.get_temp_mut_or_default(Id::new(image_uri)) =
|
||||
*data.get_temp_mut_or_default(Id::unique(image_uri)) =
|
||||
animated_image.frame_durations.clone();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ impl Strip<'_, '_> {
|
||||
flags,
|
||||
width,
|
||||
height,
|
||||
egui::Id::new(self.size_index),
|
||||
egui::IdSalt::new(self.size_index),
|
||||
add_contents,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -285,9 +285,9 @@ impl CodeTheme {
|
||||
#![expect(clippy::needless_return)]
|
||||
|
||||
let (id, default) = if style.visuals.dark_mode {
|
||||
(egui::Id::new("dark"), Self::dark as fn(f32) -> Self)
|
||||
(egui::Id::unique("dark"), Self::dark as fn(f32) -> Self)
|
||||
} else {
|
||||
(egui::Id::new("light"), Self::light as fn(f32) -> Self)
|
||||
(egui::Id::unique("light"), Self::light as fn(f32) -> Self)
|
||||
};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
@@ -312,9 +312,9 @@ impl CodeTheme {
|
||||
/// There is one dark and one light theme stored at any one time.
|
||||
pub fn store_in_memory(self, ctx: &egui::Context) {
|
||||
let id = if ctx.global_style().visuals.dark_mode {
|
||||
egui::Id::new("dark")
|
||||
egui::Id::unique("dark")
|
||||
} else {
|
||||
egui::Id::new("light")
|
||||
egui::Id::unique("light")
|
||||
};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
|
||||
@@ -1307,7 +1307,7 @@ impl TableRow<'_, '_> {
|
||||
flags,
|
||||
width,
|
||||
height,
|
||||
egui::Id::new((self.row_index, col_index)),
|
||||
egui::IdSalt::new((self.row_index, col_index)),
|
||||
add_cell_contents,
|
||||
);
|
||||
|
||||
|
||||
@@ -15,6 +15,15 @@ pub(crate) struct AppKindEframe<State> {
|
||||
pub frame: eframe::Frame,
|
||||
}
|
||||
|
||||
/// What [`AppKind::run_ui`] produces for the `Ui` kinds.
|
||||
pub(crate) struct UiRunOutput {
|
||||
/// The response of the scope wrapping the ui closure.
|
||||
pub response: egui::Response,
|
||||
|
||||
/// The [`egui::Ui::id`] of the `Ui` passed to the ui closure.
|
||||
pub ui_id: egui::Id,
|
||||
}
|
||||
|
||||
pub(crate) enum AppKind<'a, State> {
|
||||
Ui(AppKindUi<'a>),
|
||||
UiState(AppKindUiState<'a, State>),
|
||||
@@ -32,7 +41,7 @@ impl<State> AppKind<'_, State> {
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut State,
|
||||
sizing_pass: bool,
|
||||
) -> Option<egui::Response> {
|
||||
) -> Option<UiRunOutput> {
|
||||
match self {
|
||||
#[cfg(feature = "eframe")]
|
||||
AppKind::Eframe(AppKindEframe { get_app, frame, .. }) => {
|
||||
@@ -45,30 +54,32 @@ impl<State> AppKind<'_, State> {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_ui(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut State,
|
||||
sizing_pass: bool,
|
||||
) -> egui::Response {
|
||||
fn run_ui(&mut self, ui: &mut egui::Ui, state: &mut State, sizing_pass: bool) -> UiRunOutput {
|
||||
let mut builder = egui::UiBuilder::new();
|
||||
if sizing_pass {
|
||||
builder.sizing_pass = true;
|
||||
}
|
||||
ui.scope_builder(builder, |ui| {
|
||||
let egui::InnerResponse {
|
||||
inner: ui_id,
|
||||
response,
|
||||
} = ui.scope_builder(builder, |ui| {
|
||||
Frame::central_panel(ui.style())
|
||||
// Only set outer margin, so we show no frame for tests with only free-floating windows/popups:
|
||||
.outer_margin(8.0)
|
||||
.inner_margin(0.0)
|
||||
.show(ui, |ui| match self {
|
||||
AppKind::Ui(f) => f(ui),
|
||||
AppKind::UiState(f) => f(ui, state),
|
||||
#[cfg(feature = "eframe")]
|
||||
AppKind::Eframe(_) => unreachable!(
|
||||
"run_ui should only be called with AppKind::Ui or AppKind::UiState"
|
||||
),
|
||||
});
|
||||
})
|
||||
.response
|
||||
.show(ui, |ui| {
|
||||
match self {
|
||||
AppKind::Ui(f) => f(ui),
|
||||
AppKind::UiState(f) => f(ui, state),
|
||||
#[cfg(feature = "eframe")]
|
||||
AppKind::Eframe(_) => unreachable!(
|
||||
"run_ui should only be called with AppKind::Ui or AppKind::UiState"
|
||||
),
|
||||
}
|
||||
ui.id()
|
||||
})
|
||||
.inner
|
||||
});
|
||||
UiRunOutput { response, ui_id }
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,10 @@ use egui::{
|
||||
};
|
||||
use kittest::Queryable;
|
||||
|
||||
use crate::{app_kind::AppKind, config::config};
|
||||
use crate::{
|
||||
app_kind::{AppKind, UiRunOutput},
|
||||
config::config,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExceededMaxStepsError {
|
||||
@@ -96,7 +99,7 @@ pub struct Harness<'a, State = ()> {
|
||||
kittest: kittest::State,
|
||||
output: egui::FullOutput,
|
||||
app: AppKind<'a, State>,
|
||||
response: Option<egui::Response>,
|
||||
ui_output: Option<UiRunOutput>,
|
||||
state: State,
|
||||
renderer: Box<dyn TestRenderer>,
|
||||
|
||||
@@ -176,12 +179,12 @@ impl<'a, State> Harness<'a, State> {
|
||||
let viewport = input.viewports.get_mut(&ViewportId::ROOT).unwrap();
|
||||
viewport.native_pixels_per_point = Some(pixels_per_point);
|
||||
|
||||
let mut response = None;
|
||||
let mut ui_output = None;
|
||||
|
||||
// We need to run egui for a single frame so that the AccessKit state can be initialized
|
||||
// and users can immediately start querying for widgets.
|
||||
let mut output = ctx.run_ui(input.clone(), |ui| {
|
||||
response = app.run(ui, &mut state, false);
|
||||
ui_output = app.run(ui, &mut state, false);
|
||||
});
|
||||
|
||||
renderer.handle_delta(&mut output.textures_delta);
|
||||
@@ -198,7 +201,7 @@ impl<'a, State> Harness<'a, State> {
|
||||
.expect("AccessKit was disabled"),
|
||||
),
|
||||
output,
|
||||
response,
|
||||
ui_output,
|
||||
state,
|
||||
renderer,
|
||||
|
||||
@@ -304,7 +307,7 @@ impl<'a, State> Harness<'a, State> {
|
||||
self.input.predicted_dt = self.step_dt;
|
||||
|
||||
let mut output = self.ctx.run_ui(self.input.take(), |ui| {
|
||||
self.response = self.app.run(ui, &mut self.state, sizing_pass);
|
||||
self.ui_output = self.app.run(ui, &mut self.state, sizing_pass);
|
||||
});
|
||||
self.kittest.update(
|
||||
output
|
||||
@@ -328,7 +331,7 @@ impl<'a, State> Harness<'a, State> {
|
||||
/// Calculate the rect that includes all popups and tooltips.
|
||||
fn compute_total_rect_with_popups(&self) -> Option<Rect> {
|
||||
// Start with the standard response rect
|
||||
let mut used = self.response.as_ref()?.rect;
|
||||
let mut used = self.ui_output.as_ref()?.response.rect;
|
||||
|
||||
// Add all visible areas from other orders (popups, tooltips, etc.)
|
||||
self.ctx.memory(|mem| {
|
||||
@@ -528,6 +531,22 @@ impl<'a, State> Harness<'a, State> {
|
||||
}
|
||||
|
||||
/// Access the state.
|
||||
/// The [`egui::Ui::id`] of the [`egui::Ui`] passed to the ui closure.
|
||||
///
|
||||
/// Use this to compute the [`egui::Id`] of things shown directly in that ui,
|
||||
/// e.g. `harness.ui_id().with("my_panel")`.
|
||||
///
|
||||
/// # Panics
|
||||
/// If the harness was built from an eframe app rather than a ui closure.
|
||||
pub fn ui_id(&self) -> egui::Id {
|
||||
match &self.ui_output {
|
||||
Some(ui_output) => ui_output.ui_id,
|
||||
None => {
|
||||
panic!("Harness::ui_id is only available for harnesses built with a ui closure")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> &State {
|
||||
&self.state
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ pub struct Keypad {
|
||||
impl Keypad {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
id: egui::Id::new("keypad"),
|
||||
id: egui::Id::unique("keypad"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ fn title_bar_ui(ui: &mut egui::Ui, title_bar_rect: eframe::epaint::Rect, title:
|
||||
|
||||
let title_bar_response = ui.interact(
|
||||
title_bar_rect,
|
||||
Id::new("title_bar"),
|
||||
Id::unique("title_bar"),
|
||||
Sense::click_and_drag(),
|
||||
);
|
||||
|
||||
|
||||
@@ -101,8 +101,10 @@ fn preview_files_being_dropped(ctx: &egui::Context) {
|
||||
text
|
||||
});
|
||||
|
||||
let painter =
|
||||
ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target")));
|
||||
let painter = ctx.layer_painter(LayerId::new(
|
||||
Order::Foreground,
|
||||
Id::unique("file_drop_target"),
|
||||
));
|
||||
|
||||
let content_rect = ctx.content_rect();
|
||||
painter.rect_filled(content_rect, 0.0, Color32::from_black_alpha(192));
|
||||
|
||||
@@ -572,7 +572,7 @@ fn run_logic_should_not_disturb_ui_state() {
|
||||
const FOCUSED_BUTTON: &str = "Click me";
|
||||
|
||||
let child_viewport = egui::ViewportId::from_hash_of("My child viewport");
|
||||
let area_id = egui::Id::new("My area");
|
||||
let area_id = egui::Id::unique("My area");
|
||||
let area_layer = egui::LayerId::new(egui::Order::Middle, area_id);
|
||||
|
||||
let mut harness = Harness::builder()
|
||||
|
||||
@@ -15,7 +15,7 @@ fn interact_radius() -> f32 {
|
||||
}
|
||||
|
||||
fn widget_id() -> Id {
|
||||
Id::new("click_and_drag")
|
||||
Id::unique("click_and_drag")
|
||||
}
|
||||
|
||||
/// A harness with one click-and-drag widget of the given size at the top-left.
|
||||
@@ -36,7 +36,7 @@ fn harness_with_widget(size: Vec2, with_background: bool) -> Harness<'static, ()
|
||||
// Allocated first, so it ends up _behind_ the widget under test.
|
||||
ui.interact(
|
||||
ui.max_rect(),
|
||||
Id::new("background"),
|
||||
Id::unique("background"),
|
||||
Sense::click_and_drag(),
|
||||
);
|
||||
}
|
||||
@@ -191,7 +191,7 @@ fn click_inside_a_widget_still_clicks() {
|
||||
/// otherwise the row starts dragging the moment the user touches the button.
|
||||
#[test]
|
||||
fn press_on_a_button_inside_a_draggable_row_stays_undecided() {
|
||||
let button_id = Id::new("button");
|
||||
let button_id = Id::unique("button");
|
||||
let button_size = Vec2::new(50.0, 20.0);
|
||||
|
||||
let mut harness = Harness::builder()
|
||||
|
||||
@@ -26,6 +26,12 @@ struct State {
|
||||
panel_width: Option<f32>,
|
||||
}
|
||||
|
||||
/// Load the persisted [`egui::PanelState`] of the panel with the given `id_salt`,
|
||||
/// shown directly in the harness ui.
|
||||
fn load_panel_state<S>(harness: &Harness<'_, S>, id_salt: &str) -> Option<egui::PanelState> {
|
||||
egui::PanelState::load(&harness.ctx, harness.ui_id().with(id_salt))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_to_close_animated_inside() {
|
||||
let mut results = SnapshotResults::new();
|
||||
@@ -57,7 +63,7 @@ fn drag_to_close_animated_inside() {
|
||||
|
||||
// Query the actual resize edge from PanelState (avoids assumptions about
|
||||
// Frame margins and the harness's ui padding).
|
||||
let panel_state = egui::PanelState::load(&harness.ctx, egui::Id::new("test_left_panel"))
|
||||
let panel_state = load_panel_state(&harness, "test_left_panel")
|
||||
.expect("PanelState should be persisted after the first frame");
|
||||
let resize_x = panel_state.outer_rect.right();
|
||||
let resize_y = panel_state.outer_rect.center().y;
|
||||
@@ -131,7 +137,7 @@ fn collapse_by_drag(harness: &mut Harness<'_, State>) -> Pos2 {
|
||||
|
||||
// Query the actual resize edge from PanelState (avoids assumptions about
|
||||
// Frame margins and the harness's ui padding).
|
||||
let panel_state = egui::PanelState::load(&harness.ctx, egui::Id::new("test_left_panel"))
|
||||
let panel_state = load_panel_state(harness, "test_left_panel")
|
||||
.expect("PanelState should be persisted after the first frame");
|
||||
let fixed_edge = Pos2::new(
|
||||
panel_state.outer_rect.left(),
|
||||
@@ -284,7 +290,7 @@ fn drag_to_close_and_reopen_animated_between() {
|
||||
|
||||
// Drag-to-close: grab the top edge of the expanded bottom panel and drag
|
||||
// it down past the panel's minimum height to collapse.
|
||||
let expanded_state = egui::PanelState::load(&harness.ctx, egui::Id::new("between_expanded"))
|
||||
let expanded_state = load_panel_state(&harness, "between_expanded")
|
||||
.expect("expanded PanelState should be persisted");
|
||||
let expanded_resize_y = expanded_state.outer_rect.top();
|
||||
let drag_x = expanded_state.outer_rect.center().x;
|
||||
@@ -305,7 +311,7 @@ fn drag_to_close_and_reopen_animated_between() {
|
||||
|
||||
// Drag-to-expand: grab the top edge of the (now visible) collapsed panel
|
||||
// and drag it upward past the collapsed panel's exact_size cap.
|
||||
let collapsed_state = egui::PanelState::load(&harness.ctx, egui::Id::new("between_collapsed"))
|
||||
let collapsed_state = load_panel_state(&harness, "between_collapsed")
|
||||
.expect("collapsed PanelState should be persisted");
|
||||
let collapsed_resize_y = collapsed_state.outer_rect.top();
|
||||
|
||||
@@ -404,7 +410,7 @@ fn drag_to_close_switched_animates_while_held() {
|
||||
|
||||
let mut harness = switched_bottom_panel_harness(true);
|
||||
|
||||
let expanded = egui::PanelState::load(&harness.ctx, egui::Id::new("switched_expanded"))
|
||||
let expanded = load_panel_state(&harness, "switched_expanded")
|
||||
.expect("PanelState should be persisted after the first frame");
|
||||
let (x, bottom) = (expanded.outer_rect.center().x, expanded.outer_rect.bottom());
|
||||
let collapsed_top = bottom - collapsed_size;
|
||||
@@ -454,7 +460,7 @@ fn drag_to_close_switched_animates_while_held() {
|
||||
fn drag_to_open_switched_animates_while_held() {
|
||||
let mut harness = switched_bottom_panel_harness(false);
|
||||
|
||||
let collapsed = egui::PanelState::load(&harness.ctx, egui::Id::new("switched_collapsed"))
|
||||
let collapsed = load_panel_state(&harness, "switched_collapsed")
|
||||
.expect("PanelState should be persisted after the first frame");
|
||||
let (x, collapsed_top, bottom) = (
|
||||
collapsed.outer_rect.center().x,
|
||||
|
||||
@@ -73,7 +73,7 @@ fn build_harness(show_separator_line: bool) -> Harness<'static> {
|
||||
}
|
||||
|
||||
fn hover_resize_handle(harness: &mut Harness<'_>) {
|
||||
let outer = egui::PanelState::load(&harness.ctx, egui::Id::new(PANEL_ID))
|
||||
let outer = egui::PanelState::load(&harness.ctx, harness.ui_id().with(PANEL_ID))
|
||||
.expect("PanelState should be persisted after the first frame")
|
||||
.outer_rect;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ fn build(state: State) -> Harness<'static, State> {
|
||||
.build_ui_state(
|
||||
move |ui, state: &mut State| {
|
||||
Window::new("test_win")
|
||||
.id(Id::new("test_win"))
|
||||
.id(Id::unique("test_win"))
|
||||
.drag_area(state.drag_area)
|
||||
.movable(state.movable)
|
||||
.default_pos([100.0, 80.0])
|
||||
@@ -40,7 +40,7 @@ fn build(state: State) -> Harness<'static, State> {
|
||||
}
|
||||
|
||||
fn window_rect(harness: &Harness<'_, State>) -> egui::Rect {
|
||||
egui::AreaState::load(&harness.ctx, Id::new("test_win"))
|
||||
egui::AreaState::load(&harness.ctx, Id::unique("test_win"))
|
||||
.expect("window area should be persisted after the first frame")
|
||||
.rect()
|
||||
}
|
||||
|
||||
@@ -334,7 +334,7 @@ fn drag_and_drop_test(ui: &mut egui::Ui) {
|
||||
assert!(col < COLS, "The coll should be less than: {COLS}");
|
||||
|
||||
let value: String = value.into();
|
||||
let id = Id::new(format!("%{}% {}", self.counter, value));
|
||||
let id = Id::unique(format!("%{}% {}", self.counter, value));
|
||||
self.data.insert(id, value);
|
||||
let viewport_data = self.containers_data.entry(container).or_insert_with(|| {
|
||||
let mut res = Vec::new();
|
||||
|
||||
Reference in new issue
Block a user