mirror of
https://github.com/storytold/egui.git
synced 2026-11-25 20:11:49 +01:00
Build ComboBox from atoms, and take impl IntoAtoms (#8618)
* Closes https://github.com/emilk/egui/issues/7903 * Part of https://github.com/emilk/egui/issues/7264 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a1c276fc98
commit
b4ebd0f910
6 files changed
+418
-150
No files matched your search
@@ -1,4 +1,4 @@
|
||||
use crate::{Atom, AtomKind, Image, WidgetText};
|
||||
use crate::{Atom, AtomKind, IdSalt, Image, TextureId, WidgetText};
|
||||
use core::ops::{Deref, DerefMut};
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -73,6 +73,64 @@ impl<'a> Atoms<'a> {
|
||||
string
|
||||
}
|
||||
|
||||
/// An [`IdSalt`] based on the contents of the atoms.
|
||||
///
|
||||
/// Useful for widgets that derive their id from their label, like [`crate::ComboBox::from_label`].
|
||||
///
|
||||
/// This hashes the text of text atoms, the source of image atoms,
|
||||
/// and the [`Atom::id`] of any atom that has one.
|
||||
/// Other atom contents (e.g. closures) are ignored.
|
||||
pub fn salt(&self) -> IdSalt {
|
||||
#[derive(Debug, Hash)]
|
||||
enum SaltPart<'s> {
|
||||
Text(&'s str),
|
||||
ImageUri(Option<&'s str>),
|
||||
ImageTexture(TextureId),
|
||||
Other,
|
||||
}
|
||||
|
||||
fn salt_part<'s>(atom: &'s Atom<'_>) -> (SaltPart<'s>, Option<IdSalt>) {
|
||||
let part = match &atom.kind {
|
||||
AtomKind::Text(text) => SaltPart::Text(text.text()),
|
||||
AtomKind::Image(image) => {
|
||||
if let Some(texture_id) = image.texture_id() {
|
||||
SaltPart::ImageTexture(texture_id)
|
||||
} else {
|
||||
SaltPart::ImageUri(image.uri())
|
||||
}
|
||||
}
|
||||
AtomKind::Empty
|
||||
| AtomKind::Closure(_)
|
||||
| AtomKind::Paint(_)
|
||||
| AtomKind::Widget(_)
|
||||
| AtomKind::Container(_) => SaltPart::Other,
|
||||
};
|
||||
(part, atom.id)
|
||||
}
|
||||
|
||||
/// Hashes the atoms without collecting them into a temporary `Vec`.
|
||||
struct AtomsSalt<'s, 'a>(&'s [Atom<'a>]);
|
||||
|
||||
impl core::hash::Hash for AtomsSalt<'_, '_> {
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
state.write_usize(self.0.len());
|
||||
for atom in self.0 {
|
||||
salt_part(atom).hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for AtomsSalt<'_, '_> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_list()
|
||||
.entries(self.0.iter().map(salt_part))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
IdSalt::new(AtomsSalt(&self.0))
|
||||
}
|
||||
|
||||
/// Do any of the atoms have shrink set to `true`?
|
||||
pub fn any_shrink(&self) -> bool {
|
||||
self.iter().any(|a| a.shrink)
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
use core::cell::RefCell;
|
||||
|
||||
use epaint::Shape;
|
||||
|
||||
use crate::{
|
||||
Align2, AsIdSalt, Context, Id, IdSalt, InnerResponse, NumExt as _, Painter, Popup,
|
||||
PopupCloseBehavior, Rect, Response, Role, ScrollArea, Sense, TextStyle, TextWrapMode, Ui,
|
||||
UiBuilder, Vec2, WidgetInfo, WidgetText, epaint,
|
||||
Align2, AsIdSalt, Atom, AtomExt as _, Atoms, Context, Id, IdSalt, InnerResponse, IntoAtoms,
|
||||
NumExt as _, Painter, Popup, PopupCloseBehavior, Rect, Response, Role, ScrollArea, Sense,
|
||||
TextStyle, TextWrapMode, Ui, Vec2, WidgetAtom, WidgetInfo,
|
||||
class::{ClassName, Classes, HasClasses},
|
||||
epaint,
|
||||
style::{StyleModifier, WidgetVisuals},
|
||||
vec2,
|
||||
widget_style::ButtonStyle,
|
||||
};
|
||||
|
||||
#[expect(unused_imports)] // Documentation
|
||||
@@ -37,24 +42,31 @@ pub type IconPainter = Box<dyn FnOnce(&Ui, Rect, &WidgetVisuals, bool)>;
|
||||
/// # });
|
||||
/// ```
|
||||
#[must_use = "You should call .show*"]
|
||||
pub struct ComboBox {
|
||||
pub struct ComboBox<'a> {
|
||||
id_salt: IdSalt,
|
||||
label: Option<WidgetText>,
|
||||
selected_text: WidgetText,
|
||||
label: Option<Atoms<'a>>,
|
||||
selected_text: Atoms<'a>,
|
||||
width: Option<f32>,
|
||||
height: Option<f32>,
|
||||
icon: Option<IconPainter>,
|
||||
wrap_mode: Option<TextWrapMode>,
|
||||
close_behavior: Option<PopupCloseBehavior>,
|
||||
popup_style: StyleModifier,
|
||||
classes: Classes,
|
||||
}
|
||||
|
||||
impl ComboBox {
|
||||
impl<'a> ComboBox<'a> {
|
||||
/// Present on the button of every [`ComboBox`].
|
||||
pub const CLASS: ClassName = ClassName::from_static("egui::combo_box");
|
||||
|
||||
/// Present on the button of a [`ComboBox`] while its popup is open.
|
||||
pub const CLASS_OPEN: ClassName = ClassName::from_static("egui::combo_box::open");
|
||||
|
||||
/// Create new [`ComboBox`] with id and label
|
||||
pub fn new(id_salt: impl AsIdSalt, label: impl Into<WidgetText>) -> Self {
|
||||
pub fn new(id_salt: impl AsIdSalt, label: impl IntoAtoms<'a>) -> Self {
|
||||
Self {
|
||||
id_salt: IdSalt::new(id_salt),
|
||||
label: Some(label.into()),
|
||||
label: Some(label.into_atoms()),
|
||||
selected_text: Default::default(),
|
||||
width: None,
|
||||
height: None,
|
||||
@@ -62,14 +74,17 @@ impl ComboBox {
|
||||
wrap_mode: None,
|
||||
close_behavior: None,
|
||||
popup_style: StyleModifier::default(),
|
||||
classes: Classes::default().with_class(Self::CLASS),
|
||||
}
|
||||
}
|
||||
|
||||
/// Label shown next to the combo box
|
||||
pub fn from_label(label: impl Into<WidgetText>) -> Self {
|
||||
let label = label.into();
|
||||
/// Label shown next to the combo box.
|
||||
///
|
||||
/// The contents of the label is used as the id salt (see [`Atoms::salt`]).
|
||||
pub fn from_label(label: impl IntoAtoms<'a>) -> Self {
|
||||
let label = label.into_atoms();
|
||||
Self {
|
||||
id_salt: IdSalt::new(label.text()),
|
||||
id_salt: label.salt(),
|
||||
label: Some(label),
|
||||
selected_text: Default::default(),
|
||||
width: None,
|
||||
@@ -78,6 +93,7 @@ impl ComboBox {
|
||||
wrap_mode: None,
|
||||
close_behavior: None,
|
||||
popup_style: StyleModifier::default(),
|
||||
classes: Classes::default().with_class(Self::CLASS),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +109,7 @@ impl ComboBox {
|
||||
wrap_mode: None,
|
||||
close_behavior: None,
|
||||
popup_style: StyleModifier::default(),
|
||||
classes: Classes::default().with_class(Self::CLASS),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,10 +131,23 @@ impl ComboBox {
|
||||
self
|
||||
}
|
||||
|
||||
/// What we show as the currently selected value
|
||||
/// What we show as the currently selected value.
|
||||
///
|
||||
/// This can be any [`IntoAtoms`], e.g. an image next to some text:
|
||||
///
|
||||
/// ```
|
||||
/// # egui::__run_test_ui(|ui| {
|
||||
/// let ferris = egui::include_image!("../../assets/ferris.png");
|
||||
/// egui::ComboBox::from_label("Crab")
|
||||
/// .selected_text((egui::Image::new(ferris.clone()).max_height(16.0), "Ferris"))
|
||||
/// .show_ui(ui, |ui| {
|
||||
/// let _ = ui.selectable_label(true, (egui::Image::new(ferris).max_height(16.0), "Ferris"));
|
||||
/// });
|
||||
/// # });
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn selected_text(mut self, selected_text: impl Into<WidgetText>) -> Self {
|
||||
self.selected_text = selected_text.into();
|
||||
pub fn selected_text(mut self, selected_text: impl IntoAtoms<'a>) -> Self {
|
||||
self.selected_text = selected_text.into_atoms();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -227,41 +257,24 @@ impl ComboBox {
|
||||
wrap_mode,
|
||||
close_behavior,
|
||||
popup_style,
|
||||
classes,
|
||||
} = 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(Role::ComboBox);
|
||||
info.enabled = ui.is_enabled();
|
||||
info.current_text_value = Some(selected_text.text().to_owned());
|
||||
info
|
||||
});
|
||||
if let Some(label) = label {
|
||||
let is_empty = label.is_empty();
|
||||
let label_response = ui.label(label);
|
||||
// An empty label names nothing, so leave the name to the caller
|
||||
// (e.g. `on_hover_text`).
|
||||
if !is_empty {
|
||||
ir.response = ir.response.labelled_by(label_response.id);
|
||||
}
|
||||
ir.response |= label_response;
|
||||
}
|
||||
ir
|
||||
})
|
||||
.inner
|
||||
combo_box_dyn(
|
||||
ui,
|
||||
button_id,
|
||||
label,
|
||||
selected_text,
|
||||
menu_contents,
|
||||
icon,
|
||||
wrap_mode,
|
||||
close_behavior,
|
||||
popup_style,
|
||||
classes,
|
||||
(width, height),
|
||||
)
|
||||
}
|
||||
|
||||
/// Show a list of items with the given selected index.
|
||||
@@ -282,7 +295,7 @@ impl ComboBox {
|
||||
/// );
|
||||
/// # });
|
||||
/// ```
|
||||
pub fn show_index<Text: Into<WidgetText>>(
|
||||
pub fn show_index<Text: IntoAtoms<'a>>(
|
||||
self,
|
||||
ui: &mut Ui,
|
||||
selected: &mut usize,
|
||||
@@ -321,16 +334,28 @@ impl ComboBox {
|
||||
}
|
||||
}
|
||||
|
||||
impl HasClasses for ComboBox<'_> {
|
||||
fn classes(&self) -> &Classes {
|
||||
&self.classes
|
||||
}
|
||||
|
||||
fn classes_mut(&mut self) -> &mut Classes {
|
||||
&mut self.classes
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn combo_box_dyn<'c, R>(
|
||||
ui: &mut Ui,
|
||||
button_id: Id,
|
||||
selected_text: WidgetText,
|
||||
label: Option<Atoms<'_>>,
|
||||
selected_text: Atoms<'_>,
|
||||
menu_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
|
||||
icon: Option<IconPainter>,
|
||||
wrap_mode: Option<TextWrapMode>,
|
||||
close_behavior: Option<PopupCloseBehavior>,
|
||||
popup_style: StyleModifier,
|
||||
mut classes: Classes,
|
||||
(width, height): (Option<f32>, Option<f32>),
|
||||
) -> InnerResponse<Option<R>> {
|
||||
let popup_id = ComboBox::widget_to_popup_id(button_id);
|
||||
@@ -341,58 +366,79 @@ fn combo_box_dyn<'c, R>(
|
||||
|
||||
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);
|
||||
classes.add_class_if(ComboBox::CLASS_OPEN, is_popup_open);
|
||||
|
||||
// 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;
|
||||
// Built from the same atoms and style as a `Button`, so the two line up when put side by side.
|
||||
let ButtonStyle {
|
||||
atom_layout: atom_layout_style,
|
||||
} = ui.widget_style(button_id, &classes);
|
||||
|
||||
// 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
|
||||
// The visuals passed to the icon painter.
|
||||
// Like `ui.widget_style`, use the interaction state from the start of this pass:
|
||||
let visuals = if is_popup_open {
|
||||
ui.visuals().widgets.open
|
||||
} else if let Some(response) = ui.ctx().read_response(button_id) {
|
||||
*ui.style().interact(&response)
|
||||
} else {
|
||||
ui.visuals().widgets.inactive
|
||||
};
|
||||
|
||||
// The combo box will always have at least this width.
|
||||
let min_width = width.unwrap_or_else(|| ui.spacing().combo_width);
|
||||
let min_size = Vec2::new(min_width, 0.0).at_least(atom_layout_style.min_size);
|
||||
|
||||
let icon = RefCell::new(icon);
|
||||
let icon_atom = Atom::paint(Vec2::splat(ui.spacing().icon_width), move |ui, args| {
|
||||
let rect = args.rect.expand(visuals.expansion);
|
||||
if let Some(icon) = icon.borrow_mut().take() {
|
||||
icon(ui, rect, &visuals, is_popup_open);
|
||||
} 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());
|
||||
paint_default_icon(ui.painter(), rect, &visuals);
|
||||
}
|
||||
})
|
||||
// Grow (instead of a separate `Atom::grow()`, which would add an extra gap),
|
||||
// and stick to the right edge:
|
||||
.atom_grow(true)
|
||||
.atom_align(Align2::RIGHT_CENTER);
|
||||
|
||||
let accessible_text = selected_text.text().map(String::from).unwrap_or_default();
|
||||
let button = atom_layout_style
|
||||
.apply(
|
||||
WidgetAtom::new((selected_text, icon_atom))
|
||||
.id(button_id)
|
||||
.sense(Sense::click())
|
||||
.fallback_font(TextStyle::Button)
|
||||
.wrap_mode(wrap_mode),
|
||||
)
|
||||
.min_size(min_size);
|
||||
|
||||
let (button_response, label_response) = match label {
|
||||
Some(label) => {
|
||||
// The label is just another atom, next to the button.
|
||||
let label_text = label.text().map(String::from).unwrap_or_default();
|
||||
let outer_response = WidgetAtom::new((Atom::widget(button), label))
|
||||
.gap(ui.spacing().item_spacing.x)
|
||||
.show(ui)
|
||||
.response;
|
||||
outer_response
|
||||
.widget_info(|| WidgetInfo::labeled(Role::Label, ui.is_enabled(), &label_text));
|
||||
let button_response = ui
|
||||
.ctx()
|
||||
.read_response(button_id)
|
||||
.unwrap_or_else(|| outer_response.clone());
|
||||
(
|
||||
button_response,
|
||||
Some((outer_response, !label_text.is_empty())),
|
||||
)
|
||||
}
|
||||
None => (button.show(ui).response, None),
|
||||
};
|
||||
|
||||
button_response.widget_info(|| {
|
||||
let mut info = WidgetInfo::new(Role::ComboBox);
|
||||
info.enabled = ui.is_enabled();
|
||||
info.current_text_value = Some(accessible_text.clone());
|
||||
info
|
||||
});
|
||||
|
||||
let height = height.unwrap_or_else(|| ui.spacing().combo_height);
|
||||
@@ -428,58 +474,18 @@ fn combo_box_dyn<'c, R>(
|
||||
|
||||
InnerResponse {
|
||||
inner,
|
||||
response: button_response,
|
||||
response: match label_response {
|
||||
// An empty label names nothing, so leave the name to the caller
|
||||
// (e.g. `on_hover_text`).
|
||||
Some((label_response, true)) => {
|
||||
button_response.labelled_by(label_response.id) | label_response
|
||||
}
|
||||
Some((label_response, false)) => button_response | label_response,
|
||||
None => 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(),
|
||||
|
||||
@@ -303,6 +303,10 @@ impl Frame {
|
||||
/// This handles `expansion` by subtracting it from the outer margin and adding it to the
|
||||
/// inner margin. It also corrects for `stroke`, by subtracting the stroke width from `inner_margin`.
|
||||
///
|
||||
/// Any stroke already on the frame is replaced, and its width is given back to the `inner_margin`,
|
||||
/// so calling this again to change the stroke is fine.
|
||||
/// The `expansion` is not tracked though, so it is applied on top of any earlier expansion.
|
||||
///
|
||||
/// Use this when stroke or expansion might change on hover, and you don't want it to cause
|
||||
/// layout shifts.
|
||||
#[inline]
|
||||
@@ -312,7 +316,8 @@ impl Frame {
|
||||
expansion: f32,
|
||||
) -> Self {
|
||||
self.outer_margin = self.outer_margin - Margin::from(expansion);
|
||||
self.inner_margin = self.inner_margin + Margin::from(expansion - stroke.width);
|
||||
self.inner_margin =
|
||||
self.inner_margin + Margin::from(expansion + self.stroke.width - stroke.width);
|
||||
self.stroke = stroke;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use emath::{Align2, Vec2};
|
||||
use epaint::{Color32, Margin};
|
||||
|
||||
use crate::{
|
||||
Button, Context, Frame, TextEdit, TextStyle,
|
||||
Button, ComboBox, Context, Frame, TextEdit, TextStyle,
|
||||
class::HasClasses as _,
|
||||
theme::StyleProvider,
|
||||
widget_style::{
|
||||
@@ -38,7 +38,11 @@ impl StyleProvider<ButtonStyle> for DefaultStyle {
|
||||
..
|
||||
} = modifiers;
|
||||
let spacing = &style.spacing;
|
||||
let mut widget_visuals = *style.visuals.widgets.state(*state);
|
||||
let mut widget_visuals = if classes.has_class(&ComboBox::CLASS_OPEN) {
|
||||
style.visuals.widgets.open
|
||||
} else {
|
||||
*style.visuals.widgets.state(*state)
|
||||
};
|
||||
|
||||
if classes.has_class(&Button::CLASS_SELECTED) {
|
||||
let visuals = &style.visuals;
|
||||
|
||||
@@ -303,6 +303,15 @@ impl<'a> Image<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the texture, if this image is from [`ImageSource::Texture`].
|
||||
#[inline]
|
||||
pub(crate) fn texture_id(&self) -> Option<epaint::TextureId> {
|
||||
match &self.source {
|
||||
ImageSource::Texture(texture) => Some(texture.id),
|
||||
ImageSource::Uri(_) | ImageSource::Bytes { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the URI of the image.
|
||||
///
|
||||
/// For animated images, returns the URI without the frame number.
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use egui::{Button, ComboBox, DragValue};
|
||||
use egui_kittest::Harness;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Heights {
|
||||
inner: f32,
|
||||
outer: f32,
|
||||
}
|
||||
|
||||
fn measure_height(ui: &mut egui::Ui, f: impl FnOnce(&mut egui::Ui) -> f32) -> Heights {
|
||||
ui.style_mut().spacing.interact_size.y = 0.0;
|
||||
let mut inner = 0.0;
|
||||
let outer = ui
|
||||
.horizontal(|ui| {
|
||||
inner = f(ui);
|
||||
})
|
||||
.response
|
||||
.rect
|
||||
.height();
|
||||
Heights { inner, outer }
|
||||
}
|
||||
|
||||
/// With the default style, widgets that commonly sit next to each other in a row
|
||||
/// should all be the same height, so they line up nicely.
|
||||
#[test]
|
||||
fn default_widget_heights_should_match() {
|
||||
let mut harness = Harness::builder()
|
||||
.with_accessibility_check(false)
|
||||
.build_ui_state(
|
||||
|ui, heights: &mut BTreeMap<&'static str, Heights>| {
|
||||
ui.vertical(|ui| {
|
||||
ui.style_mut().spacing.interact_size.y = 0.0;
|
||||
|
||||
heights.insert(
|
||||
"drag_value",
|
||||
measure_height(ui, |ui| {
|
||||
let mut value = 42.0;
|
||||
ui.add(DragValue::new(&mut value)).rect.height()
|
||||
}),
|
||||
);
|
||||
|
||||
heights.insert(
|
||||
"button",
|
||||
measure_height(ui, |ui| ui.add(Button::new("Button")).rect.height()),
|
||||
);
|
||||
|
||||
heights.insert(
|
||||
"combo_box",
|
||||
measure_height(ui, |ui| {
|
||||
ComboBox::from_id_salt("combo")
|
||||
.selected_text("Combo")
|
||||
.show_ui(ui, |_ui| {})
|
||||
.response
|
||||
.rect
|
||||
.height()
|
||||
}),
|
||||
);
|
||||
});
|
||||
},
|
||||
BTreeMap::new(),
|
||||
);
|
||||
harness.run();
|
||||
|
||||
let heights = harness.state();
|
||||
assert_eq!(heights.len(), 3);
|
||||
let interact_height = egui::Style::default().spacing.interact_size.y;
|
||||
|
||||
let (first_name, first) = heights.first_key_value().unwrap();
|
||||
for (name, h) in heights {
|
||||
assert_eq!(
|
||||
h.inner, first.inner,
|
||||
"{name} and {first_name} have different heights: {heights:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
h.inner, h.outer,
|
||||
"{name} does not fill the row it is in: {h:?}"
|
||||
);
|
||||
assert!(
|
||||
h.inner <= interact_height,
|
||||
"{name} is taller ({}) than the default interact_size.y ({interact_height}), \
|
||||
so it will overflow its row and look misaligned",
|
||||
h.inner
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ComboBox`] and a [`DragValue`] placed next to each other should occupy exactly the
|
||||
/// same vertical range, regardless of [`egui::style::Spacing::interact_size`].
|
||||
#[test]
|
||||
fn combo_box_and_drag_value_should_line_up_for_any_interact_size() {
|
||||
for interact_height in [0.0, 10.0, 18.0, 21.0, 22.0, 30.0] {
|
||||
#[derive(Clone, Copy)]
|
||||
struct Rects {
|
||||
drag_value: egui::Rect,
|
||||
combo_box: egui::Rect,
|
||||
labelled_combo_box: egui::Rect,
|
||||
}
|
||||
|
||||
let mut harness = Harness::builder()
|
||||
.with_accessibility_check(false)
|
||||
.build_ui_state(
|
||||
|ui, rects: &mut Rects| {
|
||||
ui.spacing_mut().interact_size.y = interact_height;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Label");
|
||||
let mut value = 42.0;
|
||||
rects.drag_value = ui.add(DragValue::new(&mut value)).rect;
|
||||
rects.combo_box = ComboBox::from_id_salt("combo")
|
||||
.selected_text("Combo")
|
||||
.show_ui(ui, |_ui| {})
|
||||
.response
|
||||
.rect;
|
||||
rects.labelled_combo_box = ComboBox::new("labelled_combo", "Label")
|
||||
.selected_text("Combo")
|
||||
.show_ui(ui, |_ui| {})
|
||||
.response
|
||||
.rect;
|
||||
});
|
||||
},
|
||||
Rects {
|
||||
drag_value: egui::Rect::NOTHING,
|
||||
combo_box: egui::Rect::NOTHING,
|
||||
labelled_combo_box: egui::Rect::NOTHING,
|
||||
},
|
||||
);
|
||||
harness.run();
|
||||
|
||||
let Rects {
|
||||
drag_value,
|
||||
combo_box,
|
||||
labelled_combo_box,
|
||||
} = *harness.state();
|
||||
assert_eq!(
|
||||
drag_value.y_range(),
|
||||
combo_box.y_range(),
|
||||
"interact_size.y = {interact_height}: DragValue {drag_value:?} vs ComboBox {combo_box:?}"
|
||||
);
|
||||
// The response of a labelled combo box also covers the label:
|
||||
assert_eq!(
|
||||
drag_value.y_range(),
|
||||
labelled_combo_box.y_range(),
|
||||
"interact_size.y = {interact_height}: DragValue {drag_value:?} vs labelled ComboBox {labelled_combo_box:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hovering an open [`ComboBox`] must not change its size.
|
||||
#[test]
|
||||
fn open_combo_box_should_not_change_size_when_hovered() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
|
||||
let mut harness = Harness::builder()
|
||||
.with_accessibility_check(false)
|
||||
.build_ui_state(
|
||||
|ui, rect: &mut egui::Rect| {
|
||||
*rect = ComboBox::from_id_salt("combo")
|
||||
.selected_text("Combo")
|
||||
.show_ui(ui, |ui| {
|
||||
ui.label("Item");
|
||||
})
|
||||
.response
|
||||
.rect;
|
||||
},
|
||||
egui::Rect::NOTHING,
|
||||
);
|
||||
harness.run();
|
||||
let closed = *harness.state();
|
||||
|
||||
harness.get_by_role(Role::ComboBox).click();
|
||||
harness.run();
|
||||
let open_hovered = *harness.state();
|
||||
|
||||
// Move the pointer away, but keep the popup open:
|
||||
harness.event(egui::Event::PointerMoved(egui::pos2(400.0, 400.0)));
|
||||
harness.run();
|
||||
let open_not_hovered = *harness.state();
|
||||
|
||||
assert_eq!(closed, open_hovered, "size changed when opened");
|
||||
assert_eq!(
|
||||
open_hovered, open_not_hovered,
|
||||
"size of the open combo box changed with hover"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user