From dfc8ff52169c2eadf957b036da62486c2ee354b4 Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 23 Nov 2026 01:25:51 -0300 Subject: [PATCH 01/35] test(platform): restore rtf_target_prefers_text_rtf test (wordcraft#7317) --- crates/platform/src/clipboard/offer/tests.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/platform/src/clipboard/offer/tests.rs b/crates/platform/src/clipboard/offer/tests.rs index cd667d8f60..bb714d846e 100644 --- a/crates/platform/src/clipboard/offer/tests.rs +++ b/crates/platform/src/clipboard/offer/tests.rs @@ -26,3 +26,15 @@ fn cf_html_offsets_delimit_the_fragment_bytes() { assert_eq!(&data[end_html..], b"\0", "EndHTML excludes the trailing NUL"); assert_eq!(end_html, data.len() - 1); } + +/// Ported from WordCraft (#7317). When multiple RTF targets are offered, text/rtf is preferred over application/rtf and text/richtext. +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn rtf_target_prefers_text_rtf() { + use super::unix::rtf_target; + let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(rtf_target(&names(&["TARGETS", "text/richtext", "application/rtf", "text/rtf"])), Some("text/rtf")); + assert_eq!(rtf_target(&names(&["text/richtext", "UTF8_STRING"])), Some("text/richtext")); + assert_eq!(rtf_target(&names(&["text/html", "text/rtf;charset=x"])), None); + assert_eq!(rtf_target(&[]), None); +} From 362844f704ae7dc9dd04da92ee82d615599861c5 Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 23 Nov 2026 19:57:10 -0300 Subject: [PATCH 02/35] ui-contract: sync egui font color transfer function with resolved theme mode --- crates/ui-contract/src/runtime/egui/style.rs | 22 +++++++++- crates/ui-contract/src/runtime/env/root.rs | 15 +++++++ crates/ui-contract/src/runtime/frame.rs | 14 ++++++ crates/ui-contract/tests/it/style/cache.rs | 45 ++++++++++++++++++++ 4 files changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index ff7b38fd33..538165f0fc 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -1,6 +1,8 @@ -//! The theme styles' `right_to_left`. +//! The theme styles' `right_to_left` and font coverage transfer function. -use egui::{Context, Ui}; +use craft_theme::Mode; +use egui::epaint::FontColorTransferFunction; +use egui::{Context, Theme, Ui}; /// Turns off egui's own caret blink in `ui`, and hides the caret stroke unless `visible`: the runtime blinks it. pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) { @@ -63,3 +65,19 @@ pub(crate) fn set_theme_direction(ctx: &Context, root: &mut Ui, right_to_left: b pub(crate) fn set_item_spacing(ui: &mut Ui, gap: egui::Vec2) { ui.spacing_mut().item_spacing = gap; } + +/// Matches egui's font coverage transfer function to `mode` across both egui theme styles, so dark-on-light text +/// never renders with the dark-mode curve (or vice versa) when the app's mode differs from the OS's. +pub(crate) fn set_text_color_transfer(ctx: &Context, mode: Mode) { + let transfer = match mode { + Mode::Light => FontColorTransferFunction::LIGHT_MODE_DEFAULT, + Mode::Dark => FontColorTransferFunction::DARK_MODE_DEFAULT, + }; + let matches = ctx.style_of(Theme::Dark).visuals.text_options.color_transfer_function == transfer + && ctx.style_of(Theme::Light).visuals.text_options.color_transfer_function == transfer; + if !matches { + ctx.all_styles_mut(|style| { + style.visuals.text_options.color_transfer_function = transfer; + }); + } +} diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index 23fc27c0b9..dc93b733d4 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -154,6 +154,21 @@ impl RootEnv { self.resolved_for(super::system_appearance(ctx).appearance) } + /// The mode the root's theme actually shows on `ctx`: the resolved mode clamped to the theme's supported + /// variants (for example, `Mode::Light` for a light-only theme even when dark mode is requested). + pub(crate) fn effective_mode(&self, ctx: &Context) -> Mode { + let wanted = self.resolved(ctx).mode; + if let Some(def) = &self.theme_def { + return def.variants.mode_for(wanted); + } + let themes = craft_theme::builtins(); + let theme = [self.theme.as_str(), craft_theme::SUITE_DEFAULT] + .into_iter() + .find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)) + .unwrap_or(&themes[0]); + theme.variants.mode_for(wanted) + } + /// What the choices resolve to when the OS reports `system`. pub fn resolved_for(&self, system: SystemAppearance) -> ResolvedRoot { let mode = match self.mode { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index bf59ec4053..cc6af720b6 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -642,6 +642,15 @@ pub(crate) fn holds_input(ctx: &Context, viewport: ViewportId) -> bool { PerViewport::::with(ctx, viewport, |record| record.held.holds()) } +/// The mode the current frame's root theme resolves to on `ctx`. +fn effective_mode(ctx: &Context) -> Mode { + let root = pass_state::with::(ctx, |state| state.input.as_ref().map(|input| input.root.clone())); + match root { + Some(root) => root.effective_mode(ctx), + None => RootEnv::fallback(ctx).effective_mode(ctx), + } +} + /// The input hook: egui runs it before it pushes the viewport, so every step reads only `RawInput` and /// records keyed by `input.viewport_id`. pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { @@ -653,6 +662,11 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { raw_input::prepare(ctx, input); // H0b: the OS colour scheme egui's integration reports reaches the system reader. crate::runtime::env::system::input_hook(ctx, &input.events); + // H0d: match egui's font coverage transfer function to the pass's resolved theme mode before egui runs + // `Fonts::begin_pass`, so dark-on-light and light-on-dark text use the right curve even when the app's mode + // differs from the OS's. + let mode = effective_mode(ctx); + style::set_text_color_transfer(ctx, mode); // From H0 to H3 the events go with the input time each arrived at (`Arrived`): held events keep theirs, and the key // stage gives each shortcut its own. egui's events are what these stages leave. let mut events = Arrived::take(input); diff --git a/crates/ui-contract/tests/it/style/cache.rs b/crates/ui-contract/tests/it/style/cache.rs index 00909fbc5a..e2d86f03e3 100644 --- a/crates/ui-contract/tests/it/style/cache.rs +++ b/crates/ui-contract/tests/it/style/cache.rs @@ -96,3 +96,48 @@ fn a_reported_text_scale_reaches_the_systems_text_scale_and_raises_the_generatio report_os_text_scale(&frames.ctx, None); assert_eq!(system_text_scale(&frames.ctx), None); } + +/// egui's font coverage transfer function follows the pass's resolved theme mode before `Fonts::begin_pass`, so +/// dark-on-light text never renders with the dark-mode curve (or vice versa) when the app's mode differs from the +/// OS's, and single-mode themes keep their own variant's curve. +#[trial] +fn egui_font_transfer_function_follows_the_resolved_theme_mode() { + use craft_theme::ThemeId; + use egui::epaint::FontColorTransferFunction; + + let mut frames = Frames::new(); + let mut transfer = None; + + // Light app on a dark OS must use the light-mode transfer function on the same pass. + frames.root(RootEnv::new().mode(ModeChoice::Light)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT)); + + // Dark app on a light OS must use the dark-mode transfer function on the same pass. + frames.root(RootEnv::new().mode(ModeChoice::Dark)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Light)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::DARK_MODE_DEFAULT)); + + // System mode tracks OS theme changes immediately. + frames.root(RootEnv::new().mode(ModeChoice::System)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::DARK_MODE_DEFAULT)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Light)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT)); + + // A light-only theme keeps the light-mode transfer function even when dark mode is requested. + let classic = ThemeId::parse("craft.classic").expect("classic theme id"); + frames.root(RootEnv::new().theme(classic).mode(ModeChoice::Dark)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT)); +} From 7e51840348c8c48cd9ad508778e3b7d0ad3a8775 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 24 Nov 2026 01:13:22 +0100 Subject: [PATCH 03/35] WIP: own-window full-window dialogs keep their size (photocraft#16595) Co-Authored-By: Claude Opus 5.5 From 07a223c0ff56b43c51bd97828c0b3ca70411381c Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 24 Nov 2026 01:25:34 +0100 Subject: [PATCH 04/35] ui-contract: a full-window container's own window keeps its size A full-window container in its own OS window was sent its body's size every pass. The body leaves out the side panels, header and footer, so the window shrank by them each frame: RAW Develop's window ended a pixel wide and, still modal, blocked the app (photocraft#16595). The window now opens at the opener's content size and from then on its size is the user's, as a resizable window's is. Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/contract/mount.rs | 17 +++++----- .../ui-contract/tests/it/runtime/windows.rs | 32 +++++++++++++++++++ 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 8f90ce438e..1c7e632af7 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -365,25 +365,24 @@ impl Host for ViewportHost { let spec = self.spec.clone().unwrap_or_else(by_rank); let placed = self.overlay.placed; let full_window = self.overlay.is_full_window(); - // A full-window container fills its window, so the window's own layout memory holds the size the user gave - // it; before it has one the window opens at the opener's content size, large enough for a workspace. - let measured = || { - let remembered = layout_memory::read(&ctx, id); - if full_window { remembered.or_else(|| Some(ctx.content_rect().size())) } else { remembered } - }; + // A full-window container fills its window and has no content size: its window opens at the opener's content + // size, large enough for a workspace. What its body took is no size for the window: side panels, header and + // footer are no part of it, and a window sent it shrank by them each pass (photocraft#16595). + let measured = || if full_window { Some(ctx.content_rect().size()) } else { layout_memory::read(&ctx, id) }; let open = ViewportOpen { id, title: title.as_str(), // A placed rect is the caller's size for the window, within the window's limits, which the OS would clamp it // to; then a resizable fallback's default size, as the layer takes it; the measured size is for a window // sized by content: what its body took in the window, recorded once the window reported its place - // (`steps::record_body_size`). + // (`steps::record_body_size`), or a full-window container's opening size. size: placed .map(|rect| self.overlay.size_limits.clamp(rect.size())) .or(self.overlay.size.filter(|_| self.overlay.fit == overlay::OverlayFit::Resizable)) .or_else(measured), - // A resizable window takes its default or content size to open; from then on its size is the user's. - follows_size: placed.is_some() || self.overlay.fit != overlay::OverlayFit::Resizable, + // A resizable window takes its default or content size to open; from then on its size is the user's, as a + // full-window container's is. + follows_size: placed.is_some() || (!full_window && self.overlay.fit != overlay::OverlayFit::Resizable), save: self.save.as_deref(), spec: &spec, limits: (Some(self.overlay.size_limits.min), self.overlay.size_limits.max), diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 4827c04c64..1349e98cad 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -764,6 +764,38 @@ fn a_content_sized_window_takes_its_content_size_once_it_reported_its_place() { ); } +/// photocraft#16595: a full-window container in a window of its own keeps the size the window has. Its body takes +/// less than the window (side panels, header and footer are no part of it), and the window was sent that size each +/// frame, so it shrank until it was a pixel wide. +#[trial] +fn a_full_window_viewport_keeps_its_window_size() { + const GIVEN: Vec2 = Vec2::new(1000.0, 700.0); + let windows = Windows::new(); + let frame = || { + windows.frame(vec![], vec![], |ui| { + Palette::full_window("Workspace").show(ui, |ui, _| { + ui.allocate_exact_size(Vec2::new(300.0, 200.0), egui::Sense::hover()); + }); + }) + }; + let (dialog, _) = builder_titled(&frame(), "Workspace"); + let given = Rect::from_min_size(Pos2::new(100.0, 100.0), GIVEN); + windows.child_info(ViewportInfo { + inner_rect: Some(given), + outer_rect: Some(given), + native_pixels_per_point: Some(1.0), + ..ViewportInfo::default() + }); + let sent: Vec = (0..6) + .flat_map(|_| frame().commands) + .filter_map(|(id, command)| match command { + ViewportCommand::InnerSize(size) if id == dialog => Some(size), + _ => None, + }) + .collect(); + assert_eq!(sent, Vec::::new(), "the workspace's window keeps the size it has"); +} + /// Placing a minimized window below its smallest inner size restores it and lowers that size to the placed one, so the /// window takes the place it is given. #[trial] From 87ed3c0be0b9572d6e1915795369cb7fba2bd6e2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:00:07 +0000 Subject: [PATCH 05/35] ui-contract: one modal stack across viewports, ordered by the frame each top modal opened in A modal viewport blocks only the viewports whose top modal opened in an earlier frame, and those with none. Modals that open in the same frame form one level and block none of each other, so the screen picker's capture windows, opened over a modal Color Picker, take the click, right-click and Escape that end the pick, while the Color Picker's window stays blocked until they close. The input hook, key ownership, the blocked cursor, the close refusal and the window raises all read that one fact. --- crates/ui-contract/src/runtime/overlay.rs | 51 ++++---- .../ui-contract/tests/it/runtime/windows.rs | 111 +++++++++++++++++- 2 files changed, 136 insertions(+), 26 deletions(-) diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index f8b607866f..21e96b6ba2 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -289,7 +289,12 @@ pub(crate) struct TopModal { pub(crate) struct Persist { raised: IdMap, counter: u64, - modal: bool, + /// The viewport's place in the app's modal stack: the root frame its top live modal layer over the whole window + /// first showed in, as of its last finished pass, or `None` without one. A modal viewport blocks the viewports whose + /// top modal opened in an earlier frame and those with none (`modal_viewport`). Modals that open in the same frame + /// form one level and block none of each other: the screen picker opens a capture window over each monitor in one + /// pass, and each must take its click. When the top modal closes, the one under it keeps its own first frame. + modal: Option, /// The layers of the last pass, bottom to top, as `end_pass` handed them to egui. stack: Vec, /// A press the modal drop removed, for the window host to raise the modal's window. @@ -853,6 +858,7 @@ pub(crate) fn end_pass(ctx: &Context) { let (current, last_ids, raise) = with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::>(), pass.raise.clone())); let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); + let now = pass::root_frame_nr(ctx); let order = with_persist(ctx, viewport, |persist| { let stamp = |id: Id, persist: &mut Persist| { persist.counter += 1; @@ -902,9 +908,9 @@ pub(crate) fn end_pass(ctx: &Context) { persist.stack.push(member.id); } } - persist.modal = current.iter().any(|entry| entry.blocks_window() && !entry.exiting); - persist.top_modal = - current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting).map(|entry| TopModal { id: entry.id, cover: entry.cover }); + let top = current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting); + persist.modal = top.map(|entry| persist.appeared.get(&entry.id).map_or(now, |(frame, _)| *frame)); + persist.top_modal = top.map(|entry| TopModal { id: entry.id, cover: entry.cover }); persist.popup_over_modal = current.iter().filter(|entry| entry.rank == Rank::Popup && !entry.exiting).any(|popup| { let mut at = popup.parent; while let Some(parent) = at.and_then(|id| current.iter().find(|entry| entry.id == id)) { @@ -928,7 +934,6 @@ pub(crate) fn end_pass(ctx: &Context) { }); areas::set_layer_order(ctx, &order); // An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown. - let now = pass::root_frame_nr(ctx); pass_state::with::(ctx, |closes| closes.0.retain(|(.., queued, carried)| *carried || queued + 1 >= now)); let top_modal = current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting); if let Some(entry) = top_modal.filter(|entry| !entry.window) { @@ -936,19 +941,15 @@ pub(crate) fn end_pass(ctx: &Context) { } let any = { let here = top_modal.is_some(); - here || modal_in_other_viewports(ctx, viewport) + here || modal_elsewhere(ctx, viewport) }; commands::set_modal_open(ctx, any, viewport, top_modal.map(|entry| entry.id)); } -fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool { - modal_viewport(ctx, running).is_some() -} - -/// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook -/// reads (H3). +/// Whether a modal layer in another viewport blocks `viewport` (`modal_viewport`): the app-modal fact the input hook +/// (H3), key ownership and the command state read. pub(crate) fn modal_elsewhere(ctx: &Context, viewport: ViewportId) -> bool { - modal_in_other_viewports(ctx, viewport) + modal_viewport(ctx, viewport).is_some() } /// Records that the input hook dropped a press for `viewport` because a modal is open elsewhere. @@ -994,7 +995,7 @@ pub(crate) fn key_layer(ctx: &Context, scopes: &[Id], below: Option) -> Laye (_, None, None) => true, _ => false, }); - if above || modal_in_other_viewports(ctx, viewport) { + if above || modal_elsewhere(ctx, viewport) { return LayerKeys::Blocked; } inside.map_or(LayerKeys::Window, |entry| LayerKeys::Class(entry.keys)) @@ -1015,22 +1016,28 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option) { .max_by_key(|(shown, _)| *shown) .map(|(_, id)| id) }); - (root.is_some() || modal_in_other_viewports(ctx, viewport), root) + (root.is_some() || modal_elsewhere(ctx, viewport), root) } -/// The live viewports with a modal layer open as of their last finished pass. -fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { - pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal)) +/// The live viewports with a modal layer open as of their last finished pass, each with its place in the modal stack +/// (`Persist::modal`). +fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { + pass::live_viewports(ctx).into_iter().filter_map(|viewport| with_persist(ctx, viewport, |persist| persist.modal).map(|opened| (viewport, opened))) } -/// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises. +/// The viewport whose modal layer blocks `viewport`: of the other viewports whose top modal opened in a later frame +/// than `viewport`'s own (any, when it has none), the one that opened last, the window a blocked press raises. pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option { - modal_viewports(ctx).find(|other| *other != viewport) + let own = with_persist(ctx, viewport, |persist| persist.modal); + modal_viewports(ctx) + .filter(|(other, opened)| *other != viewport && own.is_none_or(|own| *opened > own)) + .max_by_key(|(_, opened)| *opened) + .map(|(other, _)| other) } -/// A viewport that has a modal layer open: the window that blocks the app's other windows. +/// The viewport at the top of the modal stack: the window that blocks the app's other windows. pub(crate) fn app_modal_viewport(ctx: &Context) -> Option { - modal_viewports(ctx).next() + modal_viewports(ctx).max_by_key(|(_, opened)| *opened).map(|(viewport, _)| viewport) } /// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index f328f8a89d..b5c23a5453 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -5,15 +5,17 @@ //! loss, non-finite injected points, a repeated injected press, the window that has the keys, a wheel with no known //! pointer, the placement of a minimized window, the root frame decided again, a held close, and `act`. -use craft_behavior::{Cursor, CursorIcon, PointerButton}; +use craft_behavior::{Cursor, CursorIcon, PointerButton, Sense}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; use craft_keymap::{Key, Mods}; use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _}; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::focus::FocusPolicy; -use craft_ui::runtime::windows::{WindowHost, WindowSpec}; +use craft_ui::runtime::overlay::CloseReason; +use craft_ui::runtime::windows::{WindowHost, WindowLevel, WindowSpec}; use craft_ui::style::StyleCx; -use craft_ui::testing::pointer::{moved, press, wheel}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::{moved, press, release, wheel}; use craft_ui::testing::windows::{FakeSystem, NoWindows}; use craft_ui::testing::{Fixture, trial}; use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen}; @@ -359,7 +361,7 @@ fn a_window_an_app_modal_in_another_window_blocks_takes_no_wheel() { #[trial] fn wheel_over_a_modal_never_reaches_a_view_under_it_during_a_drag() { - use craft_behavior::{Sense, WheelTaker}; + use craft_behavior::WheelTaker; use craft_ui::testing::wheel::{register, take}; let windows = Windows::new(); let view = egui::Id::unique("dragging view"); @@ -466,6 +468,107 @@ fn a_blocking_modal_is_raised_when_the_main_window_gains_focus() { assert!(raised(&frame()), "the main window gained focus: the dialog's window is raised"); } +/// A modal window that opens over a modal in another window comes first in the app's modal stack: the screen picker's +/// capture windows, one per monitor and all opened in one frame, take the click and the Escape that end the pick and +/// block none of each other, while the window of the Color Picker under them stays blocked until they close. +#[trial] +fn modal_windows_opened_over_a_modal_in_another_window_take_input_and_block_it() { + let windows = Windows::new(); + let screen = Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0)); + windows.child_info(ViewportInfo { inner_rect: Some(screen), focused: Some(true), ..ViewportInfo::default() }); + let titles = ["monitor 1", "monitor 2"]; + let seen = [RefCell::new(Seen::default()), RefCell::new(Seen::default())]; + let closed = RefCell::new(Vec::new()); + // The capture windows shown, in show order. The trial's renderer hands the child events to the first child pass of + // the frame, so the order picks the window a click goes to. + let frame = |shown: &[usize], root: Vec, child: Vec| { + windows.frame(root, child, |ui| { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("color picker").show(ui, |_, _| {}); + for &at in shown { + Capture::new(titles[at], screen, &closed).show(ui, |ui, _| { + Probe::new(&seen[at]).size(Vec2::splat(120.0)).sense(Sense::CLICK).show(ui); + }); + } + }) + }; + let (both, flipped) = ([0, 1], [1, 0]); + let blocked = Some(Cursor::System(CursorIcon::NotAllowed)); + for _ in 0..3 { + frame(&[], vec![], vec![]); + } + let mut out = frame(&both, vec![], vec![]); + for _ in 0..3 { + out = frame(&both, vec![], vec![]); + } + let captures = titles.map(|title| builder_titled(&out, title).0); + + let at = Pos2::new(50.0, 50.0); + for order in [both, flipped] { + frame(&order, vec![], vec![moved(at)]); + frame(&order, vec![], vec![press(at)]); + frame(&order, vec![], vec![release(at)]); + frame(&order, vec![], vec![]); + } + let clicks: Vec = seen.iter().map(|seen| seen.borrow().activations).collect(); + assert_eq!(clicks, [1, 1], "a click reaches each capture window"); + + assert_eq!(craft_ui::runtime::cursor::current(&windows.ctx), blocked, "the Color Picker's window is blocked"); + let mut sent = frame(&both, vec![moved(at), press(at)], vec![]).commands; + sent.extend(frame(&both, vec![release(at)], vec![]).commands); + assert!( + sent.iter().any(|(id, command)| captures.contains(id) && *command == ViewportCommand::Focus), + "a press in the Color Picker's window raises a capture window: {sent:?}" + ); + + frame(&both, vec![], vec![key_press(egui::Key::Escape, egui::Modifiers::NONE)]); + frame(&both, vec![], vec![]); + assert_eq!(*closed.borrow(), [CloseReason::Escape], "Escape closes the capture window, which ends the pick"); + for _ in 0..3 { + frame(&[], vec![], vec![]); + } + assert_ne!(craft_ui::runtime::cursor::current(&windows.ctx), blocked, "the pick ended: the Color Picker's window takes input again"); +} + +/// A modal container in an OS window of its own over `over`, as the screen picker's capture windows mount, that adds +/// how it closed to `closed`. +#[derive(craft_ui::contract::Component)] +#[component(container)] +struct Capture<'a> { + #[common] + common: Common, + #[container] + props: ContainerProps, + closed: &'a RefCell>, +} + +impl<'a> Capture<'a> { + fn new(title: &'static str, over: Rect, closed: &'a RefCell>) -> Self { + let mount = Mount::viewport_with(Overlay::modal().placed(over), WindowSpec::dialog().level(WindowLevel::AlwaysOnTop).taskbar(false)); + Capture { common: Common::new(), props: ContainerProps::new().mount(mount), closed }.label(title).id_salt(title) + } +} + +impl Component for Capture<'_> { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: CaptureStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(120.0, 60.0)) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +impl Container for Capture<'_> { + fn closed(&mut self, why: CloseReason) { + self.closed.borrow_mut().push(why); + } +} + /// A container mounted in an OS viewport that opens as `spec`, with a body the trial gives it. #[derive(craft_ui::contract::Component)] #[component(container)] From c7dbf52f594ae385dfaae29ce76e3d664ee95f91 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:04:36 +0000 Subject: [PATCH 06/35] ui-contract: a tooltip keeps its text width in an inspector cell, a press hides it until the pointer leaves, and a sampled press does not nudge its modal - Scoped::start_layer clears inside_label, cell_fills and least: a layer is outside its opener's flow, so the tooltip of a control beside an inspector label no longer fills the layer's cap of the window (photocraft#16593). - A press on a tooltip's subject keeps the tooltip hidden until neither the pointer nor the keyboard is on it, so a popover the press opens is not covered. Tooltips shown at the pointer keep hiding only while pressed. - A press the canvas a modal keeps open takes (a colour sampled under the Color Picker) is not a press outside that modal, so it neither nudges nor closes it. --- .../src/contract/overlay/dismissal.rs | 9 ++- crates/ui-contract/src/contract/tooltip.rs | 17 ++++- crates/ui-contract/src/runtime/env.rs | 7 ++ crates/ui-widgets/tests/it/label/tooltip.rs | 74 ++++++++++++++++++- crates/ui-widgets/tests/it/overlay/sampler.rs | 33 +++++++++ 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index e2c8379e34..7801d2f649 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -4,9 +4,10 @@ use super::host::{Layer, LayerMemory}; use super::props::Outside; use crate::contract::{Component, Cx}; use crate::runtime::commands::FireSource; +use crate::runtime::egui::pass; use crate::runtime::focus::{self, FocusPolicy, Initial}; use crate::runtime::overlay::{self, CloseReason, Rank}; -use crate::runtime::{frame, keys, pointer}; +use crate::runtime::{frame, keys, pointer, sampler}; use craft_behavior::CancelRule; use craft_keymap::Mods; use egui::{Context, Rect}; @@ -94,13 +95,15 @@ pub(super) fn popup_dismissal( (here || away || crate::runtime::windows::pressed_elsewhere(ctx, popup, appears)).then_some(CloseReason::Outside) } -/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. +/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. A press the +/// canvas the layer keeps open took (a colour sampled under the Color Picker) is the canvas's, not one beside the layer. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { let Some(press) = pointer::primary_press(ctx) else { return false; }; let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press)); - !rect.contains(press) && !anchor.contains(press) && !inside_family + let sampled = || sampler::through(ctx, pass::current_viewport(ctx), layer.id).is_some() && sampler::admitted_press(ctx, press); + !rect.contains(press) && !anchor.contains(press) && !inside_family && !sampled() } /// Whether the focused stop sits in no scope that belongs to a shown layer. diff --git a/crates/ui-contract/src/contract/tooltip.rs b/crates/ui-contract/src/contract/tooltip.rs index 09ca81d2e1..53464e1f29 100644 --- a/crates/ui-contract/src/contract/tooltip.rs +++ b/crates/ui-contract/src/contract/tooltip.rs @@ -2,7 +2,8 @@ //! //! A tooltip shows after one delay while the pointer rests on the component, or on keyboard focus after the same //! delay, and at once while a neighbour's tooltip was hiding a moment ago. A press, a menu that owns keys and a -//! running drag hide it. +//! running drag hide it. A press on the component keeps its tooltip hidden until the pointer leaves it, so what the +//! press opens (a popover under a swatch) is not covered. //! //! A component with no tooltip shows its own label as the tooltip when its type declares `Component::SHOWS_LABEL` //! false (or an instance does, through `Component::shows_label`): no text paints that name, inside a field or not. A @@ -42,6 +43,8 @@ struct TipState { shown: bool, /// The part the tooltip belongs to; `None` for the component's own. subject: Option, + /// A press on the subject hid the tooltip; it stays hidden until neither the pointer nor the keyboard is on it. + dismissed: bool, } /// When the last tooltip of the context hid. @@ -279,7 +282,8 @@ struct TipCall<'a> { text: &'a dyn Fn() -> Option, rich: Option>, spec: Option<&'a TooltipSpec>, - /// The tooltip shows at the pointer whatever its spec's `at` says. + /// The tooltip shows at the pointer whatever its spec's `at` says. Such a tip has no subject a press could + /// dismiss it from: it hides only while the press lasts. at_pointer: bool, /// The pointer rests on the subject or the keyboard is on it. wants_input: bool, @@ -313,7 +317,12 @@ fn show_tip(call: TipCall<'_>) { } let when_now = spec.is_some_and(|spec| spec.when == TooltipWhen::Now); let screen = areas::layer_to_screen(ctx, rect_layer) * rect; - let suppressed = pressed || overlay_blocks(ctx, screen.center()) || pointer::press_captured(ctx) || drag::running(ctx); + if !wants_input { + state.dismissed = false; + } else if pressed && !at_pointer { + state.dismissed = true; + } + let suppressed = pressed || state.dismissed || overlay_blocks(ctx, screen.center()) || pointer::press_captured(ctx) || drag::running(ctx); if wants { state.since.get_or_insert(now); } else { @@ -334,7 +343,7 @@ fn show_tip(call: TipCall<'_>) { state.shown = show; let tip_id = sub(id, "tip"); let presence = motion::layer_presence(ctx, tip_id, owner, env.motion, show, overlay_motion()); - if state.shown || state.since.is_some() || presence.visible { + if state.shown || state.since.is_some() || state.dismissed || presence.visible { store::put(ctx, state_id, state); } if !presence.visible { diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index ec0063526b..f878fd9223 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -412,8 +412,15 @@ impl Scoped { /// Starts a layer from its opener's scope: the inherited group stays, the layer-local fields start fresh, and the /// layer is no line of a bar it was opened from. A layer's content measures and runs in this. + /// + /// The layer is outside its opener's flow: an inside label and a filling cell belong to the beside label's own + /// control, and the opener's least measure is not the layer's. A tooltip of a control in an inspector cell keeps + /// its text width, not the layer's cap. pub(crate) fn start_layer(&mut self) { self.start_room(); + self.inside_label = None; + self.cell_fills = false; + self.least = false; self.bracket = None; self.measure = None; self.arena = None; diff --git a/crates/ui-widgets/tests/it/label/tooltip.rs b/crates/ui-widgets/tests/it/label/tooltip.rs index 1028f6a802..b27928077a 100644 --- a/crates/ui-widgets/tests/it/label/tooltip.rs +++ b/crates/ui-widgets/tests/it/label/tooltip.rs @@ -8,9 +8,9 @@ use craft_behavior::Sense; use craft_ui::buttons::Button; use craft_ui::contract::tooltip::DELAY; use craft_ui::contract::{ - CommandSet, Common, Component, Cx, GlyphLabel, LabelKind, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, SideLabel, + CommandSet, Common, Component, Cx, GlyphLabel, LabelKind, LabelScheme, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, SideLabel, }; -use craft_ui::form::Field; +use craft_ui::form::{Field, FieldGroup}; use craft_ui::runtime::commands::CommandState; use craft_ui::style::StyleCx; use craft_ui::testing::pointer::moved; @@ -298,3 +298,73 @@ fn a_tooltip_shown_from_inside_a_body_keeps_its_rect_frame_to_frame() { let first = frames[0].1; assert!(first.is_some() && frames.iter().all(|(passes, rect)| *passes == 1 && *rect == first), "one pass a frame and one rect: {frames:?}"); } + +/// A tooltip longer than a mark's cell and far shorter than the layer's cap. +const STROKE_TIP: &str = "Set shape stroke type"; + +/// The width of the tooltip a rest on a mark labelled `STROKE_TIP` shows in a wide window, with `inspector` in an +/// inspector's field, whose control fills the cell its label leaves; and the window's width. +fn stroke_tip_width(inspector: bool) -> (f32, f32) { + let at = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&at); + let mut fixture = Fixture::new(move |ui| { + let field = |ui: &mut Ui| { + Field::new("Stroke").show(ui, |ui, _| seen.set(Mark { common: Common::new() }.label(STROKE_TIP).show(ui).rect)); + }; + if inspector { + FieldGroup::new("Shape").labels(LabelScheme::Inspector).show(ui, |ui, _| field(ui)); + } else { + field(ui); + } + }); + let room = Vec2::new(1600.0, 600.0); + fixture.room(room); + fixture.settle(); + fixture.frame(vec![moved(at.get().center())]); + fixture.advance(DELAY); + fixture.settle(); + let tip = fixture.by_role(Role::TOOLTIP).first().map(|tip| tip.rect).expect("the tooltip shows"); + (tip.width(), room.x) +} + +/// A control beside an inspector label fills its cell, its tooltip does not: the tooltip layer takes its text's width, +/// as it does outside an inspector, not the layer's cap of the window (photocraft#16593). +#[trial] +fn a_tooltip_of_a_control_in_an_inspector_cell_keeps_its_text_width() { + let (plain, _) = stroke_tip_width(false); + let (inspector, room) = stroke_tip_width(true); + assert!(inspector <= plain + 0.5, "the tooltip in an inspector cell is as wide as outside one: {inspector} vs {plain}"); + assert!(inspector < room / 4.0, "the tooltip does not span the window: {inspector} of {room}"); +} + +/// A press on a control hides its tooltip until the pointer leaves the control, so what the press opens (a popover +/// under a swatch) is not covered; a rest after the pointer came back shows it again. +#[trial] +fn a_press_on_a_control_hides_its_tooltip_until_the_pointer_leaves() { + let at = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&at); + let mut fixture = Fixture::new(move |ui| { + ui.add_space(20.0); + seen.set(Button::new("Stroke").tooltip(STROKE_TIP.to_owned()).show(ui).rect); + }); + fixture.settle(); + let shows = |fixture: &Fixture| fixture.texts().iter().any(|run| run.text == STROKE_TIP); + let center = at.get().center(); + fixture.frame(vec![moved(center)]); + fixture.advance(DELAY); + fixture.settle(); + assert!(shows(&fixture), "a rest on the button shows its tooltip"); + + fixture.click_at(center); + fixture.advance(DELAY); + fixture.settle(); + assert!(!shows(&fixture), "after a press on the button its tooltip stays hidden while the pointer rests there"); + + fixture.frame(vec![moved(at.get().right_bottom() + Vec2::splat(200.0))]); + fixture.advance(DELAY); + fixture.settle(); + fixture.frame(vec![moved(center)]); + fixture.advance(DELAY); + fixture.settle(); + assert!(shows(&fixture), "once the pointer left and came back, a rest shows the tooltip again"); +} diff --git a/crates/ui-widgets/tests/it/overlay/sampler.rs b/crates/ui-widgets/tests/it/overlay/sampler.rs index 5f7ceb7b49..b484618b87 100644 --- a/crates/ui-widgets/tests/it/overlay/sampler.rs +++ b/crates/ui-widgets/tests/it/overlay/sampler.rs @@ -422,3 +422,36 @@ fn a_press_under_a_modal_starts_nothing_on_the_canvas() { assert!(!scene.took(PointerButton::Primary), "the press stays blocked while the dialog is open"); assert!(scene.dialog.shown.get(), "the presses leave the dialog open"); } + +/// A press on the canvas a modal dialog keeps open for its gesture is the canvas's (a colour sampled): it does not +/// nudge the dialog, which stays where it is. A press beside both the dialog and the canvas still nudges it. +#[trial] +fn a_press_the_kept_canvas_takes_does_not_nudge_the_dialog() { + use craft_ui::testing::snapshot::layer_rects; + let mut frames = Frames::new(); + frames.root(craft_ui::runtime::env::RootEnv::default().motion(craft_behavior::MotionMode::Full)); + let scene = Scene::new(Arm::Gesture(CanvasGesture::PRIMARY)); + scene.open_dialog(&mut frames); + let rest = layer_rects(&frames.ctx); + assert_eq!(rest.len(), 1, "the dialog's layer shows: {rest:?}"); + let press = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // A press and release at `at`, then a few frames; whether the dialog's layer moved from its rest meanwhile. + let moved_by_press = |frames: &mut Frames, at: Pos2| { + let mut moved_away = false; + for events in [vec![moved(at)], vec![press(at, true)], vec![press(at, false)], vec![], vec![], vec![]] { + scene.frame(frames, events); + moved_away |= layer_rects(&frames.ctx) != rest; + } + scene.settle(frames, 20); + moved_away + }; + + assert!(!moved_by_press(&mut frames, CANVAS.center()), "a press the canvas takes does not nudge the dialog"); + assert!(scene.took(PointerButton::Primary), "the press reached the canvas"); + scene.assert_dialog_holds(&frames); + + let beside = Pos2::new(760.0, 560.0); + assert!(!CANVAS.contains(beside) && !OPENER.contains(beside) && !rest[0].contains(beside), "the point lies beside dialog and canvas"); + assert!(moved_by_press(&mut frames, beside), "a press beside the dialog and the canvas nudges it"); + assert!(scene.dialog.shown.get(), "the press beside leaves the dialog open"); +} From cfca45a97b87dc9288834ae745c37ce945981731 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:07:24 +0000 Subject: [PATCH 07/35] docking: a tab drag names its panel inside the drop region, and a tab join marks the group as shown A collection picks its row drag preview with one named option, RowPreview (Badge, Named, None), in place of the drag_badge flag. A dock tab strip takes Named, so a tab drag shows the panel's name inside the region a drop takes, as group, column and icon drags do, with no badge by the pointer. A tab join marks the group under the pointer at its current size, with the tab line, as production did; other drops keep the rect the panels take once dropped. --- crates/ui-contract/src/contract/collection.rs | 2 +- .../src/contract/collection/props.rs | 35 ++++++++--- crates/ui-contract/src/contract/items/drag.rs | 17 ++++-- crates/ui-contract/src/contract/mod.rs | 2 +- crates/ui-macros/src/props.rs | 8 ++- crates/ui-panels/src/docking/drop.rs | 21 ++++--- crates/ui-panels/src/docking/group.rs | 2 + crates/ui-panels/src/docking/targets.rs | 14 +++++ .../tests/it/docking/drop_preview.rs | 58 ++++++++++++++++++- crates/ui-widgets/src/tabs/document.rs | 2 +- 10 files changed, 133 insertions(+), 28 deletions(-) diff --git a/crates/ui-contract/src/contract/collection.rs b/crates/ui-contract/src/contract/collection.rs index 11417d5159..da36f5cb0c 100644 --- a/crates/ui-contract/src/contract/collection.rs +++ b/crates/ui-contract/src/contract/collection.rs @@ -13,7 +13,7 @@ pub use events::{ }; pub use props::{ ActivateOn, CollectionProps, DeleteTarget, DragPayload, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, - RowState, SelectMode, SpaceAction, + RowPreview, RowState, SelectMode, SpaceAction, }; pub(crate) use response::Gestures; pub(crate) use response::ItemsOut; diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 2e2fd99e25..fc7416ed45 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -37,6 +37,23 @@ pub enum DeleteTarget { FocusOrHover, } +/// What a row drag shows while it runs. The text is the count word for the dragged items +/// (`CollectionProps::drag_count`), else the number of items for several and the item's text for one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum RowPreview { + /// The text in a badge by the pointer. + #[default] + Badge, + /// The text inside the region a drop would take, where the target marks one ([`DragPreview::Named`]); nothing + /// by the pointer. + /// + /// [`DragPreview::Named`]: crate::runtime::drag::DragPreview::Named + Named, + /// No preview: the dragged row shows alone. + None, +} + /// How the user may reorder items. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] @@ -246,11 +263,11 @@ pub struct CollectionProps { /// Map a row drag to the payloads that other drop targets take (8.4), one per type. A map starts row drags by /// itself, with or without a reorder rule. pub drag_payloads: Vec, - /// The count word the drag badge shows for the dragged items, one item included ("1 page", "3 pages"); `None` - /// shows the number of items for several and the item's text for one. + /// The count word a row drag's preview shows for the dragged items, one item included ("1 page", "3 pages"); + /// `None` shows the number of items for several and the item's text for one. pub drag_count: Option, - /// Whether a row drag shows its badge by the pointer. Off, the drag carries no preview. - pub drag_badge: bool, + /// What a row drag shows while it runs. + pub drag_preview: RowPreview, /// The collection takes the full height of its rows and owns no scroll, so it can sit inside a scrolling page: /// every row is built, the wheel and the keys that move past an end act on the page's scroll owner, and moving /// the lead scrolls the page to keep the row in view. For short collections only; a long one keeps its own @@ -369,7 +386,7 @@ impl CollectionProps { delete_target: DeleteTarget::Focus, drag_payloads: Vec::new(), drag_count: None, - drag_badge: true, + drag_preview: RowPreview::Badge, natural_height: false, min_rows: 0, max_rows: None, @@ -424,14 +441,14 @@ impl CollectionProps { self } - /// Whether a row drag shows its badge by the pointer (on by default). + /// What a row drag shows while it runs (a badge by the pointer by default). #[must_use] - pub const fn drag_badge(mut self, on: bool) -> Self { - self.drag_badge = on; + pub const fn drag_preview(mut self, preview: RowPreview) -> Self { + self.drag_preview = preview; self } - /// The drag badge reads `count` for the number of dragged items. + /// A row drag's preview reads `count` for the number of dragged items. #[must_use] pub const fn drag_count(mut self, count: Counted) -> Self { self.drag_count = Some(count); diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index dc7c0e161e..7a98c8f73d 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -10,7 +10,7 @@ use super::marquee::MarqueeDrag; use super::{ItemsHooks, Placement}; use crate::contract::collection::{ - CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, + CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, RowPreview, ToggleColumn, ToggleEdit, }; use crate::contract::reorder; @@ -25,6 +25,7 @@ use craft_behavior::{ }; use egui::{Pos2, Rect, Vec2}; use std::any::Any; +use std::borrow::Cow; /// Maps a point to layout coordinates once for every collection type. fn logical_point(layout: &dyn ItemLayout, rect: Rect, rtl: bool, at: Pos2) -> Pos2 { @@ -591,11 +592,15 @@ impl ItemsHooks<'_, '_, C> { let key = self.source.key(at); let keys = self.keys_at(&self.acted_on(at)); let count = keys.len() as u64; - let preview = match props.drag_count.filter(|_| props.drag_badge) { - Some(word) => DragPreview::Badge(Label::from(cx.env.counted(word, count))), - None if !props.drag_badge => DragPreview::None, - None if count > 1 => DragPreview::Badge(Label::from(count.to_string())), - None => self.source.text(at).map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text.into_owned()))), + let text = || match props.drag_count { + Some(word) => Some(cx.env.counted(word, count)), + None if count > 1 => Some(count.to_string()), + None => self.source.text(at).map(Cow::into_owned), + }; + let preview = match props.drag_preview { + RowPreview::Badge => text().map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text))), + RowPreview::Named => text().map_or(DragPreview::None, |text| DragPreview::Named(Label::from(text))), + _ => DragPreview::None, }; let drag = ListDrag::new(id, keys, key.clone()); let also: Vec<_> = props.drag_payloads.iter().filter_map(|map| map.of(&drag)).collect(); diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index a00a5fad11..5b93f879ee 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -61,7 +61,7 @@ pub use collection::{ ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove, ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DeleteTarget, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, - RowPressed, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, + RowPressed, RowPreview, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, }; #[doc(hidden)] pub use container::InBar; diff --git a/crates/ui-macros/src/props.rs b/crates/ui-macros/src/props.rs index ff8addf8db..005cce8e7f 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -194,8 +194,12 @@ const COLLECTION: &[Forwarded] = &[ ("marquee", "bool", "A drag on the background selects the rows it covers."), ("deletable", "bool", "Delete and Backspace at the lead report the items to delete."), ("delete_target", "$ui::contract::DeleteTarget", "Where a deletable collection takes Delete and Backspace."), - ("drag_count", "$ui::runtime::env::Counted", "The drag badge reads this count word for the dragged items, one included."), - ("drag_badge", "bool", "A row drag shows its badge by the pointer (default on); off, the dragged row shows alone."), + ("drag_count", "$ui::runtime::env::Counted", "A row drag's preview reads this count word for the dragged items, one included."), + ( + "drag_preview", + "$ui::contract::RowPreview", + "What a row drag shows: a badge by the pointer (default), its name inside the drop region, or nothing.", + ), ("natural_height", "bool", "The collection takes its full content height and owns no scroll: for a short collection inside a scrolling page."), ("min_rows", "u16", "The collection is at least this many rows tall; rows it does not have count the row height."), ("max_rows", "u16", "The collection shows at most this many rows and scrolls the rest, inside a scrolling body too."), diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 8376328a18..8aa8668a3b 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -299,8 +299,8 @@ where /// The drop target of one dock over one layout, for a tab drag ([`PanelDrag`]) and a group drag ([`GroupDrag`]). /// /// It accepts a move only. A release over a spot docks the unit there. With `placing`, the mark over a spot is the -/// region the unit takes once dropped, laid out in the room the dock registered ([`placed_rect`]), with the tab line -/// of a tab insertion; a reorder inside the unit's own group, and a drop whose panels get no rect of their own, mark +/// region the unit takes once dropped, laid out in the room the dock registered ([`placed_rect`]); a tab insertion +/// marks the group it joins as shown now, with its tab line; a reorder inside the unit's own group, and a drop whose panels get no rect of their own, mark /// the spot ([`DockSpot::mark`]). Ctrl or Cmd held at the release floats it /// instead (Photoshop: the key prevents docking), and with `float_on_empty` a release that no spot takes floats it; /// both float it into `space` under the pointer. A floating window dragged by its title bar moves itself and never @@ -365,13 +365,20 @@ impl DockDropTarget<'_, P> { self.float(&unit, at, drag.source(), drag.strip(), drag.press()) } - /// The rect the panels of `unit` take in `after`, the layout once dropped on `spot`; `None` without `placing` or - /// a registered room, for a reorder inside the unit's own group, which marks only its tab line, and where the - /// panels get no rect of their own. + /// The region a drop of `unit` on `spot` marks: for a tab join, the group it joins as shown now (production's + /// mark: the group under the pointer, not the size it grows to); else the rect the panels of `unit` take in + /// `after`, the layout once dropped. `None` without `placing` or a registered room, for a reorder inside the + /// unit's own group, which marks only its tab line, and where the panels get no rect of their own. fn region(&self, spot: &DockSpot

, unit: &DragUnit

, after: &Layout

) -> Option { let placing = self.placing.as_ref()?; - if matches!(spot, DockSpot::Tab { .. }) && on_unit(self.layout, spot, unit) { - return None; + if let DockSpot::Tab { anchor, .. } = spot { + if on_unit(self.layout, spot, unit) { + return None; + } + let group = members(self.layout, anchor); + if let Some(rect) = DockTargets::

::group_rect(self.ctx, self.dock, |panel| group.contains(panel)) { + return Some(rect); + } } let room = DockTargets::

::room(self.ctx, self.dock)?; placed_rect(after, &moving_panels(self.layout, unit), room, placing, self.rtl) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index f6cf1c5855..e8635fbe5d 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -767,6 +767,8 @@ fn tab_row(row: &mu .shown(active) .tear_off() .natural_height(true) + // Group, column and icon drags name what they move inside the drop region; a tab drag does the same. + .drag_preview(crate::contract::RowPreview::Named) .can_close(move |key: &PanelKey| panels.iter().any(|panel| &panel.key == key && closes(panel))) .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: None, started: None })); if row.wheel_selects { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index d1a2954d3b..442708638c 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -528,6 +528,20 @@ impl DockTargets

{ pub fn resolve(ctx: &Context, dock: Id, at: Pos2) -> Option<(DockSpot

, Rect)> { Self::with_pass(ctx, |pass| pass.before.iter().find(|(id, _)| *id == dock).and_then(|(_, targets)| targets.at(at))).flatten() } + + /// The rect of a group in the dock `dock` as the previous pass showed it, by the side spots it registered (a + /// [`DockSpot::Group`] applies to its group's rect); `in_group` tells the group's panels. `None` outside a pass + /// and for a group that registered no side spots, such as a minimized one. + pub(crate) fn group_rect(ctx: &Context, dock: Id, in_group: impl Fn(&P) -> bool) -> Option { + Self::with_pass(ctx, |pass| { + let (_, targets) = pass.before.iter().find(|(id, _)| *id == dock)?; + targets.targets.iter().find_map(|target| match &target.spot { + DockSpot::Group { anchor, .. } if in_group(anchor) => Some(target.applies), + _ => None, + }) + }) + .flatten() + } } /// The registrations of a pass. A settled memoized view's run record keeps each one to make it again and compares it diff --git a/crates/ui-patterns/tests/it/docking/drop_preview.rs b/crates/ui-patterns/tests/it/docking/drop_preview.rs index 021ccf828e..412ef3e703 100644 --- a/crates/ui-patterns/tests/it/docking/drop_preview.rs +++ b/crates/ui-patterns/tests/it/docking/drop_preview.rs @@ -9,7 +9,7 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag::{self, DropMark}; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, trial}; -use egui::{Pos2, Rect, Ui, Vec2}; +use egui::{Pos2, Rect, Shape, Ui, Vec2}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; @@ -93,6 +93,17 @@ fn drop_tab(bed: &mut Bed, panel: usize, to: Pos2) -> DropMark { mark } +/// Presses the tab of `panel` and drags it to `to`, holding the button there. +fn hold_tab_at(bed: &mut Bed, panel: usize, to: Pos2) { + let from = tab(bed, panel).center(); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for step in 1..=4 { + bed.fixture.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))]); + } + bed.fixture.frame(Vec::new()); +} + /// The rect the area shows the group of `panel` in. fn group_rect(bed: &Bed, panel: usize) -> Rect { let layout = bed.workspace.borrow().layout().clone(); @@ -133,6 +144,51 @@ fn a_tab_joining_a_group_marks_the_group_and_its_tab_line_and_a_reorder_marks_th assert!(matches!(mark, DropMark::Line { .. }), "a reorder inside its own strip marks its line only: {mark:?}"); } +/// A tab that joins a group whose rect grows once its own group goes marks the group as it is under the pointer, as +/// production did, not the larger rect the group takes after the drop. +#[trial] +fn a_tab_joining_a_group_marks_the_group_as_shown_now_not_the_rect_it_grows_to() { + let mut bed = bed(); + let before = group_rect(&bed, 3); + let target = tab(&bed, 3); + let mark = drop_tab(&mut bed, 4, Pos2::new(target.right() + 20.0, target.center().y)); + let DropMark::Region { area, line: Some(_), .. } = mark else { panic!("a tab join marks a region with its tab line: {mark:?}") }; + let after = group_rect(&bed, 4); + assert_eq!(after, group_rect(&bed, 3), "the tab joined the right group"); + assert!(after.height() > before.height() + SLACK, "the group grew once the top group went: {before:?} -> {after:?}"); + assert!(same(area, before), "the mark {area:?} is the group as it was under the pointer: {before:?}"); +} + +/// A tab drag names its panel inside the region a drop takes, at the region's top, as group drags do; no badge with +/// the name follows the pointer. +#[trial] +fn a_tab_drag_names_its_panel_inside_the_drop_region_and_not_by_the_pointer() { + let mut bed = bed(); + let own = tab(&bed, 2); + let right = group_rect(&bed, 3); + let to = Pos2::new(right.center().x, right.bottom() - right.height() * 0.2); + hold_tab_at(&mut bed, 2, to); + let Some(DropMark::Region { area, .. }) = drag::mark(bed.fixture.ctx()) else { panic!("the dock marks the region below the right group") }; + assert!(to.y > area.center().y, "the pointer {to:?} is in the region's lower half: {area:?}"); + let names: Vec = bed + .fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Text(text) if text.galley.text() == "Panel 2" => Some(shape.visual_bounding_rect()), + _ => None, + }) + .filter(|rect| !own.intersects(*rect)) + .collect(); + assert!(!names.is_empty(), "the panel's name shows while it is dragged"); + for name in &names { + // The pointer is in the region's lower half, so a badge beside it would be too. + assert!(area.contains_rect(*name) && name.bottom() < area.center().y, "the name {name:?} sits at the top of the region {area:?}"); + } + bed.fixture.frame(vec![release(to)]); + bed.fixture.settle(); +} + /// A strip along the layout's top edge takes tab joins: the band there, where a drop adds a full-width row, reaches /// into the strip only near the edge. #[trial] diff --git a/crates/ui-widgets/src/tabs/document.rs b/crates/ui-widgets/src/tabs/document.rs index 104182da8c..ec2454decb 100644 --- a/crates/ui-widgets/src/tabs/document.rs +++ b/crates/ui-widgets/src/tabs/document.rs @@ -289,7 +289,7 @@ impl<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Documen strip = strip .reorder(ReorderRule::new()) // The held tab is the preview; production shows no filename badge beside the pointer. - .drag_badge(false) + .drag_preview(crate::contract::RowPreview::None) .can_drag(move |key: &D| tabs.iter().find(|tab| &tab.id == key).is_none_or(|tab| tab.movable)) .accepts(move |drag: &ListDrag, _, insert| { // `insert` counts every tab; `keeps_fixed` takes the place among the tabs left without the dragged ones. From 8b4e49d62fa4fa378b43853b99a22c3cfb0eef79 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:07:24 +0000 Subject: [PATCH 08/35] drag: the window a drag moves paints the drop mark over itself A native floating window moved by its title row lies over the mark the target under it shows. Its own ghost layer paints the mark too, mapped to the same desktop place through the windows' inner rects, the mapping pointer_in uses, so the mark reads over the faded window. --- crates/ui-contract/src/runtime/drag.rs | 28 ++++++++--- .../ui-contract/src/runtime/windows/host.rs | 13 ++++- crates/ui-patterns/tests/it/docking/native.rs | 50 ++++++++++++++++++- crates/ui-test-kit/src/windows.rs | 18 +++++++ 4 files changed, 98 insertions(+), 11 deletions(-) diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index bfe0156945..099e17c232 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -925,14 +925,26 @@ pub(crate) struct Ghost { pub mark: Option<(DropMark, Arc)>, } -/// The running session's ghost data. +/// The running session's ghost data for the running viewport. The mark paints in the window whose target registered +/// it, and also in the window the session moves, mapped to the same desktop place: that window lies over the mark, +/// which would otherwise show only through it. pub(crate) fn ghost(ctx: &Context) -> Option { let viewport = pass::current_viewport(ctx); - board(ctx, |board| { - board.session.as_ref().map(|session| Ghost { - preview: session.preview.clone(), - env: session.env.clone(), - mark: session.mark.as_ref().filter(|shown| shown.viewport == viewport).map(|shown| (shown.mark, shown.tokens.clone())), - }) - }) + let (preview, env, mark, moves_this) = board(ctx, |board| { + board + .session + .as_ref() + .map(|session| (session.preview.clone(), session.env.clone(), session.mark.clone(), session.moving.viewport == Some(viewport))) + })?; + let mark = mark.and_then(|shown| { + let offset = if shown.viewport == viewport { + Vec2::ZERO + } else if moves_this { + WindowHost::of(ctx).offset_between(shown.viewport, viewport)? + } else { + return None; + }; + Some((shown.mark.mapped(|point| point + offset), shown.tokens)) + }); + Some(Ghost { preview, env, mark }) } diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 0d747a7260..a6002db479 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -477,9 +477,20 @@ impl WindowHost { /// The desktop pointer in the coordinates of `viewport`, when it lies inside that window. pub fn pointer_in(&self, viewport: ViewportId) -> Option { let desktop = self.desktop_pointer()?; - let inner = PerViewport::::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner))?; + let inner = self.inner_on_desktop(viewport)?; inner.contains(desktop).then(|| Pos2::ZERO + (desktop - inner.min)) } + + /// What a point of `from`'s window adds to land at the same desktop place in `to`'s window, by the inner rects + /// the windows last reported, as [`Self::pointer_in`] maps the desktop pointer. + pub(crate) fn offset_between(&self, from: ViewportId, to: ViewportId) -> Option { + Some(self.inner_on_desktop(from)?.min - self.inner_on_desktop(to)?.min) + } + + /// The inner rect of `viewport`'s window on the desktop, as the window last reported it. + fn inner_on_desktop(&self, viewport: ViewportId) -> Option { + PerViewport::::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner)) + } } /// The frame of `viewport`'s window as its chrome and the caption buttons it was opened with tell it, for a window diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index aa82dee486..81f0909430 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -25,7 +25,9 @@ use craft_ui::testing::trial; use craft_ui::testing::windows::{FakeSystem, HeldButtons}; use craft_ui::text::NumberField; use craft_ui_test_kit::windows::{AppKitWindow, FilesOver, Out, Windows}; -use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; +use egui::{ + Event, HoveredFile, Key, Modifiers, Pos2, Rect, Shape, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo, +}; use std::sync::Arc; /// The root window and the palette overlap; the palette is the larger. @@ -270,6 +272,8 @@ struct NativeDock { palette: Option, /// The tree the palette window's pass produced in the last frame. palette_tree: Option, + /// The shapes the palette window's pass painted in the last frame. + palette_shapes: Vec, /// Whether Auto-Collapse Iconic Panels is on in the frames of a collapsed palette. auto_collapse: bool, } @@ -293,7 +297,17 @@ impl NativeDock { windows.child_info(info(true, FLOAT_AT)); let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]))); let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped }); - let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None, auto_collapse: false }; + let mut dock = NativeDock { + windows, + workspace, + stepped, + specs, + builder: None, + palette: None, + palette_tree: None, + palette_shapes: Vec::new(), + auto_collapse: false, + }; for _ in 0..3 { dock.frame(vec![]); } @@ -320,6 +334,7 @@ impl NativeDock { } let palette = self.palette; self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); + self.palette_shapes = out.shapes.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, shapes)| shapes).unwrap_or_default(); for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { @@ -384,6 +399,37 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_app_moves_windo assert!(!docked, "a cancelled move docks nothing"); } +/// A palette moved by its title row over the main window's group lies over the mark the group shows: its own window +/// paints the mark too, at the same desktop place by the windows' inner rects, so the mark shows over the palette and +/// not only through its faded window. +#[trial] +fn a_native_palette_moved_over_a_drop_target_paints_the_mark_over_itself() { + let mut dock = NativeDock::on(Os::Linux, Arc::new(FakeSystem::new())); + let step = (OVER_GROUP - (FLOAT_AT.min + ROW_AT.to_vec2())) / 3.0; + for events in [vec![moved(ROW_AT)], vec![press(ROW_AT)]] { + dock.frame(events); + } + for _ in 0..3 { + dock.frame(vec![moved(ROW_AT + step)]); + } + dock.frame(vec![]); + let area = match drag::mark(&dock.windows.ctx) { + Some(DropMark::Region { area, .. } | DropMark::Into(area)) => area, + mark => panic!("the main window's group marks the region the palette takes: {mark:?}"), + }; + dock.frame(vec![]); + let palette = dock.palette.expect("the palette has its window"); + let inner = dock.windows.facts(palette).inner_rect.expect("the palette reports its inner rect"); + let mapped = area.translate(MAIN_AT.min - inner.min); + let shows = dock.palette_shapes.iter().any( + |shape| matches!(shape, Shape::Rect(rect) if (rect.rect.min - mapped.min).length() < 0.5 && (rect.rect.max - mapped.max).length() < 0.5), + ); + assert!(shows, "the palette's window paints the mark at {mapped:?}, where the main window's {area:?} lies under it"); + for events in [vec![key_press(Key::Escape, Modifiers::NONE)], vec![release(ROW_AT)], vec![]] { + dock.frame(events); + } +} + /// Where the app moves windows itself and the platform tells the system pointer (Windows): the window follows the /// system pointer, not the pass's pointer event, which can be an older sample than the window's current place (the /// window moves between passes). Measured from such an event the window lands a step behind the pointer each pass and diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index d54eafd75c..bbda539b5c 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -36,6 +36,8 @@ thread_local! { static COMMANDS: RefCell> = const { RefCell::new(Vec::new()) }; /// The AccessKit tree each viewport's last pass produced, in pass order. static TREES: RefCell> = const { RefCell::new(Vec::new()) }; + /// The shapes each pass of the frame painted, nested shapes flattened. + static SHAPES: RefCell)>> = const { RefCell::new(Vec::new()) }; /// The time every pass of the frame runs at. static NOW: Cell = const { Cell::new(0.0) }; /// Each child's builder as its window has it: a later builder patches it, and what changed goes to the window as @@ -205,6 +207,18 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { fn keep_tree(output: &mut FullOutput, viewport: ViewportId) { let tree = tree_of(output); TREES.with(|kept| kept.borrow_mut().push((viewport, tree))); + let mut shapes = Vec::new(); + for clipped in &output.shapes { + flatten(&clipped.shape, &mut shapes); + } + SHAPES.with(|kept| kept.borrow_mut().push((viewport, shapes))); +} + +fn flatten(shape: &egui::Shape, into: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten(shape, into)), + shape => into.push(shape.clone()), + } } /// An OS window as macOS runs egui's window commands on it through winit, in desktop points with y down: a position @@ -256,6 +270,8 @@ pub struct Out { /// The AccessKit tree each viewport's pass produced, in pass order: the children's first, as they run inside the /// root's pass. pub trees: Vec<(ViewportId, AccessTree)>, + /// The shapes each viewport's pass painted, nested shapes flattened, in the order of `trees`. + pub shapes: Vec<(ViewportId, Vec)>, } /// A context with the runtime installed whose child viewports are OS windows. @@ -343,6 +359,7 @@ impl Windows { root_dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); CHILD_FILES.with(|files| *files.borrow_mut() = child_files); TREES.with(|kept| kept.borrow_mut().clear()); + SHAPES.with(|kept| kept.borrow_mut().clear()); set_input(&self.ctx, FrameInput::new(self.root.borrow().clone())); let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)), @@ -373,6 +390,7 @@ impl Windows { commands: COMMANDS.with(|kept| std::mem::take(&mut *kept.borrow_mut())), builders, trees: TREES.with(|kept| std::mem::take(&mut *kept.borrow_mut())), + shapes: SHAPES.with(|kept| std::mem::take(&mut *kept.borrow_mut())), } } } From 48936610c5f6393cce167a6247ee001b5c575bec Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:07:24 +0000 Subject: [PATCH 09/35] arrange: Tile All tiles docked cells in the document area Tile All Vertically and Horizontally dock every document first and give each its own cell, as Tile does, instead of floating every document into its own window. --- crates/behavior/src/dock/arrange.rs | 9 ++-- crates/behavior/src/dock/windows.rs | 2 +- .../ui-panels/src/docking/commands/arrange.rs | 21 +++------- crates/ui-panels/tests/it/arrange.rs | 42 +++++++++++++++++++ crates/ui-panels/tests/it/main.rs | 1 + 5 files changed, 54 insertions(+), 21 deletions(-) create mode 100644 crates/ui-panels/tests/it/arrange.rs diff --git a/crates/behavior/src/dock/arrange.rs b/crates/behavior/src/dock/arrange.rs index ec2bc27d85..7984ce4498 100644 --- a/crates/behavior/src/dock/arrange.rs +++ b/crates/behavior/src/dock/arrange.rs @@ -4,15 +4,16 @@ use emath::{Rect, vec2}; /// One Window › Arrange entry. The n-up entries split the document area into that many -/// cells and put one document group in each, and Tile one cell per document; the rest act on -/// windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). +/// cells and put one document group in each, and Tile All and Tile one cell per document; the +/// rest act on windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Arrangement { - /// Tiles every document window across the document area, side by side. + /// One cell per document across the document area, side by side, floating windows docked + /// first. TileAllVertically, - /// Tiles every document window across the document area, stacked. + /// One cell per document across the document area, stacked, floating windows docked first. TileAllHorizontally, /// Two cells, side by side. TwoUpVertical, diff --git a/crates/behavior/src/dock/windows.rs b/crates/behavior/src/dock/windows.rs index 47246507bc..64d3a81b54 100644 --- a/crates/behavior/src/dock/windows.rs +++ b/crates/behavior/src/dock/windows.rs @@ -33,7 +33,7 @@ pub struct DocumentWindows { /// The floating groups, each with its window rect. #[serde(with = "floating_serde")] pub floating: Vec<(DocumentGroup, Rect)>, - /// The n-up or Tile arrangement the document area shows: set by Window › Arrange, cleared by + /// The n-up, Tile All or Tile arrangement the document area shows: set by Window › Arrange, cleared by /// Consolidate and by floating a document. #[serde(default)] pub arrangement: Option, diff --git a/crates/ui-panels/src/docking/commands/arrange.rs b/crates/ui-panels/src/docking/commands/arrange.rs index 0f02c7bb40..91829b958f 100644 --- a/crates/ui-panels/src/docking/commands/arrange.rs +++ b/crates/ui-panels/src/docking/commands/arrange.rs @@ -1,7 +1,7 @@ //! The Window › Arrange commands and how they place the document windows. use crate::runtime::commands::CommandState; -use craft_behavior::dock::{Arrangement, DocumentWindows, arrange_rects}; +use craft_behavior::dock::{Arrangement, DocumentWindows}; use craft_behavior::placement::cascade_rects; use egui::{Rect, Vec2}; use std::hash::Hash; @@ -11,10 +11,10 @@ use std::hash::Hash; #[command(prefix = "arrange")] #[non_exhaustive] pub enum ArrangeCommands { - /// Tile every document window across the document area, side by side. + /// Every document in its own cell of the document area, side by side, floating windows docked first. #[command(label = "Tile All Vertically")] TileAllVertically, - /// Tile every document window across the document area, stacked. + /// Every document in its own cell of the document area, stacked, floating windows docked first. #[command(label = "Tile All Horizontally")] TileAllHorizontally, /// Two document groups, side by side. @@ -154,7 +154,7 @@ impl ArrangeSpace { #[non_exhaustive] pub enum Arranged { /// The document windows changed: the host applies `DocumentWindows::to_actions`, and lays the docked groups out - /// with `arrange_rects` for an n-up or Tile arrangement. + /// with `arrange_rects` for an n-up, Tile All or Tile arrangement. Windows, /// Every document view takes the active view's zoom, location and rotation, as flagged. #[non_exhaustive] @@ -174,11 +174,7 @@ pub fn arrange(windows: &mut DocumentWindows, command: let ArrangeSpace { area, size, step, active } = space; let next_slot = |windows: &DocumentWindows| cascade_rects(*area, *size, windows.floating.len() + 1, *step).pop(); match arrangement { - Arrangement::TileAllVertically | Arrangement::TileAllHorizontally => { - windows.float_all(*area, *size, *step); - tile_floating(windows, arrangement, *area); - } - Arrangement::Tile => { + Arrangement::TileAllVertically | Arrangement::TileAllHorizontally | Arrangement::Tile => { windows.consolidate(active.as_ref()); let documents = windows.docked.first().map_or(0, |group| group.documents.len()); windows.split_into(documents); @@ -221,10 +217,3 @@ pub fn arrange(windows: &mut DocumentWindows, command: } Arranged::Windows } - -fn tile_floating(windows: &mut DocumentWindows, arrangement: Arrangement, area: Rect) { - let Some(rects) = arrange_rects(arrangement, area, windows.floating.len()) else { return }; - for ((_, rect), tiled) in windows.floating.iter_mut().zip(rects) { - *rect = tiled; - } -} diff --git a/crates/ui-panels/tests/it/arrange.rs b/crates/ui-panels/tests/it/arrange.rs new file mode 100644 index 0000000000..7390f91b4f --- /dev/null +++ b/crates/ui-panels/tests/it/arrange.rs @@ -0,0 +1,42 @@ +//! Window › Arrange over the document windows. + +use craft_behavior::dock::{Arrangement, DocumentGroup, DocumentWindows, arrange_rects}; +use craft_ui::docking::{ArrangeCommands, ArrangeSpace, Arranged, arrange}; +use craft_ui::testing::trial; +use egui::{Pos2, Rect, Vec2}; + +const AREA: Rect = Rect { min: Pos2::new(0.0, 40.0), max: Pos2::new(900.0, 640.0) }; + +/// Two documents docked in one group and a third in a floating window. +fn windows() -> DocumentWindows { + let mut windows = DocumentWindows::default(); + windows.docked = vec![DocumentGroup::new(0, vec![1, 2])]; + windows.floating = vec![(DocumentGroup::new(1, vec![3]), Rect::from_min_size(Pos2::new(50.0, 80.0), Vec2::new(300.0, 200.0)))]; + windows +} + +/// Tile All lays every document out in docked cells of the document area, as Tile does: no document is left in (or +/// moved into) a floating window, each gets its own group, and the cells run across or down the area. +#[trial] +fn tile_all_docks_every_document_in_its_own_cell_of_the_document_area() { + let space = ArrangeSpace::new(AREA, Vec2::new(400.0, 300.0), 24.0, Some(1)); + for (command, arrangement) in [ + (ArrangeCommands::TileAllVertically, Arrangement::TileAllVertically), + (ArrangeCommands::TileAllHorizontally, Arrangement::TileAllHorizontally), + ] { + let mut windows = windows(); + assert_eq!(arrange(&mut windows, command, &space), Arranged::Windows); + assert!(windows.floating.is_empty(), "{command:?} leaves no floating window: {:?}", windows.floating); + let groups: Vec<_> = windows.docked.iter().map(|group| group.documents.clone()).collect(); + assert_eq!(groups, [vec![1], vec![2], vec![3]], "{command:?} gives each document its own docked group"); + assert_eq!(windows.arrangement, Some(arrangement), "{command:?} is the arrangement the document area shows"); + let cells = arrange_rects(arrangement, AREA, groups.len()).expect("Tile All has cells for three documents"); + assert!(cells.iter().all(|cell| AREA.contains_rect(*cell)), "the cells lie in the document area: {cells:?}"); + let across = cells.windows(2).all(|pair| pair[1].left() >= pair[0].right() - 0.5); + let down = cells.windows(2).all(|pair| pair[1].top() >= pair[0].bottom() - 0.5); + match arrangement { + Arrangement::TileAllVertically => assert!(across, "Tile All Vertically puts the cells side by side: {cells:?}"), + _ => assert!(down, "Tile All Horizontally stacks the cells: {cells:?}"), + } + } +} diff --git a/crates/ui-panels/tests/it/main.rs b/crates/ui-panels/tests/it/main.rs index 70872c8f4c..83aaa72406 100644 --- a/crates/ui-panels/tests/it/main.rs +++ b/crates/ui-panels/tests/it/main.rs @@ -4,6 +4,7 @@ extern crate craft_ui_panels as craft_ui; pub(crate) mod access; +pub(crate) mod arrange; pub(crate) mod body; pub(crate) mod dialogs; pub(crate) mod dock_group; From 0bf0a39d79dd1647835b836623fc9e9c74ac755d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:28:26 +0000 Subject: [PATCH 10/35] text: the Character panel's fields fill their columns Kerning, tracking and the plain number fields fill their grid cell, as the length fields do, and kerning shows its mark inside its box. Family, style, font height, anti-aliasing and language span the panel. The row helpers take the select's sizing from the caller, so the type bar keeps its widths; Format Text and Style Options fill their cells as well. --- crates/text/src/ui/character.rs | 28 ++++++-- crates/text/src/ui/character/format_text.rs | 4 +- crates/text/src/ui/character/rows.rs | 41 ++++++++---- crates/text/src/ui/character/style_options.rs | 7 +- crates/text/src/ui/type_bar.rs | 6 +- crates/text/tests/it/character.rs | 66 ++++++++++++++++++- 6 files changed, 126 insertions(+), 26 deletions(-) diff --git a/crates/text/src/ui/character.rs b/crates/text/src/ui/character.rs index 2e9c288892..3caf14d2f2 100644 --- a/crates/text/src/ui/character.rs +++ b/crates/text/src/ui/character.rs @@ -975,14 +975,22 @@ impl<'a> CharacterControls<'a> { let columns = if ui.available_width() < pair_width { &TWO_COLUMNS[..1] } else { &TWO_COLUMNS }; let shown = Stack::new().label(self.label).show(ui, |ui, _| { #[cfg(feature = "font-picker")] - let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, picker.as_mut()); + let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, Some(Sizing::FillWidth), picker.as_mut()); #[cfg(not(feature = "font-picker"))] - let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None); + let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, Some(Sizing::FillWidth)); preview_family = family.preview; rested_family = family.rested; picker_id = family.picker; edits.extend(family.edits); - edits.extend(select_row(ui, &words.style, hidden_side(), mixed(values.style.clone()), &style_entries, CharacterChange::Style)); + edits.extend(select_row( + ui, + &words.style, + hidden_side(), + mixed(values.style.clone()), + &style_entries, + Some(Sizing::FillWidth), + CharacterChange::Style, + )); #[cfg(feature = "font-picker")] if let Some(axes) = axes { let held = values.axes.clone().unwrap_or_default(); @@ -1061,6 +1069,7 @@ impl<'a> CharacterControls<'a> { hidden_side(), mixed(values.font_height), &entries, + Some(Sizing::FillWidth), CharacterChange::FontHeight, )); } @@ -1070,7 +1079,7 @@ impl<'a> CharacterControls<'a> { let event = lengths.kerning( ui, words.kerning.clone(), - mark(GlyphLabel::icon(IconId::new("text_cursor")), Some(words.kerning_hint.clone()), FieldLayout::Beside), + mark(GlyphLabel::icon(IconId::new("text_cursor")), Some(words.kerning_hint.clone()), FieldLayout::Inside), kerning_shown, &kerning_presets, Some(keys::KERNING), @@ -1122,6 +1131,7 @@ impl<'a> CharacterControls<'a> { hidden_side(), mixed(values.anti_alias), &entries, + Some(Sizing::FillWidth), CharacterChange::AntiAlias, )); } @@ -1211,7 +1221,15 @@ impl<'a> CharacterControls<'a> { } if let Some(entries) = &language_entries { - edits.extend(select_row(ui, &words.language, hidden_side(), mixed(values.language.clone()), entries, CharacterChange::Language)); + edits.extend(select_row( + ui, + &words.language, + hidden_side(), + mixed(values.language.clone()), + entries, + Some(Sizing::FillWidth), + CharacterChange::Language, + )); } }); CharacterControlsOutput { response: shown.output, edits, preview_family, rested_family, requests, picker: picker_id } diff --git a/crates/text/src/ui/character/format_text.rs b/crates/text/src/ui/character/format_text.rs index 5a5de1ef6c..caafa3c2fd 100644 --- a/crates/text/src/ui/character/format_text.rs +++ b/crates/text/src/ui/character/format_text.rs @@ -338,9 +338,9 @@ impl<'a> FormatText<'a> { let panel = Stack::new().label(self.label).show(ui, |ui, _| { // The font, across the panel. #[cfg(feature = "font-picker")] - let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), picker.as_mut()); + let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), Some(Sizing::FillWidth), picker.as_mut()); #[cfg(not(feature = "font-picker"))] - let family = family_field(ui, &cw, character, families, reason(FormatControl::Font)); + let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), Some(Sizing::FillWidth)); edits.extend(character_edits(family.edits)); if let Some(key) = family.host_picked { edits.push(picked_event(FormatTextChange::HostFont(key), cw.family.as_str())); diff --git a/crates/text/src/ui/character/rows.rs b/crates/text/src/ui/character/rows.rs index cd192092ab..42a3d2cc65 100644 --- a/crates/text/src/ui/character/rows.rs +++ b/crates/text/src/ui/character/rows.rs @@ -106,7 +106,7 @@ impl Lengths<'_> { field.inner.unwrap_or_default() } - /// The kerning field: a number or the name of a presets row (Metrics, Optical). + /// The kerning field: a number or the name of a presets row (Metrics, Optical). The field fills its grid cell. pub(super) fn kerning( &self, ui: &mut Ui, @@ -118,7 +118,11 @@ impl Lengths<'_> { ) -> EditEvents> { let units = self.units; let shown = Field::new(label.clone()).side(side).show(ui, |ui, _| { - let field = NumberField::named(label.clone(), Bind::given(mixed(value))).range(TRACKING_RANGE).presets(presets).scrub_by_label(); + let field = NumberField::named(label.clone(), Bind::given(mixed(value))) + .range(TRACKING_RANGE) + .presets(presets) + .scrub_by_label() + .sizing(Sizing::FillWidth); let field = field.codec(NumberCodec::new(units.reader(None), 0)); match key { Some(key) => field.doc_key(key), @@ -131,7 +135,7 @@ impl Lengths<'_> { shown.inner.unwrap_or_default() } - /// A field over a number that is not a length: its event and the preset row picked. + /// A field over a number that is not a length: its event and the preset row picked. The field fills its grid cell. pub(crate) fn plain(&self, ui: &mut Ui, spec: PlainRow<'_>) -> (EditEvents>, Option) { self.plain_keyed(ui, spec, None) } @@ -141,7 +145,8 @@ impl Lengths<'_> { let PlainRow { label, side, value, range, percent, presets, disabled } = spec; let units = self.units; let shown = Field::new(label.clone()).side(side).show(ui, |ui, _| { - let field = NumberField::new(label.clone(), Bind::given(value)).range(range.clone()).presets(presets).scrub_by_label(); + let field = + NumberField::new(label.clone(), Bind::given(value)).range(range.clone()).presets(presets).scrub_by_label().sizing(Sizing::FillWidth); let field = if percent { field.unit_kind(UnitKind::Percent).step(UnitKind::Percent.step()) } else { @@ -275,21 +280,30 @@ pub(crate) fn string_entries(pairs: impl Iterator) -> V pairs.map(|(value, text)| Entry::new(value, text)).collect() } -/// A row with a select over `entries`; its pick as a change. +/// A row with a select over `entries`, sized by `sizing` (`None` keeps the select's own width); its pick as a change. pub(crate) fn select_row( ui: &mut Ui, label: &Label, side: SideLabel, value: Mixed, entries: &[Entry], + sizing: Option, change: impl Fn(V) -> C, ) -> EditEvents { let shown = Field::new(label.clone()) .side(side) - .show(ui, |ui, _| Select::new(label.clone(), Bind::given(value.clone()), entries).placeholder("—").show(ui).events); + .show(ui, |ui, _| sized(Select::new(label.clone(), Bind::given(value.clone()), entries).placeholder("—"), sizing).show(ui).events); shown.inner.unwrap_or_default().map(&change) } +/// `component` sized by `sizing`; `None` keeps its own sizing. +fn sized(component: P, sizing: Option) -> P { + match sizing { + Some(sizing) => component.sizing(sizing), + None => component, + } +} + /// One toggle button of a row: its name, icon, state (`None` while the selection mixes) and the change it makes. pub(crate) struct Toggle { pub(crate) name: Label, @@ -347,27 +361,29 @@ pub(crate) struct FamilyField { } /// The family field of the character controls, the style options and the type bar: the font picker in a -/// hidden-label field when a `picker` source is given, else a select over `families`. A `disabled` reason disables the -/// field and shows in its tooltip. +/// hidden-label field when a `picker` source is given, else a select over `families`, sized by `sizing` (`None` keeps +/// the control's own width). A `disabled` reason disables the field and shows in its tooltip. pub(crate) fn family_field( ui: &mut Ui, words: &CharacterWords, values: &CharacterValues, families: &[String], disabled: Option<&Label>, + sizing: Option, #[cfg(feature = "font-picker")] picker: Option<&mut FontPickerSource<'_>>, ) -> FamilyField { #[cfg(feature = "font-picker")] { - family_field_keyed(ui, words, values, families, None, disabled, picker) + family_field_keyed(ui, words, values, families, None, disabled, sizing, picker) } #[cfg(not(feature = "font-picker"))] { - family_field_keyed(ui, words, values, families, None, disabled) + family_field_keyed(ui, words, values, families, None, disabled, sizing) } } /// As [`family_field`], the picker carrying the document `key` a host focuses it by (the plain select has none). +#[allow(clippy::too_many_arguments)] pub(crate) fn family_field_keyed( ui: &mut Ui, words: &CharacterWords, @@ -376,6 +392,7 @@ pub(crate) fn family_field_keyed( #[cfg(feature = "font-picker")] key: Option, #[cfg(not(feature = "font-picker"))] _key: Option, disabled: Option<&Label>, + sizing: Option, #[cfg(feature = "font-picker")] picker: Option<&mut FontPickerSource<'_>>, ) -> FamilyField { let value = mixed(values.family.clone()); @@ -403,7 +420,7 @@ pub(crate) fn family_field_keyed( if let Some(key) = key { field = field.doc_key(key); } - disabled_for(field, &words.family, disabled).show(ui) + disabled_for(sized(field, sizing), &words.family, disabled).show(ui) }); let Some(out) = shown.inner else { return FamilyField::default() }; let id = craft_ui::contract::Outcome::response(&out).id; @@ -422,7 +439,7 @@ pub(crate) fn family_field_keyed( let entries = string_entries(families.iter().map(|name| (name.clone(), name.clone()))); let shown = Field::new(words.family.clone()).side(hidden_side()).show(ui, |ui, _| { let select = Select::new(words.family.clone(), Bind::given(value.clone()), &entries).placeholder("—"); - disabled_for(select, &words.family, disabled).show(ui).events + disabled_for(sized(select, sizing), &words.family, disabled).show(ui).events }); let edits = shown.inner.unwrap_or_default().map(CharacterChange::Family).into_iter().collect(); FamilyField { edits, ..FamilyField::default() } diff --git a/crates/text/src/ui/character/style_options.rs b/crates/text/src/ui/character/style_options.rs index f6b9856149..b7ad6ed8ea 100644 --- a/crates/text/src/ui/character/style_options.rs +++ b/crates/text/src/ui/character/style_options.rs @@ -308,9 +308,9 @@ impl<'a> TextStyleOptions<'a> { let found = match attribute { StyleAttribute::Font => include_row(ui, &words.include, attribute, on, |ui| { #[cfg(feature = "font-picker")] - let family = family_field(ui, &cw, c, families, None, picker.as_mut()); + let family = family_field(ui, &cw, c, families, None, Some(Sizing::FillWidth), picker.as_mut()); #[cfg(not(feature = "font-picker"))] - let family = family_field(ui, &cw, c, families, None); + let family = family_field(ui, &cw, c, families, None, Some(Sizing::FillWidth)); let mut found = character(family.edits); found.extend(character(select_row( ui, @@ -318,6 +318,7 @@ impl<'a> TextStyleOptions<'a> { hidden_side(), mixed(c.style.clone()), &style_entries, + Some(Sizing::FillWidth), CharacterChange::Style, ))); found @@ -390,7 +391,7 @@ impl<'a> TextStyleOptions<'a> { let align_of = |key: String| { ParagraphChange::Align(ALIGNS.iter().find(|(_, k)| *k == key).map_or_else(TextAlign::default, |(align, _)| *align)) }; - paragraph_changes(select_row(ui, &pw.alignment, hidden_side(), mixed(key), &align_entries, align_of)) + paragraph_changes(select_row(ui, &pw.alignment, hidden_side(), mixed(key), &align_entries, Some(Sizing::FillWidth), align_of)) }), StyleAttribute::FirstLineIndent => include_row(ui, &words.include, attribute, on, |ui| { let row = LengthRow { diff --git a/crates/text/src/ui/type_bar.rs b/crates/text/src/ui/type_bar.rs index b81e31b8a7..bcf3d03aa2 100644 --- a/crates/text/src/ui/type_bar.rs +++ b/crates/text/src/ui/type_bar.rs @@ -178,14 +178,14 @@ impl<'a> TypeBar<'a> { .extend(toggle.events.map(|on| TypeBarChange::Orientation(if on { TextOrientation::Vertical } else { TextOrientation::Horizontal }))); #[cfg(feature = "font-picker")] - let family = family_field(ui, &character_words, character, families, None, picker.as_mut()); + let family = family_field(ui, &character_words, character, families, None, None, picker.as_mut()); #[cfg(not(feature = "font-picker"))] - let family = family_field(ui, &character_words, character, families, None); + let family = family_field(ui, &character_words, character, families, None, None); preview_family = family.preview; rested_family = family.rested; edits.extend(family.edits.into_iter().map(|event| event.map(TypeBarChange::Character))); - let style = select_row(ui, &bar_words.style, hidden_side(), mixed(character.style.clone()), &style_entries, CharacterChange::Style); + let style = select_row(ui, &bar_words.style, hidden_side(), mixed(character.style.clone()), &style_entries, None, CharacterChange::Style); edits.extend(style.into_iter().map(|event| event.map(TypeBarChange::Character))); // The size glyph the Character panel's size row shows. diff --git a/crates/text/tests/it/character.rs b/crates/text/tests/it/character.rs index f7c97491f5..8671198e28 100644 --- a/crates/text/tests/it/character.rs +++ b/crates/text/tests/it/character.rs @@ -1,6 +1,7 @@ use craft_text::ui::character::{CharacterControls, CharacterRows, CharacterValues, Kerning, Leading}; +use craft_theme::TextSize; use craft_ui::testing::{Fixture, trial}; -use egui::vec2; +use egui::{Rect, vec2}; #[trial] fn character_fields_are_readable_when_the_panel_is_narrowed() { @@ -44,3 +45,66 @@ fn the_properties_rows_leave_out_baseline_shift_and_the_style_toggles() { } } } + +/// Edges closer than this are the same edge. +const EDGE: f32 = 0.5; + +#[trial] +fn character_fields_line_up_in_their_columns_at_every_width_and_text_size() { + let families = vec!["Inter".to_owned()]; + let styles = vec!["Regular".to_owned()]; + let mut fixture = Fixture::new(move |ui| { + let values = CharacterValues { + family: Some("Inter".to_owned()), + style: Some("Regular".to_owned()), + size: Some(12.0), + leading: Some(Leading::Auto), + kerning: Some(Kerning::Metrics), + ..CharacterValues::default() + }; + CharacterControls::new("Character", &values, &families, &styles).show(ui); + }); + let left = ["Font size", "Kerning", "Vertical scale", "Baseline shift"]; + let right = ["Leading", "Tracking", "Horizontal scale"]; + let across = ["Font family", "Style"]; + + for text_size in [TextSize::Small, TextSize::Large] { + fixture.text_size(text_size); + for width in [222.0, 300.0, 340.0, 402.0, 520.0] { + fixture.room(vec2(width, 900.0)).settle(); + let at = format!("at {width} pt, {text_size:?} text"); + let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown {at}")).rect; + let same = |a: f32, b: f32| (a - b).abs() <= EDGE; + let size = rect("Font size"); + let leading = rect("Leading"); + let lined_up = |labels: &[&str], column: Rect| { + for label in labels { + let field = rect(label); + assert!( + same(field.left(), column.left()) && same(field.right(), column.right()), + "{label} {field:?} spans its column {column:?} {at}" + ); + } + }; + let full = Rect::from_x_y_ranges(size.left()..=leading.right(), size.y_range()); + if size.bottom() <= leading.top() { + // One column: every field spans it. + lined_up(&left, size); + lined_up(&right, size); + lined_up(&across, size); + assert!(same(rect("Text color").right(), size.right()), "the colour well ends at the column's end {at}"); + } else { + assert!(size.right() <= leading.left(), "the columns do not overlap {at}"); + lined_up(&left, size); + lined_up(&right, leading); + lined_up(&across, full); + assert!(same(rect("Text color").right(), leading.right()), "the colour well ends at the right column's end {at}"); + } + assert!(full.right() <= size.left() + width + EDGE, "no field runs past the panel {at}"); + for value in ["12", "Metrics"] { + let text = fixture.texts().iter().find(|run| run.text == value).unwrap_or_else(|| panic!("{value} is painted {at}")).clone(); + assert!(!text.elided && text.clip.expand(EDGE).contains_rect(text.rect), "{value} fits inside its field {at}: {text:?}"); + } + } + } +} From 45c8a4a3f7f297b9f7496a4bf465589b1839e895 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 04:50:46 +0000 Subject: [PATCH 11/35] draw: Shift while dragging a Bezier handle turns it to the nearest 45 degrees about its anchor --- crates/draw/src/ui/pen/bezier/mod.rs | 11 ++++++++--- crates/draw/tests/it/bezier.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index be40e447ac..a480816dc3 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -212,6 +212,8 @@ enum Target { knot: KnotRef, side: HandleSide, from: Point, + /// The handle's anchor at the press: ⇧ turns the handle about it. + anchor: Point, }, /// A curved segment, grabbed at `t` where it passes `from`. Bend { @@ -635,7 +637,8 @@ impl<'a> BezierOverlay<'a> { let knot_at = |path: u64, knot: KnotRef| Self::path(paths, path).and_then(|p| p.knot(knot)); match (self.tool, hit) { (_, BezierHit::Handle { path, knot, side }) if self.tool != BezierTool::Curvature => { - Target::Handle { path, knot, side, from: knot_at(path, knot).map_or(Point::ZERO, |k| k.handle(side)) } + let at = knot_at(path, knot); + Target::Handle { path, knot, side, from: at.map_or(Point::ZERO, |k| k.handle(side)), anchor: at.map_or(Point::ZERO, |k| k.anchor) } } (BezierTool::Curvature, BezierHit::Anchor { path, knot }) => { self.report.select = Some(self.selecting(path, vec![knot], None)); @@ -728,8 +731,10 @@ impl<'a> BezierOverlay<'a> { Target::Anchors { path, anchors, from } => { PathEdit::MoveAnchors { path: *path, anchors: anchors.clone(), by: snapped(*from + locked(delta)) - *from } } - &Target::Handle { path, knot, side, from } => { - PathEdit::MoveHandle { path, knot, side, to: snapped(from + delta), alone: tool == BezierTool::Convert || mods.alt } + &Target::Handle { path, knot, side, from, anchor } => { + // ⇧ turns the handle to the nearest 45° about its anchor, as the Pen's pull does. + let to = if mods.shift { handle_45(anchor, from + delta) } else { snapped(from + delta) }; + PathEdit::MoveHandle { path, knot, side, to, alone: tool == BezierTool::Convert || mods.alt } } &Target::Bend { path, segment, t, from } => PathEdit::BendSegment { path, segment, t, by: snapped(from + delta) - from }, &Target::Convert { path, knot } => PathEdit::Convert { path, knot, out: Some(snapped(view.to_doc(pointer))) }, diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 65b671f93e..aa17f19146 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -739,6 +739,33 @@ fn shift_keeps_an_anchor_drag_on_the_axis_or_the_diagonal() { } } +// ⇧ during a handle drag turns the handle to the nearest 45° about its anchor, also when pressed mid-drag: about 20° +// lands on the axis, about 40° on the diagonal, and photocraft#15760's measured (-78, +140) on (-78, +78); without ⇧ +// the handle follows the pointer. +#[trial] +fn shift_locks_a_handle_drag_to_the_nearest_45_degrees() { + let anchor = p(260.0, 60.0); + let cases = + [(p(360.0, 96.0), p(360.0, 60.0)), (p(340.0, 127.0), p(327.0, 127.0)), (anchor + Vec2::new(-78.0, 140.0), anchor + Vec2::new(-78.0, 78.0))]; + for (shift, (target, locked)) in cases.iter().flat_map(|c| [(true, *c), (false, *c)]) { + let mut h = two_paths(); + h.update(|st| st.selection = sel(1, &[(0, 2)])); + let handle = h.screen(p(290.0, 100.0)); + let to = h.screen(target); + h.press_at(handle); + h.move_to(handle + (to - handle) * 0.5); + if shift { + h.fixture.hold(egui::Modifiers::SHIFT); + } + h.move_to(to); + let Some(PathEdit::MoveHandle { to: got, .. }) = h.last_change() else { panic!("a handle move: {:?}", h.last_change()) }; + h.release_at(to); + h.fixture.hold(egui::Modifiers::NONE); + let want = if shift { locked } else { target }; + assert!(got.distance(want) < 1e-3, "shift {shift}: {target:?} gives {got:?}, wants {want:?}"); + } +} + // Delete Anchor with only some subpaths' anchors shown (#12769): a click on a hidden anchor deletes nothing and // edits nothing, selects that anchor and shows only its subpath; the next click on it deletes it. #[trial] From 225de8b83cb6a40eb518431f2f6ab8f08f515d42 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 06:45:13 +0000 Subject: [PATCH 12/35] automation: the actions file keeps every set's order ActionList::to_file stored only the empty sets, so a set created empty before filled ones moved after them on reload. The file gains an optional set_order, written when loading would not give the list's order; files without it load as before. --- crates/automation/src/actions/file.rs | 12 ++++++++++-- crates/automation/src/actions/list.rs | 20 +++++++++++++++++--- crates/automation/src/actions/tests.rs | 16 ++++++++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/automation/src/actions/file.rs b/crates/automation/src/actions/file.rs index 845fd82a0e..3553932c91 100644 --- a/crates/automation/src/actions/file.rs +++ b/crates/automation/src/actions/file.rs @@ -22,6 +22,12 @@ pub struct ActionsFile { /// Sets that hold no action. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sets: Vec, + /// Every set name in display order, empty sets included. Written only when loading `actions` + /// and `sets` would not give this order (the actions' sets in order of first appearance, then + /// the empty sets), so files in that natural order, PhotoCraft's included, save unchanged. + /// Files without it load in the natural order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub set_order: Vec, /// The folder occurrences a PhotoCraft file carried; empty for every other file. #[serde(skip)] pub(super) occurrences: FileOccurrences, @@ -55,6 +61,8 @@ struct RawFile { #[serde(default)] sets: Vec, #[serde(default)] + set_order: Vec, + #[serde(default)] set_rows: Vec, } @@ -71,7 +79,7 @@ impl From for ActionsFile { let (actions, occurrences): (Vec, Vec) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip(); let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default()); let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } }; - ActionsFile { version: raw.version, actions, sets: raw.sets, occurrences } + ActionsFile { version: raw.version, actions, sets: raw.sets, set_order: raw.set_order, occurrences } } } @@ -117,7 +125,7 @@ impl ActionsFile { /// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`. pub fn new(actions: Vec, sets: Vec) -> Self { - ActionsFile { version: Self::VERSION, actions, sets, occurrences: FileOccurrences::default() } + ActionsFile { version: Self::VERSION, actions, sets, set_order: Vec::new(), occurrences: FileOccurrences::default() } } /// Reads a file's JSON text. diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index 4828bcb13e..ce533f7469 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -576,12 +576,13 @@ impl ActionList { /// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back /// in [`MergedFile::ids`]. pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { - let ActionsFile { mut actions, sets, occurrences, .. } = file; + let ActionsFile { mut actions, sets, set_order, occurrences, .. } = file; if replace { let named: BTreeSet<&str> = actions .iter() .filter_map(|action| action.set.as_deref()) .chain(sets.iter().map(String::as_str)) + .chain(set_order.iter().map(String::as_str)) .chain(occurrences.set_rows.iter().map(String::as_str)) .collect(); self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set))); @@ -596,6 +597,9 @@ impl ActionList { for (&i, name) in order.iter().zip(claimed) { given[i] = name; } + for set in &set_order { + self.record_set(set); + } let mut merged = MergedFile::default(); let ids = file_ids(&occurrences.actions); for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() { @@ -757,10 +761,20 @@ impl ActionList { self.touch(); } - /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`). + /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`, the set order in `set_order` when it is not the natural one). pub fn to_file(&self) -> ActionsFile { let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set))); - ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) + let mut file = ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()); + let mut natural: Vec<&str> = Vec::new(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()).chain(file.sets.iter().map(String::as_str)) { + if !natural.contains(&set) { + natural.push(set); + } + } + if natural != self.sets() { + file.set_order = self.sets().into_iter().map(str::to_owned).collect(); + } + file } /// Puts `set` at the end of the set order when the order lacks it. diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 7bea5df8c7..2ae7845e9f 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -80,6 +80,22 @@ fn action_list_file_round_trip_keeps_pc_json() { assert_eq!(back.sets, ["Empty"]); assert_eq!(ActionList::from_file(back).sets(), ["S", "Empty"]); } +// An empty set made before filled ones keeps its place through a save; a file of the older layout +// (empty sets in `sets`, no `set_order`) loads with its filled sets first. +#[trial] +fn set_order_survives_the_file() { + let mut list = ActionList::new(); + list.new_set("A").unwrap(); + list.new_set("B").unwrap(); + list.new_set("C").unwrap(); + list.push(Action { set: Some("B".into()), ..action("X", &[]) }).unwrap(); + list.push(Action { set: Some("C".into()), ..action("Y", &[]) }).unwrap(); + let back = ActionList::from_file(ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap()); + assert_eq!(back.sets(), ["A", "B", "C"]); + + let old = r#"{"version":1,"actions":[{"name":"X","steps":[],"set":"F"}],"sets":["E"]}"#; + assert_eq!(ActionList::from_file(ActionsFile::from_json(old).unwrap()).sets(), ["F", "E"]); +} // A file that repeats a name keeps a later action's own name: `Foo, Foo, Foo 2` renames the repeat // (`Foo 3`), never the real `Foo 2`; a merge does the same against the names already in the list. #[trial] From 50a9ed02ae51793964be1b8af9efd39cc5fc58ee Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 07:16:18 +0000 Subject: [PATCH 13/35] Right-click on guides, rulers and the transform box is theirs again; percent fields keep the caller's decimals; a mixed font family shows an empty field - Guides and the rulers' strips and corner sense CONTEXT_CLICK, so a right-click opens their menu instead of reaching the tool host (the press machine gives a secondary press only to CONTEXT_CLICK shapes since 21e77e2b58). - TransformBox::own_context_menu: the caller hangs a context menu on the box, and every part takes the right-click. TransformOverlay sets it for the whole-box reach, where it opens the mode menu. - NumberField: a percent field's one-decimal default yields to the caller's fixed or maximum decimals, and shows none with commit_decimals(0) ("10%"). - FontPicker: a selection of several families leaves the family field empty, on screen and in its accessible value, as the reference applications do. --- .../draw/src/ui/transform/session_overlay.rs | 1 + crates/draw/src/ui/transform/transform_box.rs | 30 ++++++++------ crates/draw/tests/it/transform_box.rs | 18 +++++++-- crates/font-manager/src/picker.rs | 14 +------ crates/font-manager/tests/it/picker.rs | 14 +++++-- crates/ui-canvas/src/canvas/rulers/mod.rs | 8 +++- .../src/canvas_controls/guides/mod.rs | 2 +- crates/ui-canvas/tests/it/canvas/rulers.rs | 40 +++++++++++++++++++ .../tests/it/canvas_controls/guides.rs | 38 +++++++++++++++++- crates/ui-widgets/src/text/number.rs | 28 ++++++++----- crates/ui-widgets/tests/it/text/number.rs | 22 ++++++++++ 11 files changed, 171 insertions(+), 44 deletions(-) diff --git a/crates/draw/src/ui/transform/session_overlay.rs b/crates/draw/src/ui/transform/session_overlay.rs index de65d190e0..f5414abac0 100644 --- a/crates/draw/src/ui/transform/session_overlay.rs +++ b/crates/draw/src/ui/transform/session_overlay.rs @@ -160,6 +160,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> { .reference_point(session.reference_point()) .reach(self.reach) .rotate_zone(self.rotate_zone) + .own_context_menu(self.reach == TransformReach::Box) .id_source(self.id); if let Some(mods) = self.mods { tbox = tbox.mods(mods); diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index c5605959ca..837fe4dee1 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -509,6 +509,10 @@ pub struct TransformBox<'a> { /// and an open drag's Escape still cancels the drag. #[prop] session_commit: bool, + /// The caller hangs a context menu of its own on the box (`Menu::context` over its response): every part takes the + /// right click, so it does not reach the tool under the box. + #[prop] + own_context_menu: bool, /// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves. pivot_held: bool, /// Whether this pass holds a drag that began, so a live line's box shows as it scales. @@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> { reach: TransformReach::Box, color: None, session_commit: true, + own_context_menu: false, pivot_held: false, dragging: false, report: Report::default(), @@ -1098,11 +1103,11 @@ fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, co /// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border, /// as a strip along each side and a round sector outside each corner (PhotoCraft's type move reach measures the /// distance to the nearest side, pc-prod-e76 type_transform.rs:156-196). -fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32) { +fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32, context: Sense) { let outward = outward_normals(quad); let mut declare = |part: usize, shape: Vec| { cx.part(MOVE_RING.at(part as u64), HitShape::Polygon(shape)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Body, RING_SUB)) .pointer_only(MOVE_BY_KEY); }; @@ -1250,9 +1255,10 @@ impl Component for TransformBox<'_> { let style = cx.style; let screen = on_screen(&space.view, &state); let quad: [Pos2; 4] = screen.quad.map(pos); + let context = if self.own_context_menu { Sense::CONTEXT_CLICK } else { Sense::empty() }; if self.move_only().is_some() { if let Some(points) = self.ring_reach() { - declare_ring(cx, &quad, points); + declare_ring(cx, &quad, points, context); } return; } @@ -1279,13 +1285,13 @@ impl Component for TransformBox<'_> { ) } }; - cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable(); + cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part) | context).priority(priority).focus_shape(focus).focusable(); any = true; } if let Some(line) = self.line { for (end, at) in line.free_ends() { cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK) + .sense(Sense::DRAG | Sense::CLICK | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(LINE_END_BY_KEY); } @@ -1299,7 +1305,7 @@ impl Component for TransformBox<'_> { let band = if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) }; cx.part(EDGE.at(u64::from(k)), band) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)) | context) .priority(HitPriority::new(HitLevel::Handle, EDGE_SUB)) .pointer_only(EDGE_BY_KEY); } @@ -1309,7 +1315,7 @@ impl Component for TransformBox<'_> { for (end, side) in [(0u64, corner), (1, (corner + 3) % 4)] { let Some(reach) = corner_reach(&quad, side, corner, style.side_band) else { continue }; cx.part(CORNER_REACH.at(2 * u64::from(k) + end), reach) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(CORNER_BY_KEY); } @@ -1317,7 +1323,7 @@ impl Component for TransformBox<'_> { if self.declares_centre() { let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0; cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(MOVE_BY_KEY); } @@ -1328,7 +1334,7 @@ impl Component for TransformBox<'_> { RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => { for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Background, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1336,7 +1342,7 @@ impl Component for TransformBox<'_> { RotateZone::Band if self.rules.allows(BoxPart::Outside) => { for (corner, ring) in band_rings(&screen, style).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(ring)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1347,7 +1353,7 @@ impl Component for TransformBox<'_> { if self.has_knob() { let (knob, _) = knob_at(&quad, rect, style); cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } @@ -1355,7 +1361,7 @@ impl Component for TransformBox<'_> { RotateZone::Handle if self.rules.allows(BoxPart::Outside) => { let (_, knob) = rotate_handle(&quad, style.rotate_stem); cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 0fbf30cc63..e8b32bb82e 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1070,20 +1070,28 @@ fn a_jittery_double_click_inside_applies_with_no_move_committed() { assert_eq!(h.host.borrow().applied, 1, "the double click applies"); } -/// A secondary click on the session's box opens the mode menu (its rows are on the page); with the menu closed again, a -/// secondary click away from the box opens none. +/// A secondary click on the session's box opens the mode menu (its rows are on the page) and is the box's alone: the +/// tool host under it asks for no menu of its own. With the menu closed again, a secondary click away from the box +/// opens none. #[trial] fn a_secondary_click_on_the_box_opens_the_mode_menu() { + use craft_draw::ui::transform::TransformTool; + use craft_ui::canvas::{ToolHost, tool_pass}; let session = TransformSession::<()>::new(RECT); let settings = TransformSettings::default(); let view = Rc::new(RefCell::new(CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0))); - let shown_view = Rc::clone(&view); + let host_asked = Rc::new(Cell::new(false)); + let (shown_view, asked) = (Rc::clone(&view), Rc::clone(&host_asked)); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let at = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); *shown_view.borrow_mut() = at; Canvas::new("Document").view(at).show(ui, |ui, body| { - TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + let shown = TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + if let Some(pass) = tool_pass(&body.env) { + let mut tool = TransformTool::new(&session, shown.snapped.clone()); + asked.set(asked.get() || ToolHost::new().run(ui, &pass, &mut tool).context.is_some()); + } }); }); fixture.settle(); @@ -1098,8 +1106,10 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() { right_click(&mut fixture, screen(Point::new(1000.0, 1000.0))); assert!(fixture.by_label("Distort").is_none(), "a secondary click away from the box opens no mode menu"); + host_asked.set(false); right_click(&mut fixture, screen(Point::new(200.0, 150.0))); assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu"); + assert!(!host_asked.get(), "the tool host under the box asks for no menu"); } /// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 887faf69c5..e25ff17667 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -19,7 +19,7 @@ use craft_host::Section; use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ - Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop, }; use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow}; @@ -59,8 +59,6 @@ craft_ui::words! { /// The name of the preview banner, with `{family}` for the family it shows. preview_of: template "fontPicker.previewOf" = "Font preview: {family}"; no_match: "fontPicker.noMatch" = "No fonts match"; - /// The family field's label when the selection has several families. - mixed: "fontPicker.mixed" = "Mixed"; /// The name of a row's star, with `{row}` for the row's label. favorite: template "fontPicker.favorite" = "Favorite {row}"; list: "fontPicker.list" = "Fonts"; @@ -934,10 +932,8 @@ impl Component for FontPicker<'_> { } let mut options = TextOptions::new(); options.select_on_focus = true; + // A selection of several families shows an empty field, as the reference applications do. options.mixed = cx.value().is_none(); - if options.mixed { - options.placeholder = Some(cx.words::().mixed.clone()); - } if !self.catalog.is_ready() { // The first scan runs on a background thread; the field asks again until it ends. self.catalog.scan_in_background(); @@ -954,12 +950,6 @@ impl Component for FontPicker<'_> { Some(self.family.reborrow()) } - fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { - if cx.value().is_none() && cx.text(&text_key()).is_none_or(|text| text.draft.as_deref().is_none_or(str::is_empty)) { - access.value(cx.words::().mixed.as_str()); - } - } - /// A changed draft filters the list: it opens on the matches, and closes when the draft ended (committed, /// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the /// list is closed, the arrows and the wheel step through the host rows and the families. diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 5b1f60c26b..bf185a32cd 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -122,8 +122,10 @@ fn present(fx: &Fixture, text: &str) -> bool { fx.by_label(text).is_some() || fx.texts().iter().any(|painted| painted.text == text) } +/// A selection of several families leaves the family field empty, on screen and to assistive technology, as the +/// reference applications do: no family name and no word stands in for it. #[trial] -fn mixed_family_is_named_until_a_font_is_chosen() { +fn a_mixed_family_shows_an_empty_field() { let catalog = catalog_of(&[INTER_REGULAR]); let mut family = craft_behavior::Mixed::::Mixed; let mut fx = Fixture::new(move |ui| { @@ -132,8 +134,14 @@ fn mixed_family_is_named_until_a_font_is_chosen() { fx.in_room(Room::Window); fx.settle(); let field = fx.by_role(craft_ui::runtime::access::Role::COMBO_BOX).into_iter().next().expect("the family field"); - let label = fx.tree().value_of(field.node).filter(|value| !value.is_empty()).expect("the mixed family has an accessible label"); - assert!(present(&fx, label), "the accessible mixed label is also visible"); + assert!(fx.tree().value_of(field.node).is_none_or(str::is_empty), "the mixed family has no accessible value"); + let words: Vec = fx + .texts() + .iter() + .filter(|painted| field.rect.contains_rect(painted.rect) && painted.text.chars().any(char::is_alphabetic)) + .map(|painted| painted.text.clone()) + .collect(); + assert!(words.is_empty(), "the field paints no text: {words:?}"); } #[trial] diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index bed29b8ea2..96acf884f3 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -402,7 +402,7 @@ impl Component for Rulers<'_> { for (part, strip) in [(RulerPart::Horizontal, top), (RulerPart::Vertical, left)] { let declared = cx.part(part.part(), strip).priority(handle).pointer_only("the New Guide... command places a guide by number"); if self.interactive { - let declared = declared.sense(Sense::DRAG | Sense::CLICK); + let declared = declared.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK); if let Some(space) = space { declared.cursor(resize_cursor(&space.view, motion_across(part.guide_along()))); } @@ -410,7 +410,11 @@ impl Component for Rulers<'_> { } let declared = cx.part(CORNER, corner).priority(handle); if self.interactive { - let sense = if self.origin_locked { Sense::CLICK | Sense::CONTEXT_CLICK } else { Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS }; + let sense = if self.origin_locked { + Sense::CLICK | Sense::CONTEXT_CLICK + } else { + Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS + }; let declared = declared.sense(sense); if self.origin_locked { declared.pointer_only("the zero point is locked"); diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index c84c921be0..f66ebb358a 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -499,7 +499,7 @@ impl Component for Guides<'_> { let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, rect) else { continue }; let part = cx .part(guide.key.part(GUIDE), HitShape::segment(a, b)) - .sense(Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS) + .sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS) .priority(HitPriority::new(HitLevel::Edge, 0)) .cursor(resize_cursor(&space.view, motion_across(guide.along))) .focusable(); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 7176fc6ff1..16aa582880 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -265,3 +265,43 @@ fn a_corner_drag_the_host_cancelled_lands_nothing_at_its_release() { fixture.settle(); assert_eq!(*zero.borrow(), host, "the release after the host's change leaves the zero point where the host put it"); } + +/// A right-click on a ruler strip or on the corner is the rulers': they report the part, for their units menu, and +/// the tool host under them asks for no menu of its own. +#[trial] +fn a_right_click_on_a_ruler_is_the_rulers_not_the_tools() { + use craft_ui::canvas::{RulerPart, ToolHost, tool_pass}; + let zero = Rc::new(RefCell::new(Point::ZERO)); + let asked: Rc, bool)>> = Rc::new(RefCell::new((None, false))); + let (shown_zero, seen) = (Rc::clone(&zero), Rc::clone(&asked)); + let room = Rc::new(Cell::new(Rect::NOTHING)); + let shown_room = Rc::clone(&room); + let tool = RefCell::new(Overpaint); + let mut fixture = Fixture::new(move |ui| { + let at = ui.available_rect_before_wrap(); + shown_room.set(at); + let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0); + let mut zero = shown_zero.borrow_mut(); + let mut host_asked = false; + let canvas = Canvas::new("Document").view(view).with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut *zero)))).show(ui, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + host_asked = ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(canvas.output.rulers.as_ref().and_then(|rulers| rulers.context)); + seen.1 |= host_asked; + }); + fixture.room(Vec2::new(500.0, 400.0)).settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![craft_ui::testing::pointer::moved(at)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + let canvas = room.get(); + assert_eq!(right_click(egui::pos2(canvas.center().x, canvas.min.y + 4.0)), (Some(RulerPart::Horizontal), false), "the top strip"); + assert_eq!(right_click(canvas.min + Vec2::splat(4.0)), (Some(RulerPart::Corner), false), "the corner, its zero point unlocked"); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/guides.rs b/crates/ui-canvas/tests/it/canvas_controls/guides.rs index 3f32ad108a..9336a261b6 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/guides.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/guides.rs @@ -6,7 +6,7 @@ use craft_behavior::{Axis, CancelReason, CanvasView}; use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft_ui::canvas_controls::Guides; use craft_ui::canvas_controls::reading::{GuideReading, running}; -use craft_ui::contract::{Bind, BodyCx, Show as _}; +use craft_ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::Draw; use craft_ui::testing::{ToolFixture, pointer, tool_fixture, trial}; use egui::{Id, Key, Modifiers, Pos2, Rect, Vec2, pos2, vec2}; @@ -284,3 +284,39 @@ fn a_deleted_guide_hands_focus_on_without_selecting_the_next_guide() { assert!(at(&guides, Axis::Y, 200.0).is_none(), "Delete removes it: {:?}", guides.borrow()); assert_eq!(*selected.borrow(), None, "and selects no other guide"); } + +// A right-click on an unlocked guide is the guide's: the guides report its menu request and the tool host under them +// reports none. Off the guide the right-click reaches the host, which asks for its own menu. +#[trial] +fn a_right_click_on_a_guide_asks_for_the_guide_menu_not_the_tools() { + use craft_ui::canvas::{Canvas, ToolHost, tool_pass}; + use craft_ui::testing::Fixture; + use craft_ui::testing::tool_fixture::DOCUMENT; + let guides: Shared> = Rc::new(RefCell::new(vec![guide(1, Axis::Y, 200.0)])); + let asked: Shared<(Option, bool)> = Rc::new(RefCell::new((None, false))); + let (shown, seen) = (Rc::clone(&guides), Rc::clone(&asked)); + let tool = RefCell::new(Recorder::default()); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(tool_fixture::canvas_id("Document")).document(DOCUMENT).view(view_at(1.0)(room)); + let _ = canvas.show(ui, |ui, body| { + let out = Guides::new("Guides", canvas_of(body), Bind::bound(&mut *shown.borrow_mut())).interactive(true).show_at(ui, body.rect); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(out.context.map(|(key, _)| key)); + if let Some(pass) = tool_pass(&body.env) { + seen.1 |= ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + }); + fixture.settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + assert_eq!(right_click(pos2(200.0, 300.0)), (Some(GuideKey::new(1)), false), "on the guide: its menu, not the tool's"); + assert_eq!(right_click(pos2(400.0, 300.0)), (None, true), "off the guide: the tool's menu"); +} diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 464009b74a..51bdb02b38 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -194,7 +194,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// A typed value goes to the nearest multiple of the step when it commits. #[prop] snap_typed: bool, - /// The decimals a committed value is rounded to; the display keeps the codec's. + /// The decimals a committed value is rounded to; the display keeps the codec's, except that a percent field with no + /// decimals of its own shows none when this is 0 ("10%"). #[prop] commit_decimals: Option, /// An empty field means automatic: it shows the "Auto" word as its placeholder. @@ -442,11 +443,21 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { value.and_then(NumberValue::number).map(|stored| self.to_shown(stored)) } - /// Whether the field counts percent: it writes its precision's decimals in full, its sign right after the number. + /// Whether the field counts percent: it shows its sign right after the number. fn is_percent(&self) -> bool { self.codec.is_none() && self.unit_kind == Some(UnitKind::Percent) } + /// The decimals a percent field writes in full when the caller sets none of its own: one at the standard precision + /// ("100.0%"), none at the measured precision ("100%") or for a field whose committed values carry none + /// (`commit_decimals(0)`). + fn percent_decimals(&self) -> Option { + (self.is_percent() && self.fixed_decimals.is_none() && self.max_decimals.is_none()).then(|| match self.precision { + NumberPrecision::Standard => self.commit_decimals.unwrap_or(1).min(1), + NumberPrecision::Measured => 0, + }) + } + /// Whether the field uses the dash for a missing or invalid value. fn shows_blank(&self, shown: Option<&V>) -> bool { shown.is_none() || non_finite(shown) || (self.status_zoom && shown.and_then(NumberValue::number).is_none()) @@ -461,19 +472,18 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { None => units.reader(self.unit_kind), }; let codec = NumberCodec::new(reader, self.decimals()); - if self.fixed_decimals.is_some() || self.is_percent() { codec.fixed() } else { codec } + if self.fixed_decimals.is_some() || self.percent_decimals().is_some() { codec.fixed() } else { codec } }) } - /// The decimals the field shows: its codec's, fixed or maximum precision, else its unit kind's. + /// The decimals the field shows: its codec's, fixed or maximum precision, a percent field's own, else its unit + /// kind's. fn shown_decimals(&self) -> RangeInclusive { + if let Some(percent) = self.percent_decimals() { + return percent..=percent; + } match (&self.codec, self.fixed_decimals, self.max_decimals, self.unit_kind) { (Some(codec), _, _, _) => 0..=codec.decimals(), - // A percentage reads "100.0%": one decimal, written in full; whole at the measured precision. - (None, _, _, Some(UnitKind::Percent)) => match self.precision { - NumberPrecision::Standard => 1..=1, - NumberPrecision::Measured => 0..=0, - }, (None, Some(fixed), _, _) => fixed..=fixed, (None, None, Some(max), _) => 0..=max.min(12), (None, None, None, Some(kind)) => match (self.precision, self.lengths) { diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index d3bce13238..3420c531a2 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -775,3 +775,25 @@ fn a_percent_field_reads_one_decimal_then_the_sign() { let sign = painted("%").unwrap_or_else(|| panic!("the field shows the sign")); assert!(sign.min.x - number.max.x <= 5.0, "the sign follows the number closely: {number:?} {sign:?}"); } + +/// A percent field whose committed values carry no decimals (`commit_decimals(0)`, a paint bar's Opacity) shows none, +/// "10%"; one that sets no decimals of its own keeps the one-decimal look, "10.0%". +#[trial] +fn a_percent_field_shows_the_decimals_its_caller_commits() { + let shown = |commit: Option| { + let mut value = Some(10.0f64); + let mut fixture = craft_ui::testing::Fixture::new(move |ui| { + let field = NumberField::new("Opacity", Bind::bound(&mut value)).unit_kind(UnitKind::Percent).range(0.0..=100.0); + let _ = match commit { + Some(decimals) => field.commit_decimals(decimals).show(ui), + None => field.show(ui), + }; + }); + fixture.settle(); + fixture.texts().iter().map(|run| run.text.clone()).collect::>() + }; + let whole = shown(Some(0)); + assert!(whole.iter().any(|text| text == "10") && !whole.iter().any(|text| text == "10.0"), "commit_decimals(0) shows 10%: {whole:?}"); + let default = shown(None); + assert!(default.iter().any(|text| text == "10.0"), "with no decimals set the field shows 10.0%: {default:?}"); +} From 6692f1b83a8c9f82a37064d56e2c4431cae70345 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 08:05:29 +0000 Subject: [PATCH 14/35] A memoized view whose content fills the axis its body shares is one of the children that fill that body A MemoView in a Stack or Row body that shares its height or width counted as one unit sized by its content's measure, so a fill child inside took its measured size: a whole title bar shown through a memoized view in the shell's title slot spanned only brand, menus and captions, the captions sat after Help and no title was painted (the title's gap takes no width of its own since F-24). A direct child of the view's content that is given the shared axis to fill now tells the view (Scoped::fill_view, noted in layout::fill_size). The body counts the view in the first sweep of its measuring run and gives it its share as the room of its place, as it does a child that fills it directly; the axis is kept with the view's measure (lazy::Measured::fills), so replays keep it and an idle frame still replays every call. A row unit in a row that does not share its width keeps sizing its content from its content along x. --- crates/ui-contract/src/contract/lazy.rs | 116 +++++++++++++----- crates/ui-contract/src/contract/memo_view.rs | 27 ++-- crates/ui-contract/src/layout/body.rs | 34 ++++- crates/ui-contract/src/layout/mod.rs | 8 +- crates/ui-contract/src/runtime/env.rs | 36 +++++- .../ui-contract/src/runtime/layout_memory.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 15 ++- crates/ui-contract/src/runtime/pass_state.rs | 1 + .../ui-contract/tests/it/contract/memo_row.rs | 86 +++++++++++++ crates/ui-shell/tests/it/shell/title_bar.rs | 67 ++++++++++ 10 files changed, 340 insertions(+), 51 deletions(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 17dab55ca4..328fb86710 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -11,6 +11,7 @@ use crate::runtime::lazy::{self, Call, Decision, Key, Place}; use crate::runtime::measure::{MemoRun, count_memo_run}; use crate::runtime::memory::sub; use crate::runtime::replay; +use craft_behavior::Axis; use egui::{Pos2, Rect, Ui, UiBuilder, Vec2}; use std::hash::Hash; @@ -67,33 +68,48 @@ impl Lazy { } } + /// The id of the child in `ui`: under its scroll area, or under `ui`'s scope outside every scroll area. + pub(super) fn id(&self, ui: &Ui) -> egui::Id { + match Env::of(ui).view().lazy_view() { + Some(view) => sub(view.owner, ("lazy", self.key)), + None => sub(ui.scope_id(), ("lazy", self.key)), + } + } + /// The one runner of a `Lazy` child and a memoized view (`MemoView`), named `name` in the count trials: runs `add`, /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. pub(super) fn run_keyed(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); let env = Env::of(ui); let view = env.view().lazy_view(); - let id = match view { - Some(view) => sub(view.owner, ("lazy", self.key)), - None => sub(ui.scope_id(), ("lazy", self.key)), - }; + let id = self.id(ui); let rtl = ui.layout().prefer_right_to_left(); let memo = matches!(key, Key::Memo(_)); - // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width - // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not - // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a - // new content runs it once and the discard pass its new size asks for replays that run. - let shrink = env.shrink.filter(|_| memo); - let cap = match shrink { - Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), - _ => None, - }; - let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)); - let available = if memo { on_row_line(ui, id, available) } else { available }; let sizing = ui.is_sizing_pass(); // The child is not part of its body's transcript: in a real run it counts there by its extent, whether it // runs or not, so what scrolls into reach does not change the body's content. let real = !sizing && !crate::runtime::measure::active(&ctx); + // A memoized view whose content filled the axis the body around it shares is one of the children that fill + // that body: a real run shows it in its share, as the body gives a child that fills it directly. + let share = env + .shares() + .filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis)) + .and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share))); + // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width + // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not + // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a + // new content runs it once and the discard pass its new size asks for replays that run. A view that fills the + // row takes no part in its shrink step, as a body that fills it does not. + let shrink = env.shrink.filter(|_| memo); + let cap = match shrink { + Some(Shrink::Apply(row)) if share.is_none() => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), + _ => None, + }; + let available = match share { + Some((axis, share)) => share_of(flow_region(ui), rtl, axis, share), + None => cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)), + }; + let available = if memo { on_row_line(ui, id, available) } else { available }; let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); @@ -147,7 +163,8 @@ impl Lazy { { // A real replay is where the run's content went, moved with the room. let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) }; - let took = place_view(ui, rect); + let fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None }; + let took = place_unit(ui, (shrink, fills), id, rect, rtl); let kept = if real { layout_memory::backstop(&ctx, id, size); let kept = lazy::replay_settled(&ctx, id, &shift); @@ -160,7 +177,6 @@ impl Lazy { // the extent this call takes, never from rects in it. lazy::kept_output(&ctx, id) }; - report_unit(&ctx, shrink, id, rect.size()); #[cfg(feature = "testing")] count_memo_run(&ctx, name, id, MemoRun::Replayed, real); return Shown::Replayed(kept, shift); @@ -177,6 +193,9 @@ impl Lazy { if run.recording { open_record(&ctx, audited.is_some()); } + if memo { + crate::layout::open_view_fill(&ctx, id); + } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The // content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their @@ -185,6 +204,7 @@ impl Lazy { let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); + let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None }; let record = run.recording.then(|| replay::close(&ctx, place.layer)); if let Some(shift) = audited { return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); @@ -199,15 +219,14 @@ impl Lazy { layout_memory::backstop(&ctx, id, rect.size()); } if memo { - place_view(ui, rect); - report_unit(&ctx, shrink, id, rect.size()); + place_unit(ui, (shrink, fills.filter(|_| !real)), id, rect, rtl); } else { crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } if view.is_some() || memo { let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone())); - lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow }, registered); + lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow, fills }, registered); } if let Some(view) = view && real @@ -296,17 +315,58 @@ fn at_most(region: Rect, rtl: bool, width: f32) -> Rect { Rect::from_min_size(at_start(region, rtl, size), size) } -/// Reports the extent `size` of the memoized view `id` to the shrinking row around it: what it takes, in the row's -/// counting sweep, and its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows -/// from what it takes in no room down to what it takes with every leaf at its least. -fn report_unit(ctx: &egui::Context, shrink: Option, id: egui::Id, size: Vec2) { - match shrink { - Some(Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, (false, None)), - Some(Shrink::Least(row)) => crate::layout::report_least(ctx, row, id, size.x), - _ => {} +/// `region` cut to `share` at most along `axis`, from its start edge: the room of a memoized view that fills the body +/// around it. +fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect { + match axis { + Axis::X => at_most(region, rtl, share), + _ => Rect::from_min_size(region.min, Vec2::new(region.width(), share.min(region.height()))), } } +/// Places the extent `rect` of the memoized view `id` in flow in `ui` (`place_view`) as one unit of the body around it, +/// and returns the rect it took. `fills` is the axis the body shares which the view's content filled in a measuring +/// run: the view is then one of the children that fill the body, as a child shown there directly is. It takes its +/// share along the axis once the body knows it; in the first sweep of the body's measuring run it is counted and takes +/// nothing there (`counting_fills`), outside the least measure, where it takes what its content took. In a shrinking +/// row it is a unit that does not narrow below what it takes, as a body that fills the row is. +/// +/// Any other view reports its extent to the shrinking row around it: what it takes, in the row's counting sweep, and +/// its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows from what it takes +/// in no room down to what it takes with every leaf at its least. +fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { + let ctx = ui.ctx().clone(); + let env = Env::of(ui); + let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else { + let took = place_view(ui, rect); + match shrink { + Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)), + Some(Shrink::Least(row)) => crate::layout::report_least(&ctx, row, id, rect.width()), + _ => {} + } + return took; + }; + let content = rect.size(); + let along = match crate::layout::fill_share(ui, axis) { + Some(share) => Some(share), + None if crate::layout::counting_fills(ui, axis) && !env.least => { + crate::layout::count_fill_view(ui); + Some(0.0) + } + None => None, + }; + let size = match (axis, along) { + (Axis::X, Some(along)) => Vec2::new(along, content.y), + (_, Some(along)) => Vec2::new(content.x, along), + (_, None) => content, + }; + let took = place_view(ui, Rect::from_min_size(at_start(rect, rtl, size), size)); + if let (Axis::X, Some(Shrink::Count(row))) = (axis, shrink) { + crate::layout::report_shrink(&ctx, row, id, size.x, size.x, Some((size.x, size.x)), (false, None)); + } + took +} + /// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the /// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content /// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index de103c619b..46a1150b02 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -3,7 +3,7 @@ use super::lazy::{Lazy, Shown}; use super::memo::{MemoKey, MemoProps}; -use crate::runtime::env::{Env, Scoped, Shrink}; +use crate::runtime::env::{Env, Shrink}; use crate::runtime::shift::Shift; use egui::Ui; use std::fmt; @@ -48,9 +48,9 @@ use std::sync::Arc; /// Its other inputs are the framework's, and each reaches the key or the settled test: /// - its place: the room it is given, the clip, the layer, the layout, the scale, the scope's style inputs (tokens, /// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a -/// content-sized or a given column, the axes it sizes from its content, a least measure, the axes a scroll leaves -/// unbounded, a beside label's cell, whether its leaves fit the room), compared for every view and for each kind of -/// run on its own; +/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that +/// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the +/// room), compared for every view and for each kind of run on its own; /// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every /// app value, and the rest of `Scoped::scope_key`), in the key; /// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the @@ -64,8 +64,15 @@ use std::sync::Arc; /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its /// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no -/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as -/// they fit the room of a `Stack` the view is shown in. +/// room, in the row's flow region. Its leaves fit the view's room, as they fit the room of a `Stack` the view is shown +/// in. +/// +/// In a `Stack` or `Row` body that shares its height or width among the children that fill it, a view whose content +/// fills that axis (a direct child of the content given it to fill, as a fill-width bar in a shell slot) is one of +/// those children, as that child shown without the view would be: the body counts it, and gives it its share as the +/// room of its place, so a new share runs it. Which axis its content filled is kept with its measure. In a shrinking +/// `Row` that does not share its width, its content sizes from its content along x: a child that fills there takes its +/// measured width. /// /// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept /// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once @@ -120,12 +127,14 @@ impl MemoVie let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_))); let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true))); let env = Env::of(ui); + let id = lazy.id(ui); let key = Self::key(&ctx, &env, &props, show); let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how - // that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so - // the view takes what its content used there, as the same content shown without the view would. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); + // that body sizes from its content, whether its leaves fit their room and which axis it shares among the + // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the + // same content shown without the view would. + let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.start_view_room(id))); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 1483647d6a..21b214e0dd 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -141,6 +141,11 @@ pub(crate) struct Cursors(IdMap); #[derive(Default)] pub(crate) struct FillCounts(IdMap); +/// The memoized views running this pass whose content holds a direct child that fills the axis the body around the +/// view shares (`Scoped::fill_view`), by view id, with that axis. +#[derive(Default)] +pub(crate) struct ViewFills(IdMap); + /// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column /// settles its width from the others, and the column's second sweep gives it the settled width. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -423,6 +428,9 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 if !given { return measured; } + if let Some((view, along)) = env.fill_view.filter(|(_, along)| *along == axis) { + pass_state::with::(ui.ctx(), |fills| fills.0.insert(view, along)); + } // In a body that shares the axis and scrolls along it, a share never cuts the child's content: what is past the // view scrolls. if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() { @@ -452,12 +460,36 @@ fn main_fill(ui: &Ui, id: Id, axis: Axis) -> MainFill { return MainFill::Share(share, layout_memory::fill_least(ui.ctx(), id, axis)); } if measure::active(ui.ctx()) { - pass_state::with::(ui.ctx(), |counts| *counts.0.entry(body).or_insert(0) += 1); + count_fill(ui.ctx(), body); return MainFill::Measuring; } MainFill::Room(layout_memory::fill_least(ui.ctx(), id, axis)) } +/// Counts one child that fills the main axis of the sharing body `body`, in the first sweep of its measuring run. +fn count_fill(ctx: &egui::Context, body: Id) { + pass_state::with::(ctx, |counts| *counts.0.entry(body).or_insert(0) += 1); +} + +/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the +/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted. +pub(crate) fn count_fill_view(ui: &Ui) { + if let Some((body, _)) = Env::of(ui).fill_body { + count_fill(ui.ctx(), body); + } +} + +/// Opens the record of whether the content of the memoized view `view` fills the axis its body shares, before its run. +pub(crate) fn open_view_fill(ctx: &egui::Context, view: Id) { + pass_state::with::(ctx, |fills| fills.0.remove(&view)); +} + +/// The axis the content of the memoized view `view` filled in the run that just ended, as `fill_size` noted it; closes +/// the record. +pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option { + pass_state::with::(ctx, |fills| fills.0.remove(&view)) +} + /// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child /// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index c9afb1e1d7..43254724e9 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,8 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, - flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, - place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, - take_bracket, take_cell, take_in_flow, view_room, + BodyLine, BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, fill_share, + fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, + open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, + run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_view_fill, view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index ec0063526b..689391f6bf 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -78,7 +78,8 @@ pub(crate) struct FooterSlotOf { } /// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a -/// content-sized or a given column, the axes it sizes from its content, whether the view runs in a least measure, the +/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill +/// it, whether the view runs in a least measure, the /// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's /// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its /// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`, @@ -88,6 +89,7 @@ pub(crate) struct Flow { content_column: bool, given_column: bool, content: (bool, bool), + shares: Option, least: bool, unbounded: (bool, bool), cell_fills: bool, @@ -180,6 +182,10 @@ pub struct Scoped { /// extents of the other children and the gaps, over the number of children that fill. `None` while the body is /// measured, and without a measuring run of this pass. pub(crate) fill_share: Option, + /// The memoized view whose content the scope's direct children run in, with the axis the body around that view + /// shares (its `fill_body`'s): a child given that axis to fill tells the view (`layout::fill_size`), which then is + /// a child that fills that body (`contract::lazy`). + pub(crate) fill_view: Option<(Id, craft_behavior::Axis)>, /// The shrink step of the unwrapped `Row` or `Stack` body that encloses the scope, as its direct children in flow /// take part in it. pub(crate) shrink: Option, @@ -450,6 +456,7 @@ impl Scoped { self.column_row = false; self.fill_body = None; self.fill_share = None; + self.fill_view = None; self.shrink = None; self.column = None; self.offered = None; @@ -469,6 +476,7 @@ impl Scoped { || self.column_row || self.fill_body.is_some() || self.fill_share.is_some() + || self.fill_view.is_some() || self.shrink.is_some() || self.column.is_some() || self.offered.is_some() @@ -479,12 +487,17 @@ impl Scoped { /// content axes. The view's content then measures and /// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from /// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's - /// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its - /// content along x, as the row counted it: a child that fills there takes its measured width, not the row's flow - /// region a view the row does not narrow is shown in. - pub(crate) fn start_view_room(&mut self) { + /// content fit the room the view is given (`Shrink::Fit`). + /// + /// In a body that shares an axis among the children that fill it (`fill_body`), a direct child of the content + /// given that axis to fill tells the view `view` (`fill_view`): the view is then one of the children that fill the + /// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a + /// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child + /// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in. + pub(crate) fn start_view_room(&mut self, view: Id) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); + let shares = self.shares(); let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); // The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in // it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children @@ -493,14 +506,23 @@ impl Scoped { self.start_room(); (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); self.row_line = line; + self.fill_view = shares.map(|axis| (view, axis)); if fits { self.shrink = Some(Shrink::Fit); } - if row_unit { + if row_unit && shares != Some(craft_behavior::Axis::X) { self.content.0 = true; } } + /// The axis the enclosing body shares among its direct children that fill it (`fill_body`). + pub(crate) const fn shares(&self) -> Option { + match self.fill_body { + Some((_, axis)) => Some(axis), + None => None, + } + } + /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body /// and a wrapping `Row`, whose leaves show at most its room (a whole line), and as one of the units a shrinking /// `Row` narrows. In a `Grid` cell or a `Ui` with no body around it a leaf keeps its measured width, and so does the @@ -554,6 +576,7 @@ impl Scoped { content_column: self.content_column, given_column: self.given_column, content: self.content, + shares: self.shares(), least: self.least, unbounded: self.unbounded, cell_fills: self.cell_fills, @@ -701,6 +724,7 @@ impl Env { footer_slot: None, fill_body: None, fill_share: None, + fill_view: None, shrink: None, column: None, least: false, diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index bb4ca41799..9a7ac16ccc 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1244,6 +1244,7 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), + ("layout::body::ViewFills", "view fills: opened and closed by the memoized view's own run"), ("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index b30b718296..9c6694bf8e 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -160,14 +160,16 @@ struct Entry { } /// What a run that showed a child measured: the extent it took, the key of the content it showed, the room it was -/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports) and the flow of the body around -/// it (the default for a collection row). +/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports), the flow of the body around +/// it (the default for a collection row) and the axis that body shares which a memoized view's content filled, which +/// makes the view one of the children that fill the body (`layout::fill_size`). #[derive(Clone, Copy, Debug)] pub(crate) struct Measured { pub(crate) size: Vec2, pub(crate) key: Key, pub(crate) room: Rect, pub(crate) flow: Flow, + pub(crate) fills: Option, } /// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment, @@ -457,6 +459,13 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas }); } +/// The axis the content of the memoized view `id` filled in its last run of this kind (`sizing`), else of the other +/// kind: the run of this pass once one ran, else the kept one. `None` before any run showed it. +pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option { + let (own, other) = (usize::from(!sizing), usize::from(sizing)); + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[own].or(entry.sizes[other])).and_then(|measured| measured.fills)) +} + /// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it /// ran), at whatever room it had; `None` before any run showed it. pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option { @@ -740,7 +749,7 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) { pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { write(ctx, id, |store, pass_nr, frame| { let entry = store.touch(Some(owner), id, frame); - entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default() }); + entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default(), fills: None }); entry.measured_in = Some(pass_nr); }); } diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 012b094a13..b4b18b795c 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -94,6 +94,7 @@ pass_state! { bar_rules: crate::contract::BarRules, surface_frames: crate::primitives::SurfaceFrames, fill_counts: crate::layout::body::FillCounts, + view_fills: crate::layout::body::ViewFills, held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, diff --git a/crates/ui-contract/tests/it/contract/memo_row.rs b/crates/ui-contract/tests/it/contract/memo_row.rs index 7fd587c014..a3660f5e47 100644 --- a/crates/ui-contract/tests/it/contract/memo_row.rs +++ b/crates/ui-contract/tests/it/contract/memo_row.rs @@ -58,3 +58,89 @@ fn a_memoized_row_unit_replays_after_the_rows_counting_call() { let calls = of_view(last_frame_memo_runs(&frames.ctx)); assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}"); } + +thread_local! { + /// The rect the fill panel of a `Filled` view took in its last run. + static FILLED: RefCell = RefCell::default(); +} + +/// A view whose content is one panel that fills the main axis of the body around it (`axis`: 0 the width, 1 the height). +#[derive(MemoProps)] +struct Filled { + axis: u8, +} + +fn filled(props: &mut Filled, ui: &mut Ui) { + fill_panel(ui, props.axis); +} + +/// The panel that fills `axis`, holding one probe. +fn fill_panel(ui: &mut Ui, axis: u8) { + let sizing = if axis == 0 { Sizing::FillWidth } else { Sizing::FillHeight }; + FILLED.with(|seen| { + Panel::new().seen(seen).sizing(sizing).id_salt("fill").show(ui, |ui, _| { + let inner = RefCell::new(Seen::default()); + Probe::new(&inner).id_salt("inner").show(ui); + }); + }); +} + +/// The rects of the fill panel and the probes before and after it in a body along `axis` (0 a row, 1 a stack) given its +/// room, the panel shown through a memoized view when `memo`, after the frames settle; and how the view took part in +/// the calls of one more frame. +fn shared_body(axis: u8, memo: bool) -> ([Rect; 3], Vec) { + let (before, after) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let mut frames = Frames::new(); + let (layout, room) = if axis == 0 { (BodyLayout::row(), Vec2::new(400.0, 40.0)) } else { (BodyLayout::stack(), Vec2::new(200.0, 300.0)) }; + let frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), room), |ui| { + Panel::new().layout(layout.clone()).sizing(Sizing::Fill).id_salt("body").show(ui, |ui, _| { + Probe::new(&before).id_salt("before").show(ui); + if memo { + let _ = MemoView::new("view", Filled { axis }, filled).show(ui); + } else { + fill_panel(ui, axis); + } + Probe::new(&after).id_salt("after").show(ui); + }); + }); + }); + }; + for _ in 0..30 { + frame(&mut frames); + } + frame(&mut frames); + let runs = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(name, _, _)| name.contains("Filled")).map(|(_, _, run)| run).collect(); + ([before.borrow().rect, FILLED.with(|seen| seen.borrow().rect), after.borrow().rect], runs) +} + +/// A memoized view whose content fills the width of the row around it is one of the children that fill the row, as the +/// content shown without the view is: it takes the row's free width and the probe after it keeps its place at the row's +/// end. With nothing changed every call of a frame replays the view. +#[trial] +fn a_memoized_view_whose_content_fills_the_row_takes_its_free_width() { + let (direct, _) = shared_body(0, false); + let (memo, runs) = shared_body(0, true); + let [before, fill, after] = memo; + assert!(fill.left() >= before.right() && after.left() >= fill.right(), "the view lies between the probes: {memo:?}"); + for (shown, alone) in memo.iter().zip(direct) { + assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}"); + } + assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}"); +} + +/// A memoized view whose content fills the height of the stack around it takes its share of the stack's height, as the +/// content shown without the view does: the probe after it stays inside the stack. With nothing changed every call of a +/// frame replays the view. +#[trial] +fn a_memoized_view_whose_content_fills_the_stack_takes_its_share_of_the_height() { + let (direct, _) = shared_body(1, false); + let (memo, runs) = shared_body(1, true); + let [before, fill, after] = memo; + assert!(fill.top() >= before.bottom() && after.top() >= fill.bottom(), "the view lies between the probes: {memo:?}"); + for (shown, alone) in memo.iter().zip(direct) { + assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}"); + } + assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}"); +} diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index fdbadce91a..6c35d47517 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -353,3 +353,70 @@ fn the_lights_room_follows_the_lights_without_mirroring_the_bar() { assert!(rect("Home").left() >= lights - 0.5, "Home {:?} after the lights at the left", rect("Home")); assert!(rect("Preferences").right() >= width - 20.0, "Preferences {:?} at the right end", rect("Preferences")); } + +/// The props of a whole title bar an app shows through a memoized view. +#[derive(craft_ui::contract::MemoProps)] +struct WholeBar { + version: u64, +} + +/// A Windows title bar with a brand button, a menu bar of an image editor's menus and the document title. +fn whole_bar(_: &mut WholeBar, ui: &mut Ui) { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + use craft_ui::menu::MenuItem; + use craft_ui::menu::bar::{MenuBar, MenuTitle}; + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout }); + let _ = TitleBar::new().frame(frame).show_titled( + ui, + Title::new("Untitled-1.psd"), + |ui, _| { + Button::new("Brand").show(ui); + let names = ["&File", "&Edit", "&Image", "&Layer", "&Type", "&Select", "Fil&ter", "&3D", "&View", "&Plugins", "&Window", "&Help"]; + let titles = names + .into_iter() + .map(|name| { + MenuTitle::new(name, |ui| { + MenuItem::new("Row").show(ui); + }) + }) + .collect(); + MenuBar::new("Main menu", titles).show(ui); + }, + |_, _| {}, + ); +} + +/// A whole title bar an app shows through a memoized view in the shell's title slot (1600 × 1000 px at 125 %) fills +/// the slot as the bar shown directly does: the captions end at the slot's end edge and the document title is drawn +/// whole after the last menu. +#[trial] +fn a_memoized_title_bar_fills_the_title_slot() { + use craft_host::target::Os; + use craft_ui::contract::MemoView; + let slot = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&slot); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .title_bar(|ui, _, _: &mut ()| { + let _ = MemoView::new("title bar", WholeBar { version: 0 }, whole_bar).show(ui); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + if let Some(rect) = shown.regions.slots.iter().find(|(key, _)| *key == "title").map(|(_, rect)| *rect) { + seen.set(rect); + } + }); + fixture.os(Os::Windows); + fixture.ctx().set_pixels_per_point(1.25); + fixture.room(vec2(1280.0, 800.0)).settle(); + let slot = slot.get(); + let close = fixture.by_label("Close").expect("the Close caption").rect; + assert!((close.right() - slot.right()).abs() <= 1.0, "the Close caption {close:?} ends at the slot's end {slot:?}"); + let help = fixture.by_label("Help").expect("Help is a title of the menu bar").rect; + let (title, elided) = + fixture.texts().iter().find(|run| run.text == "Untitled-1.psd").map(|run| (run.rect, run.elided)).expect("the document title is painted"); + assert!(title.left() > help.right() && title.right() < close.left(), "the title {title:?} lies between Help {help:?} and the captions"); + assert!(!elided, "the document title is whole"); +} From 6996c6479b6e736905a94e3ce71bfd3dd556a93e Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Tue, 24 Nov 2026 08:20:09 -0300 Subject: [PATCH 15/35] font-manager: skip building FontPicker stops on idle closed frames --- crates/font-manager/src/picker.rs | 113 +++++++++++++++++-------- crates/font-manager/tests/it/picker.rs | 32 +++++++ 2 files changed, 108 insertions(+), 37 deletions(-) diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 887faf69c5..d6c8ab848d 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -732,6 +732,18 @@ pub struct FontPicker<'a> { host_picked: Option, } +/// How many times a closed [`FontPicker`] built its stop list on `ctx`, for regression trials. +#[cfg(feature = "screen-testing")] +#[derive(Clone, Copy, Default)] +struct StopBuilds(u64); + +/// How many times a closed [`FontPicker`] built its stop list on `ctx`. +#[doc(hidden)] +#[cfg(feature = "screen-testing")] +pub fn stop_builds(ctx: &egui::Context) -> u64 { + ctx.data(|data| data.get_temp::(egui::Id::unique("font_picker_stop_builds")).unwrap_or_default().0) +} + impl<'a> FontPicker<'a> { /// A picker named `label` over the family `family` of `catalog`. pub fn new(label: impl Into

{ pub resized: Vec<(P, f32)>, /// The width the user gave the column on its inner edge this pass. pub width: Option, + /// The dividers drawn this pass: between each two open groups and on the inner edge, each with the rect of its + /// handle and the id of the handle's accessibility node. + pub dividers: Vec<(DividerKind

, Rect, Id)>, } impl

Outcome for DockColumnOutput

{ @@ -563,7 +566,20 @@ impl Component for DockColumn<'_, P> { } fn finish(self, cx: Cx<'_, Self>) -> DockColumnOutput

{ + let node = |part| crate::runtime::access::sub_node_id(cx.core.id, part); + let mut dividers = Vec::new(); + for pair in self.laid.as_ref().map_or(&[][..], |plan| &plan.open[..]).windows(2) { + let part = DIVIDER.at(pair[0] as u64); + if let (Some(shown), Some(anchor)) = (cx.part_if_declared(part), self.anchor(pair[0])) { + dividers.push((DividerKind::Groups(anchor.clone()), shown.rect, node(part))); + } + } + let edge = EDGE.at(0); + if let (Some(shown), Some(first)) = (cx.part_if_declared(edge), self.anchor(0)) { + dividers.push((DividerKind::ColumnEdge(first.clone()), shown.rect, node(edge))); + } DockColumnOutput { + dividers, response: cx.response.clone(), placed: cx.rect, iconic: self.collapse.then_some(true), diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 466e3d1eca..e89bdfcdb8 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -23,7 +23,7 @@ use crate::primitives::IconSpec; use crate::runtime::drag::OsFile; use crate::runtime::env::{Env, Label}; use crate::runtime::overlay::CloseReason; -use crate::runtime::windows::WindowSpec; +use crate::runtime::windows::{ResizeEdge, WindowSpec}; use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow}; use crate::style::{ComponentStyle, StyleCx, SurfaceKind, UiTokens}; use craft_behavior::dock::DockEdge; @@ -194,6 +194,11 @@ pub struct FloatingGroupOutput { pub collapsed_width: Option, /// The files dropped on the group's window that no target there took. pub files: Vec, + /// The band the group is moved by this pass, with the id of its accessibility node; `None` when it has none. + pub grip: Option<(Rect, Id)>, + /// The grips the group is resized by this pass, each with the edge or corner it moves and the id of its + /// accessibility node; none while it does not resize (minimized). + pub resize: Vec<(ResizeEdge, Rect, Id)>, } impl Outcome for FloatingGroupOutput { @@ -553,6 +558,8 @@ impl Component for FloatingGroup<'_> { iconic, collapsed_width: self.collapsed_width, files: self.files, + grip: cx.move_band(), + resize: cx.resize_grips(), }; native::raise(&cx.core.ctx, &output); native::fade(&cx.core.ctx, &output); diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index a3ffef3dcf..6bc7f3a835 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -283,6 +283,11 @@ pub struct DockGroupOutput { /// The host may add the size /// the dragged unit floats at with `drag::amend` in this pass. pub drag_started: bool, + /// The tabs the strip shows this pass, each with its rect and the id of its accessibility node; none for a + /// [`titled`](DockGroup::titled) group. + pub tabs: Vec<(PanelKey, Rect, Id)>, + /// The band the group is dragged by this pass, with the id of its accessibility node. + pub grip: Option<(Rect, Id)>, } impl Outcome for DockGroupOutput { @@ -315,6 +320,7 @@ struct Reported { drag_started: bool, /// A drag started on the strip's empty room, which `finish` starts as a drag of the group. empty_drag: bool, + tabs: Vec<(PanelKey, Rect, Id)>, } /// A group of panels: a header of tab strip and panel menu button, dragged by its empty part, over the active panel's @@ -580,8 +586,9 @@ impl Component for if let Some(request) = &self.reported.menu { cx.core.memory.shown::(sub(cx.core.id, MENU_ASKED)).0 = Some(request.at); } - let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, .. } = self.reported; - DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started } + let grip = cx.part_if_declared(GRIP).map(|grip| (grip.rect, crate::runtime::access::sub_node_id(cx.core.id, GRIP.into()))); + let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, tabs, .. } = self.reported; + DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, tabs, grip } } } @@ -681,8 +688,11 @@ impl Container for .inner; self.extra = extra; // A press on the group's empty body focuses its panel, as in Photoshop. - if surface_pressed && let Some(strip) = strip { - focus::request(ui.ctx(), FocusTarget::Id(strip)); + if surface_pressed && let Some((strip, _)) = &strip { + focus::request(ui.ctx(), FocusTarget::Id(*strip)); + } + if let Some((strip, tabs)) = &strip { + self.reported.tabs = tabs.iter().map(|(key, rect)| (*key, *rect, crate::contract::item_node(*strip, key))).collect(); } let size = self.size; let reported = &mut self.reported; @@ -761,8 +771,9 @@ fn tab_marks(ctx: &egui::Context, panels: &[PanelTitle]) -> Vec<(PanelKey, Optio .collect() } -/// A group's tab strip with its tab insertion spots. Returns the strip's id. -fn tab_row(row: &mut TabRow<'_, P>, ui: &mut Ui) -> Id { +/// A group's tab strip with its tab insertion spots. Returns the strip's id and the rect of each tab it shows, which a +/// replay returns again, moved with the row. +fn tab_row(row: &mut TabRow<'_, P>, ui: &mut Ui) -> (Id, Vec<(PanelKey, Rect)>) { let env = crate::runtime::env::Env::of(ui); let name = Label::from(env.words::().panels.as_str().to_owned()); let rtl = env.direction.is_rtl(); @@ -831,7 +842,7 @@ fn tab_row(row: &mu if strip.empty_double { row.sent.send(TabEvent::EmptyDouble); } - strip.response.response.id + (strip.response.response.id, strip.tab_rects) } /// Registers the tab insertion spots of a group: the half of each shown tab nearer the start edge inserts before diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 37ceceb30e..f7dec433d9 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -15,6 +15,7 @@ pub(crate) mod floating; mod panels; mod placed; pub(crate) mod root; +mod sources; mod spec; pub(crate) mod splitter; pub mod stack; @@ -43,6 +44,7 @@ pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions}; pub use panels::{close_requests, open_requests}; pub use placed::{Placing, placed_rect, with_area_rules}; pub use root::{DockRoot, DockRootOutput, DockRootStyle}; +pub use sources::{DividerKind, DockSource, SourceKind}; pub use spec::{DockGrid, DockHeights, PanelSpec}; pub use splitter::{Splitter, SplitterStyle}; pub use targets::{DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule}; @@ -67,7 +69,7 @@ pub use window_menu::{WindowMenuRows, WindowMenuRowsOutput}; use crate::contract::{ Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, Outcome, Pad, PaintUi, - PartsCx, Props as _, Role, Sizing, WordSetCx as _, + PartsCx, Pointer as _, Props as _, Role, Sizing, WordSetCx as _, }; use crate::runtime::commands::CommandRef; use crate::runtime::env::Label; @@ -104,6 +106,17 @@ impl PanelKey { } } +/// A key names a panel: it has no place, so a replay at another place keeps it. +impl crate::runtime::Shift for PanelKey { + fn shifted(&self, _: &egui::RecordShift) -> Self { + *self + } + + fn snapped(&self, _: &Self, _: f32) -> Self { + *self + } +} + /// A panel as its group's strip shows it. #[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] @@ -214,6 +227,9 @@ pub struct SplitAreaStyle { pub struct SplitAreaOutput

{ /// The resize edits of the layout and the area's response. pub edit: EditResponse>, + /// The dividers drawn this pass: each split's path from the root (`false` for the first child), the rect of its + /// handle and the id of the handle's accessibility node. + pub dividers: Vec<(Vec, Rect, egui::Id)>, } /// The first body's share of a pair's room when its layout holds none: an even split. @@ -455,7 +471,19 @@ impl Component for SplitAr } fn finish(self, cx: Cx<'_, Self>) -> SplitAreaOutput

{ - SplitAreaOutput { edit: cx.edit_response() } + // The handles `parts` declared: a resize keeps the tree's shape, so the shown layout's handles are theirs. + let dividers = cx.value().map_or_else(Vec::new, |layout| { + handles(layout, cx.rect, &cx.style.sizes, &self.rules, cx.flow.is_rtl()) + .into_iter() + .enumerate() + .filter_map(|(at, handle)| { + let part = HANDLE.at(at as u64); + let rect = cx.part_if_declared(part)?.rect; + Some((handle.path, rect, crate::runtime::access::sub_node_id(cx.core.id, part))) + }) + .collect() + }); + SplitAreaOutput { edit: cx.edit_response(), dividers } } } diff --git a/crates/ui-panels/src/docking/sources.rs b/crates/ui-panels/src/docking/sources.rs new file mode 100644 index 0000000000..dab0552b22 --- /dev/null +++ b/crates/ui-panels/src/docking/sources.rs @@ -0,0 +1,56 @@ +//! The places a dock area drew in a pass where a press starts a dock gesture: tabs, group bars, a floating window's +//! grip and resize grips, and the dividers. A host names them for its own automation (an element id per source) and +//! reads which one holds key focus by the source's node id. + +use crate::runtime::windows::ResizeEdge; +use egui::{Id, Rect, ViewportId}; + +/// A place in a dock area where a press starts a dock gesture, as the area drew it this pass. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct DockSource

{ + /// What the gesture acts on. + pub kind: SourceKind

, + /// Where it was drawn: in the area's layer space, or in the OS window's own for a floating window in one. + pub rect: Rect, + /// The OS window it is in: `ViewportId::ROOT` unless it is in a floating window's own OS window. + pub viewport: ViewportId, + /// The id of its accessibility node, which [`focused_node`](crate::runtime::access::focused_node) reports while + /// it holds key focus. + pub id: Id, +} + +impl

DockSource

{ + /// `kind` drawn at `rect` in the app window, with the node `id`. + pub fn new(kind: SourceKind

, rect: Rect, id: Id) -> Self { + DockSource { kind, rect, viewport: ViewportId::ROOT, id } + } +} + +/// What a [`DockSource`] acts on. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum SourceKind

{ + /// The tab of a panel: a click shows it, a drag moves it. + Tab(P), + /// The bar a group is dragged by, named by the group's first panel. + GroupBar(P), + /// The band a floating window is moved by, named by the window's first panel. + WindowGrip(P), + /// A grip a floating window is resized by, named by the window's first panel, with the edge or corner it moves. + WindowResize(P, ResizeEdge), + /// A divider a drag resizes the panes beside. + Divider(DividerKind

), +} + +/// Which divider a [`SourceKind::Divider`] is. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum DividerKind

{ + /// The divider of the docked tree's split at this path from the root (`false` for the first child). + Split(Vec), + /// The divider under a group of a column, between it and the next open group, named by the group's first panel. + Groups(P), + /// The inner edge of a docked column, named by the column's first panel. + ColumnEdge(P), +} diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index c8f50a75ab..15abd1542e 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -13,10 +13,10 @@ use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::tree::FrameRules; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ - ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, - DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip, - HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, - Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, + ColumnArrow, ColumnBar, DividerKind, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, + DockScene, DockSizes, DockSource, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip, + HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SourceKind, SpecSource, + SplitArea, Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, }; use crate::layout_components::Stack; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; @@ -85,6 +85,11 @@ pub struct DockAreaOutput

{ pub windows: Vec<(P, ViewportId)>, /// The files dropped on the area's windows this pass, for the host to open. pub window_files: Vec, + /// Every place the area drew this pass where a press starts a dock gesture: each tab, each group's drag bar, each + /// floating window's grip and resize grips, and each divider, with its rect, its OS window and the id of its + /// accessibility node. Nothing the area did not draw reports: a hidden panel, the groups of a column collapsed to + /// icons, a minimized window's resize grips. + pub sources: Vec>, /// The area's response. pub response: Response, } @@ -290,6 +295,8 @@ struct Report

{ windows: Vec<(P, ViewportId)>, /// The files dropped on the floating windows that no target there took. files: Vec, + /// The gesture sources the parts drew, in the order they showed. + sources: Vec>, } /// The inputs of the workspace's derived values: the workspace, the panels' specs and the lock. @@ -413,6 +420,7 @@ struct Passed

{ columns: Vec<(P, Rect)>, windows: Vec<(P, ViewportId)>, files: Vec, + sources: Vec>, } /// How a group is shown: minimized, whether it is an accordion section (with its open state), and whether it is in @@ -569,7 +577,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { passed = Some(result); }); let requested = close_requests::

(&ctx); - let Passed { geometry, actions, events, focused, picked, edit, space, columns, windows, files } = passed.unwrap_or_else(|| Passed { + let Passed { geometry, actions, events, focused, picked, edit, space, columns, windows, files, sources } = passed.unwrap_or_else(|| Passed { geometry: Vec::new(), actions: Vec::new(), events: Vec::new(), @@ -580,6 +588,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { columns: Vec::new(), windows: Vec::new(), files: Vec::new(), + sources: Vec::new(), }); if shown.output.dropped.is_some() { cross_window::accept_cross_window(&ctx); @@ -597,6 +606,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { columns, windows, window_files: files, + sources, response: shown.output.response, } } @@ -729,6 +739,7 @@ fn show_area( placed: Vec::new(), windows: Vec::new(), files: Vec::new(), + sources: Vec::new(), }, dock: id, }; @@ -760,6 +771,8 @@ fn show_area( pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); } }); + let splits = area.output.dividers.iter().map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node)); + pass.report.sources.extend(splits); let mut edit = area.output.edit.events.map(|edited| { let mut layout = current.layout().clone(); view.write_back(&edited, &mut layout); @@ -830,6 +843,7 @@ fn show_area( columns: report.placed, windows: report.windows, files: report.files, + sources: report.sources, } } @@ -1017,12 +1031,12 @@ impl Pass<'_, P> { /// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the /// group, which floats at `size`, the group's size. A memoized view ([`rail_grip`]) held to the strip, so a frame - /// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay. - fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) { + /// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay. Returns the grip's id. + fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) -> Option { let scene = self.scene; let label = Label::from(scene.spec(shown).label.as_str().to_owned()); let mut sent = Vec::new(); - ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| { + let grip = ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| { let props = RailGrip { unit: DragUnit::Group(anchor.clone()), active: PanelKey::of(shown), @@ -1031,7 +1045,7 @@ impl Pass<'_, P> { sent: Outbox::new(&mut sent), }; // Keyed by the rail's group: unique among the rails a dock area shows. - let _ = MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::

).show(ui); + MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::

).show(ui) }); // The group's size goes on the drag here, outside the view, whose measuring runs see no size; so does the // press, which a floating rail's window keeps under the pointer when it is dropped on empty room. @@ -1041,6 +1055,7 @@ impl Pass<'_, P> { drag.press = Some(press); }); } + grip.inner } /// One group, by the host's `group_view` when it takes the group, else as a `DockGroup` over the host's panels: @@ -1154,11 +1169,18 @@ impl Pass<'_, P> { .inner; // A host view took the group: a rail's grip drags the group, as the band of a group's header does. let Some(output) = output else { - if strip.is_positive() { - self.rail_grip(ui, anchor, shown, strip, rect.size()); + if strip.is_positive() + && let Some(node) = self.rail_grip(ui, anchor, shown, strip, rect.size()) + { + self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), strip, node)); } return None; }; + let tabs = output.tabs.iter().filter_map(|(key, rect, node)| Some(DockSource::new(SourceKind::Tab(scene.panel(*key)?.clone()), *rect, *node))); + self.report.sources.extend(tabs); + if let Some((rect, node)) = output.grip { + self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), rect, node)); + } // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { @@ -1418,6 +1440,8 @@ impl Pass<'_, P> { let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| { self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); + let dividers = output.dividers.into_iter().map(|(divider, rect, node)| DockSource::new(SourceKind::Divider(divider), rect, node)); + self.report.sources.extend(dividers); let width = output.width.map(|width| width - inset); ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width, flyout: None } }; @@ -1599,6 +1623,7 @@ impl Pass<'_, P> { }); } let area_dock = std::mem::replace(&mut self.dock, dock); + let drawn = self.report.sources.len(); let shown = group.show_group(ui, |ui, body| { for (command, state) in states.iter().cloned() { body.publish(command, state); @@ -1614,6 +1639,16 @@ impl Pass<'_, P> { }); self.dock = area_dock; let output = shown.output; + // The window's grips, then everything it drew, in the OS window it shows in, if it has one. + let grips = output.grip.map(|(rect, node)| DockSource::new(SourceKind::WindowGrip(anchor.clone()), rect, node)); + let resize = output.resize.iter().map(|(edge, rect, node)| DockSource::new(SourceKind::WindowResize(anchor.clone(), *edge), *rect, *node)); + let inside = self.report.sources.split_off(drawn); + self.report.sources.extend(grips.into_iter().chain(resize).chain(inside)); + if let Some(viewport) = opening.spec.as_ref().and_then(|_| WindowHost::of(&ctx).viewport_of(output.response.id)) { + for source in &mut self.report.sources[drawn..] { + source.viewport = viewport; + } + } self.report.files.extend(output.files); if let Some(dropped) = dropped.into_inner() { cross_window::accept_cross_window(&ctx); @@ -1774,7 +1809,8 @@ struct RailGrip<'a, P> { } /// A tool rail's grip strip: the dock's grip marks over the view's room, which a drag moves the rail's group by. -fn rail_grip(props: &mut RailGrip<'_, P>, ui: &mut Ui) { +/// Returns the grip's id. +fn rail_grip(props: &mut RailGrip<'_, P>, ui: &mut Ui) -> Id { let strip = ui.max_rect(); let held = GroupGrip::new(props.unit.clone(), props.active) .ticks(true) @@ -1787,4 +1823,5 @@ fn rail_grip(props: &mut RailGrip<'_, P } // The grip takes no room in flow; the run covers the strip, so the pointer over it runs it again. ui.expand_to_include_rect(strip); + held.response.id } From ba2c36b306031256fe3b004bfd33b968c0d91b13 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 20:33:01 -0500 Subject: [PATCH 21/35] SplitArea keeps the handle paths it declared for its dividers; trial for DockAreaOutput::sources --- crates/ui-panels/src/docking/mod.rs | 30 ++-- crates/ui-patterns/src/patterns/dock/area.rs | 17 +- crates/ui-patterns/tests/it/docking/mod.rs | 1 + .../ui-patterns/tests/it/docking/sources.rs | 147 ++++++++++++++++++ 4 files changed, 174 insertions(+), 21 deletions(-) create mode 100644 crates/ui-patterns/tests/it/docking/sources.rs diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index f7dec433d9..bd11ea93d8 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -275,13 +275,15 @@ pub struct SplitArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { /// preview", "Resize timeline". #[prop(into)] divider_label: Option

>, rules: FrameRules<'a, P>) -> Self { let props = ContainerProps::new().arena(true).sizing(Sizing::Fill).pad(Pad::None); - SplitArea { common: Common::new(), props, layout, rules, divider_label: None }.label(label) + SplitArea { common: Common::new(), props, layout, rules, divider_label: None, declared: Vec::new() }.label(label) } /// A two-body area: `bodies.0` first along `axis` and `bodies.1` after it, with one divider between them. The first @@ -399,10 +401,12 @@ impl Component for SplitAr fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let Some(layout) = cx.value() else { return }; let (sizes, rtl) = (cx.style.sizes, cx.flow.is_rtl()); - for (at, handle) in handles(layout, rect, &sizes, &self.rules, rtl).iter().enumerate() { + let handles = handles(layout, rect, &sizes, &self.rules, rtl); + for (at, handle) in handles.iter().enumerate() { let divider = divider_of(layout, handle, rect, &sizes, &self.rules, rtl, false); divider::declare(cx, rect, HANDLE, at as u64, ÷r); } + self.declared = handles.into_iter().map(|handle| handle.path).collect(); } fn update(&mut self, cx: &mut Cx<'_, Self>) { @@ -471,18 +475,16 @@ impl Component for SplitAr } fn finish(self, cx: Cx<'_, Self>) -> SplitAreaOutput

{ - // The handles `parts` declared: a resize keeps the tree's shape, so the shown layout's handles are theirs. - let dividers = cx.value().map_or_else(Vec::new, |layout| { - handles(layout, cx.rect, &cx.style.sizes, &self.rules, cx.flow.is_rtl()) - .into_iter() - .enumerate() - .filter_map(|(at, handle)| { - let part = HANDLE.at(at as u64); - let rect = cx.part_if_declared(part)?.rect; - Some((handle.path, rect, crate::runtime::access::sub_node_id(cx.core.id, part))) - }) - .collect() - }); + let dividers = self + .declared + .into_iter() + .enumerate() + .filter_map(|(at, path)| { + let part = HANDLE.at(at as u64); + let rect = cx.part_if_declared(part)?.rect; + Some((path, rect, crate::runtime::access::sub_node_id(cx.core.id, part))) + }) + .collect(); SplitAreaOutput { edit: cx.edit_response(), dividers } } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 15abd1542e..cecfb37111 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -13,10 +13,10 @@ use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::tree::FrameRules; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ - ColumnArrow, ColumnBar, DividerKind, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, - DockScene, DockSizes, DockSource, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip, - HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SourceKind, SpecSource, - SplitArea, Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, + ColumnArrow, ColumnBar, DividerKind, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, + DockRoot, DockScene, DockSizes, DockSource, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, + GroupDrag, GroupGrip, HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, + SourceKind, SpecSource, SplitArea, Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, }; use crate::layout_components::Stack; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; @@ -771,7 +771,8 @@ fn show_area( pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); } }); - let splits = area.output.dividers.iter().map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node)); + let splits = + area.output.dividers.iter().map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node)); pass.report.sources.extend(splits); let mut edit = area.output.edit.events.map(|edited| { let mut layout = current.layout().clone(); @@ -1176,7 +1177,8 @@ impl Pass<'_, P> { } return None; }; - let tabs = output.tabs.iter().filter_map(|(key, rect, node)| Some(DockSource::new(SourceKind::Tab(scene.panel(*key)?.clone()), *rect, *node))); + let tabs = + output.tabs.iter().filter_map(|(key, rect, node)| Some(DockSource::new(SourceKind::Tab(scene.panel(*key)?.clone()), *rect, *node))); self.report.sources.extend(tabs); if let Some((rect, node)) = output.grip { self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), rect, node)); @@ -1641,7 +1643,8 @@ impl Pass<'_, P> { let output = shown.output; // The window's grips, then everything it drew, in the OS window it shows in, if it has one. let grips = output.grip.map(|(rect, node)| DockSource::new(SourceKind::WindowGrip(anchor.clone()), rect, node)); - let resize = output.resize.iter().map(|(edge, rect, node)| DockSource::new(SourceKind::WindowResize(anchor.clone(), *edge), *rect, *node)); + let resize = + output.resize.iter().map(|(edge, rect, node)| DockSource::new(SourceKind::WindowResize(anchor.clone(), *edge), *rect, *node)); let inside = self.report.sources.split_off(drawn); self.report.sources.extend(grips.into_iter().chain(resize).chain(inside)); if let Some(viewport) = opening.spec.as_ref().and_then(|_| WindowHost::of(&ctx).viewport_of(output.response.id)) { diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 17d129e898..60d8a2e2ec 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -19,6 +19,7 @@ pub(crate) mod floating; pub(crate) mod floating_area; pub(crate) mod floating_rail; pub(crate) mod hidden; +pub(crate) mod sources; pub(crate) mod columns; pub(crate) mod dock_back; diff --git a/crates/ui-patterns/tests/it/docking/sources.rs b/crates/ui-patterns/tests/it/docking/sources.rs new file mode 100644 index 0000000000..328b341809 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/sources.rs @@ -0,0 +1,147 @@ +//! The gesture sources a dock area reports (`DockAreaOutput::sources`): one per tab, group bar, window grip and divider +//! it drew, named by what it acts on, and none for what it did not draw. + +use super::Numbered; +use craft_behavior::Axis; +use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, Tracked}; +use craft_ui::docking::{DividerKind, DockConfig, DockPanels, DockSource, HidePanels, PanelKey, SourceKind}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::env::{BodyMode, ShellCx, ShellEntry, WindowKey}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::collections::{BTreeSet, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +/// The start dock's column: a group of two tabs over a group of one. +const UPPER: usize = 1; +const UPPER_TWO: usize = 2; +const LOWER: usize = 3; +/// The middle split: a group of two tabs beside a group of one. +const LEFT: usize = 4; +const LEFT_TWO: usize = 5; +const RIGHT: usize = 6; +/// The end dock's column, collapsed to icons. +const ICONIC: usize = 7; +/// The floating window's panel. +const FLOATING: usize = 8; + +struct Bodies; + +impl DockPanels for Bodies { + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} +} + +/// A start dock whose column holds two groups, a split of two tab groups, an end dock whose column is collapsed to +/// icons, and one floating window. +fn layout() -> Layout { + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![UPPER, UPPER_TWO], 0), Group::new(vec![LOWER], 0)])]); + let mut collapsed = Column::new(vec![Group::new(vec![ICONIC], 0)]); + collapsed.iconic = true; + let end = Node::dock(DockEdge::End, vec![collapsed]); + let middle = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![LEFT, LEFT_TWO], 0), Node::tabs(vec![RIGHT], 0)); + let root = Node::split(Axis::X, SplitSize::Ratio(0.25), start, Node::split(Axis::X, SplitSize::Ratio(0.85), middle, end)); + let window = Floating::single(FLOATING as u64, vec![FLOATING], 0, Rect::from_min_size(Pos2::new(420.0, 200.0), Vec2::new(220.0, 180.0))); + Layout::new(Some(root), vec![window]) +} + +const ROOM: Vec2 = Vec2::new(1000.0, 640.0); + +/// A fixture showing the layout under `shell`, keeping only `keep` when it names panels; what the area reported in +/// its last pass goes into the returned cell. +fn fixture(shell: Option, keep: Option>) -> (Fixture, Rc>>>) { + let reported: Rc>>> = Rc::default(); + let seen = Rc::clone(&reported); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = Arc::new(Workspace::new(layout())); + let specs = Tracked::new(Numbered); + let kept = Tracked::new(keep.iter().flatten().map(PanelKey::of).collect::>()); + let mut bodies = Bodies; + let mut area = DockArea::new("Sources", Bind::bound(&mut workspace), &specs, &mut bodies, DockConfig::default()); + if keep.is_some() { + area = area.hide(HidePanels::Except(&kept)); + } + *seen.borrow_mut() = area.show(ui).sources; + }); + fixture.room(ROOM); + if let Some(shell) = shell { + fixture.root_value(ShellEntry(Some(shell))); + } + fixture.settle(); + (fixture, reported) +} + +/// The panel a source names, for a tab, a group bar or a window's grips. +fn named(source: &DockSource) -> Option { + match &source.kind { + SourceKind::Tab(panel) | SourceKind::GroupBar(panel) | SourceKind::WindowGrip(panel) | SourceKind::WindowResize(panel, _) => Some(*panel), + SourceKind::Divider(DividerKind::Groups(panel) | DividerKind::ColumnEdge(panel)) => Some(*panel), + _ => None, + } +} + +/// The panels named by the sources `pick` takes, in order, with repeats. +fn panels(sources: &[DockSource], pick: impl Fn(&SourceKind) -> Option) -> Vec { + let mut picked: Vec = sources.iter().filter_map(|source| pick(&source.kind)).collect(); + picked.sort_unstable(); + picked +} + +#[trial] +fn a_dock_area_reports_one_source_per_tab_bar_grip_and_divider_it_drew_and_the_same_after_an_idle_pass() { + let (mut fixture, reported) = fixture(None, None); + let sources = reported.borrow().clone(); + let tabs = panels(&sources, |kind| if let SourceKind::Tab(panel) = kind { Some(*panel) } else { None }); + assert_eq!(tabs, vec![UPPER, UPPER_TWO, LOWER, LEFT, LEFT_TWO, RIGHT, FLOATING], "one tab per panel shown in a tab strip: {sources:#?}"); + let bars = panels(&sources, |kind| if let SourceKind::GroupBar(panel) = kind { Some(*panel) } else { None }); + assert_eq!(bars, vec![UPPER, LOWER, LEFT, RIGHT, FLOATING], "one drag bar per shown group, named by its first panel"); + let grips = panels(&sources, |kind| if let SourceKind::WindowGrip(panel) = kind { Some(*panel) } else { None }); + assert_eq!(grips, vec![FLOATING], "the floating window's grip, named by its panel"); + let edges: Vec<_> = + sources.iter().filter_map(|source| if let SourceKind::WindowResize(FLOATING, edge) = source.kind { Some(edge) } else { None }).collect(); + assert!(!edges.is_empty(), "the floating window reports its resize grips"); + let distinct = edges.iter().enumerate().all(|(at, edge)| !edges[..at].contains(edge)); + assert!(distinct, "each resize grip names its own edge: {edges:?}"); + + let divider = |kind: DividerKind| sources.iter().filter(|source| source.kind == SourceKind::Divider(kind.clone())).count(); + assert_eq!(divider(DividerKind::Split(vec![true, false])), 1, "the divider of the middle split, by its path"); + assert_eq!(divider(DividerKind::Groups(UPPER)), 1, "the divider under the column's upper group"); + assert_eq!(divider(DividerKind::ColumnEdge(UPPER)), 1, "the inner edge of the start dock's column"); + assert!(sources.iter().all(|source| named(source) != Some(ICONIC)), "a column collapsed to icons reports no tab, bar or divider"); + + let room = Rect::from_min_size(Pos2::ZERO, ROOM); + for source in &sources { + assert!(source.rect.is_positive() && room.contains_rect(source.rect), "every source lies in the window: {source:?}"); + } + let window = sources.iter().find(|source| source.kind == SourceKind::WindowGrip(FLOATING)).map(|source| source.rect); + let tab = sources.iter().find(|source| source.kind == SourceKind::Tab(FLOATING)).map(|source| source.rect); + assert!(window.zip(tab).is_some_and(|(grip, tab)| grip.bottom() <= tab.top() + 0.5), "the window's grip lies above its tab"); + let ids: HashSet<_> = sources.iter().map(|source| source.id).collect(); + assert_eq!(ids.len(), sources.len(), "every source has its own node id"); + + fixture.idle(3); + assert_eq!(*reported.borrow(), sources, "an idle pass, which replays the settled parts, reports the same sources"); + + let left_two = sources.iter().find(|source| source.kind == SourceKind::Tab(LEFT_TWO)).cloned().expect("the tab of the second panel"); + fixture.click_at(left_two.rect.center()).settle(); + assert_eq!( + craft_ui::runtime::access::focused_node(fixture.ctx()), + Some(left_two.id), + "the clicked tab holds focus under the id its source reports" + ); +} + +#[trial] +fn a_panel_the_shell_hides_reports_no_source() { + let room = Rect::from_min_size(Pos2::ZERO, ROOM); + let hiding = ShellCx::detached(WindowKey::main(), BodyMode::Normal, room).with_panels_hidden(true); + let keep = BTreeSet::from([UPPER, UPPER_TWO, LOWER, LEFT, LEFT_TWO, ICONIC]); + let (_fixture, reported) = fixture(Some(hiding), Some(keep)); + let sources = reported.borrow(); + assert!(sources.iter().any(|source| source.kind == SourceKind::Tab(LEFT)), "a kept panel still reports its tab"); + for hidden in [RIGHT, FLOATING] { + assert!(sources.iter().all(|source| named(source) != Some(hidden)), "the hidden panel {hidden} reports no tab, bar or grip: {sources:#?}"); + } +} From badd2a8822a28a35ec512a002bd357eff09f2cb5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 20:19:22 -0500 Subject: [PATCH 22/35] ui-contract: a host's window-input policy reaches every OS window the runtime hosts FrameInput::window_input(WindowInput::Dropped) drops a hosted window's own events and OS files in the input filter, before injected input joins, so an agent-driven session's floated panels take only injected input. eframe runs raw_input_hook for the main window only; the root's input stays the host's. The test kit's Windows takes the policy; trials cover the drop and a macOS Control+Click in a hosted window. --- .../src/runtime/egui/input_filter.rs | 18 +++- crates/ui-contract/src/runtime/frame.rs | 30 +++++- .../ui-contract/tests/it/runtime/windows.rs | 91 ++++++++++++++++++- crates/ui-test-kit/src/windows.rs | 17 +++- docs/craft-framework.md | 2 +- 5 files changed, 150 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/input_filter.rs b/crates/ui-contract/src/runtime/egui/input_filter.rs index 5b5645c81d..17ce26499b 100644 --- a/crates/ui-contract/src/runtime/egui/input_filter.rs +++ b/crates/ui-contract/src/runtime/egui/input_filter.rs @@ -3,6 +3,7 @@ //! A family crate hands the filter what it learned outside the window (a key equivalent the platform's menu //! took) and the filter puts it into the viewport's input in the hook, ahead of the stages that read keys, so it //! reaches the application as the key press the user made. No family crate touches `RawInput` or `egui::Event`. +//! The host's window-input policy (`FrameInput::window_input`) is applied here too, first. use std::collections::HashMap; @@ -12,6 +13,7 @@ use egui::{Context, Event, ViewportId}; use super::injected::{egui_modifiers, key_press, key_release}; use super::memory::Service; use super::repaint; +use crate::runtime::frame::WindowInput; use crate::runtime::windows::KeyEquivalent; #[derive(Default)] @@ -35,8 +37,10 @@ fn repeat_running_pass(ctx: &Context, viewport: ViewportId, reason: &'static str } } -/// The input hook's filter step: adds the queued key equivalents of `input.viewport_id` to `input.events`. +/// The input hook's filter step: drops a hosted window's input under [`WindowInput::Dropped`], then adds the queued +/// key equivalents of `input.viewport_id` to `input.events`. pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) { + drop_window_input(ctx, input); dismiss_input(ctx, input); let queued = Service::::run(ctx, |pending| pending.by_viewport.remove(&input.viewport_id)); let Some(queued) = queued else { return }; @@ -51,6 +55,18 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) { } } +/// The policy step: under [`WindowInput::Dropped`] a hosted window's input keeps none of the window system's events or +/// files. It runs before the injected step joins the input, so injected input still reaches the window. The root's +/// input is the host's own, in eframe's `raw_input_hook`, where the host may already have added its own events. +fn drop_window_input(ctx: &Context, input: &mut egui::RawInput) { + if input.viewport_id == ViewportId::ROOT || crate::runtime::frame::window_input(ctx) != WindowInput::Dropped { + return; + } + input.events.clear(); + input.hovered_files.clear(); + input.dropped_files.clear(); +} + /// Puts the press of `chord` ahead of its key-up when that is already in the input, else last; `tap` adds the /// release right after it. fn insert_press(input: &mut egui::RawInput, chord: Chord, platform: craft_keymap::Platform, tap: bool) { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 62925bbc54..0da9dc2900 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -32,12 +32,35 @@ pub struct FrameInput { pub host: Option>, /// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input. pub latched: Mods, + /// Whether the window system's input reaches the OS windows the runtime hosts. + pub window_input: WindowInput, +} + +/// Whether the window system's input reaches the OS windows the runtime hosts beside the root (a panel floated into +/// its own window). eframe gives the host only the root's raw input (`App::raw_input_hook`), so the host applies its +/// policy to the root there and gives it here for the rest. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum WindowInput { + /// The window system's input reaches every hosted window. + #[default] + Live, + /// An agent-driven session: a hosted window's events, hovered files and dropped files are dropped before any + /// stage reads them, so only the runtime's injected input reaches it. Its window facts (size, focus, close + /// requests) stay. + Dropped, } impl FrameInput { /// A frame with `root` and no host. pub fn new(root: RootEnv) -> Self { - FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE } + FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, window_input: WindowInput::Live } + } + + /// Sets whether the window system's input reaches the hosted windows. + pub fn window_input(mut self, window_input: WindowInput) -> Self { + self.window_input = window_input; + self } /// Sets the command input. @@ -416,6 +439,11 @@ pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages) { pass_state::with::(ctx, |state| state.input.as_ref().map(|input| (input.root.wheel, input.root.alt_codes))).unwrap_or_default() } +/// The frame's window-input policy; `Live` before the app sets any input. +pub(crate) fn window_input(ctx: &Context) -> WindowInput { + pass_state::with::(ctx, |state| state.input.as_ref().map(|input| input.window_input)).unwrap_or_default() +} + /// How far a press may move and still be a click, in points: the app's hit tolerances (`HitSizes::slop`). egui's own /// click options stay the app's. pub(crate) fn slop(ctx: &Context) -> f32 { diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index b5c23a5453..6ee89f1bed 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -3,7 +3,8 @@ //! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a //! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus //! loss, non-finite injected points, a repeated injected press, the window that has the keys, a wheel with no known -//! pointer, the placement of a minimized window, the root frame decided again, a held close, and `act`. +//! pointer, the placement of a minimized window, the root frame decided again, a held close, `act`, and a hosted +//! window's Control-click and window-input policy. use craft_behavior::{Cursor, CursorIcon, PointerButton, Sense}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -19,7 +20,7 @@ use craft_ui::testing::pointer::{moved, press, release, wheel}; use craft_ui::testing::windows::{FakeSystem, NoWindows}; use craft_ui::testing::{Fixture, trial}; use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen}; -use craft_ui_test_kit::windows::{Out, Windows}; +use craft_ui_test_kit::windows::{FilesOver, Out, Windows}; use craft_window::policy::{Decision, Desktop, DesktopKind, Frame, MacInset, Runtime, TitleBarPref}; use craft_window::restore::Store; use egui::{Event, Pos2, Rect, Response, UserAttentionType, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; @@ -1310,3 +1311,89 @@ fn a_title_with_nul_reaches_the_window_without_it() { assert_eq!(send("Notes.docx"), ["Notes.docx"], "a changed title is sent"); assert_eq!(send("\0Report\0\0 draft.docx\0"), ["Report draft.docx"], "a title changed back is sent again, every NUL dropped"); } + +/// What the hosted child window's passes saw: its last pass's pointer, events and OS files, and the clicks since the +/// last reset. +#[derive(Clone, Copy, Debug, Default)] +struct ChildSeen { + pointer: bool, + events: usize, + files: usize, + primary: bool, + secondary: bool, +} + +/// One frame of a root window that hosts the child window as an OS window with a 200-point click area at its origin: +/// `root` events go to the root, `events` and `dropped` files to the child. Returns whether the root knows the pointer. +fn hosted_frame(windows: &Windows, root: Vec, events: Vec, dropped: Vec, seen: &Cell) -> bool { + let root_pointer = Cell::new(false); + windows.frame_with_files(root, events, FilesOver::Child, Vec::new(), dropped, |ui| { + root_pointer.set(ui.ctx().input(|input| input.pointer.latest_pos().is_some())); + ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| { + let area = cui.allocate_rect(Rect::from_min_size(Pos2::ZERO, Vec2::splat(200.0)), egui::Sense::click()); + let (pointer, events, files) = cui.ctx().input(|input| { + (input.pointer.latest_pos().is_some(), input.events.len(), input.raw.hovered_files.len() + input.raw.dropped_files.len()) + }); + let was = seen.get(); + seen.set(ChildSeen { + pointer, + events, + files, + primary: was.primary || area.clicked(), + secondary: was.secondary || area.secondary_clicked(), + }); + }); + }); + root_pointer.get() +} + +/// A panel floated into its own OS window gets a macOS Control+Click as a secondary click, as the main window does: +/// the Control-click mapping runs on every hosted window's input, which eframe's `raw_input_hook` never sees. +#[trial] +fn a_control_click_in_a_hosted_window_is_a_secondary_click_on_macos() { + let shell = ShellInfo::default().os(Os::Mac).caps(Caps::native(Os::Mac)); + let windows = Windows::with(InstallSpec::new(shell, Arc::new(FakeSystem::new()))); + let seen = Cell::new(ChildSeen::default()); + let at = Pos2::new(50.0, 50.0); + let control = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::CTRL }; + hosted_frame(&windows, vec![], vec![], vec![], &seen); + hosted_frame(&windows, vec![], vec![moved(at)], vec![], &seen); + hosted_frame(&windows, vec![], vec![control(true)], vec![], &seen); + hosted_frame(&windows, vec![], vec![control(false)], vec![], &seen); + hosted_frame(&windows, vec![], vec![], vec![], &seen); + assert!(seen.get().secondary && !seen.get().primary, "the Control+Click is a secondary click there: {:?}", seen.get()); +} + +/// `WindowInput::Dropped` (an agent-driven session): a hosted window's own events and OS files reach none of its +/// passes, while the root's input stays the host's and injected input still reaches the hosted window. Under `Live` +/// the same input reaches it. +#[trial] +fn dropped_window_input_leaves_a_hosted_window_only_injected_input() { + use craft_ui::runtime::frame::WindowInput; + let at = Pos2::new(50.0, 50.0); + for policy in [WindowInput::Live, WindowInput::Dropped] { + let windows = Windows::new(); + windows.window_input(policy); + let seen = Cell::new(ChildSeen::default()); + hosted_frame(&windows, vec![], vec![], vec![], &seen); + let root_pointer = hosted_frame(&windows, vec![moved(at)], vec![moved(at)], vec!["clip.mov".to_owned()], &seen); + assert!(root_pointer, "{policy:?}: the root's input is the host's"); + let after_move = seen.get(); + hosted_frame(&windows, vec![], vec![press(at)], vec![], &seen); + hosted_frame(&windows, vec![], vec![release(at)], vec![], &seen); + hosted_frame(&windows, vec![], vec![], vec![], &seen); + let live = policy == WindowInput::Live; + assert_eq!(after_move.pointer, live, "{policy:?}: the window's pointer move {after_move:?}"); + assert_eq!(after_move.events > 0, live, "{policy:?}: the window's events {after_move:?}"); + assert_eq!(after_move.files > 0, live, "{policy:?}: the files dropped on the window {after_move:?}"); + assert_eq!(seen.get().primary, live, "{policy:?}: the window's own click {:?}", seen.get()); + + seen.set(ChildSeen::default()); + let host = WindowHost::of(&windows.ctx); + host.inject_click(child(), Pos2::new(60.0, 60.0), PointerButton::Primary, 1, Mods::NONE, false); + for _ in 0..8 { + hosted_frame(&windows, vec![], vec![], vec![], &seen); + } + assert!(seen.get().primary, "{policy:?}: the injected click reaches the window: {:?}", seen.get()); + } +} diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index bbda539b5c..a6fe258d87 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -5,7 +5,7 @@ use craft_host::target::ShellInfo; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::env::RootEnv; -use craft_ui::runtime::frame::{FrameInput, set_input}; +use craft_ui::runtime::frame::{FrameInput, WindowInput, set_input}; use craft_ui::testing::Frames; use craft_ui::testing::access::{AccessTree, tree_of}; use craft_ui::testing::windows::FakeSystem; @@ -281,6 +281,7 @@ pub struct Windows { pub ctx: Context, root_info: RefCell, root: RefCell, + window_input: Cell, } impl Default for Windows { @@ -309,7 +310,12 @@ impl Windows { COMMANDS.with(|kept| kept.borrow_mut().clear()); BUILDERS.with(|kept| kept.borrow_mut().clear()); NOW.with(|now| now.set(0.0)); - Windows { ctx, root_info: RefCell::new(ViewportInfo::default()), root: RefCell::new(RootEnv::default()) } + Windows { + ctx, + root_info: RefCell::new(ViewportInfo::default()), + root: RefCell::new(RootEnv::default()), + window_input: Cell::new(WindowInput::Live), + } } /// The window facts child passes report from now on. @@ -323,6 +329,11 @@ impl Windows { with_facts(viewport, |info| info.clone()) } + /// The window-input policy every following frame's input gives, as a host's `FrameInput::window_input` does. + pub fn window_input(&self, policy: WindowInput) { + self.window_input.set(policy); + } + /// The window facts the root viewport reports from now on. pub fn root_info(&self, info: ViewportInfo) { *self.root_info.borrow_mut() = info; @@ -360,7 +371,7 @@ impl Windows { CHILD_FILES.with(|files| *files.borrow_mut() = child_files); TREES.with(|kept| kept.borrow_mut().clear()); SHAPES.with(|kept| kept.borrow_mut().clear()); - set_input(&self.ctx, FrameInput::new(self.root.borrow().clone())); + set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()).window_input(self.window_input.get())); let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)), events: root, diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 6ba8c0c0ea..2fb56ff931 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -141,7 +141,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | When | eframe method | Call | | --- | --- | --- | | Once, when the app is created | with the `CreationContext` | `embed::install(ctx, InstallSpec, &UiFonts)`: the runtime, then the app's fonts. Returns the font `Stack`. | -| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). | +| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. | | Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. | | Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. | | Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). | From b961098d056b6364ef47a4dd24780a3e5d4d73a4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 21:09:06 -0500 Subject: [PATCH 23/35] A press on an app's own egui widget in a container body is not a press on the container's surface BodyHooks::surface_press counted a press as on the surface when no shape won it, and find_under gives no winner exactly where egui's click target is a raw egui widget. A dock group then moved focus to its tab stop on a click on an app's text field or canvas in its body. The press now leaves the surface alone when its click target is such a widget (pointer::foreign_target), for every container that senses Sense::SURFACE. --- .../ui-contract/src/contract/body/presses.rs | 11 ++--- crates/ui-panels/tests/it/dock_group.rs | 42 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/contract/body/presses.rs b/crates/ui-contract/src/contract/body/presses.rs index 98efd50590..4924066366 100644 --- a/crates/ui-contract/src/contract/body/presses.rs +++ b/crates/ui-contract/src/contract/body/presses.rs @@ -40,9 +40,9 @@ impl BodyCx<'_> { } /// Whether the primary press of this pass went down on the container's own surface, for a root that senses - /// `Sense::SURFACE`: inside its rect, on its layer, where none of its children or parts takes the press. The - /// container decides what it means (a dock group focuses its panel, as Photoshop does); it is no click and moves - /// no focus by itself. + /// `Sense::SURFACE`: inside its rect, on its layer, where none of its children or parts and no app's own egui widget + /// in its body takes the press. The container decides what it means (a dock group focuses its panel, as Photoshop + /// does); it is no click and moves no focus by itself. pub fn surface_pressed(&self) -> bool { self.memory.recall::(sub(self.id, "surface_press")).pressed } @@ -76,8 +76,8 @@ impl BodyCx<'_> { impl BodyHooks<'_> { /// Records for the container's hooks whether this pass's primary press went down on its own surface /// (`BodyCx::surface_pressed`): no shape of last pass under the press takes it, nor a component's text widget - /// egui gives it to (a focused field's), and the press lies in the - /// container's rect on its layer; and whether that press is the second of a double click + /// egui gives it to (a focused field's), nor an app's own egui widget (a raw text field or canvas in the body), and + /// the press lies in the container's rect on its layer; and whether that press is the second of a double click /// (`BodyCx::surface_double_pressed`), read from the same press's click count; and whether this pass's primary /// release ends a press that went down there (`BodyCx::surface_clicked`). The press origin waits in the press slot /// until the release; Escape and a blur clear it, and so does any pass with no button held. @@ -95,6 +95,7 @@ impl BodyHooks<'_> { inside(press.origin) && pointer::press_winner(&ctx, press.origin, pass.press_targets).is_none() && !pointer::text_takes_press(&ctx, pass.press_targets) + && !pass.press_targets.click.is_some_and(|widget| pointer::foreign_target(&ctx, widget)) }) } else { None diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index 5533928f06..7852225d7f 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -183,3 +183,45 @@ fn a_tab_mark_change_repaints_the_tab_row() { let cleared = width(&mut fixture); assert!((cleared - plain).abs() < 0.5, "the tab loses its dot again: {plain} then {cleared}"); } + +// A click on an app's own egui widget in a group's body (a raw text field) is the widget's, not a press on the +// group's empty body: the group reads no surface press, so its stop does not take the focus, and the field keeps +// egui's focus and takes typing. A press on the body's empty room still focuses the group's panel. +#[trial] +fn a_click_on_an_app_field_in_the_body_keeps_its_focus() { + use std::cell::RefCell; + let text = Rc::new(RefCell::new(String::new())); + let field = Rc::new(Cell::new(None::<(egui::Id, Rect)>)); + let surface = Rc::new(Cell::new(false)); + let (typed, shown, pressed) = (Rc::clone(&text), Rc::clone(&field), Rc::clone(&surface)); + let panels = vec![PanelTitle::new(PanelKey::new(1), "Color")]; + let mut fixture = Fixture::new(move |ui| { + let group = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key); + let (typed, shown, pressed) = (Rc::clone(&typed), Rc::clone(&shown), Rc::clone(&pressed)); + group.show_at(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 240.0)), move |ui, cx| { + pressed.set(pressed.get() || cx.surface_pressed()); + let response = egui::TextEdit::singleline(&mut *typed.borrow_mut()).desired_width(120.0).show(ui).response; + shown.set(Some((response.id, response.rect))); + }); + }); + fixture.settle(); + let Some((field_id, field_rect)) = field.get() else { panic!("the body shows the app's field") }; + let empty = Pos2::new(field_rect.center().x, field_rect.bottom() + 80.0); + + // Typing a character at a time with a click before each. The clicks are a second apart, so egui sees no double + // click (which would select the word). + for (clicks, typed) in ["a", "1"].into_iter().enumerate() { + fixture.advance(1.0).click_at(field_rect.center()).settle(); + assert!(!surface.get(), "click {clicks} on the field is no press on the group's empty body"); + assert_eq!(fixture.focused(), Some(field_id), "click {clicks} leaves egui's focus on the app's field"); + fixture.type_text(typed).settle(); + } + let on_field = fixture.focused_stop(); + assert!(text.borrow().contains("a1"), "the field takes the typing after each click: {:?}", text.borrow()); + + fixture.click_at(empty).settle(); + let group_stop = fixture.focused_stop(); + assert!(surface.get(), "a press on the empty body is the group's surface press"); + assert!(group_stop.is_some() && fixture.focused() != Some(field_id), "a press on the empty body focuses the group's panel"); + assert_ne!(on_field, group_stop, "the clicks on the field left the group's stop unfocused"); +} From dba4b84b22c47fdd65dfbd05bd3f3660c3549644 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 22:26:23 -0500 Subject: [PATCH 24/35] keys: the app's own widget, focused or the window's canvas, keeps its keys in egui again --- .../src/testing/host_key_trials.rs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index bc9876cb14..bf7681f4c6 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -509,6 +509,54 @@ fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() { assert!(!clipboard_with_canvas(KeyUse::CANVAS, chord).1.is_empty(), "a canvas without the command: the chord fires the app's Paste"); } +/// Which of the arrow keys, Home and End reached egui's input, one press each, in a window whose host declares a canvas; +/// with `focus_field` the host's text field has the focus; and whether Left moved the field's caret. +fn navigation_keys_with_canvas(focus_field: bool) -> (Vec, bool) { + const KEYS: [Key; 6] = [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Home, Key::End]; + let canvas = named_id("host canvas"); + let reached = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&reached); + let (host, mut base) = host_window(); + host.borrow_mut().text = "abc".to_owned(); + let mut show = move |ui: &mut Ui| { + seen.borrow_mut().extend(KEYS.into_iter().filter(|key| key_reached(ui.ctx(), *key))); + base(ui); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS); + }; + let mut frames = Frames::new(); + frames.frame(Vec::new(), &mut show); + if focus_field { + fixture::host_focus(&frames.ctx, field()); + frames.frame(Vec::new(), &mut show); + frames.frame(vec![key_press(Key::End, Modifiers::NONE), key_release(Key::End, Modifiers::NONE)], &mut show); + } + reached.borrow_mut().clear(); + let caret = |frames: &Frames| { + egui::TextEdit::load_state(&frames.ctx, field()).and_then(|state| state.cursor.char_range()).map(|range| range.primary.index) + }; + let at_end = caret(&frames); + let mut moved = false; + for key in KEYS { + press_key(&mut frames, &mut show, key); + if key == Key::ArrowLeft { + moved = caret(&frames) != at_end; + } + } + let mut reached = reached.take(); + reached.dedup(); + (reached, moved) +} + +#[trial] +fn a_host_canvas_leaves_navigation_keys_in_egui_for_the_app_s_widget() { + const KEYS: [Key; 6] = [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Home, Key::End]; + let (reached, caret) = navigation_keys_with_canvas(true); + assert_eq!(reached, KEYS, "a focused app field reads the arrows, Home and End from egui"); + assert!(caret, "the field's caret moved left from the end"); + assert_eq!(navigation_keys_with_canvas(false).0, KEYS, "with nothing focused, the host canvas's own keys stay in egui"); +} + /// A clipboard with a picture and no text sends a paste with no text: it fires the app's Paste as the chord does, and /// `textless_paste` reads it in that pass only. #[trial] From 16c2e06ced8e20e4848c2b8ed0356b452ceb6fed Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 23:01:29 -0500 Subject: [PATCH 25/35] ui-panels: a floating window's resize grips carry the accessible name Resize panel window --- .../ui-contract/src/contract/body/window.rs | 5 +++++ crates/ui-contract/src/contract/container.rs | 9 +++++++++ crates/ui-contract/src/contract/cx/parts.rs | 8 ++++++++ .../ui-contract/src/contract/steps/report.rs | 12 ++++++++++- crates/ui-panels/src/docking/floating.rs | 4 ++++ crates/ui-panels/tests/it/dock_group.rs | 20 +++++++++++++++++++ 6 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index dc5e45c133..a80ce73fe5 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -814,6 +814,7 @@ impl BodyHooks<'_> { let top = top_band(props, &ctx, pcx.id, pcx.tokens); let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl())); let caller_sizes = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); + let grip_name = props.resize_name.as_ref().map(|name| pcx.env.resolve(name).as_str().to_owned()); for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() { if held != Some(index) && !grip_stands(edges, pinned, dx, dy) { continue; @@ -837,6 +838,10 @@ impl BodyHooks<'_> { .pointer_only(reason) .exact_hit() .over(); + let part = match &grip_name { + Some(name) => part.node(crate::runtime::access::Role::SPLITTER, name.as_str()), + None => part, + }; // The grips of a window its caller sizes are the app's (`window_resize`), never the platform's. if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))).filter(|_| !caller_sizes) { part.exclusive(hit); diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 502851b41b..39148cc4f3 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -812,6 +812,8 @@ pub struct ContainerProps { /// The help line the footer shows under the control column of a label-scoped container; its text joins the /// control's description. pub help: Option

{ pub events: Vec>, /// The shown panel of the group that holds key focus: focus is on the group or on a control inside it. pub focused: Option

, - /// The panel whose tab the user clicked or picked this pass. + /// The panel whose tab the user clicked or picked this pass; a pick of the host's `DockArea::focus` is not the + /// user's and shows only in `actions`. pub picked: Option

, /// Why nothing was drawn, when the workspace is invalid. pub error: Option, @@ -107,6 +108,7 @@ impl

Outcome for DockAreaOutput

{ /// actions the workspace took, divider sizes and window moves included. A given workspace is not written. /// - Requests: while the pass runs, a body changes the workspace through /// [`request_actions`](crate::docking::request_actions); the output returns those actions unapplied in `requested`. +/// The host moves key focus to a panel's group with [`focus`](DockArea::focus). /// - Hiding: [`hide`](DockArea::hide), the shell's panel visibility and [`maximized`](DockArea::maximized) prune /// what shows; a pruned panel keeps its place for restore. /// - Drops: the area is the drop target of tab and group drags. Ctrl or Cmd held at the release floats the drop, and @@ -151,6 +153,13 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { /// nothing. #[prop(quantity = "panel and grab point")] continue_move: Option<(P, Vec2)>, + /// Moves key focus to the group that shows the panel and picks its tab, as a click on the tab does: the group's + /// stop takes focus in this pass, and the pick is one of the pass's `actions`. A request of the pass: a host that + /// focuses a panel itself (it opened something in it) sets it for one pass. A panel the area does not show in this + /// pass (hidden, pruned by a maximize, in a closed flyout, or in a group the host's `group_view` draws) takes + /// neither; `DockAreaOutput::focused` tells the host where focus is. + #[prop] + focus: Option

, /// Adds the host's fixed trailing controls to the docked rail containing `panel`. The panel identifies the /// column as it moves between dock sides. The host draws the controls through [`DockPanels::rail_footer`]; its /// icons scroll above them when the rail is short. Has no effect in flyout mode or on floating columns. @@ -183,6 +192,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { locked: false, flyout: None, continue_move: None, + focus: None, rail_footer: None, top_inset: 0.0, } @@ -316,6 +326,8 @@ struct Scene<'s, P> { auto_collapse: bool, /// The panel whose window takes over the held press, with its grab point (`DockArea::continue_move`). continue_move: Option<(&'s P, Vec2)>, + /// The panel whose group takes key focus in this pass (`DockArea::focus`). + focus: Option<&'s P>, rtl: bool, /// The docked places floating panels left, for Dock Panel. floated: &'s [(P, Location

)], @@ -491,6 +503,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { locked, mut flyout, continue_move, + focus, rail_footer, top_inset, } = self; @@ -550,6 +563,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { maximized: maximized.as_ref(), auto_collapse, continue_move: continue_move.as_ref().map(|(panel, grab)| (panel, *grab)), + focus: focus.as_ref(), sizes, rtl, rail_footer: rail_footer.as_ref(), @@ -655,6 +669,7 @@ struct Input<'i, P> { maximized: Option<&'i P>, auto_collapse: bool, continue_move: Option<(&'i P, Vec2)>, + focus: Option<&'i P>, sizes: DockSizes, rtl: bool, rail_footer: Option<&'i P>, @@ -689,8 +704,24 @@ fn show_area( panels: &mut dyn DockPanels

, mut flyout: Option<&mut Bind<'_, Option

>>, ) -> Passed

{ - let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, continue_move, sizes, rtl, rail_footer, top_inset } = - *input; + let Input { + id, + ctx, + current, + config, + specs, + keys, + hide, + model, + maximized, + auto_collapse, + continue_move, + focus, + sizes, + rtl, + rail_footer, + top_inset, + } = *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected()); @@ -712,6 +743,7 @@ fn show_area( bounds, auto_collapse, continue_move, + focus, rtl, floated: current.floated(), rail_footer, @@ -1058,6 +1090,8 @@ impl Pass<'_, P> { return Some(height + grip); } let shown = &members[active]; + // The host's focus request, when it names a panel of this group. + let focus = scene.focus.filter(|panel| members.contains(panel)); let words = body.words::(); let ctx = ui.ctx().clone(); let panels = RefCell::new(&mut *self.panels); @@ -1148,7 +1182,11 @@ impl Pass<'_, P> { let taken = in_room(ui, view, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)); match taken { Some(_) => None, - None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output), + None => { + let group = make(active, look.minimized); + let group = if focus.is_some() { group.take_focus() } else { group }; + Some(group.show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output) + } } }) .inner; @@ -1188,10 +1226,14 @@ impl Pass<'_, P> { let torn = torn.map(|(panel, pointer)| { float_drop(&DragUnit::Panel(panel.clone()), scene.space, pointer, Some(fitted(ui, panel)), None, scene.rtl).action }); - let picked = output.picked.and_then(|key| scene.panel(key)); + let clicked = output.picked.and_then(|key| scene.panel(key)); + if let Some(panel) = clicked { + self.report.picked = Some(panel.clone()); + } + // The host's focus request picks its panel's tab as a click does; the user's click of the pass wins. + let picked = clicked.or(focus.filter(|panel| *panel != shown)); if let Some(panel) = picked { self.report.actions.push(Action::activate(panel.clone())); - self.report.picked = Some(panel.clone()); } // A tab picked in this pass is the group's shown panel from now on, though this pass drew the one before. if focus_within(ui.ctx(), output.response.id) { diff --git a/crates/ui-patterns/tests/it/docking/focus.rs b/crates/ui-patterns/tests/it/docking/focus.rs new file mode 100644 index 0000000000..69d0dff456 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/focus.rs @@ -0,0 +1,97 @@ +//! The host's focus request: `DockArea::focus` moves key focus to the group that shows a panel, as a click on its tab +//! does. + +use super::Numbered; +use craft_behavior::dock::{Action, Layout, Node, SplitSize, Workspace}; +use craft_behavior::{Axis, PartKey}; +use craft_ui::contract::{Bind, BodyCx, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Ui, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +struct Panels; + +impl DockPanels for Panels { + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} +} + +/// What one pass of the area reported. +#[derive(Debug)] +struct Seen { + focused: Option, + picked: Option, + actions: Vec>, +} + +/// The fixture, the host's focus request for the next pass, and each pass's report. +type TwoGroups = (Fixture, Rc>>, Rc>>); + +/// A dock of group A (panel 0) beside group B (panels 1 and 2, 1 shown) with `config`; the host's focus request for the +/// next pass goes in the cell, and each pass's report is pushed to the list. +fn two_groups(config: DockConfig) -> TwoGroups { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1, 2], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let request = Rc::new(Cell::new(None)); + let seen = Rc::new(RefCell::new(Vec::new())); + let (asked, reported, specs) = (Rc::clone(&request), Rc::clone(&seen), Tracked::new(Numbered)); + let mut fixture = Fixture::new(move |ui| { + let mut panels = Panels; + let mut area = DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, config.clone()); + if let Some(panel) = asked.take() { + area = area.focus(panel); + } + let output = area.show(ui); + reported.borrow_mut().push(Seen { focused: output.focused, picked: output.picked, actions: output.actions }); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + (fixture, request, seen) +} + +/// With the user's focus on group A's tabs, the host's request for panel 2 of group B moves key focus to B's stop (the +/// one a click on B's tabs focuses) and picks 2's tab; a key there reaches B. Guards against a request that picked the +/// tab but left key focus, and so the keys, on the tabs the user clicked last. +#[trial] +fn the_hosts_focus_request_moves_key_focus_to_the_panels_group_and_picks_its_tab() { + let (mut fixture, request, seen) = two_groups(DockConfig::default()); + let tab = |fixture: &Fixture, name: &str| fixture.by_label(name).expect("a group's tab"); + let b_tab = tab(&fixture, "Panel 1"); + fixture.click(&b_tab).idle(1); + let b_stop = fixture.focused_stop().expect("a click on B's tab focuses B's stop"); + let a_tab = tab(&fixture, "Panel 0"); + fixture.click(&a_tab).idle(1); + assert_ne!(fixture.focused_stop(), Some(b_stop), "a click on A's tab moves focus to A's stop"); + assert_eq!(seen.borrow().last().and_then(|seen| seen.focused), Some(0), "A holds the focus"); + seen.borrow_mut().clear(); + + request.set(Some(2)); + fixture.idle(2); + assert_eq!(fixture.focused_stop(), Some(b_stop), "the request moves key focus to B's stop"); + { + let seen = seen.borrow(); + assert!(seen.iter().any(|pass| pass.actions.contains(&Action::activate(2))), "the request picks 2's tab: {seen:?}"); + assert!(seen.iter().all(|pass| pass.picked.is_none()), "the host's pick is not the user's: {seen:?}"); + assert_eq!(seen.last().and_then(|pass| pass.focused), Some(2), "B holds the focus, with 2 shown: {seen:?}"); + } + seen.borrow_mut().clear(); + + fixture.key(Key::ArrowLeft, Modifiers::NONE).idle(1); + fixture.key(Key::Space, Modifiers::NONE).idle(1); + let picked = seen.borrow().iter().find_map(|pass| pass.picked); + assert!(matches!(picked, Some(1 | 2)), "the keys reach B's tabs, not A's: {picked:?}"); +} + +/// A titled header has no tab row: the request moves key focus to its drag band, the group's stop, and the group +/// holds the focus. Guards against a request that a titled group dropped. +#[trial] +fn the_hosts_focus_request_focuses_a_titled_groups_drag_band() { + let (mut fixture, request, seen) = two_groups(DockConfig::default().titled_headers(true)); + request.set(Some(2)); + fixture.idle(2); + let part = fixture.focused_stop().and_then(|(_, part)| part).map(|part| part.key); + assert_eq!(part, Some(PartKey::new("grip")), "the drag band holds key focus"); + assert_eq!(seen.borrow().last().and_then(|pass| pass.focused), Some(2), "B holds the focus, with 2 shown"); +} diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 17d129e898..14fccdc59b 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -6,6 +6,7 @@ use craft_ui::testing::style::{tokens, with_cx}; pub(crate) mod render; +pub(crate) mod focus; pub(crate) mod panel_menu; pub(crate) mod runs; From b3b2eaac4f37f3e30e9d08541886f1b3c6a81827 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:10:58 +0700 Subject: [PATCH 28/35] tabs: DocumentTabLook::Semibold shows VectorCraft's document tabs, whole titles as Whole with the title and its * in the label's semibold face (Span::strong), measured as painted; a Semibold story --- .../ui-widgets/src/tabs/document/stories.rs | 19 +++++++++++++++++++ crates/ui-widgets/src/tabs/rules.rs | 2 ++ crates/ui-widgets/src/tabs/tab.rs | 18 ++++++++++++++---- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-widgets/src/tabs/document/stories.rs b/crates/ui-widgets/src/tabs/document/stories.rs index fce3c64ac9..2d3c20f505 100644 --- a/crates/ui-widgets/src/tabs/document/stories.rs +++ b/crates/ui-widgets/src/tabs/document/stories.rs @@ -77,3 +77,22 @@ fn document_tabs_with_name_part(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu let shown = *data.value("shown", 0_usize); DocumentTabs::new("Documents", &tabs).selected(shown).show(ui).response.into() } + +/// VectorCraft's tabs (`DocumentTabLook::Semibold`): whole titles in the label's semibold face, the `*` of a modified +/// tab after its name as well. The shown tab carries its view after the name. +#[story(DocumentTabs<'static, usize>, covers = [], drive = Drive::Never, title = "Semibold")] +fn semibold_document_tabs(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + const NAME: &str = "Untitled-1"; + let tabs = [ + DocumentTab::new(0, format!("{NAME} @ 93.5 % (RGB/Preview)")).modified(true).name_len(NAME.len()), + DocumentTab::new(1, "Poster.vectorcraft"), + ]; + let shown = *data.value("shown", 0_usize); + crate::runtime::env::with_env( + ui, + |overrides| { + overrides.values.set(crate::tabs::DocumentTabLook::Semibold); + }, + |ui| DocumentTabs::new("Documents", &tabs).selected(shown).reorderable(true).show(ui).response.into(), + ) +} diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 19a74b5976..153d61632d 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -15,6 +15,8 @@ pub enum DocumentTabLook { /// PdfCraft's tabs: they shrink before they overflow (a name at most 22 digits wide, at its least a readable /// prefix), stand the inline gap apart, and a modified tab shows the marker dot in place of the `*`. Shrinking, + /// VectorCraft's tabs: whole titles as [`Whole`](Self::Whole), the title and its `*` in the label's semibold face. + Semibold, } /// The look of panel tabs ([`TabKind::Panel`]): a strip's choice ([`TabStrip::panel_look`](super::TabStrip)), which a diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index 7a035282f8..a62436badb 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -20,7 +20,7 @@ use crate::contract::{ use crate::display::Progress; use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth, TextRun, Wrap}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, Flags, IconLook, RuleKind, StyleColor, StyleCx, SurfaceLook, TextLook, UiTokens}; +use crate::style::{ComponentStyle, Flags, IconLook, RuleKind, Span, StyleColor, StyleCx, SurfaceLook, TextLook, UiTokens}; use craft_behavior::{Flow, IconId, Insets, Metrics, PartKey, Proposal, Sense}; use craft_theme::{Contrast, Rgba, Stateful, States, TypeRole}; use egui::{Pos2, Rect, Response, Vec2}; @@ -140,6 +140,9 @@ pub struct TabStyle { /// Document tabs in [`DocumentTabLook::Shrinking`](super::DocumentTabLook::Shrinking): a name capped at /// `MAX_NAME_DIGITS` digits' width, a readable prefix at their least, and the marker dot for a modified tab. shrinking: bool, + /// Document tabs in [`DocumentTabLook::Semibold`](super::DocumentTabLook::Semibold): the label and its `*` in the + /// role's semibold face. + strong: bool, /// The marker dot's diameter. marker: f32, /// The marker dot of a marked tab. @@ -157,6 +160,12 @@ struct Pill { height: f32, } +/// `text` as a run of the label: in the role's semibold face where the look sets the label strong. +fn label_text<'t>(style: &TabStyle, text: impl Into>) -> TextRun<'t> { + let span = Span::new(text); + TextRun::spans(vec![if style.strong { span.strong() } else { span }]) +} + /// Where the parts of a tab lie in its content rect. #[derive(Clone, Copy, Debug)] struct Placed { @@ -265,7 +274,7 @@ impl<'a> Tab<'a> { } fn label_run<'t>(&self, style: &TabStyle, text: &'t str) -> TextRun<'t> { - TextRun::new(text).role(style.label.role) + label_text(style, text).role(style.label.role) } /// Whether the marker dot shows: the tab's content has something to show, or the document is modified and the @@ -296,7 +305,7 @@ impl<'a> Tab<'a> { /// The modified mark, in the label's type. fn mark_run(&self, style: &TabStyle) -> TextRun<'static> { - TextRun::new(MARK).role(style.label.role) + label_text(style, MARK).role(style.label.role) } /// Where the parts lie in `content`, with `natural` the unbounded width of a run. `parts` registers its parts @@ -466,6 +475,7 @@ impl Component for Tab<'_> { close_side: close_side(cx.os, cx.direction.is_rtl()), sizes, shrinking: key.kind.shrinks_in(cx.env::()), + strong: key.kind == TabKind::Document && cx.env::() == super::DocumentTabLook::Semibold, marker: marker.side, marker_color: marker.color, marker_edge: marker.edge, @@ -603,7 +613,7 @@ impl Component for Tab<'_> { draw.stroke(&line, StrokeWidth::Thick, style.underline); } let role = if selected { style.label.role } else { style.idle_role }; - let label = TextRun::new(&*shown).role(role).color(cx.resolve(&style.label.color)); + let label = label_text(style, &*shown).role(role).color(cx.resolve(&style.label.color)); draw.text(placed.label, &if self.kind.clips_label() { label.wrap(Wrap::Clip) } else { label.elide() }); if let (Some(at), Some(detail)) = (placed.detail, self.detail_text()) { draw.text(at, &TextRun::new(detail).role(style.detail.role).color(cx.resolve(&style.detail.color)).elide()); From a81bc6fe7725ea029a9c1b04d92b25de7e8132bc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:14:05 +0700 Subject: [PATCH 29/35] =?UTF-8?q?dock=20group:=20beside=20PanelTabLook::Pi?= =?UTF-8?q?ll=20tabs=20the=20panel=20menu=20button=20stands=20in=20the=20s?= =?UTF-8?q?trip's=20middle,=20level=20with=20the=20pills,=20as=20productio?= =?UTF-8?q?n's=20=E2=89=A1=20is=20centred=20in=20its=20cell;=20plain=20tab?= =?UTF-8?q?s=20keep=20it=20at=20the=20strip's=20top.=20Story=20and=20trial?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-panels/src/docking/group.rs | 7 +++++-- crates/ui-panels/src/docking/stories.rs | 18 +++++++++++++++++- crates/ui-panels/tests/it/dock_group.rs | 23 +++++++++++++++++++++++ crates/ui-widgets/src/tabs/rules.rs | 3 ++- 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index a3ffef3dcf..a5b7abc3c7 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -463,7 +463,8 @@ impl Component for } /// The band the group is dragged by and the panel menu button, at the end of the header: the band first. The - /// button sits at the strip's top, level with the tab labels' caps, as the "…" of the old tab strips did. + /// button sits at the strip's top, level with the tab labels' caps, as the "…" of the old tab strips did; beside + /// [`PanelTabLook::Pill`] tabs, in the strip's middle with their pills. fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { let Some(slot) = cx.header_slot(HeaderEdge::End) else { return }; let words = cx.words::(); @@ -475,7 +476,9 @@ impl Component for // An icon button is square: its side is the slot's room past the band and the gap. let side = (slot.width() - grip_width(cx.tokens) - cx.tokens.space.gap.item).max(0.0); let end = rest.take_end(side).0; - let button = Rect::from_min_size(egui::Pos2::new(end.left(), slot.top()), Vec2::new(end.width(), side.min(slot.height()))); + let height = side.min(slot.height()); + let top = if self.tab_look == PanelTabLook::Pill { slot.center().y - height / 2.0 } else { slot.top() }; + let button = Rect::from_min_size(egui::Pos2::new(end.left(), top), Vec2::new(end.width(), height)); let _ = cx .header_part(HeaderEdge::End, MENU, button) .sense(Sense::CLICK | Sense::FOCUS) diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 5d5797a14d..7218af0b5c 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -13,9 +13,10 @@ use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, use crate::menu::{Menu, PanelRow}; use crate::runtime::commands::CommandRef; use crate::runtime::env::Message; +use crate::tabs::PanelTabLook; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use craft_behavior::dock::{Layout, Node, SplitSize}; -use craft_behavior::{Axis, Mixed}; +use craft_behavior::{Axis, IconId, Mixed}; use egui::{Ui, Vec2}; const LAYERS: usize = 0; @@ -132,6 +133,21 @@ fn panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() } +/// VectorCraft's group header (`DockConfig::tab_look(PanelTabLook::Pill)`): the shown tab on a filled pill in the +/// strip's middle, and the panel menu button, the three-line mark, level with it at the strip's end. +#[story(DockGroup<'static, usize>, covers = [Default])] +fn pill_tabs_and_the_panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let panels = titles(&[LAYERS, CHANNELS]); + let rows = [DockCommands::FloatPanel, DockCommands::FloatGroup].map(|command| PanelRow::Command(CommandRef::from(command))).to_vec(); + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key) + .menu(move || rows.clone()) + .panel_menu_icon(IconId::new("menu")) + .tab_look(PanelTabLook::Pill) + .show(ui, |_, _| ()) + .output + .into() +} + #[story(GroupGrip, covers = [Default])] fn a_group_grip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { GroupGrip::new(DragUnit::Group(LAYERS), PanelKey::of(&LAYERS)).label("Move tab group").show(ui).into() diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index 5533928f06..ec3c0ba991 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -65,6 +65,29 @@ fn the_shown_panels_caption_sits_under_the_tabs_and_its_count_names_its_tab() { assert!(fixture.by_label("2 replies").is_none(), "Comments' caption goes with it"); } +// Beside pill tabs (VectorCraft's) the panel menu button stands in the strip's middle, level with the shown tab's pill; +// beside plain tabs it keeps to the strip's top. +#[trial] +fn the_panel_menu_button_stands_level_with_pill_tabs() { + use craft_ui::menu::PanelRow; + use craft_ui::tabs::PanelTabLook; + let middles = |look: PanelTabLook| { + let panels = vec![PanelTitle::new(PanelKey::new(1), "Layers"), PanelTitle::new(PanelKey::new(2), "Pages")]; + let mut fixture = Fixture::new(move |ui| { + let group = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).menu(Vec::::new).tab_look(look); + let _ = group.show_at(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 240.0)), |_, _| ()); + }); + fixture.settle(); + let Some(tab) = fixture.by_label("Layers") else { panic!("the shown tab shows") }; + let Some(menu) = fixture.by_label("Panel Menu") else { panic!("the panel menu button shows") }; + (tab.rect.center().y, menu.rect) + }; + let (tab, menu) = middles(PanelTabLook::Pill); + assert!((menu.center().y - tab).abs() <= 0.5, "the menu button {menu:?} is level with the pill tab's middle {tab}"); + let (_, plain) = middles(PanelTabLook::Plain); + assert!(menu.top() > plain.top() + 0.5, "beside plain tabs the button {plain:?} keeps to the strip's top, above {menu:?}"); +} + // A titled group shows the shown panel's name as a heading with its count and a close button, not a tab strip: the // panel's name is not cut to a tab's width, and the close button closes the shown panel. #[trial] diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 153d61632d..67bcc778f5 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -28,7 +28,8 @@ pub enum PanelTabLook { #[default] Plain, /// VectorCraft's tabs: the shown tab on a filled pill (`surface.control` with `shape.radius.control` corners), a - /// small control high in the middle of the strip; a tab under the pointer shows the pill too. + /// small control high in the middle of the strip; a tab under the pointer shows the pill too. A dock group's panel + /// menu button stands in the strip's middle with them. Pill, } From c26752ab90c6a2d4bd0d35510b5c631005bb9014 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 24 Nov 2026 16:20:29 +0100 Subject: [PATCH 30/35] WIP: lasso cursors: an arrow on the hotspot with the tool icon beside it (photocraft#16671) From 33774554c793aaf38e45e81ee0d9a380a90bdfc2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:21:42 +0700 Subject: [PATCH 31/35] ui-panels: a titled Panel draws the rule under its header only for a weight that stands with one, as Section does for its rule above; an Inspector's Quiet kind line has none --- crates/ui-panels/src/sections/panel.rs | 21 +++++++++++++++---- crates/ui-panels/src/sections/section.rs | 3 +-- crates/ui-panels/src/sections/title_row.rs | 8 +++++++ .../src/patterns/panels/inspector.rs | 2 +- .../src/patterns/panels/inspector/stories.rs | 2 +- 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/ui-panels/src/sections/panel.rs b/crates/ui-panels/src/sections/panel.rs index 5998fd1236..2d27b2c036 100644 --- a/crates/ui-panels/src/sections/panel.rs +++ b/crates/ui-panels/src/sections/panel.rs @@ -99,8 +99,6 @@ pub struct Panel<'a> { closed: Option, pickable: bool, framed: bool, - /// How much weight the header's title carries; a panel title by default. - #[prop] strength: HeaderStrength, } @@ -134,10 +132,25 @@ impl<'a> Panel<'a> { .label(title) } - /// A header showing the title in a title row, with a rule under it: for a panel that no dock tab or window names. + /// A header showing the title in a title row, with a rule under it unless the title's weight is a quiet one + /// ([`strength`](Panel::strength)): for a panel that no dock tab or window names. #[must_use] pub fn titled(mut self) -> Self { - self.props.header = Some(HeaderRegion::new().rule(true)); + self.props.header = Some(HeaderRegion::new().rule(self.strength.ruled())); + self + } + + /// How much weight the header's title carries, a panel title (`HeaderStrength::Strong`) by default. A quiet weight + /// (`Caption`, `Subheading`, `Quiet`, `Overline`) stands with no rule under a titled header. + #[must_use] + pub fn strength(mut self, strength: HeaderStrength) -> Self { + self.strength = strength; + // A band header stands with no rule whatever its weight. + if let Some(header) = self.props.header.as_mut() + && header.fill.is_none() + { + header.rule = strength.ruled(); + } self } diff --git a/crates/ui-panels/src/sections/section.rs b/crates/ui-panels/src/sections/section.rs index 3b757380ae..681b556f85 100644 --- a/crates/ui-panels/src/sections/section.rs +++ b/crates/ui-panels/src/sections/section.rs @@ -163,8 +163,7 @@ impl<'a> Section<'a> { #[must_use] pub fn strength(mut self, strength: HeaderStrength) -> Self { self.strength = strength; - let quiet = matches!(strength, HeaderStrength::Caption | HeaderStrength::Subheading | HeaderStrength::Quiet | HeaderStrength::Overline); - self.update_header(|header| header.rule_above(!quiet)); + self.update_header(|header| header.rule_above(strength.ruled())); self } diff --git a/crates/ui-panels/src/sections/title_row.rs b/crates/ui-panels/src/sections/title_row.rs index babc26b1d7..32cfc9763e 100644 --- a/crates/ui-panels/src/sections/title_row.rs +++ b/crates/ui-panels/src/sections/title_row.rs @@ -50,6 +50,14 @@ pub enum HeaderStrength { Overline, } +impl HeaderStrength { + /// Whether a header of this weight stands with a rule beside it: every weight but the quiet ones over a group + /// of controls (`Caption`, `Subheading`, `Quiet`, `Overline`). + pub(crate) const fn ruled(self) -> bool { + !matches!(self, HeaderStrength::Caption | HeaderStrength::Subheading | HeaderStrength::Quiet | HeaderStrength::Overline) + } +} + /// What a title row's action parts ask the container to do. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/ui-patterns/src/patterns/panels/inspector.rs b/crates/ui-patterns/src/patterns/panels/inspector.rs index c2b93509b4..e1182e9d24 100644 --- a/crates/ui-patterns/src/patterns/panels/inspector.rs +++ b/crates/ui-patterns/src/patterns/panels/inspector.rs @@ -24,7 +24,7 @@ pub(crate) mod stories; /// - Padding: none of its own. An inspector is a dock body, docked or floating, and the dock group insets it. /// - Title weight: a section heading's by default, as the headings of the sections under it; /// [`title_strength`](Inspector::title_strength) gives another, such as `Quiet` for a muted kind line over the -/// sections. +/// sections, with no rule under it. #[derive(crate::contract::Pattern)] pub struct Inspector<'a> { label: Label, diff --git a/crates/ui-patterns/src/patterns/panels/inspector/stories.rs b/crates/ui-patterns/src/patterns/panels/inspector/stories.rs index 68de15cc43..fb22c14c94 100644 --- a/crates/ui-patterns/src/patterns/panels/inspector/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/inspector/stories.rs @@ -50,7 +50,7 @@ fn inspector(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { output.into() } -/// A quiet title: the target's kind as a muted line over its sections. +/// A quiet title: the target's kind as a muted line over its sections, with no rule under it. #[story(Inspector<'static>, covers = [], drive = Drive::Never)] fn inspector_quiet_title(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let inspector = Inspector::new("Properties").target("ellipse").header("Ellipse").title_strength(HeaderStrength::Quiet); From 747dad4c1ce99ab1748d522d724f6e30a7930e9a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:21:42 +0700 Subject: [PATCH 32/35] ui-contract: CaptionInk, an env style value for the ink of a side label's name: Muted (default) or Normal, VectorCraft's field labels as production drew them; Field story field_caption_ink --- crates/ui-contract/src/contract/label.rs | 3 +- crates/ui-contract/src/contract/label/leaf.rs | 9 +++--- .../ui-contract/src/contract/label/props.rs | 15 ++++++++++ crates/ui-contract/src/contract/mod.rs | 4 +-- crates/ui-widgets/src/form/stories.rs | 28 ++++++++++++++++++- 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/contract/label.rs b/crates/ui-contract/src/contract/label.rs index 236d7bf1ab..881564478e 100644 --- a/crates/ui-contract/src/contract/label.rs +++ b/crates/ui-contract/src/contract/label.rs @@ -14,6 +14,7 @@ pub use leaf::colon_of; pub(crate) use place::{control_after, label_gap}; pub(crate) use props::inside; pub use props::{ - CaptionColumn, CellWidth, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk, Scrub, SideLabel, + CaptionColumn, CaptionInk, CellWidth, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk, Scrub, + SideLabel, }; pub(crate) use step::{LabelIn, LeafLabel, Trailing, flow_leaf, in_column, leaf, leaf_under, report_after_reach, run, show_leaf_in_flow}; diff --git a/crates/ui-contract/src/contract/label/leaf.rs b/crates/ui-contract/src/contract/label/leaf.rs index 62274da560..3e0f7cb32d 100644 --- a/crates/ui-contract/src/contract/label/leaf.rs +++ b/crates/ui-contract/src/contract/label/leaf.rs @@ -1,6 +1,6 @@ //! The side label as a leaf component: its node, press state, reset dot and colon. -use super::props::{FieldLayout, Glyph, GlyphColon, LabelKind, LabelScheme, LinkLabelInk}; +use super::props::{CaptionInk, FieldLayout, Glyph, GlyphColon, LabelKind, LabelScheme, LinkLabelInk}; use super::step::LabelIn; use crate::contract::InBar; use crate::contract::{Component, Props}; @@ -30,8 +30,8 @@ pub(super) struct LabelStyle { gap: f32, /// The detail: `text.muted`, `text.disabled` with a disabled control. detail: Stateful, - /// The name: `TypeRole::Label` in `text.muted`; after a check box or a radio, `TypeRole::Body` in `text.normal`. - /// `text.disabled` with a disabled control. + /// The name: `TypeRole::Label` in the [`CaptionInk`]; after a check box or a radio, `TypeRole::Body` in + /// `text.normal`. `text.disabled` with a disabled control. #[style(text)] name: TextLook, /// The glyph and icon: their own ink (`None`), `text.disabled` with a disabled control. @@ -173,7 +173,8 @@ impl Component for LabelLeaf { // A caption reads as secondary; a check box's or a radio's text after it is the control's own. name: { let text = &cx.tokens.color.text; - let (role, ink) = if key.after { (TypeRole::Body, text.normal) } else { (TypeRole::Label, text.muted) }; + let caption = if cx.env::() == CaptionInk::Normal { text.normal } else { text.muted }; + let (role, ink) = if key.after { (TypeRole::Body, text.normal) } else { (TypeRole::Label, caption) }; let neutral = cx.env::() == LinkLabelInk::Neutral; if key.link && !neutral { // A link label keeps its role, so it takes the room of the caption it is, in the link's ink. diff --git a/crates/ui-contract/src/contract/label/props.rs b/crates/ui-contract/src/contract/label/props.rs index 8e5785bc8f..548ed5e223 100644 --- a/crates/ui-contract/src/contract/label/props.rs +++ b/crates/ui-contract/src/contract/label/props.rs @@ -136,6 +136,21 @@ pub enum LinkLabelInk { Neutral, } +/// The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio, +/// which reads at full ink. An app sets it once at its root (`RootEnv::values`); the default is the muted ink of a +/// caption that reads as secondary. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::runtime::env::EnvValue, crate::contract::MemoProps)] +#[env(style)] +#[non_exhaustive] +pub enum CaptionInk { + /// `text.muted`. + #[default] + Muted, + /// `text.normal`, the ink of the values beside it: VectorCraft's field labels ("X:", "Angle:", "Opacity"), as + /// production drew them. + Normal, +} + /// Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is /// as wide as its own text and its control follows it at once. On, the captions keep to the row start in one column as /// wide as the widest, so the controls after them line up (production's Rotate Pages dialog: Direction:, Pages: and diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 9ba2a3a73e..e0ddf2ff56 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -93,8 +93,8 @@ pub use items::{measure_item, show_item, show_item_in_flow}; #[doc(hidden)] pub use label::colon_of; pub use label::{ - CaptionColumn, CellWidth, FieldLabelRole, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk, - Scrub, SideLabel, + CaptionColumn, CaptionInk, CellWidth, FieldLabelRole, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, + LinkLabelInk, Scrub, SideLabel, }; pub use lazy::Lazy; #[doc(hidden)] diff --git a/crates/ui-widgets/src/form/stories.rs b/crates/ui-widgets/src/form/stories.rs index 6531e98b45..94eb9530fb 100644 --- a/crates/ui-widgets/src/form/stories.rs +++ b/crates/ui-widgets/src/form/stories.rs @@ -5,7 +5,8 @@ use super::{Field, FieldGroup}; use crate::buttons::Link; use crate::choice::Swatch; use crate::contract::{ - FieldLayout, GlyphColon, GlyphLabel, LabelKind, LabelScheme, LinkLabelInk, Props as _, Show as _, ShowContainer as _, SideLabel, Validity, + CaptionInk, FieldLayout, GlyphColon, GlyphLabel, LabelKind, LabelScheme, LinkLabelInk, Props as _, Show as _, ShowContainer as _, SideLabel, + Validity, }; use crate::layout_components::{Row, Stack}; use crate::runtime::env::{Message, with_env}; @@ -86,6 +87,31 @@ fn field_link_label_ink(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { StoryOutput { clicked: accent || neutral, ..StoryOutput::default() } } +/// A field's label under each `CaptionInk`, enabled and disabled: the muted ink (the default), then the normal ink +/// VectorCraft sets at its root. A disabled label reads in the disabled ink under both. +#[story(Field, covers = [], drive = Drive::Never)] +fn field_caption_ink(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut rows = |ui: &mut Ui, key: &'static str| { + Stack::new().id_salt(key).show(ui, |ui, _| { + for (salt, enabled) in [("enabled", true), ("disabled", false)] { + Field::new("Angle") + .id_salt(salt) + .enabled(enabled) + .show(ui, |ui, _| NumberField::new("Angle", data.bind(key, Some(SIZE))).unit("°").show(ui)); + } + }); + }; + rows(ui, "muted"); + with_env( + ui, + |overrides| { + overrides.values.set(CaptionInk::Normal); + }, + |ui| rows(ui, "normal"), + ); + StoryOutput::default() +} + /// A glyph label: the icon shows, the text only names the control. #[story(Field, covers = [], drive = Drive::Never)] fn field_icon_label(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { From c7ce7e5460b3f177df9b3850efbfeef885495388 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:21:42 +0700 Subject: [PATCH 33/35] ui-widgets: ReferencePointLook::Squares fills the pick in the normal text ink and draws no sunken well or border, as production's locator; compact squares story --- .../ui-widgets/src/pickers/reference_point.rs | 25 +++++++++++++------ .../src/pickers/reference_point/stories.rs | 13 +++++++++- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/ui-widgets/src/pickers/reference_point.rs b/crates/ui-widgets/src/pickers/reference_point.rs index 1abc206f1e..e0fbdf20ff 100644 --- a/crates/ui-widgets/src/pickers/reference_point.rs +++ b/crates/ui-widgets/src/pickers/reference_point.rs @@ -12,6 +12,7 @@ use crate::runtime::env::Label; use crate::runtime::focus::{ActivateKeys, KeyUse}; use crate::style::{ComponentStyle, Flags, FocusLook, Stateful, States, StyleColor, StyleCx, SurfaceKind, SurfaceLook, UiTokens}; use craft_behavior::{Anchor9, Metrics, NavShape, PartKey, PartRef, Roving, Sense}; +use craft_theme::Rgba; use egui::{CornerRadius, Pos2, Rect, Vec2, vec2}; #[cfg(feature = "suite")] @@ -62,7 +63,7 @@ pub struct ReferencePointStyle { picked_dot: f32, /// The dots' corner radius. dot_radius: egui::CornerRadius, - /// The picked point's dot. + /// The picked point's dot or square: `accent.text`, `text.normal` in the `Squares` look. ink: Stateful, /// The side of the square one growth arrow fits in. arrow: f32, @@ -104,8 +105,9 @@ pub enum ReferencePointLook { /// A dot for each point, the pick's twice as wide. #[default] Dots, - /// Eight outer squares joined by one line round the box and a lone centre square, the pick filled, with growth - /// arrows in `Dots` only. + /// Eight outer squares joined by one line round the box and a lone centre square in the muted ink, the pick + /// filled in the normal text ink, on the surface around the picker with no well of its own. Growth arrows are + /// in `Dots` only. Squares, } @@ -213,18 +215,25 @@ impl Component for ReferencePoint<'_> { let edge = Stateful::new(cx.color(colors.line.control_edge)); let disabled = cx.color(colors.text.disabled); let look = |rest: StyleColor| Stateful::new(rest).off(States::new(rest, rest, rest, disabled)); - ReferencePointStyle { - metrics: Metrics::new(), - surface: SurfaceLook::new(Stateful::new(StyleColor(sunken.fill))) + let squares = key.look == ReferencePointLook::Squares; + // The squares stand on the surface around them, joined by their own line; the dots sit in a sunken well. + let surface = if squares { + SurfaceLook::new(Stateful::new(cx.color(Rgba::TRANSPARENT))) + } else { + SurfaceLook::new(Stateful::new(StyleColor(sunken.fill))) .kind(SurfaceKind::Sunken) .radius(sunken.radius) - .border(edge, cx.tokens.stroke.thin), + .border(edge, cx.tokens.stroke.thin) + }; + ReferencePointStyle { + metrics: Metrics::new(), + surface, focus: cx.focus_look(), cell: if key.compact { cx.tokens.size.icon.md / GRID as f32 } else { cx.tokens.size.control.md }, dot: DOT, picked_dot: if key.compact { DOT } else { DOT * 2.0 }, dot_radius: UiTokens::corner(cx.tokens.shape.radius.sm), - ink: look(cx.color(colors.accent.text)), + ink: look(cx.color(if squares { colors.text.normal } else { colors.accent.text })), arrow: cx.tokens.size.icon.sm, arrow_ink: look(cx.color(colors.text.muted)), square: cx.tokens.size.handle.sm, diff --git a/crates/ui-widgets/src/pickers/reference_point/stories.rs b/crates/ui-widgets/src/pickers/reference_point/stories.rs index 38cc1ef955..2eabe8d878 100644 --- a/crates/ui-widgets/src/pickers/reference_point/stories.rs +++ b/crates/ui-widgets/src/pickers/reference_point/stories.rs @@ -51,7 +51,8 @@ fn reference_point_alignment_unset(ui: &mut Ui, data: &mut StoryData) -> StoryOu ReferencePoint::new("Alignment", data.bind("alignment_unset", None::)).kind(ReferencePointKind::Alignment).show(ui).into() } -/// The squares look: eight squares joined by a line round the box, the centre one alone, the pick filled. +/// The squares look: eight squares joined by a line round the box, the centre one alone, the pick filled in the text +/// ink, with no well behind them. #[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)] fn reference_point_squares(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ReferencePoint::new("Reference point", data.bind("squares", Some(Anchor9::TopRight))).look(ReferencePointLook::Squares).show(ui).into() @@ -71,3 +72,13 @@ fn reference_point_squares_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutp fn reference_point_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ReferencePoint::new("Reference point", data.bind("compact", Some(Anchor9::Centre))).compact().show(ui).into() } + +/// The squares look at the options bar's size, as an inspector's transform fields lead with it. +#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)] +fn reference_point_squares_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + ReferencePoint::new("Reference point", data.bind("squares_compact", Some(Anchor9::Centre))) + .look(ReferencePointLook::Squares) + .compact() + .show(ui) + .into() +} From 2014d31f34e883840c6db195146287ad01830457 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 22:21:52 +0700 Subject: [PATCH 34/35] theme, dock grips: GripMark::Bar (shape.grip.mark "bar"), one level bar length long and width thick; a grip's length may reach 32; GripMarks paints it; VectorCraft's themes pin production's Tools grip, an 18 by 3 point bar. Trial; dumps updated --- crates/theme/src/dump.rs | 4 +- crates/theme/src/format/mod.rs | 2 +- crates/theme/src/format/parse.rs | 3 +- crates/theme/src/format/write.rs | 4 +- crates/theme/src/tokens/size.rs | 20 ++++++++-- ...ctorcraft-modern-dark-high-comfortable.txt | 6 +-- .../vectorcraft-modern-dark-high-compact.txt | 6 +-- ...craft-modern-dark-standard-comfortable.txt | 6 +-- ...ctorcraft-modern-dark-standard-compact.txt | 6 +-- ...torcraft-modern-light-high-comfortable.txt | 6 +-- .../vectorcraft-modern-light-high-compact.txt | 6 +-- ...raft-modern-light-standard-comfortable.txt | 6 +-- ...torcraft-modern-light-standard-compact.txt | 6 +-- ...ft-modern-medium-dark-high-comfortable.txt | 6 +-- ...rcraft-modern-medium-dark-high-compact.txt | 6 +-- ...odern-medium-dark-standard-comfortable.txt | 6 +-- ...ft-modern-medium-dark-standard-compact.txt | 6 +-- ...t-modern-medium-light-high-comfortable.txt | 6 +-- ...craft-modern-medium-light-high-compact.txt | 6 +-- ...dern-medium-light-standard-comfortable.txt | 6 +-- ...t-modern-medium-light-standard-compact.txt | 6 +-- .../themes/vectorcraft-modern-medium.json | 8 +++- crates/theme/themes/vectorcraft-modern.json | 8 +++- crates/ui-panels/src/docking/group.rs | 29 +++++++++----- crates/ui-panels/src/docking/iconic/trials.rs | 40 +++++++++++++++---- 25 files changed, 138 insertions(+), 76 deletions(-) diff --git a/crates/theme/src/dump.rs b/crates/theme/src/dump.rs index 6f2dd81168..6d4f822b92 100644 --- a/crates/theme/src/dump.rs +++ b/crates/theme/src/dump.rs @@ -6,7 +6,7 @@ use std::fmt::Write as _; use crate::{ - BarSizes, ColorToken, ControlSizes, DialogSizes, DockColumnSizes, Easing, Edge, Elevation, ElevationTokens, FloatSizes, FontSlot, Gaps, GripMark, + BarSizes, ColorToken, ControlSizes, DialogSizes, DockColumnSizes, Easing, Edge, Elevation, ElevationTokens, FloatSizes, FontSlot, Gaps, GripShape, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, Motion, MotionTokens, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, Rgba, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StrokeTokens, ThumbSamples, ThumbSizes, Tokens, TypeStyle, TypeTokens, WellShape, WindowSizes, @@ -76,7 +76,7 @@ fn shape_lines(out: &mut Lines, shape: &ShapeTokens) { out.line("shape.knob", if *knob == KnobShape::Round { "round" } else { "tab" }); out.line("shape.wells", if *wells == WellShape::Square { "square" } else { "round" }); let GripShape { mark, count, length, width, gap } = grip; - out.line("shape.grip.mark", if *mark == GripMark::Ticks { "ticks" } else { "dots" }); + out.line("shape.grip.mark", mark.name()); out.line("shape.grip.count", count.to_string()); for (k, v) in [("length", length), ("width", width), ("gap", gap)] { out.line(&format!("shape.grip.{k}"), len(*v)); diff --git a/crates/theme/src/format/mod.rs b/crates/theme/src/format/mod.rs index f9ea5967d1..59d490ba6a 100644 --- a/crates/theme/src/format/mod.rs +++ b/crates/theme/src/format/mod.rs @@ -42,7 +42,7 @@ const KNOB: &str = "\"round\" or \"tab\""; /// What `shape.wells` takes. const WELLS: &str = "\"square\" or \"round\""; /// What `shape.grip.mark` takes. -const GRIP_MARK: &str = "\"ticks\" or \"dots\""; +const GRIP_MARK: &str = "\"ticks\", \"dots\" or \"bar\""; /// What the numbers of `shape.grip` take. const GRIP_NUMBER: &str = "a number"; /// What `icon_pack` takes. diff --git a/crates/theme/src/format/parse.rs b/crates/theme/src/format/parse.rs index 347f4f5836..b9c37f05df 100644 --- a/crates/theme/src/format/parse.rs +++ b/crates/theme/src/format/parse.rs @@ -318,6 +318,7 @@ impl Parser { None | Some(Value::Null) => Some(None), Some(Value::String(s)) if s == "ticks" => Some(Some(GripMark::Ticks)), Some(Value::String(s)) if s == "dots" => Some(Some(GripMark::Dots)), + Some(Value::String(s)) if s == "bar" => Some(Some(GripMark::Bar)), Some(_) => { p.fail(ErrorKind::BadValue { expected: GRIP_MARK }); None @@ -340,7 +341,7 @@ impl Parser { }) }; let count = number(self, "count", 1.0, 32.0, true); - let length = number(self, "length", 0.5, 16.0, false); + let length = number(self, "length", 0.5, 32.0, false); let width = number(self, "width", 0.5, 8.0, false); let gap = number(self, "gap", 0.5, 16.0, false); Some(GripSeed { mark: mark?, count: count?.map(|c| c as u16), length: length?, width: width?, gap: gap? }) diff --git a/crates/theme/src/format/write.rs b/crates/theme/src/format/write.rs index f31bc7f71f..28376b1c43 100644 --- a/crates/theme/src/format/write.rs +++ b/crates/theme/src/format/write.rs @@ -5,7 +5,7 @@ use serde_json::{Map, Number, Value}; use super::{FormatErrors, SCHEMA, SCHEMA_VERSION, ThemeFile}; use crate::scale::Radius; use crate::theme::{AppOverrides, ContrastIntent, EdgeSeed, GripSeed, ModePins, ModeSeeds, Pins, ShapeSeed, ThemeDef, Variants}; -use crate::tokens::{GripMark, KnobShape, WellShape}; +use crate::tokens::{KnobShape, WellShape}; /// Top-level keys in the order a file lists them; other keys follow, sorted. const TOP_ORDER: [&str; 14] = [ @@ -173,7 +173,7 @@ fn update_shape(shape: &mut Map, s: &ShapeSeed) { fn grip(out: &mut Map, g: &GripSeed) { match g.mark { Some(mark) => { - out.insert("mark".to_owned(), Value::String(if mark == GripMark::Ticks { "ticks" } else { "dots" }.to_owned())); + out.insert("mark".to_owned(), Value::String(mark.name().to_owned())); } None => { out.remove("mark"); diff --git a/crates/theme/src/tokens/size.rs b/crates/theme/src/tokens/size.rs index ce32a174a8..9daaee0f88 100644 --- a/crates/theme/src/tokens/size.rs +++ b/crates/theme/src/tokens/size.rs @@ -80,19 +80,33 @@ pub enum GripMark { Ticks, /// Square dots, [`GripShape::width`] on a side. Dots, + /// One level bar, [`GripShape::length`] long and [`GripShape::width`] thick: a tick turned on its side. The count + /// and the gap do not apply. + Bar, +} + +impl GripMark { + /// The mark's name in a theme file and a token dump. + pub fn name(self) -> &'static str { + match self { + GripMark::Ticks => "ticks", + GripMark::Dots => "dots", + GripMark::Bar => "bar", + } + } } /// The row of marks a dock grip shows (the grip above an icon group, under a tool rail's column bar, at a floating /// panel's edge): what the marks are, how many, how large and how far apart, in points. #[derive(Clone, Copy, Debug, PartialEq)] pub struct GripShape { - /// Ticks or dots. + /// Ticks, dots or a bar. pub mark: GripMark, /// How many marks the row has, at every display scale. pub count: u16, - /// How tall a tick is; dots ignore it. + /// How tall a tick is, or how long the bar is; dots ignore it. pub length: f32, - /// How wide a tick is, or a dot's side. + /// How wide a tick is, a dot's side, or how thick the bar is. pub width: f32, /// The space between two marks. pub gap: f32, diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt index 203058f17e..7a10096f47 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt index ef5cc26a98..c3b5559b0c 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt index bbd3c86685..76834950c9 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt index 82eb87700f..1f0db7af85 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt index 675d61735b..8facf78e90 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt index 7e7995f7b6..1e52e2f79d 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt index e3e7042afd..dc816777a1 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt index b964bb193a..b212acf2f9 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt index be7069df77..7451513b5c 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt index c0a17cbc7f..b911c77736 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt index a0e76f1a57..aa422862bc 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt index beac805f45..3465acfd49 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt index f1f2199d9b..7958e66eb0 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt index 1591b94cf8..4fe899cf58 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt index edea9520bd..d873d8be6b 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 3 space.gap.inline = 6 diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt index 4da02566e1..a5aeb65db0 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt @@ -119,10 +119,10 @@ shape.radius.pill = 999 shape.edge = flat shape.knob = round shape.wells = square -shape.grip.mark = ticks +shape.grip.mark = bar shape.grip.count = 11 -shape.grip.length = 5 -shape.grip.width = 1 +shape.grip.length = 18 +shape.grip.width = 3 shape.grip.gap = 1 space.gap.tight = 2 space.gap.inline = 4 diff --git a/crates/theme/themes/vectorcraft-modern-medium.json b/crates/theme/themes/vectorcraft-modern-medium.json index ce7aa47004..2985b90598 100644 --- a/crates/theme/themes/vectorcraft-modern-medium.json +++ b/crates/theme/themes/vectorcraft-modern-medium.json @@ -16,7 +16,13 @@ "warn": "#f0a330" } }, - "shape": null, + "shape": { + "grip": { + "mark": "bar", + "length": 18, + "width": 3 + } + }, "light": { "accent.solid": "#d9472f", "caption.close_hover": "#c42b1c", diff --git a/crates/theme/themes/vectorcraft-modern.json b/crates/theme/themes/vectorcraft-modern.json index 49853128a1..c710606364 100644 --- a/crates/theme/themes/vectorcraft-modern.json +++ b/crates/theme/themes/vectorcraft-modern.json @@ -16,7 +16,13 @@ "warn": "#f0a330" } }, - "shape": null, + "shape": { + "grip": { + "mark": "bar", + "length": 18, + "width": 3 + } + }, "light": { "accent.solid": "#d9472f", "caption.close_hover": "#c42b1c", diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index a5b7abc3c7..20402819b8 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -15,6 +15,7 @@ use crate::contract::{ }; use crate::display::{Shade, Text}; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; +use crate::primitives::PaintShape; use crate::runtime::commands::{self, CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; @@ -42,7 +43,7 @@ pub struct GroupGripStyle { /// The row of marks a dock grip shows, centred on the grip, in the theme's `line.grip` (photocraft#16406: the /// references' 0.83 of the panel was almost invisible on our darker panels). Its shape is the theme's `shape.grip` -/// (photocraft#16426): ticks or dots, how many, how large and how far apart; by default eleven upright ticks, a thin +/// (photocraft#16426): ticks, dots or one level bar, how many, how large and how far apart; by default eleven upright ticks, a thin /// stroke wide, five points tall and a thin stroke apart. The marks keep their ink under the pointer. A toolbar's grip /// under its column bar and the grip above each icon group of a collapsed column paint the same marks. #[derive(Clone, Copy, Debug, PartialEq)] @@ -57,13 +58,9 @@ impl GripMarks { GripMarks { ink: cx.color(cx.tokens.color.line.grip), shape: cx.tokens.shape.grip } } - /// How tall the row is, in points: a tick's length, or a dot's side. + /// How tall the row is, in points. pub(super) fn height(&self) -> f32 { - let GripShape { mark, length, width, .. } = self.shape; - match mark { - GripMark::Ticks => length, - GripMark::Dots => width, - } + marks_height(self.shape) } /// Paints the row in the grip strip `strip`: centred across it, and [`GRIP_ABOVE`] below its middle, so the strip @@ -74,12 +71,25 @@ impl GripMarks { /// Paints the row centred on `centre`. fn paint(&self, ui: &PaintUi<'_>, centre: Pos2) { - let GripShape { count, width, gap, .. } = self.shape; + let GripShape { mark, count, length, width, gap } = self.shape; + if mark == GripMark::Bar { + let bar = Rect::from_center_size(centre, Vec2::new(length, width)); + ui.draw().fill(&PaintShape::Rect(bar, egui::CornerRadius::ZERO), self.ink); + return; + } let look = RuleLook { color: self.ink.egui(), width: RuleWidth::Points(width) }; ui.draw().grip_ticks(&look, centre, count.max(1), gap, self.height()); } } +/// How tall a grip's row of `shape` is, in points: a tick's length, a dot's side, or the bar's thickness. +fn marks_height(shape: GripShape) -> f32 { + match shape.mark { + GripMark::Ticks => shape.length, + GripMark::Dots | GripMark::Bar => shape.width, + } +} + /// The room a grip strip keeps above its marks beyond `space.gap.tight`, in points, in every theme: the marks stand a /// little below the strip's middle, clear of the column bar or icon group above (photocraft#16426). pub(super) const GRIP_ABOVE: f32 = 2.0; @@ -88,8 +98,7 @@ pub(super) const GRIP_ABOVE: f32 = 2.0; /// tall enough that the theme's marks keep `space.gap.tight` below them and that plus [`GRIP_ABOVE`] above them, so /// they never touch the strip's edge (photocraft#16426). pub(crate) fn grip_strip(tokens: &Tokens) -> f32 { - let GripShape { mark, length, width, .. } = tokens.shape.grip; - let marks = if mark == GripMark::Ticks { length } else { width }; + let marks = marks_height(tokens.shape.grip); tokens.size.hit.target.max(marks + 2.0 * tokens.space.gap.tight) + GRIP_ABOVE } diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 1b1f02a339..99eb56e325 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -586,11 +586,9 @@ fn a_groups_grip_is_a_row_of_upright_ticks_in_the_grip_ink() { } } -/// A theme's `shape.grip` reaches the grips (photocraft#16426): six dots, two points on a side and three apart, in the -/// theme's grip ink. -#[trial] -fn a_themes_grip_shape_reaches_the_grips() { - let shape = craft_theme::GripShape { mark: craft_theme::GripMark::Dots, count: 6, length: 5.0, width: 2.0, gap: 3.0 }; +/// The shapes a collapsed column of one group paints under a built-in theme whose `shape.grip` is `shape`, and its +/// group's grip strip. +fn themed_grip(shape: craft_theme::GripShape) -> (Vec, Rect) { let mut def = craft_theme::builtins().first().expect("a built-in theme").clone(); let mut seed = def.shape.unwrap_or(craft_theme::ShapeSeed { radius: None, @@ -604,7 +602,7 @@ fn a_themes_grip_shape_reaches_the_grips() { seed.grip = Some(craft_theme::GripSeed { mark: Some(shape.mark), count: Some(shape.count), - length: None, + length: Some(shape.length), width: Some(shape.width), gap: Some(shape.gap), }); @@ -626,10 +624,38 @@ fn a_themes_grip_shape_reaches_the_grips() { fixture.room(SCREEN).settle(); let id = fixture.root_id().expect("the column shows"); let strip = fixture.part_rect(id, GRIP.at(0)).expect("the group has its grip"); - let shapes = fixture.frame_shapes(); + (fixture.frame_shapes(), strip) +} + +/// A theme's `shape.grip` reaches the grips (photocraft#16426): six dots, two points on a side and three apart, in the +/// theme's grip ink. +#[trial] +fn a_themes_grip_shape_reaches_the_grips() { + let shape = craft_theme::GripShape { mark: craft_theme::GripMark::Dots, count: 6, length: 5.0, width: 2.0, gap: 3.0 }; + let (shapes, strip) = themed_grip(shape); let (marks, ink) = grip_ticks(&shapes, strip).expect("the grip paints its marks"); assert_eq!(marks.len(), 6, "the theme's six dots: {marks:?}"); assert!(marks.iter().all(|m| equals_token(m.width(), shape.width) && equals_token(m.height(), shape.width)), "two-point dots: {marks:?}"); assert!(marks.windows(2).all(|w| equals_token(w[1].min.x - w[0].max.x, shape.gap)), "three points apart: {marks:?}"); assert_ne!(ink, egui::Color32::TRANSPARENT); } + +/// A theme's bar grip (VectorCraft's) is one level bar as long and as thick as the theme says, centred across the +/// strip, with no row of ticks. +#[trial] +fn a_themes_bar_grip_is_one_level_bar() { + let shape = craft_theme::GripShape { mark: craft_theme::GripMark::Bar, count: 11, length: 18.0, width: 3.0, gap: 1.0 }; + let (shapes, strip) = themed_grip(shape); + assert!(grip_ticks(&shapes, strip).is_none(), "no row of ticks"); + let bars: Vec = shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::Rect(rect) if strip.expand(EPS).contains_rect(rect.rect) && rect.fill != egui::Color32::TRANSPARENT => Some(rect.rect), + _ => None, + }) + .collect(); + let [bar] = bars.as_slice() else { panic!("one bar in the strip: {bars:?}") }; + assert!(bar.width() > bar.height(), "the bar lies level: {bar:?}"); + assert!(equals_token(bar.width(), shape.length) && equals_token(bar.height(), shape.width), "the theme's 18 by 3 bar: {bar:?}"); + assert!((bar.center().x - strip.center().x).abs() <= 0.5, "centred across the strip: {bar:?} in {strip:?}"); +} From 5b190db66a7138080f87aaad38b797ce4bc13e8e Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 24 Nov 2026 16:35:25 +0100 Subject: [PATCH 35/35] Lasso cursors: an arrow on the hotspot with the tool icon beside it (photocraft#16671) The Lasso, Polygonal Lasso and Magnetic Lasso showed only their icon, with the icon box's empty top-left corner on the pointer, so the outline started at a blank spot beside the lasso. They now show the solid arrow with its tip on the pointer and the tool's icon below right of it, as the reference application does and as the Paint Bucket and Ruler pointers already do. PaintedCursor::PointerTool gains an optional badge, drawn at the icon's lower right, so the add / subtract / intersect mark stays; pointer_tool_badged builds it. pointer_tool keeps its signature. Tests: the three lassos show the arrow with their icon and the operation's badge (fails on next: the lasso returned PaintedCursor::Tool); a badged arrow pointer keeps ink on its hotspot at 1x, 1.25x and 2x with the badge at the icon's lower right. Co-Authored-By: Claude Opus 5.5 --- crates/behavior/src/cursor.rs | 11 ++++- crates/imaging/src/ui/select/lasso.rs | 12 +++--- crates/imaging/src/ui/select/magnetic.rs | 11 ++--- crates/imaging/tests/it/select.rs | 42 +++++++++++++++++++ .../ui-contract/src/primitives/pointer_art.rs | 23 +++++++--- crates/ui-contract/tests/it/runtime/cursor.rs | 35 ++++++++++++++++ 6 files changed, 113 insertions(+), 21 deletions(-) diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index 3b6a67f783..2d69e7ff7e 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -208,13 +208,15 @@ pub enum PaintedCursor { end: bool, }, /// A pointer with the tool's icon below and right of it: a crosshair (Perspective Crop), or an arrow with its tip - /// on the hotspot (Paint Bucket, Ruler). + /// on the hotspot (Paint Bucket, Ruler, the lassos). #[non_exhaustive] PointerTool { /// The pointer the icon rides beside. pointer: PointerGlyph, /// The icon. icon: IconId, + /// A mark at the icon's lower right. + badge: Option, }, /// No cursor at all. Hidden, @@ -294,7 +296,12 @@ impl PaintedCursor { /// `pointer` with the tool's icon below and right of it. pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self { - PaintedCursor::PointerTool { pointer, icon } + PaintedCursor::PointerTool { pointer, icon, badge: None } + } + + /// `pointer` with the tool's icon below and right of it, and `badge` at the icon's lower right. + pub const fn pointer_tool_badged(pointer: PointerGlyph, icon: IconId, badge: Option) -> Self { + PaintedCursor::PointerTool { pointer, icon, badge } } /// A system cursor with a mark. diff --git a/crates/imaging/src/ui/select/lasso.rs b/crates/imaging/src/ui/select/lasso.rs index 25f9a84617..ec6037b6b0 100644 --- a/crates/imaging/src/ui/select/lasso.rs +++ b/crates/imaging/src/ui/select/lasso.rs @@ -1,19 +1,16 @@ //! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares. use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation}; -use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton}; +use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton, PointerGlyph}; use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; -use egui::{Pos2, Vec2}; +use egui::Pos2; use kurbo::Rect; use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind, moved_selection_snap}; use super::{DragKind, Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectWords, SelectionProbe, SelectionShape}; -/// Where a lasso cursor's icon touches the document: the icon's own origin. -const ICON_HOTSPOT: Vec2 = Vec2::ZERO; - /// The reach of an outline's closing presses in this pass: a press within the slop of the first vertex or of the last /// closes. pub(super) fn reach(cx: &ToolContext<'_>) -> DraftReach { @@ -54,7 +51,8 @@ pub(super) struct LassoCursor<'a> { pub(super) rule: PressRule, } -/// The lasso icon with the operation's badge: the latched one while an outline is open, else the live modifiers'; +/// The arrow with its tip on the point the outline starts from, the lasso icon below and right of it and the +/// operation's badge beside the icon: the latched one while an outline is open, else the live modifiers'; /// Cmd is the Move tool's, so it shows none. Over the selection, the cursors of [`cursor_over`]. pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &ToolContext<'_>) -> Cursor { let LassoCursor { icon, draft, operation, bar, inside, rule } = shown; @@ -71,7 +69,7 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T } else { SelectionOperation::resolve(*bar, cx.mods, probe.has_selection()).badge() }; - PaintedCursor::tool(icon.icon(), ICON_HOTSPOT, badge).into() + PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, icon.icon(), badge).into() } /// The outline as marching ants and, between straight segments, the rubber band: the one painter of an diff --git a/crates/imaging/src/ui/select/magnetic.rs b/crates/imaging/src/ui/select/magnetic.rs index 8528dfa5f3..2f49645543 100644 --- a/crates/imaging/src/ui/select/magnetic.rs +++ b/crates/imaging/src/ui/select/magnetic.rs @@ -1,7 +1,7 @@ //! [`MagneticLassoTool`]: an outline that snaps to the edges the app's [`EdgeTracer`] finds. use craft_behavior::geometry::SelectionOperation; -use craft_behavior::{CancelReason, Cursor, PaintedCursor}; +use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerGlyph}; use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; @@ -12,9 +12,6 @@ use serde::{Deserialize, Serialize}; use super::lasso::{DraftKey, draft_command, outline_access}; use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectionProbe, SelectionShape}; -/// Where the magnetic lasso cursor's icon touches the document: the icon's own origin. -const ICON_HOTSPOT: Vec2 = Vec2::ZERO; - /// The detection settings of one edge query. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -478,8 +475,8 @@ impl CanvasTool for SelectToolPass<'_, MagneticLassoTool> { if self.tool.outline.as_ref().is_some_and(|o| !o.down) { ToolClaims::NONE.keyboard().deletes() } else { ToolClaims::NONE } } - /// The width circle under the canvas's precise cursor (`width * zoom`, at least the slop); otherwise the lasso - /// icon with the operation's badge. + /// The width circle under the canvas's precise cursor (`width * zoom`, at least the slop); otherwise the arrow on + /// the pointer with the lasso icon beside it and the operation's badge. fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { let tool = &*self.tool; if cx.precise() @@ -494,7 +491,7 @@ impl CanvasTool for SelectToolPass<'_, MagneticLassoTool> { None if cx.mods.cmd => None, None => SelectionOperation::resolve(tool.bar, cx.mods, self.probe.has_selection()).badge(), }; - PaintedCursor::tool(ToolIcon::MagneticLasso.icon(), ICON_HOTSPOT, badge).into() + PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, ToolIcon::MagneticLasso.icon(), badge).into() } /// The first click starts an outline; later ones close near the first point, add a straight segment with Alt (and diff --git a/crates/imaging/tests/it/select.rs b/crates/imaging/tests/it/select.rs index dfb6baf0e4..c9ef917fac 100644 --- a/crates/imaging/tests/it/select.rs +++ b/crates/imaging/tests/it/select.rs @@ -951,6 +951,48 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() { } } +/// The cursor `rig` shows over the middle of its canvas with `mods` held. +fn lasso_cursor(rig: &mut Rig, mods: Modifiers) -> Option +where + for<'a> SelectToolPass<'a, T>: CanvasTool, +{ + let ctx = rig.fixture().ctx().clone(); + let over = rig.canvas().center(); + rig.fixture().frame(vec![pointer::moved(over)]); + hold(rig, mods); + rig.fixture().frame(Vec::new()); + craft_ui::runtime::cursor::current(&ctx) +} + +// The lassos show an arrow with its tip where the outline starts and the tool's icon below right of it, as the reference +// application does; the operation's badge rides at the icon's lower right. With the icon alone on the pointer, its +// empty top-left corner was the hotspot, so the outline began beside the icon (photocraft#16671). +#[trial] +fn the_lassos_point_an_arrow_at_where_the_outline_starts() { + use craft_behavior::{Cursor, CursorBadge, PaintedCursor, PointerGlyph}; + use craft_ui::primitives::ToolIcon; + fn check(cursor: Option, icon: ToolIcon, badge: Option, what: &str) { + match cursor { + Some(Cursor::Painted(PaintedCursor::PointerTool { pointer, icon: shown, badge: b, .. })) => { + assert_eq!(pointer, PointerGlyph::Arrow, "{what}: an arrow"); + assert_eq!(shown, icon.icon(), "{what}: the tool's icon"); + assert_eq!(b, badge, "{what}: the badge"); + } + other => panic!("{what}: an arrow with the tool's icon, got {other:?}"), + } + } + let selected = Rect::new(20.0, 20.0, 60.0, 60.0); + let shift = Modifiers::SHIFT; + let mut lasso = rig("Lasso", LassoTool::new(), Fake::selected(selected)); + check(lasso_cursor(&mut lasso, Modifiers::NONE), ToolIcon::Lasso, None, "Lasso"); + check(lasso_cursor(&mut lasso, shift), ToolIcon::Lasso, Some(CursorBadge::Add), "Lasso with Shift"); + let mut polygon = rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::selected(selected)); + check(lasso_cursor(&mut polygon, Modifiers::NONE), ToolIcon::PolygonalLasso, None, "Polygonal Lasso"); + check(lasso_cursor(&mut polygon, Modifiers::ALT), ToolIcon::PolygonalLasso, Some(CursorBadge::Subtract), "Polygonal Lasso with Alt"); + let (mut magnetic, _) = magnetic(); + check(lasso_cursor(&mut magnetic, Modifiers::NONE), ToolIcon::MagneticLasso, None, "Magnetic Lasso"); +} + #[trial] fn width_steps_by_one_and_shift_jumps_to_the_limits() { let mut settings = MagneticSettings::default(); diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index 412666dde8..3c8b40a6cc 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -69,11 +69,11 @@ pub(crate) fn pointer_art(env: &Env, cursor: &PaintedCursor, closed: bool, marks PaintedCursor::Locator => locator(&pen), PaintedCursor::Arrow { hollow, toward, .. } => arrow(&pen, *hollow, *toward), PaintedCursor::PathText { start, end, .. } => path_text(&pen, *start, *end), - PaintedCursor::PointerTool { pointer, icon, .. } => { + PaintedCursor::PointerTool { pointer, icon, badge, .. } => { // The arrow's icon sits under its body, so it takes the larger size to show past the arrow. let side = if *pointer == PointerGlyph::Arrow { env.tokens.size.icon.md } else { env.tokens.size.icon.sm }; let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, Mirror::Auto); - pointer_tool(&pen, *pointer, icon, side, edge, ink); + pointer_tool(&pen, *pointer, icon, *badge, side, edge, ink); } // `Hidden` has no marks. _ => {} @@ -451,14 +451,27 @@ pub(crate) fn path_text(pen: &Pen, start: bool, end: bool) { /// `pointer` with the tool's `icon` of `side` points below and right of it: a crosshair with arms of `side` points in a /// line of `width` in `color`, as the plain crosshair pointer, beside the icon; or the solid arrow, as the plain arrow -/// pointer, over the icon's top-left corner. An icon the catalog lacks leaves only the pointer. -pub(crate) fn pointer_tool(pen: &Pen, pointer: PointerGlyph, icon: Option, side: f32, width: f32, color: Color32) { +/// pointer, over the icon's top-left corner; `badge` at the icon's lower right. An icon the catalog lacks leaves only the +/// pointer and the badge. +pub(crate) fn pointer_tool( + pen: &Pen, + pointer: PointerGlyph, + icon: Option, + badge: Option, + side: f32, + width: f32, + color: Color32, +) { let corner = match pointer { PointerGlyph::Arrow => ARROW_ICON, _ => CROSSHAIR_ICON, }; + let rect = Rect::from_min_size(v(corner).to_pos2(), Vec2::splat(side)); if let Some(icon) = icon { - icon_on_halo(pen, Rect::from_min_size(v(corner).to_pos2(), Vec2::splat(side)), icon); + icon_on_halo(pen, rect, icon); + } + if let Some(badge) = badge { + self::badge(pen, rect.right_bottom().to_vec2(), badge); } match pointer { PointerGlyph::Arrow => arrow(pen, false, None), diff --git a/crates/ui-contract/tests/it/runtime/cursor.rs b/crates/ui-contract/tests/it/runtime/cursor.rs index 92bc3835a4..6787aacba4 100644 --- a/crates/ui-contract/tests/it/runtime/cursor.rs +++ b/crates/ui-contract/tests/it/runtime/cursor.rs @@ -209,6 +209,41 @@ fn a_tool_icon_rides_below_right_of_its_pointer() { } } +/// An arrow with a tool icon keeps ink on its hotspot (the arrow's tip), and a badge lands below right of the icon: the +/// marks reach no farther left or up than without it, and farther right (photocraft#16671). +#[trial] +fn a_badged_tool_pointer_keeps_its_tip_on_the_hotspot_and_the_badge_below_right() { + fn reach(image: &CustomCursorImage) -> [i32; 4] { + let (side, [hx, hy]) = (i32::from(image.size[0]), image.hotspot.map(i32::from)); + let mut reach = [0; 4]; + for (i, px) in image.rgba.chunks(4).enumerate() { + if px[3] > 0 { + let (dx, dy) = (i as i32 % side - hx, i as i32 / side - hy); + reach = [reach[0].max(-dx), reach[1].max(-dy), reach[2].max(dx), reach[3].max(dy)]; + } + } + reach + } + for scale in [1.0, 1.25, 2.0] { + let mut frames = frames(linux(), scale); + let plain = painted(&mut frames, PaintedCursor::pointer_tool(PointerGlyph::Arrow, IconId::new("lasso"))).image.unwrap(); + let [hx, hy] = plain.hotspot.map(i32::from); + assert!(pixel(&plain, hx, hy)[3] > 0, "{scale}: the arrow's tip is on the hotspot"); + for badge in [CursorBadge::Add, CursorBadge::Subtract, CursorBadge::Intersect] { + let badged = PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, IconId::new("lasso"), Some(badge)); + let image = painted(&mut frames, badged).image.unwrap(); + let [hx, hy] = image.hotspot.map(i32::from); + assert!(pixel(&image, hx, hy)[3] > 0, "{scale} {badge:?}: the arrow's tip is on the hotspot"); + let (with, without) = (reach(&image), reach(&plain)); + assert_eq!(with[..2], without[..2], "{scale} {badge:?}: nothing reaches farther left or up"); + // A minus lies on the icon's bottom edge, so only the plus and the cross reach lower. + assert!(with[2] > without[2] && with[3] >= without[3], "{scale} {badge:?}: the badge lies at the icon's lower right"); + } + let none = PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, IconId::new("lasso"), None); + assert_eq!(reach(&painted(&mut frames, none).image.unwrap()), reach(&plain), "{scale}: no badge is the plain pointer"); + } +} + /// An unchanged pointer hands the window the same image, so the integration uploads it to the OS once; a new size or /// scale makes a new one; a frame whose winner is a system cursor, or that asks for nothing, clears it (egui keeps an /// image until it is replaced).