mirror of
https://github.com/storytold/egui.git
synced 2026-11-28 09:19:12 +01:00
Merge craft/rtl-chrome
This commit is contained in:
commit
28e76ca480
14 files changed
+1150
-114
No files matched your search
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
AsIdSalt, Context, Id, IdSalt, InnerResponse, NumExt as _, Rect, Response, Role, Sense,
|
||||
TextStyle, TextWrapMode, Ui, UiBuilder, UiKind, UiStackInfo, WidgetInfo, WidgetText, emath,
|
||||
epaint, pos2, remap, remap_clamp, vec2,
|
||||
Align, AsIdSalt, Context, Id, IdSalt, InnerResponse, Layout, NumExt as _, Rect, Response, Role,
|
||||
Sense, TextStyle, TextWrapMode, Ui, UiBuilder, UiKind, UiStackInfo, WidgetInfo, WidgetText,
|
||||
emath, epaint, pos2, remap, remap_clamp, vec2,
|
||||
};
|
||||
use emath::GuiRounding as _;
|
||||
use epaint::StrokeKind;
|
||||
@@ -131,13 +131,23 @@ impl CollapsingState {
|
||||
ui: &mut Ui,
|
||||
add_header: impl FnOnce(&mut Ui) -> HeaderRet,
|
||||
) -> HeaderResponse<'_, HeaderRet> {
|
||||
let header_response = ui.horizontal(|ui| {
|
||||
let add_contents = |ui: &mut Ui| {
|
||||
let prev_item_spacing = ui.spacing_mut().item_spacing;
|
||||
ui.spacing_mut().item_spacing.x = 0.0; // the toggler button uses the full indent width
|
||||
let collapser = self.show_default_button_indented(ui);
|
||||
ui.spacing_mut().item_spacing = prev_item_spacing;
|
||||
(collapser, add_header(ui))
|
||||
});
|
||||
};
|
||||
let header_response = if ui.style().right_to_left {
|
||||
// The toggle button comes first, on the right.
|
||||
let size = vec2(
|
||||
ui.available_size_before_wrap().x,
|
||||
ui.spacing().interact_size.y,
|
||||
);
|
||||
ui.allocate_ui_with_layout(size, Layout::right_to_left(Align::Center), add_contents)
|
||||
} else {
|
||||
ui.horizontal(add_contents)
|
||||
};
|
||||
HeaderResponse {
|
||||
state: self,
|
||||
ui,
|
||||
@@ -163,7 +173,11 @@ impl CollapsingState {
|
||||
self.show_body_unindented(ui, |ui| {
|
||||
ui.indent(id, |ui| {
|
||||
// make as wide as the header:
|
||||
ui.expand_to_include_x(header_response.rect.right());
|
||||
ui.expand_to_include_x(if ui.style().right_to_left {
|
||||
header_response.rect.left()
|
||||
} else {
|
||||
header_response.rect.right()
|
||||
});
|
||||
add_body(ui)
|
||||
})
|
||||
.inner
|
||||
@@ -342,7 +356,13 @@ pub fn paint_default_icon(ui: &mut Ui, openness: f32, response: &Response) {
|
||||
let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height()) * 0.75);
|
||||
let rect = rect.expand(visuals.expansion);
|
||||
use core::f32::consts::TAU;
|
||||
let rotation = remap(openness, 0.0..=1.0, -TAU * 0.25..=0.0);
|
||||
// Collapsed, the triangle points in the reading direction.
|
||||
let collapsed_rotation = if ui.style().right_to_left {
|
||||
TAU * 0.25
|
||||
} else {
|
||||
-TAU * 0.25
|
||||
};
|
||||
let rotation = remap(openness, 0.0..=1.0, collapsed_rotation..=0.0);
|
||||
|
||||
ui.painter().add(epaint::Shape::rotated_triangle(
|
||||
rect,
|
||||
@@ -569,8 +589,15 @@ impl CollapsingHeader {
|
||||
let (_, rect) = ui.allocate_space(desired_size);
|
||||
|
||||
let mut header_response = ui.interact(rect, id, Sense::click());
|
||||
// The icon sits at the start side, followed by the text.
|
||||
let right_to_left = ui.style().right_to_left;
|
||||
let text_x = if right_to_left {
|
||||
rect.right() - ui.spacing().indent - galley.size().x
|
||||
} else {
|
||||
text_pos.x
|
||||
};
|
||||
let text_pos = pos2(
|
||||
text_pos.x,
|
||||
text_x,
|
||||
header_response.rect.center().y - galley.size().y / 2.0,
|
||||
);
|
||||
|
||||
@@ -623,10 +650,12 @@ impl CollapsingHeader {
|
||||
|
||||
{
|
||||
let (mut icon_rect, _) = ui.spacing().icon_rectangles(header_response.rect);
|
||||
icon_rect.set_center(pos2(
|
||||
header_response.rect.left() + ui.spacing().indent / 2.0,
|
||||
header_response.rect.center().y,
|
||||
));
|
||||
let icon_x = if right_to_left {
|
||||
header_response.rect.right() - ui.spacing().indent / 2.0
|
||||
} else {
|
||||
header_response.rect.left() + ui.spacing().indent / 2.0
|
||||
};
|
||||
icon_rect.set_center(pos2(icon_x, header_response.rect.center().y));
|
||||
let icon_response = header_response.clone().with_new_rect(icon_rect);
|
||||
if let Some(icon) = icon {
|
||||
icon(ui, openness, &icon_response);
|
||||
@@ -734,3 +763,44 @@ impl<R> CollapsingResponse<R> {
|
||||
self.openness >= 1.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{CollapsingHeader, Context, RawInput, epaint::Shape};
|
||||
|
||||
/// Which way the triangle of a collapsed header points: `1.0` right, `-1.0` left.
|
||||
fn collapsed_triangle_direction(right_to_left: bool) -> f32 {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| style.right_to_left = right_to_left);
|
||||
let mut output = ctx.run_ui(RawInput::default(), |ui| {
|
||||
CollapsingHeader::new("Header").show(ui, |ui| ui.label("Body"));
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let triangles: Vec<_> = output
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
Shape::Path(path) if path.points.len() == 3 => Some(path.points.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(triangles.len(), 1, "Expected one triangle: {triangles:?}");
|
||||
let points = &triangles[0];
|
||||
let mean_x = points.iter().map(|p| p.x).sum::<f32>() / 3.0;
|
||||
let tip = points
|
||||
.iter()
|
||||
.max_by(|a, b| (a.x - mean_x).abs().total_cmp(&(b.x - mean_x).abs()))
|
||||
.expect("three points");
|
||||
(tip.x - mean_x).signum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_triangle_points_right() {
|
||||
assert_eq!(collapsed_triangle_direction(false), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_triangle_points_left_right_to_left() {
|
||||
assert_eq!(collapsed_triangle_direction(true), -1.0);
|
||||
}
|
||||
}
|
||||
@@ -397,9 +397,14 @@ fn combo_box_dyn<'c, R>(
|
||||
}
|
||||
})
|
||||
// Grow (instead of a separate `Atom::grow()`, which would add an extra gap),
|
||||
// and stick to the right edge:
|
||||
// and stick to the end edge:
|
||||
.atom_grow(true)
|
||||
.atom_align(Align2::RIGHT_CENTER);
|
||||
.atom_align(if ui.style().right_to_left {
|
||||
Align2::LEFT_CENTER
|
||||
} else {
|
||||
Align2::RIGHT_CENTER
|
||||
});
|
||||
let direction = ui.style().chrome_direction();
|
||||
|
||||
let accessible_text = selected_text.text().map(String::from).unwrap_or_default();
|
||||
let button = atom_layout_style
|
||||
@@ -408,7 +413,8 @@ fn combo_box_dyn<'c, R>(
|
||||
.id(button_id)
|
||||
.sense(Sense::click())
|
||||
.fallback_font(TextStyle::Button)
|
||||
.wrap_mode(wrap_mode),
|
||||
.wrap_mode(wrap_mode)
|
||||
.direction(direction),
|
||||
)
|
||||
.min_size(min_size);
|
||||
|
||||
@@ -418,6 +424,7 @@ fn combo_box_dyn<'c, R>(
|
||||
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)
|
||||
.direction(direction)
|
||||
.show(ui)
|
||||
.response;
|
||||
outer_response
|
||||
|
||||
@@ -271,8 +271,8 @@ impl MenuState {
|
||||
.and_then(|index| entries.get(index))
|
||||
.or_else(|| entries.last())
|
||||
.copied(),
|
||||
FocusDirection::Left => anchor_widget,
|
||||
// SubMenu handles Right on its own button before we get here.
|
||||
// SubMenu handles the key towards its submenu on its own button before we get here.
|
||||
direction if direction == submenu_close_direction(ui) => anchor_widget,
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
@@ -477,13 +477,27 @@ pub struct SubMenuButton<'a> {
|
||||
}
|
||||
|
||||
impl<'a> SubMenuButton<'a> {
|
||||
/// The submenu arrow triangle shape.
|
||||
/// The submenu arrow triangle shape, pointing right.
|
||||
pub fn arrow_shape(rect: Rect, color: impl Into<Color32>) -> Shape {
|
||||
Self::arrow_shape_towards_submenu(rect, color, false)
|
||||
}
|
||||
|
||||
/// The submenu arrow triangle shape, pointing left when `right_to_left`.
|
||||
fn arrow_shape_towards_submenu(
|
||||
rect: Rect,
|
||||
color: impl Into<Color32>,
|
||||
right_to_left: bool,
|
||||
) -> Shape {
|
||||
let rect = Rect::from_center_size(
|
||||
rect.center(),
|
||||
vec2(rect.width() * 0.55, rect.height() * 0.35),
|
||||
);
|
||||
Shape::rotated_triangle(rect, -core::f32::consts::TAU / 4.0, color)
|
||||
let rotation = if right_to_left {
|
||||
core::f32::consts::TAU / 4.0
|
||||
} else {
|
||||
-core::f32::consts::TAU / 4.0
|
||||
};
|
||||
Shape::rotated_triangle(rect, rotation, color)
|
||||
}
|
||||
|
||||
/// An [`Atom`] painting the [`Self::arrow_shape`].
|
||||
@@ -498,7 +512,11 @@ impl<'a> SubMenuButton<'a> {
|
||||
sized: SizedAtomKind::Paint {
|
||||
paint: Arc::new(move |ui: &Ui, args: AtomPaintArgs| {
|
||||
let color = color.unwrap_or(args.fallback_text_color);
|
||||
ui.painter().add(Self::arrow_shape(args.rect, color));
|
||||
ui.painter().add(Self::arrow_shape_towards_submenu(
|
||||
args.rect,
|
||||
color,
|
||||
ui.style().right_to_left,
|
||||
));
|
||||
}),
|
||||
size,
|
||||
},
|
||||
@@ -546,7 +564,8 @@ impl<'a> SubMenuButton<'a> {
|
||||
if open {
|
||||
ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open;
|
||||
}
|
||||
let response = self.button.ui(ui);
|
||||
// Mirrored in right-to-left, so the arrow sits on the side the submenu opens on.
|
||||
let response = self.button.direction(ui.style().chrome_direction()).ui(ui);
|
||||
ui.style_mut().visuals.widgets.inactive = inactive;
|
||||
|
||||
let popup_response = self.sub_menu.show(ui, &response, content);
|
||||
@@ -555,6 +574,17 @@ impl<'a> SubMenuButton<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The arrow key that moves focus from a submenu back to its button.
|
||||
///
|
||||
/// The opposite key opens the submenu.
|
||||
fn submenu_close_direction(ui: &Ui) -> FocusDirection {
|
||||
if ui.style().right_to_left {
|
||||
FocusDirection::Right
|
||||
} else {
|
||||
FocusDirection::Left
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a submenu in a menu.
|
||||
///
|
||||
/// Useful if you want to make custom menu buttons.
|
||||
@@ -649,12 +679,16 @@ impl SubMenu {
|
||||
let clicked_by_pointer = button_response.clicked_by(PointerButton::Primary);
|
||||
let clicked_by_keyboard_or_access = clicked && !clicked_by_pointer;
|
||||
let focused = button_response.enabled() && button_response.has_focus();
|
||||
let arrow_right =
|
||||
focused && ui.memory(|mem| mem.focus_direction() == FocusDirection::Right);
|
||||
if arrow_right {
|
||||
let open_direction = if ui.style().right_to_left {
|
||||
FocusDirection::Left
|
||||
} else {
|
||||
FocusDirection::Right
|
||||
};
|
||||
let arrow_open = focused && ui.memory(|mem| mem.focus_direction() == open_direction);
|
||||
if arrow_open {
|
||||
ui.memory_mut(|mem| mem.move_focus(FocusDirection::None));
|
||||
}
|
||||
let enter = arrow_right || (focused && clicked_by_keyboard_or_access);
|
||||
let enter = arrow_open || (focused && clicked_by_keyboard_or_access);
|
||||
// Only arrow keys open on focus, so Tab can still move past the submenu.
|
||||
let focus_open = focused && parent_arrow_focus == Some(button_response.id);
|
||||
let keyboard_open = enter || focus_open || (!was_open && clicked_by_keyboard_or_access);
|
||||
@@ -669,7 +703,7 @@ impl SubMenu {
|
||||
} else if !was_open || pointer_changed {
|
||||
state.ignore_hover = false;
|
||||
}
|
||||
// Left inside the submenu moves focus back to our button.
|
||||
// Left (Right in right-to-left) inside the submenu moves focus back to our button.
|
||||
let left_submenu = state.arrow_focus == Some(button_response.id);
|
||||
if left_submenu {
|
||||
state.arrow_focus = None;
|
||||
@@ -704,11 +738,17 @@ impl SubMenu {
|
||||
let expand = Vec2::new(0.0, measurement_frame.total_margin().sum().y * 0.5);
|
||||
response.interact_rect = response.interact_rect.expand2(expand);
|
||||
|
||||
let align = if ui.style().right_to_left {
|
||||
RectAlign::LEFT_START
|
||||
} else {
|
||||
RectAlign::RIGHT_START
|
||||
};
|
||||
|
||||
let popup_response = Popup::from_response(&response)
|
||||
.id(id)
|
||||
.kind(PopupKind::Menu)
|
||||
.open(is_open)
|
||||
.align(RectAlign::RIGHT_START)
|
||||
.align(align)
|
||||
.layout(Layout::top_down_justified(Align::Min))
|
||||
.gap(gap)
|
||||
.style(menu_config.style.clone())
|
||||
@@ -802,3 +842,183 @@ impl SubMenu {
|
||||
popup_response
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core::cell::Cell;
|
||||
|
||||
use crate::{
|
||||
Context, Event, Id, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, UiBuilder,
|
||||
epaint::{ClippedShape, Shape},
|
||||
pos2, vec2,
|
||||
};
|
||||
|
||||
/// A menu in the middle of the screen with one submenu.
|
||||
struct MenuTest {
|
||||
ctx: Context,
|
||||
menu_button: Cell<Rect>,
|
||||
submenu_button: Cell<(Id, Rect)>,
|
||||
submenu: Cell<Option<Rect>>,
|
||||
}
|
||||
|
||||
impl MenuTest {
|
||||
fn new(right_to_left: bool) -> Self {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| style.right_to_left = right_to_left);
|
||||
let test = Self {
|
||||
ctx,
|
||||
menu_button: Cell::new(Rect::NOTHING),
|
||||
submenu_button: Cell::new((Id::NULL, Rect::NOTHING)),
|
||||
submenu: Cell::new(None),
|
||||
};
|
||||
test.run(vec![]);
|
||||
let pos = test.menu_button.get().center();
|
||||
test.run(vec![Event::PointerMoved(pos), click(pos, true)]);
|
||||
test.run(vec![click(pos, false)]);
|
||||
test.run(vec![]);
|
||||
test
|
||||
}
|
||||
|
||||
fn run(&self, events: Vec<Event>) -> Vec<ClippedShape> {
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
self.submenu.set(None);
|
||||
let mut output = self.ctx.run_ui(input, |ui| {
|
||||
let max_rect = Rect::from_min_size(pos2(350.0, 100.0), vec2(100.0, 100.0));
|
||||
ui.scope_builder(UiBuilder::new().max_rect(max_rect), |ui| {
|
||||
let response = ui.menu_button("Menu", |ui| {
|
||||
let response = ui.menu_button("Submenu", |ui| {
|
||||
let _ = ui.button("Item");
|
||||
self.submenu.set(Some(ui.min_rect()));
|
||||
});
|
||||
self.submenu_button
|
||||
.set((response.response.id, response.response.rect));
|
||||
});
|
||||
self.menu_button.set(response.response.rect);
|
||||
});
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
output.shapes
|
||||
}
|
||||
|
||||
/// Which way the submenu arrow points (`1.0` right, `-1.0` left),
|
||||
/// and whether it is in the left half of the submenu button.
|
||||
fn submenu_arrow(&self) -> (f32, bool) {
|
||||
let button = self.submenu_button.get().1;
|
||||
let triangles: Vec<_> = self
|
||||
.run(vec![])
|
||||
.into_iter()
|
||||
.filter_map(|clipped| match clipped.shape {
|
||||
Shape::Path(path)
|
||||
if path.points.len() == 3
|
||||
&& path.points.iter().all(|p| button.contains(*p)) =>
|
||||
{
|
||||
Some(path.points)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(triangles.len(), 1, "Expected one arrow: {triangles:?}");
|
||||
let points = &triangles[0];
|
||||
let mean_x = points.iter().map(|p| p.x).sum::<f32>() / 3.0;
|
||||
let tip = points
|
||||
.iter()
|
||||
.max_by(|a, b| (a.x - mean_x).abs().total_cmp(&(b.x - mean_x).abs()))
|
||||
.expect("three points");
|
||||
((tip.x - mean_x).signum(), mean_x < button.center().x)
|
||||
}
|
||||
|
||||
fn press(&self, key: Key) {
|
||||
let event = |pressed| Event::Key {
|
||||
key,
|
||||
physical_key: None,
|
||||
pressed,
|
||||
repeat: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
};
|
||||
self.run(vec![event(true), event(false)]);
|
||||
for _ in 0..3 {
|
||||
self.run(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
fn submenu_button_is_focused(&self) -> bool {
|
||||
self.ctx.memory(|mem| mem.focused()) == Some(self.submenu_button.get().0)
|
||||
}
|
||||
|
||||
/// Hovers the submenu button, and returns its rect and the submenu rect.
|
||||
fn open_submenu_by_hover(&self) -> (Rect, Rect) {
|
||||
self.run(vec![Event::PointerMoved(
|
||||
self.submenu_button.get().1.center(),
|
||||
)]);
|
||||
for _ in 0..3 {
|
||||
self.run(vec![]);
|
||||
}
|
||||
let submenu = self.submenu.get().expect("The submenu didn't open");
|
||||
(self.submenu_button.get().1, submenu)
|
||||
}
|
||||
|
||||
/// Opens the submenu with `open` from its focused button, then goes back with `back`.
|
||||
fn assert_submenu_keys(&self, open: Key, back: Key) {
|
||||
self.press(Key::ArrowDown);
|
||||
assert!(self.submenu_button_is_focused());
|
||||
self.press(open);
|
||||
assert!(
|
||||
self.submenu.get().is_some(),
|
||||
"{open:?} didn't open the submenu"
|
||||
);
|
||||
assert!(!self.submenu_button_is_focused());
|
||||
|
||||
self.press(back);
|
||||
assert!(self.submenu_button_is_focused(), "{back:?} didn't go back");
|
||||
assert!(
|
||||
self.submenu.get().is_none(),
|
||||
"{back:?} didn't close the submenu"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn click(pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Modifiers::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_opens_to_the_right() {
|
||||
let (button, submenu) = MenuTest::new(false).open_submenu_by_hover();
|
||||
assert!(submenu.left() > button.right(), "{button:?} {submenu:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_opens_to_the_left_right_to_left() {
|
||||
let (button, submenu) = MenuTest::new(true).open_submenu_by_hover();
|
||||
assert!(submenu.right() < button.left(), "{button:?} {submenu:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_arrow_at_the_right_pointing_right() {
|
||||
assert_eq!(MenuTest::new(false).submenu_arrow(), (1.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_arrow_at_the_left_pointing_left_right_to_left() {
|
||||
assert_eq!(MenuTest::new(true).submenu_arrow(), (-1.0, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_keys() {
|
||||
MenuTest::new(false).assert_submenu_keys(Key::ArrowRight, Key::ArrowLeft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submenu_keys_right_to_left() {
|
||||
MenuTest::new(true).assert_submenu_keys(Key::ArrowLeft, Key::ArrowRight);
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,12 @@ pub struct Popup<'a> {
|
||||
impl<'a> Popup<'a> {
|
||||
/// Create a new popup
|
||||
pub fn new(id: Id, ctx: Context, anchor: impl Into<PopupAnchor>, layer_id: LayerId) -> Self {
|
||||
// Below the anchor, aligned to its start edge.
|
||||
let rect_align = if ctx.global_style().right_to_left {
|
||||
RectAlign::BOTTOM_END
|
||||
} else {
|
||||
RectAlign::BOTTOM_START
|
||||
};
|
||||
Self {
|
||||
id,
|
||||
ctx,
|
||||
@@ -201,7 +207,7 @@ impl<'a> Popup<'a> {
|
||||
info: None,
|
||||
kind: PopupKind::Popup,
|
||||
layer_id,
|
||||
rect_align: RectAlign::BOTTOM_START,
|
||||
rect_align,
|
||||
alternative_aligns: None,
|
||||
gap: 0.0,
|
||||
width: None,
|
||||
@@ -283,6 +289,9 @@ impl<'a> Popup<'a> {
|
||||
/// Set the [`RectAlign`] of the popup relative to the [`PopupAnchor`].
|
||||
/// This is the default position, and will be used if it fits.
|
||||
/// See [`Self::align_alternatives`] for more on this.
|
||||
///
|
||||
/// Default: [`RectAlign::BOTTOM_START`],
|
||||
/// or [`RectAlign::BOTTOM_END`] with [`crate::Style::right_to_left`].
|
||||
#[inline]
|
||||
pub fn align(mut self, position_align: RectAlign) -> Self {
|
||||
self.rect_align = position_align;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
Align2, AsIdSalt, Color32, Context, CursorIcon, Id, IdSalt, NumExt as _, Rect, Response, Sense,
|
||||
Shape, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, Vec2b, pos2, vec2,
|
||||
Align2, AsIdSalt, Color32, Context, CursorIcon, Id, IdSalt, NumExt as _, Pos2, Rect, Response,
|
||||
Sense, Shape, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, Vec2b, pos2, vec2,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -200,14 +200,38 @@ impl Resize {
|
||||
struct Prepared {
|
||||
id: Id,
|
||||
corner_id: Option<Id>,
|
||||
|
||||
/// The top-left corner, or the top-right one with `grip_on_left`.
|
||||
anchor: Pos2,
|
||||
|
||||
/// The resize grip is at the bottom-left ([`crate::Style::right_to_left`]).
|
||||
grip_on_left: bool,
|
||||
|
||||
state: State,
|
||||
content_ui: Ui,
|
||||
sizing_pass: bool,
|
||||
}
|
||||
|
||||
/// A rect of `size` with its top-left corner at `anchor`,
|
||||
/// or its top-right corner with `grip_on_left`.
|
||||
fn anchored_rect(anchor: Pos2, size: Vec2, grip_on_left: bool) -> Rect {
|
||||
if grip_on_left {
|
||||
Rect::from_min_size(pos2(anchor.x - size.x, anchor.y), size)
|
||||
} else {
|
||||
Rect::from_min_size(anchor, size)
|
||||
}
|
||||
}
|
||||
|
||||
impl Resize {
|
||||
fn begin(&self, ui: &mut Ui) -> Prepared {
|
||||
let position = ui.available_rect_before_wrap().min;
|
||||
// With the grip at the bottom-left, the right edge stays put while resizing.
|
||||
let grip_on_left = ui.style().right_to_left && self.resizable.any();
|
||||
let available = ui.available_rect_before_wrap();
|
||||
let anchor = if grip_on_left {
|
||||
available.right_top()
|
||||
} else {
|
||||
available.min
|
||||
};
|
||||
let id = self.id.unwrap_or_else(|| {
|
||||
let id_salt = self.id_salt.unwrap_or_else(|| IdSalt::new("resize"));
|
||||
ui.make_persistent_id(id_salt)
|
||||
@@ -248,7 +272,11 @@ impl Resize {
|
||||
&& let Some(pointer_pos) = corner_response.interact_pointer_pos()
|
||||
{
|
||||
// Respond to the interaction early to avoid frame delay.
|
||||
user_requested_size = Some(pointer_pos - position + 0.5 * corner_response.rect.size());
|
||||
let mut size = pointer_pos - anchor;
|
||||
if grip_on_left {
|
||||
size.x = -size.x;
|
||||
}
|
||||
user_requested_size = Some(size + 0.5 * corner_response.rect.size());
|
||||
}
|
||||
|
||||
let is_actively_resizing = user_requested_size.is_some();
|
||||
@@ -284,9 +312,13 @@ impl Resize {
|
||||
// user never sees the squished layout; the measured min then clamps drags.
|
||||
let inner_rect = if needs_sizing_pass {
|
||||
ui.ctx().request_discard("Resize sizing pass");
|
||||
Rect::from_min_size(position, Vec2::new(self.min_size.x, state.desired_size.y))
|
||||
anchored_rect(
|
||||
anchor,
|
||||
Vec2::new(self.min_size.x, state.desired_size.y),
|
||||
grip_on_left,
|
||||
)
|
||||
} else {
|
||||
Rect::from_min_size(position, state.desired_size)
|
||||
anchored_rect(anchor, state.desired_size, grip_on_left)
|
||||
};
|
||||
|
||||
let mut content_clip_rect = inner_rect;
|
||||
@@ -314,6 +346,8 @@ impl Resize {
|
||||
Prepared {
|
||||
id,
|
||||
corner_id,
|
||||
anchor,
|
||||
grip_on_left,
|
||||
state,
|
||||
content_ui,
|
||||
sizing_pass: needs_sizing_pass,
|
||||
@@ -331,6 +365,8 @@ impl Resize {
|
||||
let Prepared {
|
||||
id,
|
||||
corner_id,
|
||||
anchor,
|
||||
grip_on_left,
|
||||
mut state,
|
||||
content_ui,
|
||||
sizing_pass,
|
||||
@@ -362,17 +398,28 @@ impl Resize {
|
||||
size[d] = state.last_content_size[d];
|
||||
}
|
||||
}
|
||||
ui.advance_cursor_after_rect(Rect::from_min_size(content_ui.min_rect().min, size));
|
||||
// The content's top-left corner, or its top-right one when the grip is on the left.
|
||||
let anchor = if grip_on_left {
|
||||
pos2(anchor.x, content_ui.min_rect().top())
|
||||
} else {
|
||||
content_ui.min_rect().left_top()
|
||||
};
|
||||
let outer_rect = anchored_rect(anchor, size, grip_on_left);
|
||||
ui.advance_cursor_after_rect(outer_rect);
|
||||
|
||||
// ------------------------------
|
||||
|
||||
let corner_response = if let Some(corner_id) = corner_id {
|
||||
// We do the corner interaction last to place it on top of the content:
|
||||
let corner_size = Vec2::splat(ui.visuals().resize_corner_size);
|
||||
let corner_rect = Rect::from_min_size(
|
||||
content_ui.min_rect().left_top() + size - corner_size,
|
||||
corner_size,
|
||||
);
|
||||
let corner_rect = if grip_on_left {
|
||||
Rect::from_min_size(
|
||||
outer_rect.left_bottom() - vec2(0.0, corner_size.y),
|
||||
corner_size,
|
||||
)
|
||||
} else {
|
||||
Rect::from_min_size(outer_rect.right_bottom() - corner_size, corner_size)
|
||||
};
|
||||
Some(ui.interact(corner_rect, corner_id, Sense::drag()))
|
||||
} else {
|
||||
None
|
||||
@@ -381,7 +428,7 @@ impl Resize {
|
||||
// ------------------------------
|
||||
|
||||
if self.with_stroke && corner_response.is_some() {
|
||||
let rect = Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size);
|
||||
let rect = anchored_rect(anchor, state.desired_size, grip_on_left);
|
||||
let rect = rect.expand(2.0); // breathing room for content
|
||||
ui.painter().add(Shape::rect_stroke(
|
||||
rect,
|
||||
@@ -395,7 +442,11 @@ impl Resize {
|
||||
paint_resize_corner(ui, &corner_response);
|
||||
|
||||
if corner_response.hovered() || corner_response.dragged() {
|
||||
ui.set_cursor_icon(CursorIcon::ResizeNwSe);
|
||||
ui.set_cursor_icon(if grip_on_left {
|
||||
CursorIcon::ResizeNeSw
|
||||
} else {
|
||||
CursorIcon::ResizeNwSe
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,12 +455,12 @@ impl Resize {
|
||||
#[cfg(debug_assertions)]
|
||||
if ui.global_style().debug.show_resize {
|
||||
ui.debug_painter().debug_rect(
|
||||
Rect::from_min_size(content_ui.min_rect().left_top(), state.desired_size),
|
||||
anchored_rect(anchor, state.desired_size, grip_on_left),
|
||||
Color32::GREEN,
|
||||
"desired_size",
|
||||
);
|
||||
ui.debug_painter().debug_rect(
|
||||
Rect::from_min_size(content_ui.min_rect().left_top(), state.last_content_size),
|
||||
anchored_rect(anchor, state.last_content_size, grip_on_left),
|
||||
Color32::LIGHT_BLUE,
|
||||
"last_content_size",
|
||||
);
|
||||
@@ -420,9 +471,16 @@ impl Resize {
|
||||
use emath::GuiRounding as _;
|
||||
use epaint::Stroke;
|
||||
|
||||
/// Paints a resize grip in the bottom-right corner of `response.rect`,
|
||||
/// or the bottom-left one with [`crate::Style::right_to_left`].
|
||||
pub fn paint_resize_corner(ui: &Ui, response: &Response) {
|
||||
let stroke = ui.style().interact(response).fg_stroke;
|
||||
paint_resize_corner_with_style(ui, &response.rect, stroke.color, Align2::RIGHT_BOTTOM);
|
||||
let corner = if ui.style().right_to_left {
|
||||
Align2::LEFT_BOTTOM
|
||||
} else {
|
||||
Align2::RIGHT_BOTTOM
|
||||
};
|
||||
paint_resize_corner_with_style(ui, &response.rect, stroke.color, corner);
|
||||
}
|
||||
|
||||
pub fn paint_resize_corner_with_style(
|
||||
|
||||
@@ -10,7 +10,7 @@ use epaint::{Color32, Direction, Margin, Shape};
|
||||
use crate::{
|
||||
AsIdSalt, Context, CursorIcon, Id, IdSalt, MouseWheelSource, NumExt as _, Pos2, Rangef, Rect,
|
||||
Response, Role, Sense, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, Vec2b, WidgetInfo, emath,
|
||||
epaint, lerp, pass_state, pos2, remap, remap_clamp, style::KineticScrollStyle,
|
||||
epaint, lerp, pass_state, pos2, remap, remap_clamp, style::KineticScrollStyle, vec2,
|
||||
};
|
||||
|
||||
use super::scroll_physics::{AxisPhysics, WheelScroll, scroll_bounds};
|
||||
@@ -754,6 +754,9 @@ struct Prepared {
|
||||
scroll_bar_visibility: ScrollBarVisibility,
|
||||
scroll_bar_rect: Option<Rect>,
|
||||
|
||||
/// The vertical scroll bar sits on the left ([`crate::Style::right_to_left`]).
|
||||
vertical_bar_on_left: bool,
|
||||
|
||||
/// Where on the screen the content is (excludes scroll bars; includes `content_margin`).
|
||||
inner_rect: Rect,
|
||||
|
||||
@@ -859,7 +862,13 @@ impl ScrollArea {
|
||||
inner_size
|
||||
};
|
||||
|
||||
let inner_rect = Rect::from_min_size(available_outer.min, inner_size);
|
||||
let vertical_bar_on_left = ui.style().right_to_left;
|
||||
let bar_space_on_left = if vertical_bar_on_left {
|
||||
vec2(current_bar_use.x, 0.0)
|
||||
} else {
|
||||
Vec2::ZERO
|
||||
};
|
||||
let inner_rect = Rect::from_min_size(available_outer.min + bar_space_on_left, inner_size);
|
||||
|
||||
let mut content_max_size = inner_size;
|
||||
|
||||
@@ -899,8 +908,9 @@ impl ScrollArea {
|
||||
if direction_enabled[d] {
|
||||
content_clip_rect.min[d] = inner_rect.min[d];
|
||||
content_clip_rect.max[d] = inner_rect.max[d];
|
||||
} else {
|
||||
// Nice handling of forced resizing beyond the possible:
|
||||
} else if !(d == 0 && vertical_bar_on_left) {
|
||||
// Nice handling of forced resizing beyond the possible.
|
||||
// (A vertical bar on the left is never in the way of content that overflows to the right.)
|
||||
content_clip_rect.max[d] = ui.clip_rect().max[d] - current_bar_use[d];
|
||||
}
|
||||
}
|
||||
@@ -1042,6 +1052,7 @@ impl ScrollArea {
|
||||
current_bar_use,
|
||||
scroll_bar_visibility,
|
||||
scroll_bar_rect,
|
||||
vertical_bar_on_left,
|
||||
inner_rect,
|
||||
content_ui,
|
||||
viewport,
|
||||
@@ -1173,6 +1184,7 @@ impl Prepared {
|
||||
current_bar_use,
|
||||
scroll_bar_visibility,
|
||||
scroll_bar_rect,
|
||||
vertical_bar_on_left,
|
||||
content_ui,
|
||||
viewport: _,
|
||||
scroll_source,
|
||||
@@ -1299,7 +1311,12 @@ impl Prepared {
|
||||
Rect::from_min_size(inner_rect.min, inner_size)
|
||||
};
|
||||
|
||||
let outer_rect = Rect::from_min_size(inner_rect.min, inner_rect.size() + current_bar_use);
|
||||
let outer_min = if vertical_bar_on_left {
|
||||
inner_rect.min - vec2(current_bar_use.x, 0.0)
|
||||
} else {
|
||||
inner_rect.min
|
||||
};
|
||||
let outer_rect = Rect::from_min_size(outer_min, inner_rect.size() + current_bar_use);
|
||||
|
||||
let limit_rect = if ui.spacing().scroll.floating {
|
||||
outer_rect
|
||||
@@ -1423,23 +1440,33 @@ impl Prepared {
|
||||
let inner_margin = show_factor * scroll_style.bar_inner_margin;
|
||||
let outer_margin = show_factor * scroll_style.bar_outer_margin;
|
||||
|
||||
// bottom of a horizontal scroll (d==0).
|
||||
// right of a vertical scroll (d==1).
|
||||
let mut max_cross = outer_rect.max[1 - d] - outer_margin;
|
||||
|
||||
if ui.clip_rect().max[1 - d] - outer_margin < max_cross {
|
||||
// Move the scrollbar so it is visible. This is needed in some cases.
|
||||
// For instance:
|
||||
// * When we have a vertical-only scroll area in a top level panel,
|
||||
// and that panel is not wide enough for the contents.
|
||||
// * When one ScrollArea is nested inside another, and the outer
|
||||
// is scrolled so that the scroll-bars of the inner ScrollArea (us)
|
||||
// is outside the clip rectangle.
|
||||
max_cross = ui.clip_rect().max[1 - d] - outer_margin;
|
||||
}
|
||||
|
||||
let full_width = scroll_style.bar_width;
|
||||
|
||||
// The bar's cross-axis edge that faces away from the content:
|
||||
// bottom of a horizontal scroll (d==0),
|
||||
// right (or left, with `vertical_bar_on_left`) of a vertical scroll (d==1).
|
||||
let bar_on_min_side = d == 1 && vertical_bar_on_left;
|
||||
// Moving the edge so the bar stays inside the clip rectangle is needed in some cases.
|
||||
// For instance:
|
||||
// * When we have a vertical-only scroll area in a top level panel,
|
||||
// and that panel is not wide enough for the contents.
|
||||
// * When one ScrollArea is nested inside another, and the outer
|
||||
// is scrolled so that the scroll-bars of the inner ScrollArea (us)
|
||||
// is outside the clip rectangle.
|
||||
let outer_edge = if bar_on_min_side {
|
||||
outer_rect.min[1 - d].max(ui.clip_rect().min[1 - d]) + outer_margin
|
||||
} else {
|
||||
outer_rect.max[1 - d].min(ui.clip_rect().max[1 - d]) - outer_margin
|
||||
};
|
||||
// The cross range of a bar `width` wide at the outer edge.
|
||||
let at_outer_edge = |width: f32| {
|
||||
if bar_on_min_side {
|
||||
Rangef::new(outer_edge, outer_edge + width)
|
||||
} else {
|
||||
Rangef::new(outer_edge - width, outer_edge)
|
||||
}
|
||||
};
|
||||
|
||||
// The bounding rect of a fully visible bar.
|
||||
// When we hover this area, we should show the full bar.
|
||||
// The interaction rect must match where the scroll bar is drawn (outer_scroll_bar_rect),
|
||||
@@ -1447,15 +1474,9 @@ impl Prepared {
|
||||
// where no scrollbar is drawn is sensed as a scrollbar press, creating a dead zone
|
||||
// and snapping the offset to the minimum (see issue #8495).
|
||||
let max_bar_rect = if d == 0 {
|
||||
Rect::from_x_y_ranges(
|
||||
scroll_bar_rect.x_range(),
|
||||
Rangef::new(max_cross - full_width, max_cross),
|
||||
)
|
||||
Rect::from_x_y_ranges(scroll_bar_rect.x_range(), at_outer_edge(full_width))
|
||||
} else {
|
||||
Rect::from_x_y_ranges(
|
||||
Rangef::new(max_cross - full_width, max_cross),
|
||||
scroll_bar_rect.y_range(),
|
||||
)
|
||||
Rect::from_x_y_ranges(at_outer_edge(full_width), scroll_bar_rect.y_range())
|
||||
};
|
||||
|
||||
let sense = if scroll_source.scroll_bar && ui.is_enabled() {
|
||||
@@ -1487,11 +1508,11 @@ impl Prepared {
|
||||
is_hovering_bar_area_t,
|
||||
);
|
||||
|
||||
let min_cross = max_cross - width;
|
||||
Rangef::new(min_cross, max_cross)
|
||||
at_outer_edge(width)
|
||||
} else if bar_on_min_side {
|
||||
Rangef::new(outer_edge, inner_rect.min[1 - d] - inner_margin)
|
||||
} else {
|
||||
let min_cross = inner_rect.max[1 - d] + inner_margin;
|
||||
Rangef::new(min_cross, max_cross)
|
||||
Rangef::new(inner_rect.max[1 - d] + inner_margin, outer_edge)
|
||||
};
|
||||
|
||||
let outer_scroll_bar_rect = if d == 0 {
|
||||
@@ -1785,6 +1806,7 @@ fn paint_fade_areas_impl(ui: &Ui, inner_rect: Rect, content_size: Vec2, offset:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{RawInput, style::ScrollStyle};
|
||||
|
||||
#[test]
|
||||
fn clamped_offset() {
|
||||
@@ -1796,4 +1818,64 @@ mod tests {
|
||||
assert_eq!(state.clamped_offset(), Vec2::new(0.0, 100.0));
|
||||
assert_eq!(state.overscroll(), Vec2::new(-10.0, 50.0));
|
||||
}
|
||||
|
||||
/// Shows a vertical scroll area with too much content,
|
||||
/// and returns the rects of its viewport and its vertical scroll bar.
|
||||
fn vertical_scroll_bar(right_to_left: bool, scroll_style: ScrollStyle) -> (Rect, Rect) {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| {
|
||||
style.right_to_left = right_to_left;
|
||||
style.spacing.scroll = scroll_style;
|
||||
});
|
||||
let mut output = None;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0))),
|
||||
..Default::default()
|
||||
};
|
||||
for _ in 0..3 {
|
||||
ctx.run_ui(input.clone(), |ui| {
|
||||
output = Some(
|
||||
ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.max_height(200.0)
|
||||
.scroll_bar_visibility(ScrollBarVisibility::AlwaysVisible)
|
||||
.show(ui, |ui| {
|
||||
for _ in 0..50 {
|
||||
ui.label("Line");
|
||||
}
|
||||
}),
|
||||
);
|
||||
})
|
||||
.drop_without_applying_deltas();
|
||||
}
|
||||
let output = output.expect("The scroll area was not shown");
|
||||
let bar = ctx
|
||||
.read_response(output.id.with(1_usize))
|
||||
.expect("No vertical scroll bar")
|
||||
.rect;
|
||||
(output.inner_rect, bar)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_scroll_bar_on_the_right() {
|
||||
for scroll_style in [ScrollStyle::solid(), ScrollStyle::floating()] {
|
||||
let (inner, bar) = vertical_scroll_bar(false, scroll_style);
|
||||
assert!(bar.left() > inner.center().x, "{inner:?} {bar:?}");
|
||||
if !scroll_style.floating {
|
||||
assert!(bar.left() >= inner.right(), "{inner:?} {bar:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_scroll_bar_on_the_left_right_to_left() {
|
||||
for scroll_style in [ScrollStyle::solid(), ScrollStyle::floating()] {
|
||||
let (inner, bar) = vertical_scroll_bar(true, scroll_style);
|
||||
assert!(bar.right() < inner.center().x, "{inner:?} {bar:?}");
|
||||
if !scroll_style.floating {
|
||||
assert!(bar.right() <= inner.left(), "{inner:?} {bar:?}");
|
||||
assert!(bar.left() >= 0.0, "{inner:?} {bar:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -813,29 +813,52 @@ fn paint_resize_corner(
|
||||
) {
|
||||
let cr = window_frame.corner_radius;
|
||||
|
||||
let (corner, radius, corner_response) = if possible.resize_right && possible.resize_bottom {
|
||||
(Align2::RIGHT_BOTTOM, cr.se, i.right & i.bottom)
|
||||
} else if possible.resize_left && possible.resize_bottom {
|
||||
(Align2::LEFT_BOTTOM, cr.sw, i.left & i.bottom)
|
||||
} else if possible.resize_left && possible.resize_top {
|
||||
(Align2::LEFT_TOP, cr.nw, i.left & i.top)
|
||||
} else if possible.resize_right && possible.resize_top {
|
||||
(Align2::RIGHT_TOP, cr.ne, i.right & i.top)
|
||||
} else {
|
||||
// We're not in two directions, but it is still nice to tell the user
|
||||
// we're resizable by painting the resize corner in the expected place
|
||||
// (i.e. for windows only resizable in one direction):
|
||||
if possible.resize_right || possible.resize_bottom {
|
||||
(Align2::RIGHT_BOTTOM, cr.se, i.right & i.bottom)
|
||||
} else if possible.resize_left || possible.resize_bottom {
|
||||
(Align2::LEFT_BOTTOM, cr.sw, i.left & i.bottom)
|
||||
} else if possible.resize_left || possible.resize_top {
|
||||
(Align2::LEFT_TOP, cr.nw, i.left & i.top)
|
||||
} else if possible.resize_right || possible.resize_top {
|
||||
(Align2::RIGHT_TOP, cr.ne, i.right & i.top)
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// Corners in order of preference, with whether they can resize horizontally and vertically.
|
||||
let mut corners = [
|
||||
(
|
||||
Align2::RIGHT_BOTTOM,
|
||||
cr.se,
|
||||
i.right & i.bottom,
|
||||
possible.resize_right,
|
||||
possible.resize_bottom,
|
||||
),
|
||||
(
|
||||
Align2::LEFT_BOTTOM,
|
||||
cr.sw,
|
||||
i.left & i.bottom,
|
||||
possible.resize_left,
|
||||
possible.resize_bottom,
|
||||
),
|
||||
(
|
||||
Align2::LEFT_TOP,
|
||||
cr.nw,
|
||||
i.left & i.top,
|
||||
possible.resize_left,
|
||||
possible.resize_top,
|
||||
),
|
||||
(
|
||||
Align2::RIGHT_TOP,
|
||||
cr.ne,
|
||||
i.right & i.top,
|
||||
possible.resize_right,
|
||||
possible.resize_top,
|
||||
),
|
||||
];
|
||||
if ui.style().right_to_left {
|
||||
// The bottom corner at the end side comes first.
|
||||
corners.swap(0, 1);
|
||||
}
|
||||
|
||||
// If we can't resize in two directions, it is still nice to tell the user
|
||||
// we're resizable by painting the resize corner in the expected place
|
||||
// (i.e. for windows only resizable in one direction):
|
||||
let Some((corner, radius, corner_response, _, _)) = corners
|
||||
.iter()
|
||||
.find(|(_, _, _, x, y)| *x && *y)
|
||||
.or_else(|| corners.iter().find(|(_, _, _, x, y)| *x || *y))
|
||||
.copied()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Adjust the corner offset to accommodate for window rounding
|
||||
@@ -1341,8 +1364,21 @@ fn title_ui(
|
||||
|
||||
let expanded = collapsing.openness(ui.ctx()) > 0.0;
|
||||
|
||||
if collapsible {
|
||||
atoms.push_right(Atom::custom(collapse_atom_id, button_allocation_size));
|
||||
let right_to_left = ui.style().right_to_left;
|
||||
let (left_button, right_button) = if right_to_left {
|
||||
(
|
||||
open.is_some().then_some(close_atom_id),
|
||||
collapsible.then_some(collapse_atom_id),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
collapsible.then_some(collapse_atom_id),
|
||||
open.is_some().then_some(close_atom_id),
|
||||
)
|
||||
};
|
||||
|
||||
if let Some(left_button) = left_button {
|
||||
atoms.push_right(Atom::custom(left_button, button_allocation_size));
|
||||
}
|
||||
|
||||
atoms.push_right(Atom::grow());
|
||||
@@ -1359,8 +1395,8 @@ fn title_ui(
|
||||
|
||||
atoms.push_right(Atom::grow());
|
||||
|
||||
if open.is_some() {
|
||||
atoms.push_right(Atom::custom(close_atom_id, button_allocation_size));
|
||||
if let Some(right_button) = right_button {
|
||||
atoms.push_right(Atom::custom(right_button, button_allocation_size));
|
||||
}
|
||||
|
||||
let spacing = ui.spacing().item_spacing.x;
|
||||
@@ -1395,7 +1431,11 @@ fn title_ui(
|
||||
// Collapse triangle icon
|
||||
if collapsible && let Some(rect) = layout_response.rect(collapse_atom_id) {
|
||||
let rect = rect.shrink2(button_shrink);
|
||||
title_click_rect = title_click_rect.with_min_x(rect.max.x);
|
||||
title_click_rect = if right_to_left {
|
||||
title_click_rect.with_max_x(rect.min.x)
|
||||
} else {
|
||||
title_click_rect.with_min_x(rect.max.x)
|
||||
};
|
||||
let icon_response = child_ui.interact(
|
||||
rect,
|
||||
child_ui.auto_id_with("collapse_button"),
|
||||
@@ -1420,7 +1460,11 @@ fn title_ui(
|
||||
&& let Some(rect) = layout_response.rect(close_atom_id)
|
||||
{
|
||||
let rect = rect.shrink2(button_shrink);
|
||||
title_click_rect = title_click_rect.with_max_x(rect.min.x);
|
||||
title_click_rect = if right_to_left {
|
||||
title_click_rect.with_min_x(rect.max.x)
|
||||
} else {
|
||||
title_click_rect.with_max_x(rect.min.x)
|
||||
};
|
||||
if close_button(&mut child_ui, rect).clicked() {
|
||||
*open = false;
|
||||
}
|
||||
@@ -1629,3 +1673,93 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod title_bar_tests {
|
||||
use core::cell::Cell;
|
||||
|
||||
use crate::{
|
||||
Context, Event, Id, LayerId, Modifiers, Order, PointerButton, Pos2, RawInput, Rect, Vec2,
|
||||
Window, vec2,
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Outcome {
|
||||
Collapsed,
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Clicks the leftmost title-bar button of a window and reports what happened.
|
||||
fn click_leftmost_title_bar_button(right_to_left: bool) -> Outcome {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| style.right_to_left = right_to_left);
|
||||
let window_id = Id::unique("window");
|
||||
let open = Cell::new(true);
|
||||
let collapsed = Cell::new(false);
|
||||
let run = |events: Vec<Event>| {
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
ctx.run_ui(input, |ui| {
|
||||
let mut is_open = open.get();
|
||||
let response = Window::new("Window")
|
||||
.id(window_id)
|
||||
.open(&mut is_open)
|
||||
.show(ui.ctx(), |ui| ui.label("Hello"));
|
||||
open.set(is_open);
|
||||
collapsed.set(response.is_some_and(|response| response.inner.is_none()));
|
||||
})
|
||||
.drop_without_applying_deltas();
|
||||
};
|
||||
|
||||
run(vec![]);
|
||||
run(vec![]);
|
||||
let button_size = Vec2::splat(ctx.global_style().spacing.icon_width);
|
||||
let layer_id = LayerId::new(Order::Middle, window_id);
|
||||
let mut buttons: Vec<Rect> = ctx.prev_pass_state(|pass| {
|
||||
pass.widgets
|
||||
.get_layer(layer_id)
|
||||
.filter(|widget| widget.sense.senses_click() && widget.rect.size() == button_size)
|
||||
.map(|widget| widget.rect)
|
||||
.collect()
|
||||
});
|
||||
assert_eq!(
|
||||
buttons.len(),
|
||||
2,
|
||||
"Expected two title-bar buttons: {buttons:?}"
|
||||
);
|
||||
buttons.sort_by(|a, b| a.left().total_cmp(&b.left()));
|
||||
|
||||
let pos = buttons[0].center();
|
||||
let button = |pressed| Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Modifiers::NONE,
|
||||
};
|
||||
run(vec![Event::PointerMoved(pos), button(true)]);
|
||||
run(vec![button(false)]);
|
||||
// Let the collapse animation finish.
|
||||
for _ in 0..30 {
|
||||
run(vec![]);
|
||||
}
|
||||
|
||||
match (open.get(), collapsed.get()) {
|
||||
(true, true) => Outcome::Collapsed,
|
||||
(false, _) => Outcome::Closed,
|
||||
(true, false) => panic!("Clicking the button did nothing"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_button_on_the_left() {
|
||||
assert_eq!(click_leftmost_title_bar_button(false), Outcome::Collapsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_button_on_the_left_right_to_left() {
|
||||
assert_eq!(click_leftmost_title_bar_button(true), Outcome::Closed);
|
||||
}
|
||||
}
|
||||
@@ -440,6 +440,9 @@ pub mod widgets;
|
||||
mod callstack;
|
||||
pub mod class;
|
||||
|
||||
#[cfg(test)]
|
||||
mod right_to_left_tests;
|
||||
|
||||
pub use accesskit;
|
||||
pub use accesskit::Role;
|
||||
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
//! [`crate::Style::right_to_left`] for widget chrome, in both directions.
|
||||
|
||||
use core::cell::Cell;
|
||||
|
||||
use crate::{
|
||||
Button, Checkbox, CollapsingHeader, ComboBox, Context, Event, Id, Modifiers, PointerButton,
|
||||
Popup, Pos2, RadioButton, RawInput, Rect, Resize, Ui, Window,
|
||||
collapsing_header::CollapsingState,
|
||||
epaint::{ClippedShape, Shape},
|
||||
vec2,
|
||||
};
|
||||
|
||||
fn context(right_to_left: bool) -> Context {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| style.right_to_left = right_to_left);
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Runs one frame and returns what it painted.
|
||||
fn run(ctx: &Context, events: Vec<Event>, mut add: impl FnMut(&mut Ui)) -> Vec<ClippedShape> {
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
let mut output = ctx.run_ui(input, |ui| add(ui));
|
||||
output.textures_delta.clear();
|
||||
output.shapes
|
||||
}
|
||||
|
||||
/// Runs a few frames, so popups and animations settle, and returns what the last one painted.
|
||||
fn run_frames(ctx: &Context, add: impl FnMut(&mut Ui)) -> Vec<ClippedShape> {
|
||||
let add = core::cell::RefCell::new(add);
|
||||
for _ in 0..4 {
|
||||
run(ctx, vec![], |ui| (add.borrow_mut())(ui));
|
||||
}
|
||||
run(ctx, vec![], |ui| (add.borrow_mut())(ui))
|
||||
}
|
||||
|
||||
/// The bounding rect of the text shape showing `text`.
|
||||
fn text_rect(shapes: &[ClippedShape], text: &str) -> Rect {
|
||||
shapes
|
||||
.iter()
|
||||
.find(|clipped| matches!(&clipped.shape, Shape::Text(t) if t.galley.text() == text))
|
||||
.unwrap_or_else(|| panic!("No text {text:?}"))
|
||||
.shape
|
||||
.visual_bounding_rect()
|
||||
}
|
||||
|
||||
/// The bounding rect of all non-text shapes inside `rect`.
|
||||
fn non_text_rect(shapes: &[ClippedShape], rect: Rect) -> Rect {
|
||||
let bounds = shapes
|
||||
.iter()
|
||||
.filter(|clipped| !matches!(clipped.shape, Shape::Text(_)))
|
||||
.map(|clipped| clipped.shape.visual_bounding_rect())
|
||||
.filter(|bounds| bounds.is_positive() && rect.contains_rect(*bounds))
|
||||
.fold(Rect::NOTHING, |a, b| a.union(b));
|
||||
assert!(bounds.is_positive(), "Nothing painted in {rect:?}");
|
||||
bounds
|
||||
}
|
||||
|
||||
/// The triangles (three-point paths) painted inside `rect`.
|
||||
fn triangles(shapes: &[ClippedShape], rect: Rect) -> Vec<Vec<Pos2>> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
Shape::Path(path)
|
||||
if path.points.len() == 3 && path.points.iter().all(|p| rect.contains(*p)) =>
|
||||
{
|
||||
Some(path.points.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn click(pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Modifiers::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Returns the anchor button rect and the popup rect.
|
||||
fn popup_below_wide_button(right_to_left: bool) -> (Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let button = Cell::new(Rect::NOTHING);
|
||||
let popup = Cell::new(Rect::NOTHING);
|
||||
run_frames(&ctx, |ui| {
|
||||
ui.add_space(100.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(200.0);
|
||||
let response = ui.add_sized([300.0, 20.0], Button::new("Button"));
|
||||
button.set(response.rect);
|
||||
if let Some(inner) = Popup::from_response(&response)
|
||||
.open(true)
|
||||
.show(|ui| ui.label("Popup"))
|
||||
{
|
||||
popup.set(inner.response.rect);
|
||||
}
|
||||
});
|
||||
});
|
||||
assert!(popup.get().width() < button.get().width() - 50.0);
|
||||
(button.get(), popup.get())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_aligned_to_the_left() {
|
||||
let (button, popup) = popup_below_wide_button(false);
|
||||
assert_eq!(popup.left(), button.left(), "{button:?} {popup:?}");
|
||||
assert!(popup.top() >= button.bottom());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_aligned_to_the_right_right_to_left() {
|
||||
let (button, popup) = popup_below_wide_button(true);
|
||||
// Areas round their left-top corner to whole pixels, so with a fractional popup width
|
||||
// (real fonts) the right edge can be up to half a pixel off.
|
||||
// Painting rounds the frame edges to pixels too, so it still looks aligned.
|
||||
let ppp = Context::default().pixels_per_point();
|
||||
assert!(
|
||||
(popup.right() - button.right()).abs() <= 0.5 / ppp,
|
||||
"{button:?} {popup:?}"
|
||||
);
|
||||
assert!(popup.top() >= button.bottom());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Returns the x of the triangle center, the header text rect, and the header rect.
|
||||
fn collapsing_header(right_to_left: bool) -> (f32, Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let header = Cell::new(Rect::NOTHING);
|
||||
let shapes = run_frames(&ctx, |ui| {
|
||||
let response = CollapsingHeader::new("Header").show(ui, |ui| ui.label("Body"));
|
||||
header.set(response.header_response.rect);
|
||||
});
|
||||
let triangles = triangles(&shapes, header.get());
|
||||
assert_eq!(triangles.len(), 1, "{triangles:?}");
|
||||
let icon_x = triangles[0].iter().map(|p| p.x).sum::<f32>() / 3.0;
|
||||
(icon_x, text_rect(&shapes, "Header"), header.get())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsing_header_icon_before_text() {
|
||||
let (icon_x, text, header) = collapsing_header(false);
|
||||
assert!(icon_x < text.left(), "{icon_x} {text:?}");
|
||||
assert!(icon_x < header.center().x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsing_header_icon_before_text_right_to_left() {
|
||||
let (icon_x, text, header) = collapsing_header(true);
|
||||
assert!(icon_x > text.right(), "{icon_x} {text:?}");
|
||||
assert!(icon_x > header.center().x);
|
||||
}
|
||||
|
||||
/// Returns the toggle button rect and the header label rect of [`CollapsingState::show_header`].
|
||||
fn collapsing_state_header(right_to_left: bool) -> (Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let rects = Cell::new((Rect::NOTHING, Rect::NOTHING));
|
||||
run_frames(&ctx, |ui| {
|
||||
let (toggle, header, _) =
|
||||
CollapsingState::load_with_default_open(ui.ctx(), Id::unique("state"), false)
|
||||
.show_header(ui, |ui| ui.label("Header"))
|
||||
.body(|ui| ui.label("Body"));
|
||||
rects.set((toggle.rect, header.inner.rect));
|
||||
});
|
||||
rects.get()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsing_state_toggle_before_header() {
|
||||
let (toggle, header) = collapsing_state_header(false);
|
||||
assert!(toggle.right() <= header.left(), "{toggle:?} {header:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsing_state_toggle_before_header_right_to_left() {
|
||||
let (toggle, header) = collapsing_state_header(true);
|
||||
assert!(toggle.left() >= header.right(), "{toggle:?} {header:?}");
|
||||
}
|
||||
|
||||
/// Returns the available rect and the indented child's max rect.
|
||||
fn indent(right_to_left: bool) -> (Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let rects = Cell::new((Rect::NOTHING, Rect::NOTHING));
|
||||
run(&ctx, vec![], |ui| {
|
||||
let available = ui.available_rect_before_wrap();
|
||||
let indented = ui.indent("indent", |ui| ui.max_rect()).inner;
|
||||
rects.set((available, indented));
|
||||
});
|
||||
rects.get()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indent_from_the_left() {
|
||||
let (available, indented) = indent(false);
|
||||
let indent = Context::default().global_style().spacing.indent;
|
||||
assert_eq!(indented.left(), available.left() + indent);
|
||||
assert_eq!(indented.right(), available.right());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indent_from_the_right_right_to_left() {
|
||||
let (available, indented) = indent(true);
|
||||
let indent = Context::default().global_style().spacing.indent;
|
||||
assert_eq!(indented.left(), available.left());
|
||||
assert_eq!(indented.right(), available.right() - indent);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Returns the rects of a closed combo box's arrow, selected text and label.
|
||||
fn combo_box(right_to_left: bool) -> (Rect, Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let shapes = run_frames(&ctx, |ui| {
|
||||
ComboBox::from_label("Label")
|
||||
.selected_text("Selected")
|
||||
.show_ui(ui, |ui| ui.label("Option"));
|
||||
});
|
||||
let arrows = triangles(&shapes, Rect::EVERYTHING);
|
||||
assert_eq!(arrows.len(), 1, "{arrows:?}");
|
||||
(
|
||||
Rect::from_points(&arrows[0]),
|
||||
text_rect(&shapes, "Selected"),
|
||||
text_rect(&shapes, "Label"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_box_arrow_at_the_right_label_after() {
|
||||
let (arrow, selected, label) = combo_box(false);
|
||||
assert!(arrow.left() > selected.right(), "{arrow:?} {selected:?}");
|
||||
assert!(label.left() > arrow.right(), "{label:?} {arrow:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_box_arrow_at_the_left_label_after_right_to_left() {
|
||||
let (arrow, selected, label) = combo_box(true);
|
||||
assert!(arrow.right() < selected.left(), "{arrow:?} {selected:?}");
|
||||
assert!(label.right() < arrow.left(), "{label:?} {arrow:?}");
|
||||
}
|
||||
|
||||
/// Returns the icon rect and the label rect of a checkbox and of a radio button.
|
||||
fn check_and_radio(right_to_left: bool) -> [(Rect, Rect); 2] {
|
||||
let ctx = context(right_to_left);
|
||||
let responses = Cell::new((Rect::NOTHING, Rect::NOTHING));
|
||||
let shapes = run_frames(&ctx, |ui| {
|
||||
let mut checked = true;
|
||||
let checkbox = ui.add(Checkbox::new(&mut checked, "Check")).rect;
|
||||
let radio = ui.add(RadioButton::new(true, "Radio")).rect;
|
||||
responses.set((checkbox, radio));
|
||||
});
|
||||
let (checkbox, radio) = responses.get();
|
||||
[
|
||||
(
|
||||
non_text_rect(&shapes, checkbox),
|
||||
text_rect(&shapes, "Check"),
|
||||
),
|
||||
(non_text_rect(&shapes, radio), text_rect(&shapes, "Radio")),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_and_radio_icons_left_of_label() {
|
||||
for (icon, label) in check_and_radio(false) {
|
||||
assert!(icon.right() <= label.left(), "{icon:?} {label:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_and_radio_icons_right_of_label_right_to_left() {
|
||||
for (icon, label) in check_and_radio(true) {
|
||||
assert!(icon.left() >= label.right(), "{icon:?} {label:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// A resizable area: returns its grip rect, its rect, and its rect after dragging the grip
|
||||
/// 50 points outwards (right, or left in right-to-left).
|
||||
fn resize_grip(right_to_left: bool) -> (Rect, Rect, Rect) {
|
||||
let ctx = context(right_to_left);
|
||||
let id = Id::unique("resize");
|
||||
let content = Cell::new(Rect::NOTHING);
|
||||
let show = |ui: &mut Ui| {
|
||||
ui.add_space(100.0);
|
||||
Resize::default()
|
||||
.id(id)
|
||||
.default_size([200.0, 100.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label("Content");
|
||||
content.set(ui.max_rect());
|
||||
});
|
||||
};
|
||||
run_frames(&ctx, show);
|
||||
let grip = ctx
|
||||
.read_response(id.with("__resize_corner"))
|
||||
.expect("No resize grip")
|
||||
.rect;
|
||||
let before = content.get();
|
||||
|
||||
let from = grip.center();
|
||||
let to = from + vec2(if right_to_left { -50.0 } else { 50.0 }, 0.0);
|
||||
run(
|
||||
&ctx,
|
||||
vec![Event::PointerMoved(from), click(from, true)],
|
||||
show,
|
||||
);
|
||||
run(&ctx, vec![Event::PointerMoved(from.lerp(to, 0.5))], show);
|
||||
run(&ctx, vec![Event::PointerMoved(to)], show);
|
||||
run(&ctx, vec![click(to, false)], show);
|
||||
run_frames(&ctx, show);
|
||||
(grip, before, content.get())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_grip_at_the_bottom_right() {
|
||||
let (grip, before, after) = resize_grip(false);
|
||||
assert_eq!(
|
||||
grip.right_bottom(),
|
||||
before.right_bottom(),
|
||||
"{grip:?} {before:?}"
|
||||
);
|
||||
assert_eq!(after.left(), before.left());
|
||||
assert!(
|
||||
after.width() > before.width() + 40.0,
|
||||
"{before:?} {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_grip_at_the_bottom_left_right_to_left() {
|
||||
let (grip, before, after) = resize_grip(true);
|
||||
assert_eq!(
|
||||
grip.left_bottom(),
|
||||
before.left_bottom(),
|
||||
"{grip:?} {before:?}"
|
||||
);
|
||||
assert_eq!(after.right(), before.right());
|
||||
assert!(
|
||||
after.width() > before.width() + 40.0,
|
||||
"{before:?} {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns how many line segments a resizable window paints near its bottom-left and
|
||||
/// bottom-right corners.
|
||||
fn window_grip_lines(right_to_left: bool) -> (usize, usize) {
|
||||
let ctx = context(right_to_left);
|
||||
let window = Cell::new(Rect::NOTHING);
|
||||
let shapes = run_frames(&ctx, |ui| {
|
||||
let response = Window::new("Window")
|
||||
.default_pos([200.0, 200.0])
|
||||
.default_size([200.0, 200.0])
|
||||
.show(ui.ctx(), |ui| ui.label("Hello"));
|
||||
window.set(response.expect("window").response.rect);
|
||||
});
|
||||
let window = window.get();
|
||||
let corner = |pos: Pos2| Rect::from_center_size(pos, vec2(30.0, 30.0));
|
||||
let lines_in = |rect: Rect| {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|clipped| match &clipped.shape {
|
||||
Shape::LineSegment { points, .. } => points.iter().all(|p| rect.contains(*p)),
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
};
|
||||
(
|
||||
lines_in(corner(window.left_bottom())),
|
||||
lines_in(corner(window.right_bottom())),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_grip_at_the_bottom_right() {
|
||||
let (left, right) = window_grip_lines(false);
|
||||
assert!(left == 0 && right > 0, "{left} {right}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_grip_at_the_bottom_left_right_to_left() {
|
||||
let (left, right) = window_grip_lines(true);
|
||||
assert!(left > 0 && right == 0, "{left} {right}");
|
||||
}
|
||||
@@ -339,6 +339,17 @@ pub struct Style {
|
||||
|
||||
/// Use a more compact style for menus.
|
||||
pub compact_menu_style: bool,
|
||||
|
||||
/// Mirror egui's own chrome for right-to-left interfaces.
|
||||
///
|
||||
/// When `true`, submenus open to the left, vertical scroll bars sit on the left,
|
||||
/// collapsed collapsing-header triangles point left,
|
||||
/// and window title bars put the close button on the left and the collapse button on the right.
|
||||
///
|
||||
/// This does not change how [`crate::Ui`] lays out widgets; use a right-to-left [`crate::Layout`] for that.
|
||||
///
|
||||
/// Default: `false`.
|
||||
pub right_to_left: bool,
|
||||
}
|
||||
|
||||
// Compile-time check that `Style` is `Send + Sync` on every target.
|
||||
@@ -349,6 +360,16 @@ const _: () = {
|
||||
};
|
||||
|
||||
impl Style {
|
||||
/// The direction egui lays out the parts of its own widgets in, like a checkbox and its label:
|
||||
/// right to left if [`Self::right_to_left`].
|
||||
pub(crate) fn chrome_direction(&self) -> crate::Direction {
|
||||
if self.right_to_left {
|
||||
crate::Direction::RightToLeft
|
||||
} else {
|
||||
crate::Direction::LeftToRight
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(emilk): rename style.interact() to maybe… `style.interactive` ?
|
||||
/// Use this style for interactive things.
|
||||
/// Note that you must already have a response,
|
||||
@@ -377,6 +398,12 @@ impl Style {
|
||||
pub fn text_styles(&self) -> Vec<TextStyle> {
|
||||
self.text_styles.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Set [`Self::right_to_left`]. A method as well as a field, so callers built against egui
|
||||
/// without the field can fall back to a no-op trait method of the same name.
|
||||
pub fn set_right_to_left(&mut self, right_to_left: bool) {
|
||||
self.right_to_left = right_to_left;
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls the sizes and distances between widgets.
|
||||
@@ -1555,6 +1582,7 @@ impl Default for Style {
|
||||
always_scroll_the_only_direction: false,
|
||||
scroll_animation: ScrollAnimation::default(),
|
||||
compact_menu_style: true,
|
||||
right_to_left: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1913,6 +1941,7 @@ impl Style {
|
||||
always_scroll_the_only_direction,
|
||||
scroll_animation,
|
||||
compact_menu_style,
|
||||
right_to_left,
|
||||
} = self;
|
||||
|
||||
crate::Grid::new("_options").show(ui, |ui| {
|
||||
@@ -2020,6 +2049,11 @@ impl Style {
|
||||
|
||||
ui.checkbox(compact_menu_style, "Compact menu style");
|
||||
|
||||
ui.checkbox(right_to_left, "Right-to-left interface")
|
||||
.on_hover_text(
|
||||
"Mirror submenus, scroll bars, collapsing headers and window title bars",
|
||||
);
|
||||
|
||||
ui.checkbox(explanation_tooltips, "Explanation tooltips")
|
||||
.on_hover_text(
|
||||
"Show explanatory text when hovering DragValue:s and other egui widgets",
|
||||
|
||||
+24
-8
@@ -2351,7 +2351,8 @@ impl Ui {
|
||||
CollapsingHeader::new(heading).show(self, add_contents)
|
||||
}
|
||||
|
||||
/// Create a child ui which is indented to the right.
|
||||
/// Create a child ui which is indented to the right
|
||||
/// (to the left with [`crate::Style::right_to_left`]).
|
||||
///
|
||||
/// The `id_salt` here be anything at all.
|
||||
// TODO(emilk): remove `id_salt` argument?
|
||||
@@ -2376,8 +2377,13 @@ impl Ui {
|
||||
);
|
||||
|
||||
let indent = self.spacing().indent;
|
||||
let right_to_left = self.style().right_to_left;
|
||||
let mut child_rect = self.placer.available_rect_before_wrap();
|
||||
child_rect.min.x += indent;
|
||||
if right_to_left {
|
||||
child_rect.max.x -= indent;
|
||||
} else {
|
||||
child_rect.min.x += indent;
|
||||
}
|
||||
|
||||
let mut child_ui = self.new_child(UiBuilder::new().id_salt(id_salt).max_rect(child_rect));
|
||||
let ret = add_contents(&mut child_ui);
|
||||
@@ -2391,19 +2397,29 @@ impl Ui {
|
||||
}
|
||||
|
||||
let stroke = self.visuals().widgets.noninteractive.bg_stroke;
|
||||
let left_top = child_rect.min - 0.5 * indent * Vec2::X;
|
||||
let left_bottom = pos2(left_top.x, child_ui.min_rect().bottom() - 2.0);
|
||||
// The line sits in the middle of the indent, on the start side.
|
||||
let line_x = if right_to_left {
|
||||
child_rect.max.x + 0.5 * indent
|
||||
} else {
|
||||
child_rect.min.x - 0.5 * indent
|
||||
};
|
||||
let line_top = pos2(line_x, child_rect.min.y);
|
||||
let line_bottom = pos2(line_x, child_ui.min_rect().bottom() - 2.0);
|
||||
|
||||
if left_vline {
|
||||
// draw a faint line on the left to mark the indented section
|
||||
self.painter.line_segment([left_top, left_bottom], stroke);
|
||||
// draw a faint line to mark the indented section
|
||||
self.painter.line_segment([line_top, line_bottom], stroke);
|
||||
}
|
||||
|
||||
if end_with_horizontal_line {
|
||||
let fudge = 2.0; // looks nicer with button rounding in collapsing headers
|
||||
let right_bottom = pos2(child_ui.min_rect().right() - fudge, left_bottom.y);
|
||||
let end_x = if right_to_left {
|
||||
child_ui.min_rect().left() + fudge
|
||||
} else {
|
||||
child_ui.min_rect().right() - fudge
|
||||
};
|
||||
self.painter
|
||||
.line_segment([left_bottom, right_bottom], stroke);
|
||||
.line_segment([line_bottom, pos2(end_x, line_bottom.y)], stroke);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -311,6 +311,15 @@ impl<'a> Button<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the direction the atoms are laid out along.
|
||||
///
|
||||
/// Default: [`crate::Direction::LeftToRight`].
|
||||
#[inline]
|
||||
pub(crate) fn direction(mut self, direction: crate::Direction) -> Self {
|
||||
self.layout = self.layout.direction(direction);
|
||||
self
|
||||
}
|
||||
|
||||
/// Output the button's [`Atoms`].
|
||||
///
|
||||
/// This includes any images you have on the button.
|
||||
|
||||
@@ -90,7 +90,9 @@ impl Widget for Checkbox<'_> {
|
||||
|
||||
let text = atoms.text().map(String::from);
|
||||
|
||||
let layout = WidgetAtom::new(atoms).sense(Sense::click());
|
||||
let layout = WidgetAtom::new(atoms)
|
||||
.sense(Sense::click())
|
||||
.direction(ui.style().chrome_direction());
|
||||
let mut prepared = atom_layout.apply(layout).min_size(min_size).allocate(ui);
|
||||
|
||||
if prepared.response.clicked() {
|
||||
|
||||
@@ -64,6 +64,7 @@ impl Widget for RadioButton<'_> {
|
||||
|
||||
let mut prepared = WidgetAtom::new(atoms)
|
||||
.sense(Sense::click())
|
||||
.direction(ui.style().chrome_direction())
|
||||
.min_size(min_size)
|
||||
.allocate(ui);
|
||||
|
||||
|
||||
Reference in new issue
Block a user