From dfc8ff52169c2eadf957b036da62486c2ee354b4 Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 23 Nov 2026 01:25:51 -0300 Subject: [PATCH 01/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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