From eeeb27013dbea08af6fd46182865b3cccceea5c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH] Properties: the shared sheet controls (rows, bands, sliders, number fields that hold the pointer, switches, picture dropdowns, section tabs) --- crates/ui-egui/src/pointer_lock/hold.rs | 36 +++ crates/ui-egui/src/pointer_lock/lock.rs | 19 ++ crates/ui-egui/src/pointer_lock/mod.rs | 129 +++++++++ .../src/pointer_lock/system_pointer.rs | 75 +++++ crates/ui-egui/src/pointer_lock/tests.rs | 117 ++++++++ .../ui-egui/src/property_sheet/axis_rows.rs | 135 +++++++++ .../src/property_sheet/band_response.rs | 9 + .../ui-egui/src/property_sheet/button_icon.rs | 14 + crates/ui-egui/src/property_sheet/choice.rs | 256 ++++++++++++++++++ .../ui-egui/src/property_sheet/eye_toggle.rs | 48 ++++ crates/ui-egui/src/property_sheet/group.rs | 134 +++++++++ crates/ui-egui/src/property_sheet/hold_pad.rs | 34 +++ .../ui-egui/src/property_sheet/info_icon.rs | 86 ++++++ crates/ui-egui/src/property_sheet/mod.rs | 208 ++++++++++++++ .../src/property_sheet/number_field.rs | 212 +++++++++++++++ .../ui-egui/src/property_sheet/open_card.rs | 10 + .../src/property_sheet/preview_block.rs | 153 +++++++++++ .../src/property_sheet/preview_edit.rs | 8 + .../src/property_sheet/preview_lower.rs | 10 + .../src/property_sheet/preview_size.rs | 20 ++ crates/ui-egui/src/property_sheet/row.rs | 236 ++++++++++++++++ crates/ui-egui/src/property_sheet/row_lead.rs | 30 ++ .../src/property_sheet/section_tabs.rs | 136 ++++++++++ .../section_tabs/section_scope.rs | 8 + .../section_tabs/section_tops.rs | 21 ++ .../src/property_sheet/sheet_measure.rs | 15 + crates/ui-egui/src/property_sheet/slider.rs | 238 ++++++++++++++++ crates/ui-egui/src/property_sheet/slot.rs | 64 +++++ .../src/property_sheet/stack_slider.rs | 20 ++ .../src/property_sheet/switch_control.rs | 204 ++++++++++++++ crates/ui-egui/src/property_sheet/tests.rs | 243 +++++++++++++++++ .../src/property_sheet/tests/filtering.rs | 19 ++ .../src/property_sheet/tests/gallery.rs | 15 + crates/ui-egui/src/property_sheet/tooltip.rs | 32 +++ crates/ui-egui/src/property_sheet/track.rs | 13 + .../ui-egui/src/property_sheet/value_text.rs | 63 +++++ 36 files changed, 3070 insertions(+) create mode 100644 crates/ui-egui/src/pointer_lock/hold.rs create mode 100644 crates/ui-egui/src/pointer_lock/lock.rs create mode 100644 crates/ui-egui/src/pointer_lock/mod.rs create mode 100644 crates/ui-egui/src/pointer_lock/system_pointer.rs create mode 100644 crates/ui-egui/src/pointer_lock/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/axis_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/band_response.rs create mode 100644 crates/ui-egui/src/property_sheet/button_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/choice.rs create mode 100644 crates/ui-egui/src/property_sheet/eye_toggle.rs create mode 100644 crates/ui-egui/src/property_sheet/group.rs create mode 100644 crates/ui-egui/src/property_sheet/hold_pad.rs create mode 100644 crates/ui-egui/src/property_sheet/info_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/number_field.rs create mode 100644 crates/ui-egui/src/property_sheet/open_card.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_block.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_lower.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_size.rs create mode 100644 crates/ui-egui/src/property_sheet/row.rs create mode 100644 crates/ui-egui/src/property_sheet/row_lead.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs create mode 100644 crates/ui-egui/src/property_sheet/sheet_measure.rs create mode 100644 crates/ui-egui/src/property_sheet/slider.rs create mode 100644 crates/ui-egui/src/property_sheet/slot.rs create mode 100644 crates/ui-egui/src/property_sheet/stack_slider.rs create mode 100644 crates/ui-egui/src/property_sheet/switch_control.rs create mode 100644 crates/ui-egui/src/property_sheet/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/filtering.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/gallery.rs create mode 100644 crates/ui-egui/src/property_sheet/tooltip.rs create mode 100644 crates/ui-egui/src/property_sheet/track.rs create mode 100644 crates/ui-egui/src/property_sheet/value_text.rs diff --git a/crates/ui-egui/src/pointer_lock/hold.rs b/crates/ui-egui/src/pointer_lock/hold.rs new file mode 100644 index 00000000..e4d6dc5c --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/hold.rs @@ -0,0 +1,36 @@ +//! How the system lets a drag hold its pointer + +/// How a drag holds the pointer on this platform +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Hold { + /// The pointer moves, and is put back where the press began after every frame; the put-back's own move arrives among the others (X11) + PutBack, + /// Put back the same way, but the system folds its waiting moves into one, read from where it put the pointer (Windows) + PutBackFolded, + /// The system keeps the pointer still and reports raw motion (macOS, Wayland, which cannot move a pointer) + Locked, + /// The pointer cannot be held (the browser): drags read it as it moves + Free, +} + +impl Hold { + /// The way this platform holds a pointer; Wayland is told apart from X11 the way the window system picks it + pub(crate) fn of_platform() -> Hold { + if cfg!(target_arch = "wasm32") { + Hold::Free + } else if cfg!(target_os = "macos") { + Hold::Locked + } else if cfg!(target_os = "windows") { + Hold::PutBackFolded + } else if std::env::var_os("WAYLAND_DISPLAY").is_none() { + Hold::PutBack + } else { + Hold::Locked + } + } + + /// The pointer is held by putting it back after every frame + pub(crate) fn puts_back(self) -> bool { + matches!(self, Hold::PutBack | Hold::PutBackFolded) + } +} diff --git a/crates/ui-egui/src/pointer_lock/lock.rs b/crates/ui-egui/src/pointer_lock/lock.rs new file mode 100644 index 00000000..bb593ce2 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/lock.rs @@ -0,0 +1,19 @@ +use egui::Pos2; + +use super::Hold; + +/// A drag holding the pointer, kept in egui's memory between frames +#[derive(Clone, Copy, Debug)] +pub(super) struct Lock { + pub(super) hold: Hold, + /// Where the press began: the pointer is kept there and comes back there + pub(super) anchor: Pos2, + /// Where the system's pointer is + pub(super) seen: Pos2, + /// Where egui sees the pointer: the anchor plus every move since, as far as it goes + pub(super) at: Pos2, + /// A put-back is on its way: the pointer move that brings it back is no motion + pub(super) putting_back: bool, + /// The drag let go: the next frame shows egui the pointer back at the anchor and forgets the lock + pub(super) let_go: bool, +} diff --git a/crates/ui-egui/src/pointer_lock/mod.rs b/crates/ui-egui/src/pointer_lock/mod.rs new file mode 100644 index 00000000..f3e09661 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/mod.rs @@ -0,0 +1,129 @@ +//! Drags that hold the pointer (Move on model, number fields that scrub): hidden while held, its motion endless so no screen edge stops it, back where the press began when let go. egui sees a pointer that keeps going: the raw input is rewritten to that endless position, so every drag reads its usual positions and deltas + +mod hold; +mod lock; +#[cfg(test)] +pub(crate) mod system_pointer; +#[cfg(test)] +mod tests; + +use egui::{Context, CursorIcon, Event, Id, RawInput, ViewportCommand}; + +pub(crate) use hold::Hold; +use lock::Lock; + +/// Points from where the press began within which a pointer move is the put-back arriving (the system rounds it to whole pixels) +const PUT_BACK_REACH: f32 = 1.0; + +fn lock_id() -> Id { + Id::unique("tc_pointer_lock") +} + +fn asked_id() -> Id { + Id::unique("tc_pointer_lock_asked") +} + +fn hold_override_id() -> Id { + Id::unique("tc_pointer_lock_hold") +} + +/// A drag under way asks for the pointer this frame; it keeps it as long as it asks every frame +pub(crate) fn ask_for_hold(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(asked_id(), pass)); +} + +/// The app's raw input hook: while a drag holds the pointer, its moves become moves of the endless pointer egui sees +pub(crate) fn rewrite(ctx: &Context, raw: &mut RawInput) { + let Some(mut lock) = ctx.data(|data| data.get_temp::(lock_id())) else { + return; + }; + + if lock.let_go { + raw.events.insert(0, Event::PointerMoved(lock.anchor)); + ctx.data_mut(|data| data.remove::(lock_id())); + return; + } + + let zoom = ctx.zoom_factor().max(f32::EPSILON); + let events = std::mem::take(&mut raw.events); + for event in events { + match event { + Event::PointerMoved(to) => { + let put_back = lock.putting_back && to.distance(lock.anchor) <= PUT_BACK_REACH; + lock.putting_back &= !put_back; + if lock.hold.puts_back() && !put_back { + lock.at += to - lock.seen; + raw.events.push(Event::PointerMoved(lock.at)); + } + lock.seen = to; + } + Event::MouseMoved(delta) => { + if lock.hold == Hold::Locked { + lock.at += delta / zoom; + raw.events.push(Event::PointerMoved(lock.at)); + } + raw.events.push(event); + } + Event::PointerButton { button, pressed, modifiers, .. } => raw.events.push(Event::PointerButton { pos: lock.at, button, pressed, modifiers }), + // The pointer never really leaves: the drag goes on + Event::PointerGone => {} + other => raw.events.push(other), + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// The end of the app's frame: a drag that asked this frame takes or keeps the pointer (hidden, put back), one that stopped asking lets it go +pub(crate) fn settle(ctx: &Context) { + let asked = ctx.data(|data| data.get_temp::(asked_id())) == Some(ctx.cumulative_pass_nr()); + let held = ctx.data(|data| data.get_temp::(lock_id())).filter(|lock| !lock.let_go); + let mut lock = match (asked, held) { + (true, Some(lock)) => lock, + (true, None) => { + let hold = ctx.data(|data| data.get_temp::(hold_override_id())).unwrap_or_else(Hold::of_platform); + let (origin, latest) = ctx.input(|input| (input.pointer.press_origin(), input.pointer.latest_pos())); + let (Some(seen), false) = (latest, hold == Hold::Free) else { + return; + }; + + if hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + } + Lock { hold, anchor: origin.unwrap_or(seen), seen, at: seen, putting_back: false, let_go: false } + } + (false, Some(mut lock)) => { + // Put back before the grab ends: Wayland moves only a locked pointer + if lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + } + if lock.hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::None)); + } + lock.let_go = true; + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); + ctx.request_repaint(); + return; + } + (false, None) => return, + }; + + ctx.set_cursor_icon(CursorIcon::None); + if lock.hold.puts_back() && lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + + // A folding system reads every later move from where it put the pointer, its own move folded in + if lock.hold == Hold::PutBackFolded { + lock.seen = lock.anchor; + } else { + lock.putting_back = true; + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// Tests pick how the pointer is held, as a platform would +#[cfg(test)] +pub(crate) fn hold_like(ctx: &Context, hold: Hold) { + ctx.data_mut(|data| data.insert_temp(hold_override_id(), hold)); +} diff --git a/crates/ui-egui/src/pointer_lock/system_pointer.rs b/crates/ui-egui/src/pointer_lock/system_pointer.rs new file mode 100644 index 00000000..156cd8ee --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/system_pointer.rs @@ -0,0 +1,75 @@ +//! The system's pointer in tests: the mouse moves it, and it obeys the app's put-backs, grabs and hidden cursor as a window system does + +use egui::{CursorGrab, CursorIcon, Event, Modifiers, PointerButton, Pos2, Vec2, ViewportCommand, ViewportId}; +use egui_kittest::Harness; + +/// Where the system's pointer is and how the app holds it +#[derive(Clone, Copy, Debug)] +pub(crate) struct SystemPointer { + pub(crate) at: Pos2, + pub(crate) locked: bool, + pub(crate) hidden: bool, + pub(crate) put_backs: usize, + /// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own + pub(crate) folds: bool, +} + +impl SystemPointer { + /// The pointer resting at `at` over the window + pub(crate) fn at(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer { + let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false }; + harness.input_mut().events.push(Event::PointerMoved(at)); + pointer.frame(harness); + pointer + } + + /// One frame in which the mouse moves by `by` with `modifiers` held: a held pointer reports raw motion only, a free one moves + pub(crate) fn moves(&mut self, harness: &mut Harness<'_, S>, by: Vec2, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::MouseMoved(by)); + if !self.locked { + self.at += by; + input.events.push(Event::PointerMoved(self.at)); + } + self.frame(harness); + } + + /// The mouse moves by `by` over `frames` frames + pub(crate) fn drags(&mut self, harness: &mut Harness<'_, S>, by: Vec2, frames: usize, modifiers: Modifiers) { + for _ in 0..frames { + self.moves(harness, by / frames as f32, modifiers); + } + } + + /// One frame in which `button` goes down or up where the pointer is + pub(crate) fn button(&mut self, harness: &mut Harness<'_, S>, button: PointerButton, pressed: bool, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::PointerButton { pos: self.at, button, pressed, modifiers }); + self.frame(harness); + } + + /// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked + pub(crate) fn frame(&mut self, harness: &mut Harness<'_, S>) { + let ctx = harness.ctx.clone(); + super::rewrite(&ctx, harness.input_mut()); + harness.step(); + let output = harness.output(); + self.hidden = output.platform_output.cursor_icon == CursorIcon::None; + let commands = output.viewport_output.get(&ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default(); + for command in commands { + match command { + ViewportCommand::CursorPosition(to) => { + self.at = to; + self.put_backs += 1; + if !self.folds { + harness.input_mut().events.push(Event::PointerMoved(to)); + } + } + ViewportCommand::CursorGrab(grab) => self.locked = grab == CursorGrab::Locked, + _ => {} + } + } + } +} diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs new file mode 100644 index 00000000..bbce1297 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -0,0 +1,117 @@ +use egui::{Modifiers, PointerButton, Pos2, Rect, Sense, Vec2, pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::system_pointer::SystemPointer; +use super::{Hold, ask_for_hold, hold_like, settle}; + +/// A strip that scrubs: dragging it adds the pointer's moves to the state, holding the pointer while it does +fn scrub_strip(hold_as: Hold) -> Harness<'static, Vec2> { + let mut harness = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( + |ui, moved: &mut Vec2| { + let response = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 24.0)), ui.scope_id().with("scrub"), Sense::drag()); + if response.dragged() { + ask_for_hold(ui.ctx()); + *moved += response.drag_delta(); + } + settle(ui.ctx()); + }, + Vec2::ZERO, + ); + hold_like(&harness.ctx, hold_as); + harness.run_steps(1); + harness +} + +const PRESS: Pos2 = pos2(60.0, 20.0); + +/// Drags the strip 1500 points right (far past the 400-point window) and back up 40, then lets go +fn scrub_past_the_edge(harness: &mut Harness<'static, Vec2>) -> SystemPointer { + let mut pointer = SystemPointer::at(harness, PRESS); + pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is hidden while the drag holds it"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts, past the window's edge: {:?}", harness.state()); + pointer +} + +#[test] +fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_began() { + let mut harness = scrub_strip(Hold::PutBack); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.put_backs >= 30, "the pointer went back after every move: {}", pointer.put_backs); + assert!(pointer.at.distance(PRESS) < 1.0, "it never strayed from the press: {:?}", pointer.at); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden, "let go, the pointer shows again"); + assert_eq!(pointer.at, PRESS, "where the press began"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too"); + let moved = *harness.state(); + pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again"); + assert_eq!(*harness.state(), moved, "and drags nothing"); +} + +/// A system that folds the put-back into the next move (Windows) reads that move from the press point: the drag counts in full and never stalls +#[test] +fn a_folded_put_back_counts_every_move_from_the_press() { + let mut harness = scrub_strip(Hold::PutBackFolded); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.folds = true; + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state()); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}"); +} + +#[test] +fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() { + let mut harness = scrub_strip(Hold::Locked); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.locked, "the system holds the pointer"); + assert_eq!(pointer.at, PRESS, "it never moved"); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began"); +} + +#[test] +fn a_browser_pointer_is_not_held() { + let mut harness = scrub_strip(Hold::Free); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE); + assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows"); + assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves"); +} + +/// A number field in the Properties panel scrubs with the pointer held: hidden, kept where the press began, a drag far past the window's edge counted in full +#[test] +fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar"); + hold_like(&harness.ctx, Hold::PutBack); + let press = harness.get_by_label("Offset X").rect().center(); + let mut pointer = SystemPointer::at(&mut harness, press); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + let window = harness.ctx.content_rect().width(); + pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); + assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}"); + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}"); + + let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else { + panic!("still tri-planar") + }; + + let expected = 2.0 * window * crate::fill_panel::OFFSET_FIELD_SPEED; + assert!((offset[0] - expected).abs() < 0.05 * expected, "the whole drag counts, not only the part inside the window: {offset:?}, {expected}"); +} diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs new file mode 100644 index 00000000..13d65ee9 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -0,0 +1,135 @@ +//! Rows a symmetry needs: a section caption with its own switch, sliders lettered by axis, and a picture beside a stack of sliders + +use std::ops::RangeInclusive; + +use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::row::SECTION_CAPTION_CENTER; +use super::slider::KNOB_RADIUS; +use super::switch_control::PILL_SIZE; +use super::track::Track; +use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; +use crate::theme::semibold; + +/// From the right edge to the centre of a caption's switch: the pill ends on the edge +const CAPTION_SWITCH_INSET: f32 = PILL_SIZE.x / 2.0; + +/// The click area around a caption's switch +const CAPTION_SWITCH_HIT: egui::Vec2 = vec2(30.0, 20.0); + +/// Least air between a caption and the reason standing in for its switch +const UNAVAILABLE_AIR: f32 = 12.0; + +/// From the controls column to where a lettered slider's track starts, past its axis letter +const LETTER_TO_TRACK: f32 = 16.0; + +/// From one part of a lettered value to the next +const PART_LINE: f32 = 22.0; + +/// A stacked slider's caption line, its track's line, and the air between stacked sliders +const STACK_CAPTION_LINE: f32 = 18.0; +const STACK_PART_LINE: f32 = 22.0; +const STACK_GAP: f32 = 6.0; + +/// The picture's top below the block's (the first caption's letters), how much shorter it is than the stack, and its air before the controls column +const PICTURE_TOP: f32 = 4.0; +const PICTURE_SHORTER: f32 = 10.0; +const PICTURE_TO_COLUMN: f32 = 6.0; + +impl PropertySheet<'_> { + /// A section caption with its on/off switch at the right edge + pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { + self.section_in(title, false, self.tokens.text); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center = pos2(self.right - CAPTION_SWITCH_INSET, top + SECTION_CAPTION_CENTER); + let id = self.next_id(); + let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title)); + self.pill(center, on, true); + response + } + + /// A dim section caption whose switch can't be used: `reason` stands in its place at the right edge, cut with "…" to fit (then its tooltip reads it whole) + pub(crate) fn section_unavailable(&mut self, title: &str, reason: &str) { + let tokens = self.tokens; + self.section_in(title, false, tokens.text_dim); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center_y = top + SECTION_CAPTION_CENTER; + let painter = self.ui.painter().clone(); + let caption = painter.layout_no_wrap(title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text_dim).size().x; + let room = self.right - self.left - caption - UNAVAILABLE_AIR; + let galley = crate::widgets::elided(&painter, reason, SMALL_TEXT_SIZE, tokens.text_dim, room); + let cut = galley.elided; + let rect = Rect::from_min_size(pos2(self.right - galley.size().x, center_y - galley.size().y / 2.0), galley.size()); + painter.galley(rect.min, galley, tokens.text_dim); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, false, reason)); + if cut { + self.tip(response, reason); + } + } + + /// One value's parts on lettered signed sliders (Axis position X, Y): the label on the first row, each part's axis letter in its colour; returns the part edited and whether it merges + pub(crate) fn lettered_sliders( + &mut self, + label: &str, + parts: &mut [(&str, Color32, f32)], + range: RangeInclusive, + decimals: usize, + ) -> Option<(usize, bool)> { + let (control, first) = self.row(label); + let extra = parts.len().saturating_sub(1) as f32 * PART_LINE; + if extra > 0.0 { + self.take(extra); + } + let mut edit = None; + for (index, (letter, color, value)) in parts.iter_mut().enumerate() { + let center_y = first + index as f32 * PART_LINE; + self.ui.painter().text(pos2(control.left(), center_y), Align2::LEFT_CENTER, *letter, semibold(TEXT_SIZE), *color); + let id = self.next_id(); + let track = Track { start: control.left() + LETTER_TO_TRACK + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; + let name = format_args!("{label} {letter}"); + let dragged = self.track(id, name, &track, value, &range); + let typed = self.value_field(id, name, center_y, *value, &range, decimals, ""); + if let Some(merge) = Self::apply_typed(value, typed, dragged) { + edit = Some((index, merge)); + } + self.drawn(center_y + super::CONTROL_HEIGHT / 2.0); + } + edit + } + + /// A picture at the left edge beside captioned sliders in the controls column, as tall as their stack; returns the slider edited and whether it merges + pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>]) -> Option<(usize, bool)> { + let count = sliders.len().max(1) as f32; + let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let x0 = self.column(); + let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let mut edit = None; + let mut y = block.top(); + for (index, slider) in sliders.iter_mut().enumerate() { + let dim = self.tokens.text_dim; + let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; + let id = self.next_id(); + let track = Track { start: x0 + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); + let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); + if let Some(merge) = Self::apply_typed(slider.value, typed, dragged) { + edit = Some((index, merge)); + } + y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; + } + self.drawn(square.bottom().max(block.bottom() - STACK_PART_LINE / 2.0 + KNOB_RADIUS)); + self.space(BLOCK_MARGIN); + edit + } +} diff --git a/crates/ui-egui/src/property_sheet/band_response.rs b/crates/ui-egui/src/property_sheet/band_response.rs new file mode 100644 index 00000000..fb230951 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/band_response.rs @@ -0,0 +1,9 @@ +/// What a band did this frame +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct BandResponse { + /// The band is open: show its rows + pub(crate) open: bool, + + /// Its Restore defaults button was clicked + pub(crate) reset: bool, +} diff --git a/crates/ui-egui/src/property_sheet/button_icon.rs b/crates/ui-egui/src/property_sheet/button_icon.rs new file mode 100644 index 00000000..be97a317 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/button_icon.rs @@ -0,0 +1,14 @@ +//! What a full-width button shows before its words: an icon font glyph or an icon drawn in code + +/// A full-width button's icon +#[derive(Clone, Copy, Debug)] +pub(crate) enum ButtonIcon<'a> { + /// A glyph of the icon font + Glyph(&'a str), +} + +impl<'a> From<&'a str> for ButtonIcon<'a> { + fn from(glyph: &'a str) -> Self { + ButtonIcon::Glyph(glyph) + } +} diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs new file mode 100644 index 00000000..15d3d03f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -0,0 +1,256 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Frame, Margin, Painter, Rect, RectAlign, Response, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, ICON_SIZE, PropertySheet, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::{HARD_SHADOW, semibold}; + +/// Draws an option's picture into its square +pub(super) type ChoicePicture<'a, T> = &'a dyn Fn(&Painter, Rect, T); + +/// Size of a picture in a dropdown button and in its list +const PICTURE_SIZE: f32 = 18.0; + +/// From a picture dropdown's left edge to its picture +const PICTURE_INSET: f32 = 6.0; + +/// From a plain dropdown's left edge to its value +pub(super) const VALUE_INSET: f32 = 8.0; + +/// Air between a picture and the words after it +const PICTURE_TO_TEXT: f32 = 8.0; + +/// From a dropdown's right edge to its caret's centre +pub(super) const CARET_INSET: f32 = 10.0; + +/// Room a dropdown keeps for its caret: its value is cut with "…" before it +pub(super) const CARET_ROOM: f32 = 24.0; + +/// The open list's border, drawn outside its options: the list's outer edge is its button's +pub(super) const LIST_BORDER: f32 = 1.0; + +/// The open list's corner radius and the air above its first option and below its last +const LIST_RADIUS: u8 = 6; +const LIST_PADDING: i8 = 4; + +/// The open list's hard shadow, offset down and right like the other popups' +const LIST_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +/// Height of one option in an open list +const OPTION_HEIGHT: f32 = 26.0; + +/// How far an option's words sit above its centre, to look centred beside their capitals +const OPTION_TEXT_LIFT: f32 = 1.0; + +/// Gap under an option's hover fill, so neighbouring fills never touch +const HOVER_BOTTOM_GAP: f32 = 2.0; + +/// How far an option's hover fill sits inside the list's edges +const HOVER_INSET: f32 = 3.0; + +/// From the list's right edge to the hovered option's preview eye +const EYE_INSET: f32 = 16.0; + +/// Lists narrower than this have no room for the preview eye +const EYE_MIN_LIST_WIDTH: f32 = 80.0; + +/// The lettering of a set-once choice, cut with "…" to fit `room` +pub(super) fn truncated(painter: &Painter, text: &str, room: f32, color: Color32) -> std::sync::Arc { + let font = semibold(TEXT_SIZE); + let full = painter.layout_no_wrap(text.to_owned(), font.clone(), color); + if full.size().x <= room { + return full; + } + + let mut cut: String = text.to_owned(); + while cut.pop().is_some() { + let candidate = painter.layout_no_wrap(format!("{}…", cut.trim_end()), font.clone(), color); + if candidate.size().x <= room { + return candidate; + } + } + painter.layout_no_wrap("…".to_owned(), font, color) +} + +/// The chosen option's accent bar, inset from the option's left, top and bottom +const CHOSEN_BAR_LEFT: f32 = 2.0; +const CHOSEN_BAR_RIGHT: f32 = 4.0; +const CHOSEN_BAR_TOP: f32 = 5.0; +const CHOSEN_BAR_BOTTOM: f32 = 7.0; + +/// The chosen option's accent bar is 2 px wide: a 1 px radius rounds its ends fully +const CHOSEN_BAR_RADIUS: u8 = 1; + +/// The hovered option's eye glyph size +const EYE_SIZE: f32 = 13.0; + +impl PropertySheet<'_> { + /// A set-once choice whose list hangs from its button; returns the picked and the hovered option + pub(crate) fn dropdown( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.dropdown_led(RowLead::label(label), current, options, name, picture) + } + + /// [`Self::dropdown`] led by `lead` (a label stacked above it, when its values differ only at their end) + pub(crate) fn dropdown_led( + &mut self, + lead: RowLead<'_>, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(lead, current, &name, picture); + self.hanging_list(&response, current, options, &name, picture) + } + + /// [`Self::dropdown`] whose `options` are built only while its list is open + pub(crate) fn dropdown_built>( + &mut self, + label: &str, + current: T, + options: impl FnOnce() -> Options, + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(RowLead::label(label), current, &name, picture); + self.hanging_groups(&response, current, || [(None, options())], &name, picture) + } + + /// A dropdown's row led by `lead`, its button showing `current` and described by the row's name; returns the button's response + fn dropdown_row(&mut self, lead: RowLead<'_>, current: T, name: &impl Fn(T) -> String, picture: Option>) -> Response { + let x0 = self.lead_with(lead); + let row = self.take(super::ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + CONTROL_HEIGHT / 2.0); + let button = self.control_box(x0, center_y); + let response = self.dropdown_button(button, &name(current), picture.map(|draw| move |painter: &Painter, rect: Rect| draw(painter, rect, current))); + self.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(lead.text())); + response + } + + /// Paints a dropdown's button in `rect` and returns its response + pub(super) fn dropdown_button(&mut self, rect: Rect, value: &str, picture: Option) -> Response { + self.dropdown_button_led(rect, value, |painter| match picture { + Some(draw) => { + let picture_rect = + Rect::from_min_size(pos2(rect.left() + PICTURE_INSET, rect.center().y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)); + draw(painter, picture_rect); + picture_rect.right() + PICTURE_TO_TEXT + } + None => rect.left() + VALUE_INSET, + }) + } + + /// [`Self::dropdown_button`] whose left end `lead` paints on the button's face, returning where the value starts + pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); + + let text_x = lead(painter); + let galley = truncated(painter, value, rect.right() - CARET_ROOM - text_x, tokens.text); + painter.galley(pos2(text_x, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(ICON_SIZE), tokens.text); + response + } + + /// The open list of `button`: 1 px below it, its width, over the rows below; returns the picked and the hovered option + pub(crate) fn hanging_list( + &mut self, + button: &Response, + current: T, + options: &[T], + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.hanging_groups(button, current, || [(None, options.iter().copied())], name, picture) + } + + /// [`Self::hanging_list`] of options in groups, each under its caption (a dim line that can't be picked) when it has one; `groups` runs only while the list is open + fn hanging_groups<'g, T: Copy + PartialEq, Groups: IntoIterator, Options)>, Options: IntoIterator>( + &mut self, + button: &Response, + current: T, + groups: impl FnOnce() -> Groups, + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let tokens = self.tokens; + let width = button.rect.width() - 2.0 * LIST_BORDER; + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(LIST_BORDER, tokens.field_border)) + .corner_radius(CornerRadius::same(LIST_RADIUS)) + .inner_margin(Margin::symmetric(0, LIST_PADDING)) + .shadow(LIST_SHADOW); + let shown = egui::Popup::from_toggle_button_response(button).align(RectAlign::BOTTOM_START).gap(1.0).width(width).frame(frame).show(|ui| { + let mut picked = None; + let mut hovered = None; + for (caption, options) in groups() { + if let Some(caption) = caption { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, caption)); + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + ui.painter().text( + pos2(rect.left() - LIST_BORDER + VALUE_INSET, center_y), + Align2::LEFT_CENTER, + caption, + FontId::proportional(SMALL_TEXT_SIZE), + tokens.text_dim, + ); + } + for option in options { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::click()); + let painter = ui.painter(); + let chosen = option == current; + response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option))); + if response.hovered() { + hovered = Some(option); + let fill = + Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); + painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); + } + if chosen { + let bar = Rect::from_min_max( + pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), + pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), + ); + painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); + } + + // The rows sit inside the list's border: measured from the button's edge, text and picture keep the button's x + let button_left = rect.left() - LIST_BORDER; + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + let mut text_x = button_left + VALUE_INSET; + if let Some(draw) = picture { + draw( + painter, + Rect::from_min_size(pos2(button_left + PICTURE_INSET, center_y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)), + option, + ); + text_x = button_left + PICTURE_INSET + PICTURE_SIZE + PICTURE_TO_TEXT; + } + let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }; + painter.text(pos2(text_x, center_y), Align2::LEFT_CENTER, name(option), font, tokens.text); + if response.hovered() && width >= EYE_MIN_LIST_WIDTH { + painter.text(pos2(rect.right() - EYE_INSET, center_y), Align2::CENTER_CENTER, ic::EYE, FontId::proportional(EYE_SIZE), tokens.accent); + } + if response.clicked() && !chosen { + picked = Some(option); + } + } + } + (picked, hovered) + }); + shown.map(|inner| inner.inner).unwrap_or((None, None)) + } +} diff --git a/crates/ui-egui/src/property_sheet/eye_toggle.rs b/crates/ui-egui/src/property_sheet/eye_toggle.rs new file mode 100644 index 00000000..17fff24e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/eye_toggle.rs @@ -0,0 +1,48 @@ +//! A dropdown row that ends in an eye: shows or hides what the setting draws over the 3D view + +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, PropertySheet}; + +/// Air between the dropdown and its eye +const EYE_GAP: f32 = 6.0; + +/// Size of the eye glyph +const EYE_GLYPH_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// [`Self::dropdown`] narrowed by an eye at the row's end (`eye`: open while shown, else slashed and dim; its tip); returns the pick and the eye's click + pub(crate) fn dropdown_with_eye( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + (shown, tip): (bool, &str), + ) -> (Option, bool) { + let right = self.right; + self.right -= CONTROL_HEIGHT + EYE_GAP; + let (picked, _) = self.dropdown(label, current, options, name, picture); + self.right = right; + + let center_y = self.cursor_y() - super::ROW_HEIGHT / 2.0; + let rect = Rect::from_center_size(pos2(right - CONTROL_HEIGHT / 2.0, center_y), vec2(CONTROL_HEIGHT, CONTROL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, shown, tip)); + let response = self.tip(response, tip); + paint_eye(self.ui.painter(), rect, shown, response.hovered(), &self.tokens); + (picked, response.clicked()) + } +} + +/// The eye's square: button fill, its edge lit while hovered; the eye open, or slashed and dim +fn paint_eye(painter: &Painter, rect: Rect, shown: bool, hovered: bool, tokens: &crate::theme::Tokens) { + let border = if hovered { tokens.accent } else { tokens.button_border }; + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.button, Stroke::new(1.0, border), StrokeKind::Inside); + let (glyph, color) = if shown { (ic::EYE, tokens.text) } else { (ic::EYE_SLASH, tokens.text_dim) }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(EYE_GLYPH_SIZE), color); +} diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs new file mode 100644 index 00000000..d115e162 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -0,0 +1,134 @@ +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use crate::theme::semibold; + +/// Draws a band's picture in its rect +type BandPicture<'a> = &'a dyn Fn(&egui::Painter, Rect); + +/// Height of a top-level band +const BAND_HEIGHT: f32 = 30.0; + +/// A card's padding above its name and below its last control +const CARD_PADDING: f32 = 10.0; + +/// How far a card's face reaches past its rows on both sides +pub(super) const CARD_BLEED: f32 = 6.0; + +/// Corner radius of a card +pub(super) const CARD_RADIUS: u8 = 6; + +/// From the right edge to the centre of a band's reset button +const BAND_RESET_INSET: f32 = 26.0; + +/// From the right edge to where a band's or folded group's value ends +const BAND_VALUE_INSET: f32 = 22.0; + +/// Side of the picture before a band's value, and the air between them +const BAND_PICTURE_SIZE: f32 = 16.0; +const BAND_PICTURE_AIR: f32 = 8.0; + +/// A band's reset button click square +const BAND_RESET_TARGET: f32 = 20.0; + +impl PropertySheet<'_> { + /// A top-level group across the whole panel with a caret and a reset (`Some(changed)`) or a value; a click folds it + pub(crate) fn band(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>) -> BandResponse { + self.band_drawn(title, default_open, reset, value, None) + } + + fn band_drawn(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>, picture: Option>) -> BandResponse { + if self.card.is_none() { + self.space(GROUP_GAP); + } + + // A band is top-level: it ends a held card too + self.release_card(); + + self.scope = self.id; + let id = self.named_id("band", title); + self.band_scope = id; + self.scope = id; + + let rect = self.take(BAND_HEIGHT); + let band = Rect::from_x_y_ranges(self.ui.max_rect().x_range(), rect.y_range()); + + let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); + let response = self.ui.interact(band, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + + let reset_rect = Rect::from_center_size(pos2(self.right - BAND_RESET_INSET, rect.center().y), vec2(BAND_RESET_TARGET, BAND_RESET_TARGET)); + let mut reset_clicked = false; + let mut reset_hovered = false; + if let Some(changed) = reset { + // At the defaults it is inert: a click there folds the band like the rest of it + let sense = if changed { Sense::click() } else { Sense::hover() }; + let reset_response = self.ui.interact(reset_rect, id.with("reset"), sense); + if changed { + // Right above the glyph, as far right as it: over the card or toggles above the band, never a value + let mut tooltip = egui::Tooltip::for_enabled(&reset_response); + tooltip.popup = tooltip.popup.anchor(reset_rect).align(egui::RectAlign::TOP_END).align_alternatives(&[egui::RectAlign::LEFT]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + reset_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, crate::i18n::tr("Restore defaults"))); + reset_clicked = changed && reset_response.clicked(); + reset_hovered = reset_response.hovered(); + } + if response.clicked() && !reset_clicked { + open = !open; + self.ui.data_mut(|data| data.insert_temp(id, open)); + } + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(band, CornerRadius::ZERO, self.band_fill()); + painter.line_segment([band.left_top(), band.right_top()], Stroke::new(1.0, tokens.separator)); + painter.line_segment([band.left_bottom(), band.right_bottom()], Stroke::new(1.0, tokens.separator)); + let center_y = rect.center().y; + painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if let Some(changed) = reset { + // The round section reset, as on a section caption: faint where it does nothing + let color = self.reset_glyph_color(changed, reset_hovered, tokens.text_strong); + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + } + if let Some(value) = value { + let shown = + painter.text(pos2(self.right - BAND_VALUE_INSET, center_y), Align2::RIGHT_CENTER, value, FontId::proportional(TEXT_SIZE), tokens.text_dim); + if let Some(draw) = picture { + let left = shown.left() - BAND_PICTURE_AIR - BAND_PICTURE_SIZE; + draw(painter, Rect::from_min_size(pos2(left, center_y - BAND_PICTURE_SIZE / 2.0), vec2(BAND_PICTURE_SIZE, BAND_PICTURE_SIZE))); + } + } + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + + self.drawn(band.bottom()); + self.space(GROUP_GAP); + self.air_at = Some(self.cursor_y()); + BandResponse { open, reset: reset_clicked } + } + + /// Ends [`Self::hold_card`] and closes the held card + pub(crate) fn release_card(&mut self) { + self.held = false; + self.close_card(); + } + + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted + pub(crate) fn close_card(&mut self) { + if self.held { + return; + } + + let Some(card) = self.card.take() else { return }; + + self.scope = self.band_scope; + + let bottom = self.drawn_bottom + CARD_PADDING; + let face = Rect::from_min_max(pos2(self.left - CARD_BLEED, card.top), pos2(self.right + CARD_BLEED, bottom)); + self.ui.painter().set(card.face, Shape::rect_filled(face, CornerRadius::same(CARD_RADIUS), self.tokens.row)); + let below = bottom + GROUP_GAP - self.cursor_y(); + self.space(below.max(0.0)); + self.air_at = Some(self.cursor_y()); + } +} diff --git a/crates/ui-egui/src/property_sheet/hold_pad.rs b/crates/ui-egui/src/property_sheet/hold_pad.rs new file mode 100644 index 00000000..24fd7dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/hold_pad.rs @@ -0,0 +1,34 @@ +//! A picture that is also a press-and-hold surface: a badge in its corner says so, and the edge and badge light while hovered or held + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, vec2}; + +use super::PropertySheet; + +/// Side of the badge in the picture's bottom-right corner, and its inset from the picture's edges +const BADGE_SIZE: f32 = 16.0; +const BADGE_INSET: f32 = 4.0; +const BADGE_ROUNDING: u8 = 3; + +/// Size of the badge's glyph +const BADGE_GLYPH_SIZE: f32 = 11.0; + +impl PropertySheet<'_> { + /// Makes the already painted `picture` a press-and-hold surface named `name`, marked by `glyph` in a badge; `held` lights it as hover does. It follows a drag that starts on it, wherever the pointer goes + pub(crate) fn hold_pad(&mut self, picture: Rect, glyph: &str, name: &str, held: bool) -> Response { + let id = self.next_id(); + let response = self.ui.interact(picture, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, name)); + + let tokens = self.tokens; + let lit = held || response.hovered(); + let painter = self.ui.painter(); + let badge = Rect::from_min_size(picture.right_bottom() - vec2(BADGE_INSET + BADGE_SIZE, BADGE_INSET + BADGE_SIZE), vec2(BADGE_SIZE, BADGE_SIZE)); + let (fill, edge) = if lit { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + painter.rect(badge, CornerRadius::same(BADGE_ROUNDING), fill, Stroke::new(1.0, edge), StrokeKind::Inside); + painter.text(badge.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(BADGE_GLYPH_SIZE), tokens.text); + if lit { + painter.rect_stroke(picture, 0, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } + response + } +} diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs new file mode 100644 index 00000000..b18c0513 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -0,0 +1,86 @@ +use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use crate::theme::HARD_SHADOW; + +/// The i's slot at the panel edge; a row with an i at its left starts this much further right +pub(super) const INFO_SLOT: f32 = 16.0; + +/// The i's centre, from the panel's left padding +const INFO_CENTER: f32 = 6.0; + +/// Size of the i glyph +const INFO_ICON_SIZE: f32 = 13.0; + +/// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch +const TIP_VALUE_ROOM: f32 = 70.0; + +/// How far the tooltip reaches up into its row +const TIP_OVERLAP: f32 = 2.0; + +/// The tooltip's text padding, line pitch, rounding and shadow +const TIP_MARGIN: Margin = Margin::symmetric(8, 5); +const TIP_LINE_HEIGHT: f32 = 15.0; +const TIP_ROUNDING: u8 = 5; +const TIP_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +impl<'u> PropertySheet<'u> { + /// Gives the next row led by a label or picture an i at the panel edge that explains it on hover; its lead and its child rows move right to make room + pub(crate) fn info(&mut self, tip: &'u str) -> &mut Self { + self.info = Some(tip); + self + } + + /// How far the next row's lead moves right: past a pending i + pub(super) fn lead_shift(&self) -> f32 { + if self.info.is_some() { INFO_SLOT } else { 0.0 } + } + + /// Paints the pending i at the panel edge on the row centred at `center_y`, and its tooltip while the pointer rests on it + pub(super) fn paint_info(&mut self, center_y: f32) { + self.paint_info_in(self.left, self.left + INFO_CENTER, center_y); + } + + /// [`Self::paint_info`] at the row's right end, the i's right edge on the values' edge + pub(super) fn paint_info_at_end(&mut self, center_y: f32) { + self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); + } + + /// Paints the pending i at `glyph_x` in its slot from `slot_left` + fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { + let Some(tip) = self.info.take() else { return }; + let row_top = center_y - ROW_HEIGHT / 2.0; + let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(pos2(glyph_x, center_y), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Under the row from the i, ending before the value column; above it where the window ends first + let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(1.0, tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW); + let text_width = anchor.width() - TIP_MARGIN.sum().x; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::BOTTOM_START) + .align_alternatives(&[RectAlign::TOP_START]) + .gap(-TIP_OVERLAP) + .frame(frame) + .width(text_width); + tooltip.show(|ui| { + ui.set_width(text_width); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 53afe419..cbd25d6a 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,8 +1,216 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod axis_rows; +mod band_response; +mod button_icon; +mod choice; +mod eye_toggle; +mod group; +mod hold_pad; +mod info_icon; +mod number_field; +mod open_card; +mod preview_block; +mod preview_edit; +mod preview_lower; +mod preview_size; +mod row; +mod row_lead; mod section_tabs; +mod sheet_measure; +mod slider; +mod slot; +mod stack_slider; +mod switch_control; +mod tooltip; +mod track; +mod value_text; pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; +#[cfg(test)] +mod tests; + +pub(crate) use band_response::BandResponse; +pub(crate) use button_icon::ButtonIcon; +pub(crate) use number_field::NumberField; +pub(crate) use preview_lower::PreviewLower; +pub(crate) use preview_size::PreviewSize; +pub(crate) use row_lead::RowLead; +pub(crate) use stack_slider::StackSlider; + +use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; + +use crate::theme::{Tokens, semibold}; +use open_card::OpenCard; +use sheet_measure::SheetMeasure; /// Side padding: every row starts and ends this far inside the panel pub(crate) const PAD: f32 = 12.0; + +/// Row pitch: every control row is one box this tall with its control centred +pub(crate) const ROW_HEIGHT: f32 = 28.0; + +/// Height of dropdowns, fields, switches and buttons +const CONTROL_HEIGHT: f32 = 24.0; + +/// Air between groups and after loose rows +const GROUP_GAP: f32 = 6.0; + +/// The narrowest label column, from the panel's left padding to the controls +const LABEL_COLUMN_MIN: f32 = 90.0; + +/// Labels wider than this stack above a full-width control and never widen the column +const LABEL_MAX: f32 = 132.0; + +/// Air between the widest label and the controls column +const LABEL_TO_CONTROL: f32 = 12.0; + +/// A label fits beside its control when it leaves at least this much air before the column +const LABEL_MIN_AIR: f32 = 8.0; + +/// The least air a loose label leaves before the controls column +const LOOSE_LABEL_AIR: f32 = 2.0; + +/// The narrowest value column at a slider's right end +const VALUE_MIN_WIDTH: f32 = 26.0; + +/// Air between a slider track's end and the value column, room for the knob and a gap +const TRACK_TO_VALUE: f32 = 14.0; + +/// Size of regular labels and SemiBold values +const TEXT_SIZE: f32 = 12.0; + +/// Size of captions, pill names and the switch's words +const SMALL_TEXT_SIZE: f32 = 11.0; + +/// Size of the caret and small glyphs drawn as icons +const ICON_SIZE: f32 = 12.0; + +/// Size of a picture row's picture, and the air after it +const ROW_PICTURE_SIZE: f32 = 18.0; +const ROW_PICTURE_AIR: f32 = 8.0; + +/// How far above and below a row's centre a slider track or a typed value takes the pointer +const ROW_HIT_HALF_HEIGHT: f32 = 10.0; + +/// Corner radius of dropdowns, fields and buttons +const CONTROL_RADIUS: u8 = 4; + +/// Air above and below a picture block, as a control has in its row +const BLOCK_MARGIN: f32 = 2.0; + +/// The Properties panel being laid out this frame: where the controls column is, which card is open, and what this frame measured for the next one +pub(crate) struct PropertySheet<'u> { + pub(crate) ui: &'u mut Ui, + tokens: Tokens, + id: Id, + scope: Id, + band_scope: Id, + named: Vec, + left: f32, + right: f32, + used: SheetMeasure, + seen: SheetMeasure, + card: Option, + air_at: Option, + drawn_bottom: f32, + empty: bool, + sections: Vec<(String, f32)>, + info: Option<&'u str>, + held: bool, +} + +impl<'u> PropertySheet<'u> { + /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen + pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let id = ui.make_persistent_id(id_salt); + let used = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { + tokens: Tokens::get(ui.ctx()), + id, + scope: id, + band_scope: id, + named: Vec::new(), + left: rect.left() + PAD, + right: rect.right() - PAD, + used, + seen: SheetMeasure::default(), + card: None, + air_at: None, + drawn_bottom: rect.top(), + empty: true, + sections: Vec::new(), + info: None, + held: false, + ui, + }; + let result = body(&mut sheet); + sheet.close_card(); + if !sheet.sections.is_empty() { + let view_top = sheet.ui.clip_rect().top(); + section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); + } + + let seen = sheet.seen; + if seen != used { + sheet.ui.data_mut(|data| data.insert_temp(id, seen)); + sheet.ui.ctx().request_discard("Properties columns changed"); + } + result + } + + /// The controls column: wide enough for this panel's labels, capped at [`LABEL_MAX`] + fn column(&self) -> f32 { + self.left + LABEL_COLUMN_MIN.max(self.used.label_width + LABEL_TO_CONTROL) + } + + /// Where the knob of a slider's track ends: left of this panel's widest value + fn track_end(&self) -> f32 { + self.right - self.used.value_width.max(VALUE_MIN_WIDTH) - TRACK_TO_VALUE + } + + /// Records a value's width for the panel's value column + fn measure_value(&mut self, text: &str) { + let width = self.text_width(text, semibold(TEXT_SIZE)); + self.seen.value_width = self.seen.value_width.max(width); + } + + fn text_width(&self, text: &str, font: FontId) -> f32 { + self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x + } + + /// Takes the next `height` pixels of the panel, full width; marks what it draws down to + fn take(&mut self, height: f32) -> Rect { + let (rect, _) = self.ui.allocate_exact_size(vec2(self.ui.available_width(), height), egui::Sense::hover()); + self.empty = false; + rect + } + + /// Leaves `height` pixels of air + fn space(&mut self, height: f32) { + self.ui.add_space(height); + } + + fn cursor_y(&self) -> f32 { + self.ui.cursor().top() + } + + /// Notes that something was painted down to `bottom`, so an open card ends its padding below it + fn drawn(&mut self, bottom: f32) { + self.drawn_bottom = self.drawn_bottom.max(bottom); + } + + /// A control's box: [`CONTROL_HEIGHT`] tall, centred in its row, from `x0` to the right edge + fn control_box(&self, x0: f32, center_y: f32) -> Rect { + Rect::from_min_max(pos2(x0, center_y - CONTROL_HEIGHT / 2.0), pos2(self.right, center_y + CONTROL_HEIGHT / 2.0)) + } + + /// The colour of a top-level band: between the window frame and a card + fn band_fill(&self) -> Color32 { + let tokens = &self.tokens; + let mid = |a: u8, b: u8| ((u16::from(a) + u16::from(b)) / 2) as u8; + Color32::from_rgb(mid(tokens.chrome.r(), tokens.row.r()), mid(tokens.chrome.g(), tokens.row.g()), mid(tokens.chrome.b(), tokens.row.b())) + } +} diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs new file mode 100644 index 00000000..22337ebb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -0,0 +1,212 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air between neighbouring fields of one row +const FIELD_GAP: f32 = 4.0; + +/// Room kept at the row's end for the link button, on every row of a group that has one +const LINK_SLOT: f32 = 26.0; + +/// Size of the link button +pub(super) const LINK_SIZE: f32 = 18.0; + +/// From a field's left edge to its axis letter's left edge +const TAG_LETTER_INSET: f32 = 7.0; + +/// From a field's left edge to its glyph's centre +const TAG_GLYPH_CENTER: f32 = 10.0; + +/// From a field's right edge to its value's right end +const VALUE_INSET: f32 = 6.0; + +/// Least air between a field's tag and its value: a value that would come closer drops decimals +const TAG_VALUE_GAP: f32 = 5.0; + +/// One part of a row of number fields: its tag (an axis letter in its colour, or a glyph) and value +pub(crate) struct NumberField<'a> { + pub(crate) tag: &'a str, + + /// The axis letter's colour; `None` draws `tag` as a dim glyph + pub(crate) tag_color: Option, + + pub(crate) value: f32, + + /// Change per pixel dragged + pub(crate) speed: f32, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} + +/// The air between a field's axis tag and its typing box +const TAG_TO_TYPING: f32 = 6.0; + +impl PropertySheet<'_> { + /// A row of number fields (drag or type); returns the edited index and whether it continues a drag + pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { + let (control, center_y) = self.row(label); + let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let count = fields.len().max(1) as f32; + let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; + + let mut edited = None; + for (index, field) in fields.iter_mut().enumerate() { + let left = control.left() + index as f32 * (width + FIELD_GAP); + let rect = Rect::from_min_size(pos2(left, control.top()), vec2(width, control.height())); + if let Some(merge) = self.number_field(rect, label, field) { + edited = Some((index, merge)); + } + } + + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// The link that keeps two values together; returns whether it was clicked + pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *linked, crate::i18n::tr("Link"))); + let response = self.tip(response, crate::i18n::tr("Link")); + if response.clicked() { + *linked = !*linked; + } + + let tokens = self.tokens; + let (fill, border) = if *linked { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + response.clicked() + } + + /// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X") + fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option { + let id = self.next_id(); + let typing_id = id.with("typed"); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + match field.tag_color { + Some(color) => { + painter.text(pos2(rect.left() + TAG_LETTER_INSET, rect.center().y), Align2::LEFT_CENTER, field.tag, semibold(SMALL_TEXT_SIZE), color); + } + None => { + painter.text( + pos2(rect.left() + TAG_GLYPH_CENTER, rect.center().y), + Align2::CENTER_CENTER, + field.tag, + FontId::proportional(ICON_SIZE), + tokens.text_dim, + ); + } + } + + let decimals = field.decimals; + if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { + let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit); + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + return None; + } + + let untouched = self.end_typing(typing_id, &text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || text.trim() == shown_number(field.value, decimals) { + return None; + } + + let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?; + if !typed.is_finite() || typed == field.value { + return None; + } + + field.value = typed; + return Some(false); + } + + self.skip_typing_edit(); + let response = self.ui.interact(rect, id, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(field.value), format!("{label} {}", field.tag))); + let tag_right = match field.tag_color { + Some(_) => rect.left() + TAG_LETTER_INSET + painter.layout_no_wrap(field.tag.to_owned(), semibold(SMALL_TEXT_SIZE), tokens.text).size().x, + None => rect.left() + TAG_GLYPH_CENTER + ICON_SIZE / 2.0, + }; + let room = rect.right() - VALUE_INSET - tag_right - TAG_VALUE_GAP; + let shown = fitting_number(field.value, decimals, field.suffix, room, |text| { + painter.layout_no_wrap(text.to_owned(), semibold(TEXT_SIZE), tokens.text).size().x + }); + painter.text(pos2(rect.right() - VALUE_INSET, rect.center().y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + if response.hovered() || response.dragged() { + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + + if response.clicked() { + self.start_typing(typing_id, shown_number(field.value, decimals)); + return None; + } + + if response.dragged() { + crate::pointer_lock::ask_for_hold(self.ui.ctx()); + } + let delta = response.drag_delta().x; + let moved = response.dragged() && delta != 0.0; + if moved { + field.value += delta * field.speed; + } + crate::widgets::press_edit(self.ui, response.id, moved) + } +} + +/// `value` and `suffix` with up to `decimals` decimals, as many as fit `room` wide (as measured by `width`), at least none +fn fitting_number(value: f32, decimals: usize, suffix: &str, room: f32, width: impl Fn(&str) -> f32) -> String { + let mut decimals = decimals; + loop { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + if decimals == 0 || width(&shown) <= room { + return shown; + } + + decimals -= 1; + } +} + +/// `value` with `decimals` decimals, a value that rounds to zero reading 0 without a minus sign +pub(super) fn shown_number(value: f32, decimals: usize) -> String { + let shown = format!("{value:.decimals$}"); + let zero = shown.trim_start_matches('-').chars().all(|digit| matches!(digit, '0' | '.')); + if zero { shown.trim_start_matches('-').to_owned() } else { shown } +} + +#[cfg(test)] +mod tests { + use super::fitting_number; + + /// Every character is 7 wide + fn width(text: &str) -> f32 { + 7.0 * text.chars().count() as f32 + } + + #[test] + fn a_value_too_wide_for_its_field_drops_decimals_before_it_reaches_the_tag() { + assert_eq!(fitting_number(1.0, 2, "", 28.0, width), "1.00"); + assert_eq!(fitting_number(1.0, 2, "", 27.0, width), "1.0"); + assert_eq!(fitting_number(-12.5, 2, "°", 30.0, width), "-12°"); + assert_eq!(fitting_number(12345.0, 2, "", 1.0, width), "12345"); + } +} diff --git a/crates/ui-egui/src/property_sheet/open_card.rs b/crates/ui-egui/src/property_sheet/open_card.rs new file mode 100644 index 00000000..2063742d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/open_card.rs @@ -0,0 +1,10 @@ +use egui::layers::ShapeIdx; + +/// A card whose rows are being laid out; its face is painted behind them once they end +pub(super) struct OpenCard { + /// Where the card starts + pub(super) top: f32, + + /// The placeholder the card's face is painted into, behind its rows + pub(super) face: ShapeIdx, +} diff --git a/crates/ui-egui/src/property_sheet/preview_block.rs b/crates/ui-egui/src/property_sheet/preview_block.rs new file mode 100644 index 00000000..e76045cf --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_block.rs @@ -0,0 +1,153 @@ +use egui::{Align2, FontId, Painter, Rect, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::LINK_SIZE; +use super::preview_edit::PreviewEdit; +use super::preview_lower::PreviewLower; +use super::preview_size::PreviewSize; +use super::row::CAPTION_LINE; +use super::track::Track; +use super::{BLOCK_MARGIN, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE}; + +/// One slider line beside the preview square +const PART_LINE: f32 = 22.0; + +/// Air between the size and what follows it +const PART_GAP: f32 = 6.0; + +/// From the block's top to the square's top: the first caption's letters +const SQUARE_TOP: f32 = 4.0; + +/// The square stops this far above the block's bottom: the last knob's bottom +const SQUARE_SHORTER: f32 = 10.0; + +/// Air between the square and the controls beside it +const SQUARE_TO_SIDE: f32 = 12.0; + +/// From the side's left edge to a direction glyph's centre, and to the track after it +const GLYPH_CENTER: f32 = 5.0; +const GLYPH_TRACK: f32 = 18.0; + +/// Room kept at the right edge for the link, on every line, so the tracks end together +pub(super) const LINK_ROOM: f32 = 24.0; + +/// The value column's width beside the square: every track ends this far left of the value's end +const SIDE_VALUE_WIDTH: f32 = 46.0; + +/// The air kept between a side slider's track and its value +const SIDE_VALUE_AIR: f32 = 8.0; + +impl PropertySheet<'_> { + /// A preview square beside its stack (the size, then Offset or one setting), exactly as tall as the stack + pub(crate) fn preview_block(&mut self, picture: &dyn Fn(&Painter, Rect), size: PreviewSize<'_>, lower: PreviewLower<'_>) -> PreviewEdit { + let size_rows = if *size.linked { 1 } else { 2 }; + let lower_rows = match lower { + PreviewLower::Offset { .. } => 2, + PreviewLower::Slider { .. } => 1, + }; + let height = CAPTION_LINE + PART_LINE * size_rows as f32 + PART_GAP + CAPTION_LINE + PART_LINE * lower_rows as f32; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let top = block.top(); + + let side = (height - SQUARE_SHORTER).max(1.0); + let square = Rect::from_min_size(pos2(self.left, top + SQUARE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let x0 = square.right() + SQUARE_TO_SIDE; + let value_right = self.right - LINK_ROOM; + let track_end = value_right - SIDE_VALUE_WIDTH; + let mut edit = PreviewEdit { square, size: None, lower: None }; + let mut y = top; + + self.side_caption(x0, y, size.label); + y += CAPTION_LINE; + let linked = *size.linked; + for part in 0..size_rows { + let center_y = y + PART_LINE / 2.0; + let start = if linked { x0 } else { self.direction_glyph(x0, center_y, part) }; + let mut value = size.values[part]; + let label = format_args!("{}{}", size.label, part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut value, (&size.range, &size.typed), size.decimals, false) + { + size.values[part] = value; + if linked { + size.values[1] = value; + } + edit.size = Some(merge); + } + y += PART_LINE; + } + let link_center = pos2(self.right - LINK_SIZE / 2.0, y - PART_LINE / 2.0); + if self.link_button(link_center, size.linked) && *size.linked && size.values[1] != size.values[0] { + size.values[1] = size.values[0]; + edit.size = Some(false); + } + y += PART_GAP; + + match lower { + PreviewLower::Offset { values, range, typed } => { + let offset = crate::i18n::tr("Offset"); + self.side_caption(x0, y, offset); + y += CAPTION_LINE; + for part in 0..2 { + let center_y = y + PART_LINE / 2.0; + let start = self.direction_glyph(x0, center_y, part); + let label = format_args!("{offset}{}", part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut values[part], (&range, &typed), 2, true) { + edit.lower = Some(merge); + } + y += PART_LINE; + } + } + PreviewLower::Slider { label, value, range, decimals } => { + self.side_caption(x0, y, label); + y += CAPTION_LINE; + if let Some(merge) = self.side_slider(label, x0, track_end, value_right, y + PART_LINE / 2.0, value, (&range, &range), decimals, false) { + edit.lower = Some(merge); + } + } + } + self.drawn(square.bottom()); + self.space(BLOCK_MARGIN); + edit + } + + fn side_caption(&self, x: f32, top: f32, text: &str) { + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x, top + CAPTION_LINE / 2.0), Align2::LEFT_CENTER, text, FontId::proportional(SMALL_TEXT_SIZE), dim); + } + + /// The ⇄ (across) or ⇅ (down) glyph before a part's track; returns where the track starts + fn direction_glyph(&self, x0: f32, center_y: f32, part: usize) -> f32 { + let glyph = if part == 0 { ic::ARROWS_LEFT_RIGHT } else { ic::ARROWS_DOWN_UP }; + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x0 + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), dim); + x0 + GLYPH_TRACK + } + + #[allow(clippy::too_many_arguments)] + fn side_slider( + &mut self, + label: impl std::fmt::Display, + start: f32, + end: f32, + value_right: f32, + center_y: f32, + value: &mut f32, + (range, typed_range): (&std::ops::RangeInclusive, &std::ops::RangeInclusive), + decimals: usize, + signed: bool, + ) -> Option { + let id = self.next_id(); + let dragged = self.track(id, &label, &Track { start, end, center_y, zero: signed.then_some(0.0), ramp: false }, value, range); + let typed = self.value_field_at(id, &label, value_right, SIDE_VALUE_WIDTH - SIDE_VALUE_AIR, center_y, *value, typed_range, decimals, ""); + Self::apply_typed(value, typed, dragged) + } +} + +/// What a part's name adds to its caption: nothing for the first, " 2" for the second +fn part_suffix(part: usize) -> &'static str { + if part == 0 { "" } else { " 2" } +} diff --git a/crates/ui-egui/src/property_sheet/preview_edit.rs b/crates/ui-egui/src/property_sheet/preview_edit.rs new file mode 100644 index 00000000..8ba1324f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_edit.rs @@ -0,0 +1,8 @@ +/// What a preview block's controls changed this frame (`Some(merge)` per edited part), and where its square is +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PreviewEdit { + /// Where the preview square sits, for a surface over it + pub(crate) square: egui::Rect, + pub(crate) size: Option, + pub(crate) lower: Option, +} diff --git a/crates/ui-egui/src/property_sheet/preview_lower.rs b/crates/ui-egui/src/property_sheet/preview_lower.rs new file mode 100644 index 00000000..085ff6c5 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_lower.rs @@ -0,0 +1,10 @@ +use std::ops::RangeInclusive; + +/// What sits under the size beside a preview square +pub(crate) enum PreviewLower<'a> { + /// Offset across and down, signed + Offset { values: &'a mut [f32; 2], range: RangeInclusive, typed: RangeInclusive }, + + /// One other setting (tri-planar Hardness) + Slider { label: &'a str, value: &'a mut f32, range: RangeInclusive, decimals: usize }, +} diff --git a/crates/ui-egui/src/property_sheet/preview_size.rs b/crates/ui-egui/src/property_sheet/preview_size.rs new file mode 100644 index 00000000..c2ebc45e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_size.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// The size beside a preview square: one slider while linked, one per direction otherwise +pub(crate) struct PreviewSize<'a> { + /// The caption above it (Tiling, Size (cm), Scaling) + pub(crate) label: &'a str, + + /// Across and down; while linked, down follows across + pub(crate) values: &'a mut [f32; 2], + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may be: wider than the track + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + pub(crate) linked: &'a mut bool, +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs new file mode 100644 index 00000000..28af9dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -0,0 +1,236 @@ +use egui::{Align2, FontId, Id, Rect, Response, Sense, Stroke, pos2}; +use egui_phosphor::regular as ic; + +use super::{ + CONTROL_HEIGHT, ICON_SIZE, LABEL_MAX, LABEL_MIN_AIR, LOOSE_LABEL_AIR, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, + SMALL_TEXT_SIZE, TEXT_SIZE, +}; +use crate::theme::semibold; + +/// Air above a stacked label +const STACK_AIR: f32 = 4.0; + +/// Height of a stacked label's line, from its air to the control row under it +const STACK_LABEL_LINE: f32 = 14.0; + +/// A stacked label's centre below its line's top +const STACK_LABEL_CENTER: f32 = 8.0; + +/// A caption line's height +pub(super) const CAPTION_LINE: f32 = 18.0; + +/// How far small text reaches below its centre line +const SMALL_TEXT_HALF_LINE: f32 = 6.0; + +/// The square a row-end glyph answers the pointer in +const GLYPH_BOX: f32 = 20.0; + +/// Air above a section caption that follows other rows, and the hairline's distance below it +const SECTION_AIR: f32 = 6.0; + +/// The hairline above a later section caption, to the caption's top +pub(super) const SECTION_RULE_TO_CAPTION: f32 = 12.0; + +/// Air above the panel's first section caption +const FIRST_SECTION_AIR: f32 = 12.0; + +/// Height of a section caption's line, including the air under it +const SECTION_CAPTION_LINE: f32 = 24.0; + +/// From a section caption's line top to its text's centre +pub(super) const SECTION_CAPTION_CENTER: f32 = 7.0; + +/// Size of a section's menu glyph +const SECTION_MENU_ICON_SIZE: f32 = 14.0; + +/// Distance from the right edge to the centre of a right-edge glyph (caret, menu) +pub(super) const EDGE_GLYPH_INSET: f32 = 6.0; + +/// Size of the round reset glyph on a section caption or a band +pub(super) const RESET_ICON_SIZE: f32 = 14.0; + +/// Opacity of a reset glyph at the defaults, where it does nothing +const RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// From the right edge to the centre of a section caption's reset: its 14 px glyph ends at the dropdowns' right edge +const SECTION_RESET_INSET: f32 = RESET_ICON_SIZE / 2.0; + +impl PropertySheet<'_> { + /// [`Self::section`] with the round section reset at the caption's right end: faint and inert at the defaults (`changed` false); returns whether it was clicked + pub(crate) fn section_reset(&mut self, title: &str, changed: bool) -> bool { + let text = self.tokens.text; + let center_y = self.section_caption(title, text); + + let glyph = Rect::from_center_size(pos2(self.right - SECTION_RESET_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_reset", title)); + let sense = if changed { Sense::click() } else { Sense::hover() }; + let response = self.ui.interact(glyph, id, sense); + + let label = crate::i18n::tr("Reset to defaults"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, format_args!("{title}: {label}"))); + + if changed { + // Left of the glyph, on the caption's line: it covers no value + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(glyph).align(egui::RectAlign::LEFT).align_alternatives(&[egui::RectAlign::BOTTOM_END]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + + let color = self.reset_glyph_color(changed, response.hovered(), self.tokens.text_strong); + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + changed && response.clicked() + } + + /// A reset or clear glyph's colour: faint where it does nothing (`live` false), `hover_color` under the pointer, dim otherwise + pub(super) fn reset_glyph_color(&self, live: bool, hovered: bool, hover_color: egui::Color32) -> egui::Color32 { + match (live, hovered) { + (false, _) => self.tokens.text_dim.gamma_multiply(RESET_AT_DEFAULT_OPACITY), + (true, true) => hover_color, + (true, false) => self.tokens.text_dim, + } + } + + /// [`Self::section`] with its caption in `color` + pub(super) fn section_in(&mut self, title: &str, menu: bool, color: egui::Color32) -> Option { + let center_y = self.section_caption(title, color); + if !menu { + return None; + } + + let glyph = Rect::from_center_size(pos2(self.right - EDGE_GLYPH_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_menu", title)); + let response = self.ui.interact(glyph, id, Sense::click()); + let color = if response.hovered() { self.tokens.text } else { self.tokens.text_dim }; + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::LIST, FontId::proportional(SECTION_MENU_ICON_SIZE), color); + Some(response) + } + + /// A section caption in capitals in `color`, a hairline above a later one; returns the caption's centre line + fn section_caption(&mut self, title: &str, color: egui::Color32) -> f32 { + self.close_card(); + + // Named state before the section's first band is keyed by the section, not by the band above it + if self.card.is_none() { + let section = self.id.with(("section", title)); + self.band_scope = section; + self.scope = section; + } + + if !self.empty { + self.space(SECTION_AIR); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(SECTION_RULE_TO_CAPTION); + } else { + self.space(FIRST_SECTION_AIR); + } + + let rect = self.take(SECTION_CAPTION_LINE); + self.sections.push((title.to_owned(), rect.top())); + if super::section_tabs::take_jump(self.ui, title) { + // Scroll by the distance itself: a top-aligned scroll_to_rect stops short by the scroll area's item spacing, which the sheet cannot see + let hairline = rect.top() - SECTION_RULE_TO_CAPTION; + let to_top = self.ui.clip_rect().top() - hairline; + self.ui.scroll_with_delta(egui::vec2(0.0, to_top)); + } + + let center_y = rect.top() + SECTION_CAPTION_CENTER; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), color); + self.drawn(center_y + SMALL_TEXT_HALF_LINE); + self.air_at = None; + center_y + } + + /// One setting's row: label beside the controls column or stacked above; returns the control's box and centre + pub(crate) fn row(&mut self, label: &str) -> (Rect, f32) { + self.row_with(RowLead::label(label)) + } + + /// [`Self::row`] led by `lead` + pub(crate) fn row_with(&mut self, lead: RowLead<'_>) -> (Rect, f32) { + let x0 = self.lead_with(lead); + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let picture = matches!(lead, RowLead::Picture { .. }); + self.drawn(center_y + if picture { ROW_PICTURE_SIZE } else { CONTROL_HEIGHT } / 2.0); + (self.control_box(x0, center_y), center_y) + } + + /// Paints a row's lead and returns where its control starts; pictures and children never widen the column + pub(crate) fn lead_with(&mut self, lead: RowLead<'_>) -> f32 { + let font = FontId::proportional(TEXT_SIZE); + let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; + let shift = self.lead_shift(); + let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; + let (label, stack, text_color) = match lead { + RowLead::Label { text, stack } => (text, stack, self.tokens.text), + RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Loose(text) => return self.stacked_label(text, shift), + RowLead::Picture { picture, text } => { + self.paint_info(center_y); + let square = Rect::from_center_size(pos2(self.left + shift + ROW_PICTURE_SIZE / 2.0, center_y), egui::vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Child(text) => { + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text_dim); + return self.column(); + } + }; + + // The i's slot counts as part of the label + let width = shift + self.text_width(label, font.clone()); + if width <= LABEL_MAX { + self.seen.label_width = self.seen.label_width.max(width); + } + + if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); + return self.column(); + } + + self.stacked_label(label, shift) + } + + /// Paints `label` on its own line above a full-width control, `shift` right of the edge after its i; returns the control's left edge + fn stacked_label(&mut self, label: &str, shift: f32) -> f32 { + self.space(STACK_AIR); + let rect = self.take(STACK_LABEL_LINE); + let center_y = rect.top() + STACK_LABEL_CENTER; + self.paint_info(center_y); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + self.left + } + + /// A caret pointing down (open) or right (folded), centred on `center` + pub(super) fn caret(&self, center: egui::Pos2, open: bool, color: egui::Color32) { + let glyph = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + self.ui.painter().text(center, Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), color); + } + + /// The next control's id: stable while the panel shows the same rows + pub(super) fn next_id(&mut self) -> Id { + let id = self.ui.next_auto_id(); + self.ui.skip_ahead_auto_ids(1); + id + } + + /// The id of a group or colour bar whose state outlives the frame: keyed by its name inside the open band and card, so rows shown or hidden above it never hand it another's state + pub(super) fn named_id(&mut self, kind: &str, title: &str) -> Id { + let mut id = self.scope.with((kind, title)); + + // A repeated name in one scope (two cards of one effect) takes the next free id + while self.named.contains(&id) { + id = id.with(kind); + } + self.named.push(id); + id + } +} diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs new file mode 100644 index 00000000..5d3b981c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -0,0 +1,30 @@ +use egui::{Painter, Rect}; + +/// What leads a setting's row, left of its control +#[derive(Clone, Copy)] +pub(crate) enum RowLead<'a> { + /// A label beside the controls column; it stacks above a full-width control when it doesn't fit, or always with `stack` + Label { text: &'a str, stack: bool }, + + /// A label beside the controls column that never widens it; it stacks only when it can't fit with [`super::LOOSE_LABEL_AIR`] before the column + Loose(&'a str), + + /// A picture at the left edge with its label after it (culling rows) + Picture { picture: &'a dyn Fn(&Painter, Rect), text: &'a str }, + + /// A setting of the row above, dim, its label on the label column like its parent's + Child(&'a str), +} + +impl<'a> RowLead<'a> { + /// A label beside the controls column + pub(crate) fn label(text: &'a str) -> RowLead<'a> { + RowLead::Label { text, stack: false } + } + + /// The row's name, as assistive tech reads it + pub(crate) fn text(self) -> &'a str { + match self { + } + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 5b7d6187..99edf990 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -1,13 +1,116 @@ use egui::{CornerRadius, Painter, Rect, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Painter, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use crate::theme::Tokens; +use super::row::SECTION_RULE_TO_CAPTION; +use super::{PAD, SMALL_TEXT_SIZE}; +use crate::theme::{Tokens, semibold}; + +mod section_scope; +mod section_tops; + +pub(crate) use section_scope::SectionScope; +pub(super) use section_tops::SectionTops; + +/// Height of the tab strip +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// From the panel's left edge to the first tab +const FIRST_TAB: f32 = PAD - FIRST_TAB_OUTDENT; + +/// A tab's width beyond its name: icon and air (the resource picker's tabs share these measures) +pub(crate) const TAB_PADDING: f32 = 38.0; + +/// Air between tabs +pub(crate) const TAB_GAP: f32 = 2.0; /// The chosen tab starts this far below the strip's top and reaches this far into the panel +pub(crate) const TAB_TOP: f32 = 4.0; const TAB_BELOW: f32 = 6.0; /// Corner rounding of the chosen tab pub(crate) const TAB_ROUNDING: u8 = 5; +/// From a tab's left edge to its icon's centre, and to its name +pub(crate) const TAB_ICON_CENTER: f32 = 14.0; +pub(crate) const TAB_NAME_LEFT: f32 = 26.0; + +/// Size of a tab's icon and of its name +pub(crate) const TAB_ICON_SIZE: f32 = 13.0; +pub(crate) const TAB_TEXT_SIZE: f32 = SMALL_TEXT_SIZE; + +/// A section counts as in view once its caption is this close to the top of the scrolled area +const IN_VIEW_SLACK: f32 = 30.0; + +/// Where the scope of the sections being drawn is kept while a strip's contents run +fn scope_id() -> Id { + Id::unique("property_sheet_section_scope") +} + +/// Where a strip keeps its section positions and the section one of its tabs asked to jump to +fn sections_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_sections").with(scope) +} + +fn jump_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_jump").with(scope) +} + +/// Runs `body` with its section captions tied to the `scope` strip +pub(crate) fn in_scope(ui: &mut Ui, scope: SectionScope, body: impl FnOnce(&mut Ui) -> R) -> R { + let outer = ui.data(|data| data.get_temp::(scope_id())); + ui.data_mut(|data| data.insert_temp(scope_id(), scope)); + let result = body(ui); + ui.data_mut(|data| data.insert_temp(scope_id(), outer.unwrap_or(SectionScope::Docked))); + result +} + +/// The strip the sections being drawn belong to: the docked panel's unless a caller said otherwise +fn current_scope(ui: &Ui) -> SectionScope { + ui.data(|data| data.get_temp::(scope_id())).unwrap_or(SectionScope::Docked) +} + +/// Stores this frame's section captions for the tabs +pub(super) fn remember(ui: &Ui, tops: SectionTops) { + let scope = current_scope(ui); + ui.data_mut(|data| data.insert_temp(sections_id(scope), tops)); +} + +/// Drops the captions the sheets stored last frame, so a list drawn without sections leaves none behind; call before drawing the list +pub(crate) fn forget_sections(ui: &Ui) { + let scope = current_scope(ui); + ui.data_mut(|data| data.remove::(sections_id(scope))); +} + +/// Room to leave under the sheets just drawn in `ui`'s scroll area so the last section's top can reach the top of the view +pub(crate) fn room_past_end(ui: &Ui) -> f32 { + let scope = current_scope(ui); + let last_top = ui.data(|data| data.get_temp::(sections_id(scope))).and_then(|tops| tops.last_top()); + let Some(last_top) = last_top else { return 0.0 }; + + // Where a jump to the section scrolls to: its hairline at the top + let reach = last_top - SECTION_RULE_TO_CAPTION; + (reach + ui.clip_rect().height() - ui.min_rect().bottom()).max(0.0) +} + +/// Whether a tab asked to show `title`: the caller scrolls to it once +pub(super) fn take_jump(ui: &Ui, title: &str) -> bool { + let jump = jump_id(current_scope(ui)); + let wanted = ui.data(|data| data.get_temp::(jump)).is_some_and(|wanted| wanted == title); + if wanted { + ui.data_mut(|data| data.remove::(jump)); + } + wanted +} + +/// A tab from `left` to `right` on `strip`: from just under the strip's top down into the panel the strip sits on +fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW)) +} + /// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) @@ -17,3 +120,36 @@ pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } + +/// The tab strip on the `scope` panel's top edge, top corners rounded by `top_corner`: one tab per section; a click scrolls to it +pub(crate) fn section_tabs(ui: &mut Ui, scope: SectionScope, top_corner: u8, tabs: &[(&str, &str)]) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + let corners = CornerRadius { nw: top_corner, ne: top_corner, sw: 0, se: 0 }; + ui.painter().rect_filled(strip, corners, tokens.chrome); + let seen = ui.data(|data| data.get_temp::(sections_id(scope))).unwrap_or_default(); + let lit = seen.lit(); + + let mut x = strip.left() + FIRST_TAB; + for (index, (icon, title)) in tabs.iter().enumerate() { + let on = lit.map_or(index == 0, |lit| lit == *title); + let width = ui.painter().layout_no_wrap((*title).to_owned(), semibold(TAB_TEXT_SIZE), Color32::WHITE).size().x + TAB_PADDING; + let tab = tab_rect(strip, x, x + width); + let response = ui.interact(tab, ui.scope_id().with(("section_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, *title)); + if response.clicked() { + ui.data_mut(|data| data.insert_temp(jump_id(scope), (*title).to_owned())); + } + + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, tab); + } + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(x + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, *icon, FontId::proportional(TAB_ICON_SIZE), color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(x + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, *title, font, color); + x += width + TAB_GAP; + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs new file mode 100644 index 00000000..5fe48e1f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -0,0 +1,8 @@ +/// Which strip the sections belong to: the docked panel and the right-click popup can show the same sections at once +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub(crate) enum SectionScope { + /// The docked Properties panel + Docked, + /// The right-click Properties popup over a view + Popup, +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs new file mode 100644 index 00000000..5165c7eb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs @@ -0,0 +1,21 @@ +use super::IN_VIEW_SLACK; + +/// The sections' captions seen last frame, top to bottom, and the top of the area they scroll in +#[derive(Clone, Default)] +pub(crate) struct SectionTops { + pub(crate) tops: Vec<(String, f32)>, + pub(crate) view_top: f32, +} + +impl SectionTops { + /// The section in view: the last caption at the top (the panel scrolls far enough for the last one to get there) + pub(crate) fn lit(&self) -> Option<&str> { + let reached = self.tops.iter().rev().find(|(_, top)| *top <= self.view_top + IN_VIEW_SLACK); + reached.or(self.tops.first()).map(|(title, _)| title.as_str()) + } + + /// The top of the last section's caption + pub(crate) fn last_top(&self) -> Option { + self.tops.last().map(|(_, top)| *top) + } +} diff --git a/crates/ui-egui/src/property_sheet/sheet_measure.rs b/crates/ui-egui/src/property_sheet/sheet_measure.rs new file mode 100644 index 00000000..e4a16d55 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/sheet_measure.rs @@ -0,0 +1,15 @@ +/// What one pass of a Properties panel measured, used to place the next pass's columns +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct SheetMeasure { + /// The widest label that sits beside its control + pub(super) label_width: f32, + + /// Where the widest toggle label ends, from the panel's left padding + pub(super) toggle_label_end: f32, + + /// Where the widest picture row's name ends, from the panel's left padding + pub(super) picture_label_end: f32, + + /// The widest value at a slider's right end + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs new file mode 100644 index 00000000..cfd35af1 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -0,0 +1,238 @@ +use std::ops::RangeInclusive; + + +use super::number_field::shown_number; +use super::track::Track; +use super::value_text::ValueText; +use crate::theme::semibold; + +/// Radius of a slider's knob +pub(super) const KNOB_RADIUS: f32 = 5.0; + +/// Width of a slider's knob outline +const KNOB_STROKE: f32 = 1.5; + +/// Width of a slider's track +const TRACK_WIDTH: f32 = 2.0; + +/// Half the height of a signed slider's zero tick +const ZERO_TICK_HALF: f32 = 4.0; + +/// Radius of an angle row's dial +const DIAL_RADIUS: f32 = 8.0; + +/// The quarter turn back from the screen's 0 rad (pointing right) that points the dial's hand straight up at 0° +const DIAL_ZERO_DEGREES: f32 = 90.0; + +/// Air between the dial and the value, and between the track's end and the dial +const DIAL_AIR: f32 = 6.0; + +impl PropertySheet<'_> { + /// [`Self::slider_with_suffix`] led by `lead` (a picture row, a child setting) + pub(crate) fn slider_led(&mut self, lead: RowLead<'_>, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, lead.text(), &track, value, &range); + let typed = self.value_field(id, lead.text(), center_y, *value, &range, decimals, suffix); + Self::apply_typed(value, typed, dragged) + } + + /// An angle in degrees: the track, then a small dial just before the value + pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_led(RowLead::label(label), degrees, range) + } + + /// [`Self::angle`] led by `lead` + pub(crate) fn angle_led(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_shown(lead, degrees, range, false) + } + + /// [`Self::angle_led`], the value shown with its sign when `plus` + fn angle_shown(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive, plus: bool) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; + let track = Track { + start: control.left() + KNOB_RADIUS, + end: dial_x - DIAL_RADIUS - DIAL_AIR, + center_y, + zero: (*range.start() < 0.0).then_some(0.0), + ramp: false, + }; + let name = lead.text(); + let dragged = self.track(id, name, &track, degrees, &range); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.circle_stroke(pos2(dial_x, center_y), DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); + let turn = (*degrees - DIAL_ZERO_DEGREES).to_radians(); + let hand = pos2(dial_x + DIAL_RADIUS * turn.cos(), center_y + DIAL_RADIUS * turn.sin()); + painter.line_segment([pos2(dial_x, center_y), hand], Stroke::new(TRACK_WIDTH, tokens.text)); + + let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); + Self::apply_typed(degrees, typed, dragged) + } + + /// A typed value wins over a drag in the same frame and starts its own undo step + pub(super) fn apply_typed(value: &mut f32, typed: Option, dragged: Option) -> Option { + match typed { + Some(typed) => { + *value = typed; + Some(false) + } + None => dragged, + } + } + + /// Paints a track with its knob and moves `value` while it is clicked or dragged + pub(super) fn track(&mut self, id: Id, label: impl std::fmt::Display, track: &Track, value: &mut f32, range: &RangeInclusive) -> Option { + let (minimum, maximum) = (*range.start(), *range.end()); + let span = (maximum - minimum).max(f32::EPSILON); + let length = (track.end - track.start).max(1.0); + let hit = Rect::from_min_max( + pos2(track.start - KNOB_RADIUS, track.center_y - ROW_HIT_HALF_HEIGHT), + pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), + ); + let response = self.ui.interact(hit, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + + let mut moved = false; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let picked = kept_in(minimum + (pointer.x - track.start) / length * span, range); + if picked != *value { + *value = picked; + moved = true; + } + } + + // A press's first change starts an undo step, its later changes continue it + let edit = crate::widgets::press_edit(self.ui, response.id, moved); + + let tokens = self.tokens; + let at = |v: f32| track.start + ((v - minimum) / span).clamp(0.0, 1.0) * length; + let knob_x = at(*value); + let zero_x = track.zero.map_or(track.start, |zero| at(kept_in(zero, range))); + let painter = self.ui.painter(); + if !track.ramp { + painter.line_segment([pos2(track.start, track.center_y), pos2(track.end, track.center_y)], Stroke::new(TRACK_WIDTH, tokens.button_border)); + painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, tokens.accent)); + } + if track.zero.is_some() { + let tick = [pos2(zero_x, track.center_y - ZERO_TICK_HALF), pos2(zero_x, track.center_y + ZERO_TICK_HALF)]; + painter.line_segment(tick, Stroke::new(1.0, tokens.text_dim)); + } + let outline = if response.hovered() || response.dragged() { tokens.accent } else { tokens.text }; + painter.circle(pos2(knob_x, track.center_y), KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, outline)); + edit + } + + /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field( + &mut self, + id: Id, + label: impl std::fmt::Display, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) + } + + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + #[allow(clippy::too_many_arguments)] + pub(super) fn column_value_field( + &mut self, + id: Id, + label: &dyn std::fmt::Display, + center_y: f32, + shown: &str, + suffix: &str, + value: f32, + range: &RangeInclusive, + decimals: usize, + ) -> Option { + self.measure_value(shown); + let width = self.used.value_width.max(super::VALUE_MIN_WIDTH); + self.value_text_field(id, ValueText { label, right: self.right, width, center_y, shown, suffix }, value, range, decimals) + } + + /// [`Self::value_field`] ending at `right`, `width` wide, outside the panel's value column + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field_at( + &mut self, + id: Id, + label: impl std::fmt::Display, + right: f32, + width: f32, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) + } + + /// A value drawn as `text.shown` that turns into a field when clicked; returns the typed value (its `text.suffix` and a leading "×" or "x" allowed), kept in `range` + pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive, decimals: usize) -> Option { + let ValueText { label, right, width, center_y, shown, suffix } = value_text; + let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT)); + let field_id = id.with("typed"); + let editing = self.ui.data(|data| data.get_temp::(field_id)); + let seeded = || shown_number(value, decimals); + + let tokens = self.tokens; + let Some(mut typed_text) = editing else { + self.skip_typing_edit(); + let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + + if response.hovered() { + self.value_line(rect.left(), right, center_y, tokens.field_border); + } + if response.clicked() { + self.start_typing(field_id, seeded()); + } + return None; + }; + + // Typing happens on the value's own line: no box, the line under it goes accent + let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left(), right, center_y, edit); + self.value_line(rect.left(), right, center_y, tokens.accent); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(field_id, typed_text)); + return None; + } + + let untouched = self.end_typing(field_id, &typed_text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || typed_text.trim() == seeded() { + return None; + } + + let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; + + // A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either + typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value) + } +} + +/// `value` kept in `range`; unlike `clamp`, a reversed or NaN range never panics +pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { + value.max(*range.start()).min(*range.end()) +} diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs new file mode 100644 index 00000000..96e72f7e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -0,0 +1,64 @@ + + +/// Air between a full-width button's icon and its words +const BUTTON_ICON_GAP: f32 = 8.0; + +/// Size of a full-width button's icon +const BUTTON_ICON_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// A full-width button: centred icon and words + pub(crate) fn button<'a>(&mut self, icon: impl Into>, text: &str) -> egui::Response { + self.button_lit(icon, text, false) + } + + /// A full-width button lit in the accent while what it turns on stays on + pub(crate) fn button_lit<'a>(&mut self, icon: impl Into>, text: &str, lit: bool) -> egui::Response { + self.button_enabled(icon, text, lit, true) + } + + /// [`Self::button_lit`] that answers no clicks and dims its words while not `enabled` + pub(crate) fn button_enabled<'a>(&mut self, icon: impl Into>, text: &str, lit: bool, enabled: bool) -> egui::Response { + self.button_sensing(icon.into(), text, lit, if enabled { Sense::click() } else { Sense::hover() }) + } + + fn button_sensing(&mut self, icon: ButtonIcon<'_>, text: &str, lit: bool, sense: Sense) -> egui::Response { + let enabled = sense != Sense::hover(); + let rect = self.take(ROW_HEIGHT); + let button = self.control_box(self.left, rect.center().y); + let id = self.next_id(); + let response = self.ui.interact(button, id, sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, text)); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect( + button, + CornerRadius::same(CONTROL_RADIUS), + match (lit, enabled && response.hovered()) { + (true, _) => tokens.accent_dim, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }, + Stroke::new(1.0, if lit { tokens.accent } else { tokens.button_border }), + StrokeKind::Inside, + ); + let color = if enabled { tokens.text } else { tokens.text_dim }; + let font = FontId::proportional(TEXT_SIZE); + let (icon_width, icon_galley) = match icon { + ButtonIcon::Glyph(glyph) => { + let galley = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(BUTTON_ICON_SIZE), color); + (galley.size().x, Some(galley)) + } + }; + let text_galley = painter.layout_no_wrap(text.to_owned(), font, color); + let total = icon_width + BUTTON_ICON_GAP + text_galley.size().x; + let x = button.center().x - total / 2.0; + if let Some(galley) = icon_galley { + painter.galley(pos2(x, button.center().y - galley.size().y / 2.0), galley, color); + } + painter.galley(pos2(x + icon_width + BUTTON_ICON_GAP, button.center().y - text_galley.size().y / 2.0), text_galley, color); + self.drawn(button.bottom()); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs new file mode 100644 index 00000000..b68c602d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// One captioned slider in the stack beside a picture +pub(crate) struct StackSlider<'a> { + /// The dim caption above the track (Count, Angle span) + pub(crate) label: &'a str, + + pub(crate) value: &'a mut f32, + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may reach, at least the track's span (a radial Count types past its track's most) + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs new file mode 100644 index 00000000..e0107857 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -0,0 +1,204 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use crate::theme::semibold; + +/// Draws a picture row's picture into its square +type RowPicture<'a> = &'a dyn Fn(&Painter, Rect); + +/// Draws option `index`'s picture into its square +type SegmentPicture<'a> = &'a dyn Fn(&Painter, Rect, usize); + +/// Side of a picture beside a switch's word, and the air between them +const SEGMENT_PICTURE_SIZE: f32 = 14.0; +const SEGMENT_PICTURE_AIR: f32 = 6.0; + +/// Room a switch's word needs in its segment beyond its own width (6 px each side: Bevel Smooth's Out | In | In/Out fits beside the widest label column) +const SEGMENT_AIR: f32 = 12.0; + +/// How far the chosen segment sits inside the switch's box +const SEGMENT_INSET: f32 = 2.0; + +/// Corner radius of a switch's box +const SWITCH_RADIUS: u8 = 6; + +/// Size of a toggle's pill +pub(super) const PILL_SIZE: egui::Vec2 = vec2(22.0, 13.0); + +/// Corner radius of a toggle's pill: about half its height, so its ends are round +const PILL_RADIUS: u8 = 6; + +/// Radius of a toggle's knob, and how far it sits from the pill's middle +const TOGGLE_KNOB_RADIUS: f32 = 4.0; +const TOGGLE_KNOB_TRAVEL: f32 = 4.5; + +/// From one of a pair's toggles to the next, and from its name to its pill's centre +const PAIR_PITCH: f32 = 76.0; +const PAIR_NAME_TO_PILL: f32 = 32.0; + +impl PropertySheet<'_> { + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index + pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + self.switch_tinted(label, options, selected, &[]) + } + + /// [`Self::switch`] whose chosen word takes its colour from `tints` (axis colours) + pub(crate) fn switch_tinted(&mut self, label: &str, options: &[&str], selected: usize, tints: &[Color32]) -> Option { + let stacks = self.text_width(label, FontId::proportional(TEXT_SIZE)) > self.column() - self.left - super::LABEL_MIN_AIR; + let left = if stacks { self.left } else { self.column() }; + if !self.switch_fits(options, left) { + return self.switch_dropdown(label, options, selected); + } + + let (control, _) = self.row(label); + let runs = |index: usize| tints.get(index).map(std::slice::from_ref).unwrap_or_default(); + self.segments(control, options, selected, runs, None) + } + + /// Whether every option's word fits its share of a switch from `left` to the panel's right edge + fn switch_fits(&self, options: &[&str], left: f32) -> bool { + let segment = (self.right - left) / options.len().max(1) as f32; + options.iter().all(|option| self.text_width(option, semibold(SMALL_TEXT_SIZE)) + SEGMENT_AIR <= segment) + } + + /// The dropdown a switch whose words don't fit becomes; returns the picked index + fn switch_dropdown(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + let name = |index: usize| options.get(index).copied().unwrap_or_default().to_owned(); + self.dropdown_built(label, selected, || 0..options.len(), name, None).0 + } + + /// A boxed switch's box and segments in `control`, the chosen word in the colours `tints` gives its index (none: the text colour); returns the segment clicked when it was not the chosen one + pub(super) fn segments<'t>( + &mut self, + control: Rect, + options: &[&str], + selected: usize, + tints: impl Fn(usize) -> &'t [Color32], + picture: Option>, + ) -> Option { + let segment = control.width() / options.len().max(1) as f32; + let tokens = self.tokens; + self.ui.painter().rect(control, CornerRadius::same(SWITCH_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + let mut picked = None; + for (index, option) in options.iter().enumerate() { + let rect = Rect::from_min_size(pos2(control.left() + index as f32 * segment, control.top()), vec2(segment, control.height())); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + let on = index == selected; + response.widget_info(|| WidgetInfo::selected(Role::RadioButton, true, on, *option)); + if response.clicked() && !on { + picked = Some(index); + } + + let painter = self.ui.painter(); + if on { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.button); + } else if response.hovered() { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover); + } + let runs = tints(index); + let tint = runs.first().copied().unwrap_or(tokens.text); + let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; + let Some(draw) = picture else { + let word = + if on && runs.len() > 1 { split_word(painter, option, runs, &font) } else { painter.layout_no_wrap((*option).to_owned(), font, color) }; + painter.galley(rect.center() - word.size() / 2.0, word, color); + continue; + }; + + // The picture and the word centred together in the segment + let word = painter.layout_no_wrap((*option).to_owned(), font, color); + let left = rect.center().x - (SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR + word.size().x) / 2.0; + draw( + painter, + Rect::from_min_size(pos2(left, rect.center().y - SEGMENT_PICTURE_SIZE / 2.0), vec2(SEGMENT_PICTURE_SIZE, SEGMENT_PICTURE_SIZE)), + index, + ); + let word_left = left + SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR; + painter.galley(pos2(word_left, rect.center().y - word.size().y / 2.0), word, color); + } + picked + } + + /// A culling row on the panel's grid: its name on the label column, its picture where the controls start with the switch after it, a pending i at the row's right end + pub(crate) fn picture_toggle(&mut self, picture: RowPicture<'_>, label: &str, on: &mut bool) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + self.paint_info_at_end(center_y); + let font = FontId::proportional(TEXT_SIZE); + + // A name too long for the label column pushes every picture row's picture right instead of running under it + let label_end = self.text_width(label, font.clone()) + super::LABEL_MIN_AIR; + self.seen.picture_label_end = self.seen.picture_label_end.max(label_end); + let picture_x = self.left + (self.column() - self.left).max(self.used.picture_label_end).max(label_end); + let square = Rect::from_min_size(pos2(picture_x, center_y - ROW_PICTURE_SIZE / 2.0), vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + let pill = Rect::from_min_size(pos2(square.right() + ROW_PICTURE_AIR, center_y - PILL_SIZE.y / 2.0), PILL_SIZE); + let clicked = self.toggle_hit(Rect::from_min_max(pos2(self.left, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + + let text = self.tokens.text; + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, label, font, text); + self.pill(pill.center(), *on, true); + self.drawn(square.bottom()); + clicked + } + + /// A toggle's clickable area: a click flips `on`; returns whether it was clicked + fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label)); + response.clicked() + } + + /// Two named toggles side by side after one label (Flip copy: U, V); returns the index clicked + pub(crate) fn toggle_pair(&mut self, label: &str, names: [&str; 2], on: &mut [bool; 2]) -> Option { + let (control, center_y) = self.row(label); + let font = FontId::proportional(TEXT_SIZE); + let mut clicked = None; + for (index, (name, state)) in names.into_iter().zip(on.iter_mut()).enumerate() { + let x = control.left() + index as f32 * PAIR_PITCH; + let pill = pos2(x + PAIR_NAME_TO_PILL, center_y); + let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); + if response.clicked() { + *state = !*state; + clicked = Some(index); + } + let tokens = self.tokens; + self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim }); + self.pill(pill, *state, true); + } + clicked + } + + /// A toggle's pill centred on `center`: on (accent), off, or greyed out when not `enabled` + pub(super) fn pill(&self, center: egui::Pos2, on: bool, enabled: bool) { + let tokens = self.tokens; + let (fill, border, knob, knob_x) = match (enabled, on) { + (false, _) => (tokens.field, tokens.separator, tokens.separator, center.x - TOGGLE_KNOB_TRAVEL), + (true, true) => (tokens.accent_dim, tokens.accent, tokens.text, center.x + TOGGLE_KNOB_TRAVEL), + (true, false) => (tokens.button, tokens.button_border, tokens.text_dim, center.x - TOGGLE_KNOB_TRAVEL), + }; + let painter = self.ui.painter(); + painter.rect(Rect::from_center_size(center, PILL_SIZE), CornerRadius::same(PILL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.circle_filled(pos2(knob_x, center.y), TOGGLE_KNOB_RADIUS, knob); + } +} + +/// `word` laid out with its letters split as evenly as they go between the colours of `runs` +fn split_word(painter: &Painter, word: &str, runs: &[Color32], font: &FontId) -> std::sync::Arc { + let letters: Vec = word.chars().collect(); + let mut job = egui::text::LayoutJob::default(); + let parts = runs.len().max(1); + for (part, color) in runs.iter().enumerate() { + let (start, end) = (letters.len() * part / parts, letters.len() * (part + 1) / parts); + let text: String = letters.get(start..end).unwrap_or_default().iter().collect(); + job.append(&text, 0.0, egui::TextFormat::simple(font.clone(), *color)); + } + painter.layout_job(job) +} diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs new file mode 100644 index 00000000..546bddf2 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -0,0 +1,243 @@ +use egui::{Color32, CornerRadius, Painter, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; + +use super::number_field::shown_number; +use super::{NumberField, PropertySheet}; +use crate::theme::{Accent, Brightness, Tokens}; + +mod filtering; +mod gallery; + +use filtering::Filtering; +use gallery::Gallery; + +/// Width of the Properties panel the mockups are drawn at +const PANEL_WIDTH: f32 = 300.0; + +/// The harness window: the panel plus room on its right for popups and tips, tall enough for the whole gallery unscrolled +const HARNESS_SIZE: egui::Vec2 = egui::vec2(PANEL_WIDTH + 260.0, 1000.0); + +fn swatch(color: Color32) -> impl Fn(&Painter, Rect) { + move |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, color); + } +} + +fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering) { + let shade = match filtering { + Filtering::BilinearHq => 200, + Filtering::BilinearSharp => 150, + Filtering::Nearest => 100, + }; + painter.rect_filled(rect.shrink(2.0), CornerRadius::same(2), Color32::from_gray(shade)); +} + +fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "gallery", |sheet| { + if let Some(picked) = sheet + .dropdown( + "Filtering", + state.filtering, + &[Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest], + Filtering::name, + Some(&filtering_picture), + ) + .0 + { + state.filtering = picked; + } + + let reset = sheet.band("3D projection settings", true, Some(state.position != [0.0; 3]), None); + if reset.reset { + state.position = [0.0; 3]; + } + if reset.open { + let mut fields = [("X", 0), ("Y", 1), ("Z", 2)].map(|(tag, axis)| NumberField { + tag, + tag_color: crate::theme::AXIS_COLORS.get(axis).copied(), + value: state.position[axis], + speed: 0.01, + decimals: 2, + suffix: "", + }); + if let Some((axis, merge)) = sheet.number_fields("Position", &mut fields, Some(&mut state.linked), false) + && let Some(slot) = state.position.get_mut(axis) + { + *slot = fields[axis].value; + state.position_merges.push(merge); + } + } + }); + }); +} + +/// A harness in `brightness`, with the app's fonts from the first frame +fn builder(brightness: Brightness) -> egui_kittest::HarnessBuilder { + Harness::builder().with_size(HARNESS_SIZE).with_context_setup(move |ctx| { + crate::theme::install(ctx); + crate::theme::apply(ctx, brightness, Accent::default()); + }) +} + +fn gallery_harness(brightness: Brightness, gallery_state: Gallery) -> Harness<'static, Gallery> { + let mut harness = builder(brightness).build_ui_state(gallery, gallery_state); + harness.run_steps(3); + harness +} + +/// Two culling rows, the second named past the label column +fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "culling", |sheet| { + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth", &mut on[0]); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface culling past the column", &mut on[1]); + }); + }); +} + +/// A culling name too long for the label column moves every culling row's picture and switch, so the switches stay one column +#[test] +fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(culling_rows, [false; 2]); + harness.run_steps(3); + + let short = harness.get_by_label("Depth").rect(); + let long = harness.get_by_label("Backface culling past the column").rect(); + + assert_eq!(short.right(), long.right(), "both switches end at one x: {short:?} vs {long:?}"); +} + +/// A gray slider in a panel-wide column; records the column's right edge +fn gray_row(ui: &mut egui::Ui, state: &mut (f32, f32)) { + ui.set_width(PANEL_WIDTH); + state.1 = ui.max_rect().right(); + crate::gray_slider::gray_slider(ui, "Color", &mut state.0); +} + +/// A gray slider's invert button ends on the column's right edge (a plain button was wider than the room kept for it) +#[test] +fn a_gray_sliders_invert_button_ends_on_its_columns_right_edge() { + // the slider's typed value field (upstream's) carries no accessible name + let mut harness = builder(Brightness::MediumDark).with_accessibility_check(false).build_ui_state(gray_row, (0.5, 0.0)); + harness.run_steps(3); + + let invert = harness.get_by_role(egui::accesskit::Role::Button).rect(); + let right = harness.state().1; + assert!(invert.right() <= right + 0.5, "the button ends at {} past the column's {right}", invert.right()); +} + +/// Where `wanted` is painted, first to last +fn painted_at(harness: &Harness<'_, State>, wanted: &str) -> Vec { + let shapes = harness.output().shapes.iter(); + shapes + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text.pos), + _ => None, + }) + .collect() +} + +/// An open dropdown's options start their words at the button's own word x (they started 1 px in, inside the list's border) +#[test] +fn an_open_dropdowns_options_start_at_the_buttons_word() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + + let at = button.center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let button_word = painted_at(&harness, "Bilinear | HQ").into_iter().find(|at| button.contains(*at)).map(|at| at.x); + let option_word = painted_at(&harness, "Nearest").first().map(|at| at.x); + assert!(button_word.is_some() && option_word == button_word, "the option's word at {option_word:?}, the button's at {button_word:?}"); +} + +#[test] +fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + let at = harness.get_by_label("Bilinear | HQ").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let option = harness.get_by_label("Nearest").rect(); + let list = option.expand(super::choice::LIST_BORDER); + assert_eq!(list.left(), button.left(), "the list starts at the button's left edge"); + assert_eq!(list.width(), button.width(), "the list is the button's width"); + assert!(option.top() > button.bottom(), "the list hangs below the button"); + + let at = harness.get_by_label("Nearest").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert_eq!(harness.state().filtering, Filtering::Nearest); +} + +/// Presses and lets go at `at` through the real pointer path, so a control drawn over another gets the click it would get from a person +fn click_at(harness: &mut Harness<'_, State>, at: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(1); +} + +/// A reason too long for its caption's row is cut with "…", and hovering it shows it whole +#[test] +fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + const REASON: &str = "Not available with this projection, for a reason far too long to fit beside the caption"; + const TOOLTIP_WAIT_FRAMES: usize = 60; + let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "unavailable", |sheet| sheet.section_unavailable("Symmetry", REASON)); + }); + harness.run_steps(2); + let reason = harness.get_by_label(REASON).rect(); + assert!(reason.right() <= PANEL_WIDTH + 1.0, "the reason is cut to fit the panel: {reason:?}"); + + harness.hover_at(reason.center()); + harness.run_steps(TOOLTIP_WAIT_FRAMES); + assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); +} + +/// A number field held still until egui starts its drag, then moved, starts its own undo step with its first change +#[test] +fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let field = harness.get_by_label("Position X").rect(); + harness.drag_at(field.center()); + + // Past egui's longest click, the press becomes a drag that has not moved + harness.run_steps(5); + harness.hover_at(field.center() + egui::vec2(10.0, 0.0)); + harness.run(); + harness.hover_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + harness.drop_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + + let merges = &harness.state().position_merges; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first move starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later moves continue it: {merges:?}"); +} + +#[test] +fn a_number_field_reads_zero_without_a_minus_sign() { + assert_eq!(shown_number(-0.0, 0), "0"); + assert_eq!(shown_number(-0.004, 2), "0.00"); + assert_eq!(shown_number(-0.3, 0), "0"); + assert_eq!(shown_number(-0.6, 0), "-1"); + assert_eq!(shown_number(-1.25, 2), "-1.25"); + assert_eq!(shown_number(2.5, 1), "2.5"); +} diff --git a/crates/ui-egui/src/property_sheet/tests/filtering.rs b/crates/ui-egui/src/property_sheet/tests/filtering.rs new file mode 100644 index 00000000..b37210ca --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/filtering.rs @@ -0,0 +1,19 @@ +//! The gallery's Filtering choice + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Filtering { + BilinearHq, + BilinearSharp, + Nearest, +} + +impl Filtering { + pub(super) fn name(self) -> String { + match self { + Filtering::BilinearHq => "Bilinear | HQ", + Filtering::BilinearSharp => "Bilinear | Sharp", + Filtering::Nearest => "Nearest", + } + .to_owned() + } +} diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs new file mode 100644 index 00000000..3a9e730a --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -0,0 +1,15 @@ +//! What the gallery's controls last set + +use super::Filtering; + +pub(super) struct Gallery { + pub(super) filtering: Filtering, + pub(super) position: [f32; 3], + pub(super) position_merges: Vec, + pub(super) linked: bool, +} + +impl Default for Gallery { + fn default() -> Self { + } +} diff --git a/crates/ui-egui/src/property_sheet/tooltip.rs b/crates/ui-egui/src/property_sheet/tooltip.rs new file mode 100644 index 00000000..d9c37f65 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tooltip.rs @@ -0,0 +1,32 @@ +use egui::{RectAlign, Response}; + +use super::PropertySheet; + +/// Where a tooltip goes when the window has no room above a control in the panel's right half: below it, then the other edge +const RIGHT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_END, RectAlign::TOP_START, RectAlign::BOTTOM_START]; + +/// The same for a control in the panel's left half +const LEFT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_START, RectAlign::TOP_END, RectAlign::BOTTOM_END]; + +impl PropertySheet<'_> { + /// A tooltip for `response` right next to it: above the control, flush with its edge nearer the panel's side so it grows toward the middle + pub(crate) fn tip(&self, response: Response, text: &str) -> Response { + let (align, fallbacks) = if response.rect.center().x > self.ui.max_rect().center().x { + (RectAlign::TOP_END, &RIGHT_HALF_FALLBACKS) + } else { + (RectAlign::TOP_START, &LEFT_HALF_FALLBACKS) + }; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(align).align_alternatives(fallbacks); + tooltip.show(|ui| ui.label(text)); + response + } + + /// A tooltip for a pad, outside the panel beside it, where it covers no value of the panel; under it when the panel has no room on its left + pub(crate) fn tip_beside(&self, response: Response, text: &str) -> Response { + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(RectAlign::LEFT_START).align_alternatives(&[RectAlign::BOTTOM_START]); + tooltip.show(|ui| ui.label(text)); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/track.rs b/crates/ui-egui/src/property_sheet/track.rs new file mode 100644 index 00000000..d4f2f91c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/track.rs @@ -0,0 +1,13 @@ +//! The line a slider's knob runs along + +/// What a slider's knob runs along and shows +pub(super) struct Track { + pub(super) start: f32, + pub(super) end: f32, + pub(super) center_y: f32, + /// Where a two-sided range's fill starts and its tick sits (0 for signed ranges, 0.5 for a 0..1 range centred on "unchanged") + pub(super) zero: Option, + + /// The track is a picture of its range (a gray ramp) drawn by the caller: no line and no fill + pub(super) ramp: bool, +} diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs new file mode 100644 index 00000000..b40ca7a4 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -0,0 +1,63 @@ +//! Where a slider's value sits and how it reads + +/// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value +pub(super) struct ValueText<'a> { + pub(super) label: &'a dyn std::fmt::Display, + pub(super) right: f32, + pub(super) width: f32, + pub(super) center_y: f32, + pub(super) shown: &'a str, + pub(super) suffix: &'a str, +} + +/// How far below a value's centre its typing line runs +const LINE_DROP: f32 = 9.0; + +/// Where the field `field_id` keeps the text its typing opened with +fn opened_id(field_id: egui::Id) -> egui::Id { + field_id.with("opened") +} + +impl super::PropertySheet<'_> { + /// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it + pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) { + let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(self.ui.ctx(), field_id); + self.ui.data_mut(|data| { + data.insert_temp(opened_id(field_id), text.clone()); + data.insert_temp(field_id, text); + }); + self.ui.memory_mut(|memory| memory.request_focus(field_id)); + } + + /// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile) + pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool { + let opened = self.ui.data_mut(|data| { + data.remove::(field_id); + data.remove_temp::(opened_id(field_id)) + }); + opened.is_some_and(|opened| opened.trim() == typed.trim()) + } + + /// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are + pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response { + let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y; + let height = line.max(self.ui.spacing().interact_size.y); + let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0)); + let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); + let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)); + child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0))) + } + + /// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked + pub(super) fn skip_typing_edit(&mut self) { + self.ui.skip_ahead_auto_ids(1); + } + + /// The 1 px line under a typeable value centred on `center_y`, from `left` to `right`: grey on hover, accent while typing + pub(super) fn value_line(&self, left: f32, right: f32, center_y: f32, color: egui::Color32) { + let y = (center_y + LINE_DROP).round() + 0.5; + self.ui.painter().line_segment([egui::pos2(left, y), egui::pos2(right, y)], egui::Stroke::new(1.0, color)); + } +}