From c36394fe4bcc8c3164685006b3bc517a6e26b03e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:35:28 +0000 Subject: [PATCH 1/8] merge-fwd: item 3: the window reads the focused canvas's leftover Escape last (with_window_intents), leave_to_window goes; a full-window dialog closes on Escape from its focused canvas; trial --- crates/ui-canvas/src/canvas/tool_host.rs | 12 +-- .../ui-canvas/tests/it/full_window_parts.rs | 101 +++++++++++++++++- crates/ui-contract/src/runtime/keys.rs | 2 - .../ui-contract/src/runtime/keys/intents.rs | 77 +++++++------ 4 files changed, 141 insertions(+), 51 deletions(-) diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index a0f5bc7a1..dbf34d2a3 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -1272,7 +1272,9 @@ impl<'a, 't: 'a> Run<'a, 't> { /// The keys the canvas holds: intents routed to it while it has focus, the arrows, Enter and Escape while nothing /// in the window has focus, and the chords the tool claimed at the end of the last pass. A session control in the - /// canvas body (`KeyUse::session`) has taken the arrows, Enter and Escape it acts on before this runs. + /// canvas body (`KeyUse::session`) has taken the arrows, Enter and Escape it acts on before this runs. The Escape + /// of the focused canvas reaches the tool once, through the window's intents (`with_window_intents` offers the + /// focused document canvas's Escape); one the tool leaves stays the canvas's, for the scopes around it. fn keys(&mut self, ctx: &Context, canvas: Id, rtl: bool) { keys::with_window_intents(ctx, rtl, |window| { let mut taken = self.offer(window, |intents| intents.take_nudge().map(|(direction, mods)| ToolKey::Nudge { direction, mods })); @@ -1295,9 +1297,6 @@ impl<'a, 't: 'a> Run<'a, 't> { }); } taken |= self.offer(&mut intents, |intents| intents.take(Intent::Submit).then_some(ToolKey::Submit)); - if !self.cancelled { - taken |= self.offer(&mut intents, |intents| intents.take(Intent::Cancel).then_some(ToolKey::Cancel)); - } if taken { keys::settle(ctx, Some(canvas), &intents); } @@ -1322,10 +1321,5 @@ impl<'a, 't: 'a> Run<'a, 't> { self.response.took_key = Some(kept); } } - // An Escape the focused canvas's sessions and tool were offered and left is the window's, as it is with - // nothing focused. - if !self.cancelled { - keys::leave_to_window(ctx, canvas, |intent| *intent == Intent::Cancel); - } } } diff --git a/crates/ui-canvas/tests/it/full_window_parts.rs b/crates/ui-canvas/tests/it/full_window_parts.rs index e805db35a..23edd3399 100644 --- a/crates/ui-canvas/tests/it/full_window_parts.rs +++ b/crates/ui-canvas/tests/it/full_window_parts.rs @@ -1,4 +1,5 @@ -//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom and the mapped overlay. +//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom, Escape on a focused canvas and the +//! mapped overlay. use craft_behavior::PixelSize; use craft_ui::canvas::ViewCommands; @@ -216,6 +217,104 @@ mod momentary { } } +/// Escape on a focused canvas inside a full-window dialog. +mod escape { + use craft_behavior::{CancelReason, Intent, PixelSize}; + use craft_ui::canvas::{CanvasTool, PixelRect, RasterSource, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; + use craft_ui::contract::{Bind, ShowContainer as _}; + use craft_ui::dialog::{FullWindowCanvas, FullWindowDialog, FullWindowView}; + use craft_ui::primitives::{Draw, Revision}; + use craft_ui::runtime::access::Role; + use craft_ui::runtime::focus::Initial; + use craft_ui::runtime::keys; + use craft_ui::testing::input::key_press; + use craft_ui::testing::{Fixture, trial}; + use egui::{Color32, ColorImage, Key, Modifiers}; + use std::cell::{Cell, RefCell}; + use std::rc::Rc; + + struct Grey; + + impl RasterSource for Grey { + fn size(&self) -> PixelSize { + PixelSize::new(800, 600) + } + + fn revision(&self) -> Revision { + Revision::new(1) + } + + fn damage(&self, _: Revision) -> Option { + Some(PixelRect::default()) + } + + fn read(&self, _: PixelRect, _: u32, out: &mut ColorImage) { + out.pixels.fill(Color32::from_rgb(0x80, 0x80, 0x80)); + } + } + + /// A tool that takes its clicks and, when `takes_escape`, the Escape. + struct Picker { + takes_escape: bool, + } + + impl CanvasTool for Picker { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool { + self.takes_escape && *key == ToolKey::Cancel + } + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Edit command") + } + } + + // The RAW Develop form: the canvas a click focused leaves the Escape its tool refuses to the dialog, which closes; + // the window, reading its intents last, sees none. An Escape the tool takes closes nothing. + #[trial] + fn escape_on_a_focused_canvas_in_a_full_window_dialog_closes_the_dialog_and_not_the_window() { + for takes_escape in [false, true] { + let open = Rc::new(Cell::new(true)); + let window_cancels = Rc::new(Cell::new(0)); + let view = Rc::new(RefCell::new(FullWindowView::new())); + let (shown, seen, viewed) = (open.clone(), window_cancels.clone(), view.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut is_open = shown.get(); + let mut tool = Picker { takes_escape }; + let mut view = viewed.borrow_mut(); + FullWindowDialog::new("Workspace").opened(Bind::bound(&mut is_open)).initial_focus(Initial::Keep).show(ui, |ui, _| { + FullWindowCanvas::new(Bind::bound(&mut *view), &Grey).tool(&mut tool).show(ui); + }); + shown.set(is_open); + keys::with_window_intents(ui.ctx(), false, |window| { + let took = window.take(Intent::Cancel); + seen.set(seen.get() + u32::from(took)); + took + }); + }); + fixture.settle(); + let canvas = fixture.by_role(Role::CANVAS).remove(0); + fixture.click(&canvas).settle(); + assert!(open.get(), "a click on the canvas leaves the dialog open"); + window_cancels.set(0); + fixture.frame(vec![key_press(Key::Escape, Modifiers::NONE)]).settle(); + assert_eq!(open.get(), takes_escape, "Escape closes the dialog only when the tool leaves it (tool takes it: {takes_escape})"); + assert_eq!(window_cancels.get(), 0, "the window sees no Escape (tool takes it: {takes_escape})"); + } + } +} + /// An overlay drawn through a frame. mod mapped_overlay { use craft_behavior::PixelSize; diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 68931f9f9..dcd6bacf9 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -32,8 +32,6 @@ pub(crate) use input::{input_hook, queue_nav, take_menu_keys, take_nav}; pub use intents::Intents; #[doc(hidden)] pub use intents::intents_of; -#[doc(hidden)] -pub use intents::leave_to_window; #[cfg(feature = "testing")] pub(crate) use intents::lent_taken; #[doc(hidden)] diff --git a/crates/ui-contract/src/runtime/keys/intents.rs b/crates/ui-contract/src/runtime/keys/intents.rs index 7a2df5c0b..29bd646cc 100644 --- a/crates/ui-contract/src/runtime/keys/intents.rs +++ b/crates/ui-contract/src/runtime/keys/intents.rs @@ -1,6 +1,6 @@ //! The intents routed to a component and what it leaves untaken: Submit, Cancel, Escape and context requests. -use super::current; +use super::{Stage, current}; use super::route::push; use crate::runtime::focus::{self}; use craft_behavior::focus::{EscapeFacts, EscapeStep, escape_step}; @@ -269,44 +269,52 @@ pub fn intents_of(ctx: &Context, id: Option, rtl: bool) -> Intents { /// /// The window's intents are the keys the runtime routes to no component this pass: an Escape (`Intent::Cancel`) /// or a plain Enter (`Intent::Submit`) while no framework stop is focused, and the arrows' nudge; with the document -/// canvas focused, the Escape its sessions and its tool left (`leave_to_window`). A component or a scope that runs -/// earlier in the pass takes them first (an open dialog takes the Escape that closes it, a canvas session the one -/// that ends it), so an app that hosts the runtime reads them last in its UI to see what no component took. `rtl` -/// reads horizontal moves in the window's direction. +/// canvas focused, the Escape the canvas, its sessions, its tool and every scope around it left. A component or a +/// scope that runs earlier in the pass takes them first (an open dialog takes the Escape that closes it, a canvas +/// session the one that ends it), so an app that hosts the runtime reads them last in its UI to see what no +/// component took. `rtl` reads horizontal moves in the window's direction. pub fn with_window_intents(ctx: &Context, rtl: bool, take: impl FnOnce(&mut Intents) -> bool) -> bool { - if focus::focused_rec(ctx).is_some_and(|rec| !rec.stop.keys.chrome_key) { - return false; - } + let canvas = match focus::focused_rec(ctx) { + Some(rec) if !rec.stop.keys.chrome_key => return false, + Some(rec) => Some(rec.stop.id), + None => None, + }; let mut window = intents_of(ctx, None, rtl); + // The focused canvas's leftover Escape is offered as the window's; it stays in the canvas's slot until taken. + let lent_cancel = canvas + .filter(|canvas| !window.items.iter().any(|(item, _)| *item == Intent::Cancel) && holds(ctx, Some(*canvas), &Intent::Cancel)) + .map(|canvas| { + window.items.push((Intent::Cancel, false)); + (canvas, window.items.len() - 1) + }); let taken = take(&mut window); + if let Some((canvas, at)) = lent_cancel { + let (_, cancel_taken) = window.items.remove(at); + if cancel_taken && !crate::runtime::measure::active(ctx) { + current(ctx, |stage| take_from(stage, Some(canvas), &Intent::Cancel)); + } + } if taken { settle(ctx, None, &window); } taken } -/// Moves the intents `which` picks that the focused document canvas `from` left untaken this pass to the window's, -/// where `with_window_intents` reads them. The canvas's tool host calls it once the canvas's session members and its -/// tool had their chance. Nothing moves while `from` is not the focused stop. -#[doc(hidden)] -pub fn leave_to_window(ctx: &Context, from: Id, which: impl Fn(&Intent) -> bool) { - if crate::runtime::measure::active(ctx) || !focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == from && rec.stop.keys.chrome_key) { - return; - } - current(ctx, |stage| { - let Some(routed) = stage.routed.get_mut(&Some(from)) else { return }; - let mut left = Vec::new(); - routed.items.retain(|item| { - let moves = which(&item.intent); - if moves { - left.push(item.clone()); - } - !moves - }); - if !left.is_empty() { - stage.routed.entry(None).or_default().items.extend(left); +/// Whether an intent of the kind of `intent` is routed to `id` and not taken this pass. +fn holds(ctx: &Context, id: Option, intent: &Intent) -> bool { + current(ctx, |stage| stage.routed.get(&id).is_some_and(|routed| routed.items.iter().any(|item| item.intent.same_kind(intent)))) +} + +/// Removes one intent of the kind of `intent` routed to `id`; whether there was one. +fn take_from(stage: &mut Stage, id: Option, intent: &Intent) -> bool { + let Some(routed) = stage.routed.get_mut(&id) else { return false }; + match routed.items.iter().position(|item| item.intent.same_kind(intent)) { + Some(at) => { + routed.items.remove(at); + true } - }); + None => false, + } } /// The keys an arena's session control borrowed this pass (`KeyUse::session`), with the ids they were routed to. @@ -440,16 +448,7 @@ fn take_untaken(ctx: &Context, intent: &Intent) -> bool { if crate::runtime::measure::active(ctx) { return false; } - current(ctx, |stage| { - let Some(routed) = stage.routed.get_mut(&focused) else { return false }; - match routed.items.iter().position(|item| item.intent.same_kind(intent)) { - Some(at) => { - routed.items.remove(at); - true - } - None => false, - } - }) + current(ctx, |stage| take_from(stage, focused, intent)) } /// What an untaken Escape does in a scope: `None` when no Escape arrived or a component took it. One scope From a809ccadc6f652906d8c8722a83299458e27e891 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:37:57 +0000 Subject: [PATCH 2/8] merge-fwd: item 1: FW3: windows::mount_window decides a viewport mount's own window (not from a full-screen or Wayland-maximized opener) at all six sites; trials --- .../ui-canvas/tests/it/full_window_parts.rs | 50 +++++++++++- crates/ui-contract/src/contract/body/hooks.rs | 10 +-- .../src/contract/body/placement.rs | 2 +- .../ui-contract/src/contract/body/window.rs | 2 +- crates/ui-contract/src/contract/mount.rs | 4 +- .../ui-contract/src/runtime/egui/viewports.rs | 5 ++ crates/ui-contract/src/runtime/windows.rs | 24 +++++- .../src/runtime/windows/viewport.rs | 2 +- .../ui-contract/tests/it/runtime/windows.rs | 77 ++++++++++++++++++- 9 files changed, 160 insertions(+), 16 deletions(-) diff --git a/crates/ui-canvas/tests/it/full_window_parts.rs b/crates/ui-canvas/tests/it/full_window_parts.rs index 23edd3399..91b6b16f8 100644 --- a/crates/ui-canvas/tests/it/full_window_parts.rs +++ b/crates/ui-canvas/tests/it/full_window_parts.rs @@ -1,5 +1,5 @@ -//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom, Escape on a focused canvas and the -//! mapped overlay. +//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom, Escape on a focused canvas, the +//! close of the dialog's own window and the mapped overlay. use craft_behavior::PixelSize; use craft_ui::canvas::ViewCommands; @@ -315,6 +315,52 @@ mod escape { } } +/// A full-window dialog in a window of its own. +mod own_window { + use craft_ui::contract::{Bind, ShowContainer as _}; + use craft_ui::dialog::{DialogResult, FullWindowDialog}; + use craft_ui::runtime::overlay::CloseReason; + use craft_ui::runtime::windows::WindowSpec; + use craft_ui::testing::trial; + use craft_ui_test_kit::windows::Windows; + use egui::{ViewportEvent, ViewportInfo}; + use std::cell::Cell; + + // The OS closing the dialog's window (its close button, a window manager's close) is a cancel: the dialog reports + // `Requested`, which every host but OK reads as Cancel, so an outer gesture over its edits is taken back. + #[trial] + fn closing_a_full_window_dialogs_own_window_cancels_it() { + let windows = Windows::new(); + let open = Cell::new(true); + let closed = Cell::new(None); + let frame = || { + windows.frame(vec![], vec![], |ui| { + let mut is_open = open.get(); + let output = FullWindowDialog::new("Workspace") + .own_window(WindowSpec::dialog()) + .outer_gesture(true) + .opened(Bind::bound(&mut is_open)) + .show(ui, |_, _| {}) + .output; + open.set(is_open); + if let Some(reason) = output.closed { + closed.set(Some((reason, matches!(output.result(|| ()), Some(DialogResult::Cancel))))); + } + }) + }; + for _ in 0..4 { + frame(); + } + assert!(open.get(), "the dialog opened in its own window"); + windows.child_info(ViewportInfo { events: vec![ViewportEvent::Close], ..ViewportInfo::default() }); + for _ in 0..2 { + frame(); + } + assert!(!open.get(), "closing the dialog's window closes the dialog"); + assert_eq!(closed.get(), Some((CloseReason::Requested, true)), "the close is a cancel"); + } +} + /// An overlay drawn through a frame. mod mapped_overlay { use craft_behavior::PixelSize; diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index cd22a330e..6ea4318ea 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -24,14 +24,14 @@ use crate::primitives::SurfaceSlot; use crate::runtime::access::scope; use crate::runtime::access::{self, Politeness, Role}; use crate::runtime::commands; -use crate::runtime::egui::{alloc, areas, child, repaint, response, style, viewports}; +use crate::runtime::egui::{alloc, areas, child, repaint, response, style}; use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, RowLine}; use crate::runtime::focus::FocusPolicy; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::motion::{Driver, Presence, spec}; use crate::runtime::overlay::CloseReason; use crate::runtime::pass_state; -use crate::runtime::{keys, layout_memory, pointer, wheel}; +use crate::runtime::{keys, layout_memory, pointer, wheel, windows}; use crate::style::ComponentStyle as _; use crate::style::{ScrollBarKind, StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_style}; use craft_behavior::layout_memory::measure_tolerance; @@ -169,7 +169,7 @@ impl ShapeHooks for BodyHooks<'_> { // A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body // never sizes as a layer's content. Mount::Viewport { fallback, .. } if fallback.is_full_window() => true, - Mount::Viewport { .. } if viewports::available(&ctx) => true, + Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true, Mount::Layer(_) | Mount::Viewport { .. } => { let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); @@ -617,7 +617,7 @@ impl ShapeHooks for BodyHooks<'_> { let props = comp.props(Internal::new()); let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. })); // The OS asked a viewport mount's window to close: the container closes at step 15. - if matches!(props.mount, Mount::Viewport { .. }) && crate::runtime::windows::take_close_request(cx.core.memory.ctx(), cx.core.id) { + if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(cx.core.memory.ctx(), cx.core.id) { self.close = true; self.reason = self.reason.or(Some(CloseReason::Requested)); } @@ -654,7 +654,7 @@ impl ShapeHooks for BodyHooks<'_> { self.window_movable(viewport, cx); } self.pane_drag(props, cx); - if layer && !(matches!(props.mount, Mount::Viewport { .. }) && viewports::available(cx.core.memory.ctx())) { + if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(cx.core.memory.ctx(), cx.core.id)) { self.window_keys(props, cx); self.window_drag(props, cx); } diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index c2d28528f..7cecd02c2 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -139,7 +139,7 @@ pub(super) fn overlay_of(props: &ContainerProps) -> Option<&crate::contract::Ove pub(super) fn measure_layer(props: &ContainerProps, id: Id, ui: &Ui) -> areas::Layer { let area = sub(id, "area"); match &props.mount { - Mount::Viewport { .. } if windows::WindowHost::of(ui.ctx()).viewports_available() => ui.layer_id(), + Mount::Viewport { .. } if windows::mount_window(ui.ctx(), id) => ui.layer_id(), Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => { areas::layer_of(crate::runtime::overlay::layer_tier(ui.ctx(), overlay.rank), area) } diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 1de4c4a56..f06a06628 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -63,7 +63,7 @@ fn answered_by_platform(ctx: &Context, viewport: ViewportId) -> bool { pub(super) fn os_window(props: &ContainerProps, ctx: &Context, id: Id, env: &EnvView<'_>) -> Option { let embedded = env.get::().0.is_some_and(|shell| shell.region().is_some()); match &props.mount { - Mount::Viewport { .. } if viewports::available(ctx) => Some(viewports::viewport_id(id)), + Mount::Viewport { .. } if windows::mount_window(ctx, id) => Some(viewports::viewport_id(id)), Mount::Window { .. } | Mount::Pane(_) | Mount::Inline if !embedded => Some(pass::current_viewport(ctx)), Mount::Window { .. } | Mount::Pane(_) | Mount::Inline | Mount::Viewport { .. } | Mount::Layer(_) | Mount::FullWindow => None, } diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index d0f4fd06c..46343dc73 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -14,7 +14,7 @@ use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, SaveKey, sub}; use crate::runtime::motion::{self, Presence}; use crate::runtime::overlay::CloseReason; -use crate::runtime::windows::{self, ViewportOpen, WindowHost, WindowSpec}; +use crate::runtime::windows::{self, ViewportOpen, WindowSpec}; use craft_behavior::ScopeKind; use egui::{Id, Pos2, Rect, Ui, Vec2}; @@ -51,7 +51,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & }, Mount::FullWindow => full_window(props.focus), Mount::Viewport { fallback, spec } => { - let viewports = WindowHost::of(ctx).viewports_available(); + let viewports = windows::mount_window(ctx, at.id); // A full-window container without OS windows covers the main window, as `Mount::FullWindow` does. if !viewports && fallback.is_full_window() { full_window(fallback.focus) diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 41d68235f..bd009c5d0 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -8,6 +8,11 @@ pub(crate) fn available(ctx: &Context) -> bool { !ctx.embed_viewports() } +/// The viewport the running viewport was opened from; the root for the root. +pub(crate) fn parent(ctx: &Context) -> ViewportId { + ctx.parent_viewport_id() +} + /// How a viewport opens. pub(crate) struct Spec<'a> { /// The window title. diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index 6dfe04035..f3ec67e21 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -10,7 +10,7 @@ use crate::runtime::frame::PerViewport; use crate::runtime::overlay; use crate::runtime::pass_state; use craft_behavior::{Cursor, CursorIcon, CursorPriority}; -use craft_host::target::{Caps, EdgeInsets, Os, ShellInfo, WindowChrome, WindowKind}; +use craft_host::target::{Backend, Caps, EdgeInsets, Os, ShellInfo, WindowChrome, WindowKind, WindowState}; use craft_window::desktop::Desktop; use craft_window::native::NativeWindow; use craft_window::policy::{Captions, Decision, Frame, LayoutWatch}; @@ -301,6 +301,28 @@ pub(crate) fn blocking_modal(ctx: &Context) -> Option { overlay::modal_viewport(ctx, pass::current_viewport(ctx)) } +/// Whether container `id`'s viewport mount shows in an OS window of its own this pass: OS viewports are available, +/// and the window it opens from is neither full screen nor, on Wayland, maximized. A window opened over such a +/// window covers it; the compositor then sends the covered window no frames, and the immediate viewport, drawn inside +/// them, freezes. Otherwise the mount shows its fallback layer in the opener. +/// +/// It reads only this pass's facts, so the mount, the body (which runs inside the child's pass) and the window steps +/// agree within a pass. +pub(crate) fn mount_window(ctx: &Context, id: Id) -> bool { + if !WindowHost::of(ctx).viewports_available() { + return false; + } + let current = pass::current_viewport(ctx); + let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current }; + let shell = shell_of(ctx, opener); + let covers = match shell.window.state { + WindowState::Fullscreen => true, + WindowState::Maximized => shell.backend == Backend::Wayland, + _ => false, + }; + !covers +} + /// Refuses the close request of the running viewport while an app-modal layer blocks it, and raises the modal's /// window. True when it refused. fn refuse_close_under_modal(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index 942558bb0..55af6c762 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -128,7 +128,7 @@ pub(crate) fn take_close_request(ctx: &Context, id: Id) -> bool { /// Whether container `id` shows in an OS window that has not reported its place yet: its body lays out in room the OS /// has not given, so what it takes there is no size of its content. pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool { - super::WindowHost::of(ctx).viewports_available() + super::mount_window(ctx, id) && PerViewport::::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none()) } diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 543c348ce..edede7a73 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1,7 +1,7 @@ //! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS -//! resize (H4), the raise of a modal's window, the mount of a full-window container, the size of a content-sized -//! window, the app id of child windows, injected keys across a focus loss, non-finite injected points, the window -//! that has the keys, and `act`. +//! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a +//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, +//! injected keys across a focus loss, non-finite injected points, the window that has the keys, and `act`. use craft_behavior::{Cursor, CursorIcon, PointerButton}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -141,6 +141,24 @@ fn a_blocking_modal_is_raised_when_the_main_window_gains_focus() { windows.root_info(focus(true)); assert!(raised_child(&modal_frame(&windows)), "the main window gained focus: the modal's window is raised"); assert!(!raised_child(&modal_frame(&windows)), "the main window keeps focus: nothing more is raised"); + + // A full-window dialog in a window of its own (the Camera Raw form) is raised the same way. + let windows = Windows::new(); + let frame = || { + windows.frame(vec![], vec![], |ui| { + Palette::full_window("Workspace").show(ui, |_, _| {}); + }) + }; + windows.root_info(focus(false)); + let mut out = None; + for _ in 0..4 { + out = Some(frame()); + } + let (dialog, _) = builder_titled(&out.expect("the frames ran"), "Workspace"); + let raised = |out: &Out| out.commands.iter().any(|(id, command)| *id == dialog && *command == ViewportCommand::Minimized(false)); + assert!(!raised(&frame()), "the main window stays unfocused: the dialog's window is not raised"); + windows.root_info(focus(true)); + assert!(raised(&frame()), "the main window gained focus: the dialog's window is raised"); } /// A container mounted in an OS viewport that opens as `spec`, with a body the trial gives it. @@ -264,6 +282,59 @@ fn a_full_window_viewport_fills_the_main_window_without_viewports_and_opens_its_ assert_eq!(shown.and_then(|key| tree.bounds_of(key)), Some(content.get()), "the workspace covers the main window"); } +/// FW3: a viewport mount opened from a full-screen window, or from a maximized one on Wayland, shows in that window +/// instead of a window of its own: a window opened over it would cover it, the compositor would send it no frames, and +/// the dialog drawn inside them would freeze. A main window that goes full screen under an open dialog takes the dialog +/// in, and the dialog stays open. +#[trial] +fn a_viewport_mount_stays_in_a_full_screen_or_wayland_maximized_window() { + let state = |fullscreen: bool, maximized: bool| ViewportInfo { fullscreen: Some(fullscreen), maximized: Some(maximized), ..ViewportInfo::default() }; + let frame = |windows: &Windows| { + windows.frame(vec![], vec![], |ui| { + Palette::full_window("Workspace").show(ui, |_, _| {}); + }) + }; + let own_window = |out: &Out| out.builders.iter().any(|(_, builder)| builder.title.as_deref() == Some("Workspace")); + let in_root = |out: &Out| { + out.trees.iter().rfind(|(id, _)| *id == ViewportId::ROOT).is_some_and(|(_, tree)| { + tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::GROUP) && tree.name_of(key) == Some("Workspace")) + }) + }; + let cases = [ + (Backend::X11, false, false, true), + (Backend::X11, true, false, false), + (Backend::X11, false, true, true), + (Backend::Wayland, false, false, true), + (Backend::Wayland, true, false, false), + (Backend::Wayland, false, true, false), + ]; + for (backend, fullscreen, maximized, own) in cases { + let windows = Windows::with(InstallSpec::new(ShellInfo::default().backend(backend), Arc::new(FakeSystem::new()))); + windows.root_info(state(fullscreen, maximized)); + let mut out = None; + for _ in 0..4 { + out = Some(frame(&windows)); + } + let out = out.expect("the frames ran"); + let case = format!("{backend:?}, full screen {fullscreen}, maximized {maximized}"); + assert_eq!(own_window(&out), own, "{case}: a window of its own"); + assert_eq!(in_root(&out), !own, "{case}: shown in the main window"); + } + + let windows = Windows::with(InstallSpec::new(ShellInfo::default().backend(Backend::X11), Arc::new(FakeSystem::new()))); + for _ in 0..4 { + frame(&windows); + } + assert!(own_window(&frame(&windows)), "a normal main window: the dialog opens its own window"); + windows.root_info(state(true, false)); + let mut out = None; + for _ in 0..4 { + out = Some(frame(&windows)); + } + let out = out.expect("the frames ran"); + assert!(!own_window(&out) && in_root(&out), "the main window went full screen: the dialog shows in it and is still open"); +} + /// A window sized by its content sends no size before it has reported its place, so it never opens at what its body /// took in room the OS has not given; once it has reported, it takes its content's size. #[trial] From 014ead170fee7b45b92fe883e7f21567b11122cc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:40:51 +0000 Subject: [PATCH 3/8] merge-fwd: item 4: FW9: ui-contract and ui-shell parse and draw icons through craft-svg (features tree-core, tree, draw, tree-render; Limits.allow_dtd); resvg 0.45 goes; trials --- crates/craft/Cargo.toml | 2 ++ crates/svg/Cargo.toml | 16 ++++++---- crates/svg/src/lib.rs | 2 +- crates/svg/src/preflight.rs | 12 +++++++- crates/svg/src/tree.rs | 22 ++++++++++++-- crates/svg/src/tree/draw.rs | 8 ++--- crates/ui-contract/Cargo.toml | 4 +-- .../src/primitives/pointer_art/art.rs | 2 +- crates/ui-contract/src/primitives/svg_set.rs | 9 +++--- crates/ui-contract/src/primitives/svg_tree.rs | 30 ++++++++++++++----- crates/ui-shell/Cargo.toml | 2 +- crates/ui-shell/src/shell/caption_icons.rs | 9 ++++-- .../ui-shell/tests/it/shell/caption_button.rs | 9 ++++++ 13 files changed, 95 insertions(+), 32 deletions(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index d72241234..e454b6873 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -611,7 +611,9 @@ stencilcraft-format = ["dep:craft-stencilcraft-format"] stream-codecs = ["dep:craft-stream-codecs"] svg = ["dep:craft-svg"] +svg-draw = ["svg", "craft-svg/draw"] svg-tree = ["svg", "craft-svg/tree"] +svg-tree-core = ["svg", "craft-svg/tree-core"] svg-tree-render = ["svg", "craft-svg/tree-render"] svg-tree-render-system-fonts = ["svg", "craft-svg/tree-render-system-fonts"] svg-tree-system-fonts = ["svg", "craft-svg/tree-system-fonts"] diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 7516ddab2..a1d1e3437 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -26,17 +26,23 @@ vectorcraft-pathops = { workspace = true } usvg = { version = "=0.48.1", default-features = false, optional = true } # Rendering the parsed tree uses the matching renderer version. Keep it behind an opt-in feature # so callers that only need bounded SVG text/tree parsing do not pull in raster backends. -resvg = { version = "=0.48.1", default-features = false, features = ["text", "raster-images"], optional = true } +resvg = { version = "=0.48.1", default-features = false, optional = true } data-url = { version = "0.3.2", optional = true } [features] -# `craft_svg::tree`: usvg behind the bounded entry point. -tree = ["dep:usvg", "dep:data-url", "dep:craft-image-codecs"] +# `craft_svg::tree` without images: usvg behind the bounded entry point, the preflight, the +# limits and the draw check. For a caller that parses SVG it trusts no `` in (UI icons). +tree-core = ["dep:usvg"] +# `craft_svg::tree`: usvg behind the bounded entry point, with the data-URL image resolver. +tree = ["tree-core", "dep:data-url", "dep:craft-image-codecs"] # Text converted to paths (needs a font database in the options). tree-text = ["tree", "usvg/text"] # The system's fonts in `usvg::fontdb`. tree-system-fonts = ["tree-text", "usvg/system-fonts"] -# Bounded rendering of a parsed tree through the matching resvg/tiny-skia versions. -tree-render = ["tree", "dep:resvg"] +# Bounded drawing of a parsed tree through the matching resvg/tiny-skia versions, without text or +# raster images (`tree::draw::render`, `render_node`, the `resvg` and `tiny_skia` re-exports). +draw = ["tree-core", "dep:resvg"] +# Bounded rendering of a parsed tree with its text and raster images. +tree-render = ["tree", "draw", "resvg/text", "resvg/raster-images"] tree-render-system-fonts = ["tree-render", "resvg/system-fonts"] diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 5c70e8c60..1acdb7a9a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -26,6 +26,6 @@ pub mod paths; pub mod preflight; pub mod sniff; pub mod svgz; -#[cfg(feature = "tree")] +#[cfg(feature = "tree-core")] pub mod tree; pub mod write; diff --git a/crates/svg/src/preflight.rs b/crates/svg/src/preflight.rs index 0c2d3a7b1..8f5ed6dcf 100644 --- a/crates/svg/src/preflight.rs +++ b/crates/svg/src/preflight.rs @@ -23,6 +23,8 @@ pub struct Limits { pub attribute_work: usize, /// Maximum XML nodes after entity expansion. pub xml_nodes: u32, + /// Accept a document type declaration; `false` refuses any `(svg: &'a str, limits: &Limits) -> Result<(roxml if prescan.too_deep { return Err(Error::TooDeep(limits.depth)); } - let options = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: limits.xml_nodes, ..Default::default() }; + let options = roxmltree::ParsingOptions { allow_dtd: limits.allow_dtd, nodes_limit: limits.xml_nodes, ..Default::default() }; let xml = roxmltree::Document::parse_with_options(svg, options).map_err(|e| Error::Xml(e.to_string()))?; Ok((xml, prescan.depth, prescan.open_depth)) } @@ -123,4 +126,11 @@ mod tests { let normal = Limits::default(); assert!(matches!(parse_text_with_depth("", &normal), Err(Error::Xml(_)))); } + + #[test] + fn a_document_type_is_refused_only_when_the_limits_say_so() { + let svg = r#"]>&a;"#; + assert!(parse_text(svg, &Limits::default()).is_ok()); + assert!(matches!(parse_text(svg, &Limits { allow_dtd: false, ..Default::default() }), Err(Error::Xml(_)))); + } } diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 9cf85c3bd..613e298ff 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -22,9 +22,13 @@ //! 16 MB or so, and a 1 MB stack takes a depth of about 34. use std::borrow::Cow; +use std::collections::HashMap; +#[cfg(feature = "tree")] +use std::collections::HashSet; use std::collections::hash_map::Entry; -use std::collections::{HashMap, HashSet}; +#[cfg(feature = "tree")] use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +#[cfg(feature = "tree")] use std::sync::{Arc, Mutex, PoisonError}; pub use usvg; @@ -58,6 +62,8 @@ pub struct Limits { pub attribute_work: usize, /// Nodes the XML may hold once entities are expanded. pub xml_nodes: u32, + /// Accept a document type declaration; `false` refuses any `` data URLs, unpacked, for /// [`image_resolver`]. pub embedded_bytes: usize, @@ -80,6 +86,7 @@ impl Default for Limits { attributes: guard::MAX_ATTRIBUTES, attribute_work: guard::MAX_ATTRIBUTE_WORK, xml_nodes: 4_000_000, + allow_dtd: true, embedded_bytes: 32 << 20, embedded_depth: 4, embedded_raster_pixels: 24_000_000, @@ -189,6 +196,7 @@ pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result, Err attributes: limits.attributes, attribute_work: limits.attribute_work, xml_nodes: limits.xml_nodes, + allow_dtd: limits.allow_dtd, }; let (xml, _, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e { crate::preflight::Error::Text(e) => Error::Text(e), @@ -375,6 +383,7 @@ pub fn height(xml: &roxmltree::Document<'_>, most: usize) -> Result, } +#[cfg(feature = "tree")] impl ImageResolver { /// Create one resolver budget for one drawing import. pub fn new(limits: Limits) -> Self { @@ -483,6 +495,7 @@ impl ImageResolver { } } +#[cfg(feature = "tree")] // usvg's data-URL decoder returns before resolve_data for invalid base64. Count // these omissions separately, including feImage, without reading linked resources. fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) { @@ -504,6 +517,7 @@ fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) { } } +#[cfg(feature = "tree")] fn raster_format(data: &[u8]) -> Option { match craft_image_codecs::detect(data)? { format @ (craft_image_codecs::Format::Png @@ -514,6 +528,7 @@ fn raster_format(data: &[u8]) -> Option { } } +#[cfg(feature = "tree")] fn raster_image(used: &Used, limits: &Limits, data: Arc>, format: craft_image_codecs::Format) -> Option { let Ok((width, height)) = craft_image_codecs::probe_allocation_size(&data) else { used.invalid_raster.fetch_add(1, Ordering::Relaxed); @@ -576,6 +591,7 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc>, format: craft_ }) } +#[cfg(feature = "tree")] /// An embedded SVG document, if the budgets allow it. fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option { if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth { @@ -650,6 +666,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' } } +#[cfg(feature = "tree")] /// An image resolver for `usvg::Options::image_href_resolver` that reads `` data URLs /// only: raster images as they are (PNG, JPEG, GIF, WebP), SVG documents (SVGZ too) through the /// same checks as [`parse`] and within [`Limits::embedded_bytes`] in all and @@ -659,6 +676,7 @@ pub fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> { ImageResolver::new(limits).resolver() } +#[cfg(feature = "tree")] fn image_resolver_for(limits: Limits, used: Arc) -> usvg::ImageHrefResolver<'static> { usvg::ImageHrefResolver { resolve_data: Box::new(move |mime, data, options| { @@ -690,5 +708,5 @@ fn image_resolver_for(limits: Limits, used: Arc) -> usvg::ImageHrefResolve } } -#[cfg(test)] +#[cfg(all(test, feature = "tree"))] mod tests; diff --git a/crates/svg/src/tree/draw.rs b/crates/svg/src/tree/draw.rs index f83653284..cf9d42e14 100644 --- a/crates/svg/src/tree/draw.rs +++ b/crates/svg/src/tree/draw.rs @@ -24,9 +24,9 @@ use std::collections::HashMap; use usvg::Transform; -#[cfg(feature = "tree-render")] +#[cfg(feature = "draw")] pub use resvg; -#[cfg(feature = "tree-render")] +#[cfg(feature = "draw")] pub use resvg::tiny_skia; /// Filter primitives per filter. A result of every primitive is kept; real filters have 1 to 12 @@ -165,7 +165,7 @@ pub fn check(nodes: &[usvg::Node], ts: Transform, width: u32, height: u32, held: /// Draws a complete tree onto a transparent pixmap after checking the peak RGBA allocation. /// `held` is caller-owned RGBA storage that remains live during the draw; the target itself is /// charged by this function. -#[cfg(feature = "tree-render")] +#[cfg(feature = "draw")] pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u64, budget: u64) -> Result { check_filter_cost(tree, ts, 2_000_000_000, 10_000_000, 200)?; // Even an empty tree allocates the target. `check` only walks buffers added by nodes, so @@ -186,7 +186,7 @@ pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u /// Draws one node onto `target` after checking the peak RGBA allocation. The node remains in its /// parent's coordinate space, matching `resvg::render_node`. -#[cfg(feature = "tree-render")] +#[cfg(feature = "draw")] pub fn render_node(node: &usvg::Node, ts: Transform, target: &mut tiny_skia::Pixmap, held: u64, budget: u64) -> Result { check(std::slice::from_ref(node), ts, target.width(), target.height(), held, budget)?; Ok(resvg::render_node(node, ts, &mut target.as_mut()).is_some()) diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 7dab97453..112697346 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -62,8 +62,8 @@ craft-fonts-build = { workspace = true } # Only `color_fonts` reads it: the feature turns on epaint's colour glyphs. epaint = { version = "0.37", default-features = false, optional = true } -# Icon rasterising; the version egui_extras's `svg` feature uses, so apps build one copy. -resvg = { version = "0.45.1", default-features = false } +# Icon parsing and rasterising: the bounded usvg/resvg stack every Craft app shares, without text or raster images. +craft-svg = { workspace = true, features = ["draw"] } # `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics. web-time = "1.1" diff --git a/crates/ui-contract/src/primitives/pointer_art/art.rs b/crates/ui-contract/src/primitives/pointer_art/art.rs index b6768b4db..8d887aeed 100644 --- a/crates/ui-contract/src/primitives/pointer_art/art.rs +++ b/crates/ui-contract/src/primitives/pointer_art/art.rs @@ -4,7 +4,7 @@ use crate::primitives::SvgIcon; use crate::runtime::cursor::{CursorArt, CursorBitmap}; use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, Vec2}; -use resvg::tiny_skia; +use craft_svg::tree::draw::tiny_skia; use std::sync::Arc; /// How far past a mark's geometry its antialiasing reaches, in device pixels. diff --git a/crates/ui-contract/src/primitives/svg_set.rs b/crates/ui-contract/src/primitives/svg_set.rs index 58422549e..f6e30379b 100644 --- a/crates/ui-contract/src/primitives/svg_set.rs +++ b/crates/ui-contract/src/primitives/svg_set.rs @@ -1,7 +1,7 @@ //! The SVG icon catalog the build embeds, the app icon sets registered beside it, and their rasteriser. use egui::{Color32, ColorImage}; -use resvg::tiny_skia; +use craft_svg::tree::draw::{self as svg_draw, tiny_skia}; use std::sync::{PoisonError, RwLock}; use super::svg_tree; @@ -151,14 +151,15 @@ fn draw(svg: &[u8], own: Option, px: u32, stroke_px: f32, mirrored: bool) - let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?; tree = svg_tree::parse(scale_stroke_widths(text, units / own).as_bytes())?; } - let mut pixmap = tiny_skia::Pixmap::new(px, px).ok_or("zero size")?; let (sx, sy) = (px as f32 / view.width(), px as f32 / view.height()); let transform = if mirrored { tiny_skia::Transform::from_row(-sx, 0.0, 0.0, sy, px as f32, 0.0) } else { tiny_skia::Transform::from_scale(sx, sy) }; - resvg::render(&tree, transform, &mut pixmap.as_mut()); - Ok(pixmap) + svg_draw::render(&tree, transform, px, px, 0, ICON_DRAW_BUDGET).map_err(|refusal| refusal.message) } +/// Bytes drawing one icon may allocate, its target included. +const ICON_DRAW_BUDGET: u64 = 64 << 20; + /// `svg` with each `stroke-width="..."` attribute multiplied by `factor`. fn scale_stroke_widths(svg: &str, factor: f32) -> String { const ATTR: &str = "stroke-width=\""; diff --git a/crates/ui-contract/src/primitives/svg_tree.rs b/crates/ui-contract/src/primitives/svg_tree.rs index 52671fb2d..aaafe6da8 100644 --- a/crates/ui-contract/src/primitives/svg_tree.rs +++ b/crates/ui-contract/src/primitives/svg_tree.rs @@ -1,14 +1,31 @@ -//! The one SVG parser. Icon files come from the build and from icon themes on the user's disk, so parsing is bounded: -//! no gzip (its size is unlimited), no DTD (entity expansion), a node limit, and no `` loaded, which keeps a -//! document from making the renderer read another file or nest an SVG. +//! The one SVG parser, craft-svg's bounded entry point. Icon files come from the build and from icon themes on the +//! user's disk, so parsing is bounded: no gzip, no DTD (entity expansion), a node limit, a nesting limit, and no +//! `` loaded, which keeps a document from making the renderer read another file or nest an SVG. -use resvg::usvg; +use craft_svg::tree::{self, Limits, usvg}; /// Elements and text nodes an icon SVG may have; a glyph has a handful. const MAX_NODES: u32 = 10_000; /// The first bytes of a gzip stream. const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b]; +/// What an icon may use. Icons parse on the UI thread, whose stack may be 1 MB (Windows' main thread): craft-svg +/// gives about 34 levels for that, so nesting stops at 32. +fn icon_limits() -> Limits { + Limits { + bytes: 1 << 20, + depth: 32, + tree_depth: 32, + xml_nodes: MAX_NODES, + allow_dtd: false, + refuse_entity_markup: true, + embedded_bytes: 0, + embedded_depth: 0, + embedded_raster_pixels: 0, + ..Limits::default() + } +} + /// The render tree of `svg`, or why it was refused. #[doc(hidden)] pub fn parse(svg: &[u8]) -> Result { @@ -19,8 +36,5 @@ pub fn parse(svg: &[u8]) -> Result { image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) }, ..usvg::Options::default() }; - let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?; - let xml = usvg::roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES }; - let doc = usvg::roxmltree::Document::parse_with_options(text, xml).map_err(|e| e.to_string())?; - usvg::Tree::from_xmltree(&doc, &options).map_err(|e| e.to_string()) + tree::parse(svg, &icon_limits(), &options).map_err(|e| e.to_string()) } diff --git a/crates/ui-shell/Cargo.toml b/crates/ui-shell/Cargo.toml index e4d8fdb79..d55e80fcb 100644 --- a/crates/ui-shell/Cargo.toml +++ b/crates/ui-shell/Cargo.toml @@ -36,7 +36,7 @@ craft-i18n = { workspace = true, features = ["collate"] } # The saved forms of `ScreenMode`, `RecentView` and `RecentSort`. serde = { workspace = true } # The caption button icons. -resvg = { version = "0.45.1", default-features = false } +craft-svg = { workspace = true, features = ["draw"] } # `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics. web-time = "1.1" diff --git a/crates/ui-shell/src/shell/caption_icons.rs b/crates/ui-shell/src/shell/caption_icons.rs index 5a6f9d20d..e77ed4b57 100644 --- a/crates/ui-shell/src/shell/caption_icons.rs +++ b/crates/ui-shell/src/shell/caption_icons.rs @@ -137,10 +137,13 @@ fn theme_files(_theme: &str) -> [Option>; 4] { Default::default() } +/// Bytes drawing one caption icon may allocate, its target included. +const MASK_DRAW_BUDGET: u64 = 64 << 20; + /// An SVG's coverage (alpha) as a `px` x `px` mask, the drawing fitted and centred. `None` for an unreadable SVG or /// an absurd size. fn rasterize_mask(svg: &[u8], px: u32) -> Option { - use resvg::tiny_skia; + use craft_svg::tree::draw::{self, tiny_skia}; if !(1..=MAX_MASK_SIDE).contains(&px) { return None; } @@ -155,8 +158,8 @@ fn rasterize_mask(svg: &[u8], px: u32) -> Option { } let scale = px as f32 / side; let (dx, dy) = ((px as f32 - size.width() * scale) / 2.0, (px as f32 - size.height() * scale) / 2.0); - let mut pixmap = tiny_skia::Pixmap::new(px, px)?; - resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy), &mut pixmap.as_mut()); + let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy); + let pixmap = draw::render(&tree, transform, px, px, 0, MASK_DRAW_BUDGET).ok()?; Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect()) })) .ok() diff --git a/crates/ui-shell/tests/it/shell/caption_button.rs b/crates/ui-shell/tests/it/shell/caption_button.rs index 793569629..c12c9d388 100644 --- a/crates/ui-shell/tests/it/shell/caption_button.rs +++ b/crates/ui-shell/tests/it/shell/caption_button.rs @@ -29,6 +29,15 @@ fn hostile_svgs_render_nothing() { assert!(mask_of(image.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().all(|coverage| *coverage == 0)), "nothing drawn"); } +/// Icons parse on the UI thread: a document nested deeper than its stack takes is refused, not a stack overflow. +#[trial] +fn an_icon_nested_past_its_depth_is_refused_not_a_crash() { + let deep = format!(r#"{}{}"#, "".repeat(200), "".repeat(200)); + assert!(mask_of(deep.as_bytes(), GLYPH_PX).is_none()); + let shallow = format!(r#"{}{}"#, "".repeat(8), "".repeat(8)); + assert!(mask_of(shallow.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().any(|coverage| *coverage > 0)), "a shallow icon draws"); +} + /// A glyph is a square coverage mask of the drawing, fitted to the asked side; the glyphs a theme lacks have none. #[trial] fn masks_are_square_coverage() { From c081a17fed932dda7d29a7935724b4936015a23b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:42:49 +0000 Subject: [PATCH 4/8] merge-fwd: item 6: Export As suggests names with their boundary spaces and dots; ExportAsDialog/HostedExportAs files(count) asks for a folder for several files; trials --- .../src/patterns/form_dialogs/export.rs | 11 ++-- .../patterns/form_dialogs/export/as_dialog.rs | 30 +++++++-- .../tests/it/form_dialogs/export.rs | 18 ++++-- .../tests/it/form_dialogs/hosted.rs | 61 +++++++++++++++++++ 4 files changed, 102 insertions(+), 18 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export.rs b/crates/ui-patterns/src/patterns/form_dialogs/export.rs index 369c3bd06..b0acc9689 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export.rs @@ -512,7 +512,7 @@ impl ExportPreview { pub struct ExportAsResult { /// The settings the user confirmed. pub options: ExportOptions, - /// The file the user chose to write. + /// The file the user chose to write; the folder when the export writes more than one file. pub path: PathBuf, /// The output size in pixels. pub size: PixelSize, @@ -570,13 +570,12 @@ impl Revisions { } } -/// A file name safe on every platform: at most 80 characters, control characters and `< > : " / \ | ? *` replaced by -/// `_`, leading and trailing dots and spaces trimmed; empty becomes `fallback` ("layer" for per-layer exports, the -/// document name otherwise). +/// The file name a save dialog suggests for `name`: each control character and each character a file name can't hold +/// (`< > : " / \ | ? *`) turned into `_`, at most 80 characters; spaces and dots at the ends stay as the name holds +/// them. `fallback` for a name of nothing but whitespace and dots. pub(crate) fn export_file_name(name: &str, fallback: &str) -> String { let name: String = name.chars().take(MAX_NAME_CHARS).map(|c| if c.is_control() || RESERVED.contains(c) { '_' } else { c }).collect(); - let name = name.trim().trim_matches('.'); - if name.is_empty() { fallback.to_owned() } else { name.to_owned() } + if name.chars().all(|c| c.is_whitespace() || c == '.') { fallback.to_owned() } else { name } } const MAX_NAME_CHARS: usize = 80; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs index 864f0298e..cbbd0bbae 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs @@ -123,7 +123,8 @@ impl Outcome for ExportAsOutput { /// turns Cancel into Reset, which restores the settings the dialog opened with. Export asks the app for a file /// to write (`ExportAsOutput::requests`), or a folder with more than one Scale All row, and the dialog stays open /// until the app answers with the path. Without [`folder_export`](ExportAsDialog::folder_export), more than one row -/// refuses Export with a note. +/// refuses Export with a note. An export of several files ([`files`](ExportAsDialog::files)) asks for a folder +/// too where the app can write one. /// - Settings: the dialog opens on the value in the bind, fitted to the document, and writes its edits back. /// - Previews: whenever the settings change, `wanted_preview` carries a new revision. The app encodes a proxy and /// gives it back with `preview`; a size estimate shows at once ("≈ 1.2 MB"), and the app may follow with an exact @@ -173,6 +174,10 @@ pub struct ExportAsDialog<'a> { /// whose file dialog answers no folder (the browser) sets it off. #[prop] folder_export: bool, + /// How many files the export writes before Scale All, one per exportable layer of a layer export; the default is + /// 1. With more than one and [`folder_export`](ExportAsDialog::folder_export), Export asks for a folder. + #[prop] + files: usize, } impl<'a> ExportAsDialog<'a> { @@ -194,6 +199,7 @@ impl<'a> ExportAsDialog<'a> { remember: None, opening: None, folder_export: true, + files: 1, } } @@ -215,6 +221,7 @@ impl<'a> ExportAsDialog<'a> { remember, opening, folder_export, + files, } = self; let env = Env::of(ui); let words = env.words::(); @@ -287,7 +294,7 @@ impl<'a> ExportAsDialog<'a> { if reset.pick(picked) == Some(ResetPick::Accept) && let Some(options) = &latest { - requests.request_path(save_request(&formats, options, &file_name, &words)); + requests.request_path(save_request(&formats, options, &file_name, folder_export && files > 1, &words)); } let result = accepted.zip(answered.into_inner()).map(|(options, path)| answer_of(options, source, path, remember)); let events = events.into_inner(); @@ -301,9 +308,9 @@ impl<'a> ExportAsDialog<'a> { } /// The save dialog Export asks for: the document's name with the format's extension and filter; a folder for more than -/// one Scale All row. -fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &str, words: &ExportWords) -> PathRequest { - if options.scale_all.len() > 1 { +/// one Scale All row, or when `several_files` (a layer export of more than one layer, where the app writes a folder). +fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &str, several_files: bool, words: &ExportWords) -> PathRequest { + if options.scale_all.len() > 1 || several_files { return PathRequest::new(SAVE_KEY, PathKind::Folder); } let format = formats.iter().find(|format| format.id == options.format); @@ -360,6 +367,7 @@ pub struct HostedExportAs { /// The path the host's save dialog answered, or automation set; Export finishes with it. path: Option, folder_export: bool, + files: usize, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput, } @@ -414,6 +422,7 @@ impl HostedExportAs { remember: None, path: None, folder_export: true, + files: 1, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput::default(), } @@ -426,6 +435,13 @@ impl HostedExportAs { self } + /// How many files the export writes before Scale All ([`ExportAsDialog::files`]). + #[must_use] + pub fn files(mut self, count: usize) -> Self { + self.files = count; + self + } + /// The formats the list offers. #[must_use] pub fn formats(mut self, formats: Vec) -> Self { @@ -505,7 +521,8 @@ impl StackDialog for HostedExportAs { let Some(path) = self.path.clone() else { if !self.saving { let words = Env::of_root(ctx).words::(); - self.requests.request_path(save_request(&self.formats, &self.options, &self.file_name, &words)); + let several_files = self.folder_export && self.files > 1; + self.requests.request_path(save_request(&self.formats, &self.options, &self.file_name, several_files, &words)); self.saving = true; } return None; @@ -563,6 +580,7 @@ impl StackDialog for HostedExportAs { remember: self.remember.clone(), opening: Some(self.opening.clone()), folder_export: self.folder_export, + files: self.files, ..ExportAsDialog::new(self.file_name.clone(), self.source, Bind::bound(&mut self.options)) }; let mut shown = dialog.show(ui); diff --git a/crates/ui-patterns/tests/it/form_dialogs/export.rs b/crates/ui-patterns/tests/it/form_dialogs/export.rs index e1cd15c47..9e8c91f79 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/export.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/export.rs @@ -5,7 +5,7 @@ use craft_ui::contract::{Bind, Role, SaveKey}; use craft_ui::dialog::{DialogHost, DialogResult, StackDialog}; use craft_ui::patterns::form_dialogs::{ ExportAsDialog, ExportAsResult, ExportOptions, ExportOptionsKind, ExportSize, FormatOptions, FormatOptionsDialog, HostedExportAs, - HostedFormatOptions, JpegOptions, OutputPathRow, Resample, SizeEstimate, + HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate, }; use craft_ui::runtime::requests::PathRequest; use craft_ui::testing::{Fixture, trial}; @@ -38,13 +38,16 @@ fn requested_file(name: &str) -> String { filed.file_name.expect("the request names a file") } -/// The default file name is the document's, made safe on every platform: reserved characters become underscores, dots and -/// spaces at the ends go, and a name with nothing left is Untitled. +/// The suggested file name is the document's with what no file name holds turned into underscores; spaces and dots +/// at its ends stay, as production PhotoCraft keeps them, and a name of nothing but spaces and dots is Untitled. #[trial] -fn the_default_file_name_is_made_safe() { +fn the_suggested_file_name_keeps_its_ends_and_drops_what_no_file_name_holds() { assert_eq!(requested_file("Poster"), "Poster.png"); - assert_eq!(requested_file(" ..My: poster/v2?.. "), "My_ poster_v2_.png"); + assert_eq!(requested_file(" Artboard 1 "), " Artboard 1 .png"); + assert_eq!(requested_file(" a/b "), " a_b .png"); + assert_eq!(requested_file("a/b:c*?"), "a_b_c__.png"); assert_eq!(requested_file(" . "), "Untitled.png"); + assert_eq!(requested_file("..."), "Untitled.png"); let long = "x".repeat(100); assert_eq!(requested_file(&long).len(), 80 + ".png".len(), "at most 80 characters"); } @@ -259,7 +262,8 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones() let shown = Rc::clone(&host); let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); fixture.room(Vec2::new(1400.0, 1000.0)); - let jpeg = options("jpg", 40); + let mut jpeg = options("jpg", 40); + jpeg.scale_all = vec![ScaleRow::default(), ScaleRow::new(ScaleSize::X2, "@2x")]; let first = export_from(&host, &mut fixture, jpeg.clone()); assert_eq!(first.options.format, "jpg", "nothing stored: the dialog exports what it was given"); @@ -268,11 +272,13 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones() first.remember(fixture.ctx()); let reopened = opened_with(&host, &mut fixture, ExportOptions::default()); assert_eq!((reopened.format.as_str(), reopened.quality), ("jpg", 40), "the stored options replace the given ones at open"); + assert_eq!(reopened.scale_all, jpeg.scale_all, "the stored Scale All rows come back with them"); let webp = options("webp", 55); let _unstored = export_from(&host, &mut fixture, webp); let again = opened_with(&host, &mut fixture, ExportOptions::default()); assert_eq!((again.format.as_str(), again.quality), ("jpg", 40), "a result not stored leaves the stored options as they were"); + assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows"); } /// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 5a0a99189..c3dea6ae8 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -314,6 +314,67 @@ fn export_as_writes_one_file_per_scale_all_row_and_only_from_its_button() { assert!(pick(&host).is_none() && !host.borrow_mut().confirm::(&ctx), "without a folder two rows refuse Export"); } +/// A layer export of several files asks for a folder where the app can write one, the browser's build keeps the save +/// request, and an export of one file asks for that file by name. +#[trial] +fn an_export_of_several_files_asks_for_a_folder() { + use craft_ui::runtime::requests::PathKind; + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + let pick = |host: &Rc>| host.borrow_mut().get_mut::().and_then(HostedExportAs::pick_path); + for (files, folder_export, folder) in [(2, true, true), (2, false, false), (1, true, false)] { + host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default()).files(files).folder_export(folder_export)); + fixture.idle(10); + let export = fixture.by_label("Export…").expect("the Export button"); + fixture.click(&export).idle(4); + let request = pick(&host).expect("Export asks where to write"); + let case = format!("{files} files, folder export {folder_export}"); + assert_eq!(matches!(request.kind, PathKind::Folder), folder, "{case}: a folder"); + if !folder { + assert_eq!(request.file_name.as_deref(), Some("Poster.png"), "{case}: the file is named"); + } + fixture.key(Key::Escape, Modifiers::NONE).idle(4); + assert!(host.borrow().is_empty(), "{case}: Escape cancels"); + } +} + +/// Enter in a field of Export As commits that field and leaves the dialog open. + adds sizes in their order up to the +/// row limit, then is disabled, and a suffix is cut at its limit. +#[trial] +fn export_as_keeps_scale_all_within_its_limits_and_enter_in_a_field_only_commits_it() { + use craft_ui::patterns::form_dialogs::{ScaleRow, ScaleSize}; + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default())); + fixture.idle(10); + let options = |host: &Rc>| host.borrow().get::().map(|dialog| dialog.options().clone()).expect("open"); + + let scale = fixture.by_label("Scale").expect("the Scale field"); + fixture.click(&scale).idle(2); + fixture.key(Key::A, Modifiers::COMMAND).type_text("50"); + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert!(host.borrow().is_open::(), "Enter in the Scale field leaves the dialog open"); + assert_eq!(options(&host).output_size(PICTURE), PixelSize::new(800, 450), "Enter commits the field"); + + for _ in 1..ScaleRow::MAX_ROWS { + let add = fixture.by_label("Add a size").expect("the + button"); + fixture.click(&add).idle(4); + } + let rows = options(&host).scale_rows(); + assert_eq!(rows.len(), ScaleRow::MAX_ROWS, "+ adds rows up to the limit"); + let added: Vec = rows.iter().skip(1).map(|row| row.size).collect(); + let order: Vec = ScaleSize::ADD_ORDER.iter().copied().filter(|size| *size != rows[0].size).take(added.len()).collect(); + assert_eq!(added, order, "+ adds the sizes in their order"); + let add = fixture.by_label("Add a size").expect("the + button"); + assert!(fixture.tree().is_disabled_key(add.node), "+ is disabled at the limit"); + + let suffix = fixture.by_label("Suffix 2").expect("the second row's suffix"); + fixture.click(&suffix).idle(2); + fixture.key(Key::A, Modifiers::COMMAND).type_text(&"s".repeat(ScaleRow::MAX_SUFFIX + 10)); + fixture.key(Key::Tab, Modifiers::NONE).idle(4); + assert_eq!(options(&host).scale_rows()[1].suffix.chars().count(), ScaleRow::MAX_SUFFIX, "a suffix is cut at its limit"); +} + /// Image Size's readout counts the flat image in whole-byte rows (a Bitmap row of 9 pixels takes 2 bytes) and says /// "(was …)" only once the pixel size differs from the document's. #[trial] From 54f9aa1b0d9935020fac80e55b0307680ede403e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:43:51 +0000 Subject: [PATCH 5/8] merge-fwd: item 5: FW15: the mock counts sub_rows calls; trial: a long layer list asks only for the rows in view --- crates/layers/src/ui/mock.rs | 9 ++++- crates/layers/tests/it/panel_rows.rs | 52 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/layers/src/ui/mock.rs b/crates/layers/src/ui/mock.rs index 66602a47d..f064b7f5e 100644 --- a/crates/layers/src/ui/mock.rs +++ b/crates/layers/src/ui/mock.rs @@ -53,6 +53,7 @@ pub struct FakeLayers { /// filter's Missing. pub missing: Vec, info_calls: Cell, + sub_rows_calls: Cell, } impl FakeLayers { @@ -254,7 +255,7 @@ impl FakeLayers { tree } - /// `count` pixel layers at the top level, for the 10,000-row test; counts the `info` calls. + /// `count` pixel layers at the top level, for the long-list trials; counts the `info` and `sub_rows` calls. pub fn flat(count: usize) -> Self { let mut tree = Self::default(); for n in 0..count { @@ -305,6 +306,11 @@ impl FakeLayers { pub fn take_info_calls(&self) -> usize { self.info_calls.replace(0) } + + /// How many times `sub_rows` was called since the last [`take_sub_rows_calls`](Self::take_sub_rows_calls). + pub fn take_sub_rows_calls(&self) -> usize { + self.sub_rows_calls.replace(0) + } } impl FakeLayers { @@ -394,6 +400,7 @@ impl LayerTree for FakeLayers { } fn sub_rows(&self, id: &u32, group: SubRowGroup) -> Option { + self.sub_rows_calls.set(self.sub_rows_calls.get() + 1); let layer = self.layer(id)?; match group { SubRowGroup::Effects => layer.effects.clone(), diff --git a/crates/layers/tests/it/panel_rows.rs b/crates/layers/tests/it/panel_rows.rs index 4dc1a7fdc..c60f81df4 100644 --- a/crates/layers/tests/it/panel_rows.rs +++ b/crates/layers/tests/it/panel_rows.rs @@ -386,3 +386,55 @@ fn a_stacking_key_on_a_selected_smart_filter_row_moves_the_filter() { .collect(); assert_eq!(moves, [(SMART, SubRowGroup::SmartFilters, 0, 1)], "{events:?}"); } + +/// `count` pixel layers above a closed group and a smart object with two Smart Filters shown, at a fixed revision; +/// returns the tree and the smart object. +fn long(count: usize) -> (FakeLayers, u32) { + let mut tree = FakeLayers::flat(count); + let group = tree.add(None, LayerInfo::new("Closed Group", LayerKind::Group), false); + tree.add(Some(group), LayerInfo::new("Inside", LayerKind::Pixel), false); + let mut smart = LayerInfo::new("Smart Object", LayerKind::SmartObject); + smart.has_smart_filters = true; + let id = tree.add(None, smart, false); + let layer = tree.layer_mut(id); + layer.effects_open = true; + layer.smart_filters = Some(SubRows::new(SubRow::new("Smart Filters"), vec![sub_row("Gaussian Blur"), sub_row("Sharpen")])); + tree.selection = LayerSelection::new(vec![1], Some(1), LayerPart::Pixels); + tree.revision = Some(1); + (tree, id) +} + +/// FW15: a long layer list asks the app only for the rows in view: a settled frame makes as many `info` and +/// `sub_rows` calls for 2,000 layers as for 200, and an off-screen group or Smart Filter row lays out nothing. +/// Scrolled into view they show; a filter selected there stays selected after it scrolls away again. +#[trial] +fn a_long_layer_list_asks_only_for_the_rows_in_view() { + let mut calls = Vec::new(); + for count in [200, 2_000] { + let (tree, smart) = long(count); + let (mut fixture, app) = rig(tree); + let _ = (app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls()); + fixture.frame(vec![]); + calls.push((app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls())); + for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] { + assert!(fixture.by_label(name).is_none(), "{count} layers: the off-screen row {name:?} lays out nothing"); + } + + let list = node(&fixture, "Layers").center(); + fixture.frame(vec![pointer::moved(list)]); + fixture.frame(vec![pointer::wheel(-1.0e7)]).settle(); + for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] { + assert!(fixture.by_label(name).is_some(), "{count} layers: scrolled to the bottom, {name:?} shows"); + } + let blur = node(&fixture, "Gaussian Blur"); + fixture.click(&blur).settle(); + let selected = Some(LayerRowKey::Filters(smart, Some(0))); + assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter is selected"); + take(&app); + fixture.frame(vec![pointer::wheel(1.0e7)]).settle(); + assert!(fixture.by_label("Gaussian Blur").is_none(), "{count} layers: scrolled back to the top"); + assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing"); + assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected"); + } + assert_eq!(calls[0], calls[1], "a settled frame asks for as many rows for 2,000 layers as for 200 (info, sub_rows)"); +} From 768a1d0cfad56583d55800366f149fd9dc2b908c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:44:45 +0000 Subject: [PATCH 6/8] merge-fwd: item 7: served-font trials: a fetched face survives a reinstall, the interface language's served face leads --- crates/ui-contract/tests/it/fonts/served.rs | 53 ++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/tests/it/fonts/served.rs b/crates/ui-contract/tests/it/fonts/served.rs index b0b346cb2..4af778151 100644 --- a/crates/ui-contract/tests/it/fonts/served.rs +++ b/crates/ui-contract/tests/it/fonts/served.rs @@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex}; use craft_fonts_build::ServedFace; use craft_ui::fonts::{Family, FetchDone, FetchWake, FontFetcher, FontRef, I18nScripts, SystemFonts, UiFonts}; use craft_ui::testing::{Frames, trial}; -use egui::FontId; +use egui::{FontFamily, FontId}; const ARABIC: &[u8] = include_bytes!("../../fonts/NotoSansArabic-test.ttf"); /// Noto Sans with Vietnamese ổ but not ẫ. @@ -244,3 +244,54 @@ fn a_failed_download_moves_on_and_is_retried_later() { assert!(!draws('⇥')); assert_eq!(fetch.requested(), [MATH_URL]); } + +const ARABIC_URL: &str = "fonts/noto-sans-arabic/NotoSansArabic.ttf"; + +/// A language change installs the fonts anew in the same context: a face fetched before it stays, and is not fetched +/// again. +#[trial] +fn a_fetched_face_survives_a_reinstall() { + let faces = [ServedFace { coverage: coverage_of(ARABIC), ..served("Noto Sans Arabic", "Regular", &["Arab"], ARABIC_URL, 0) }]; + let fetch = Arc::new(FakeFetch::default()); + let (ctx, mut draws) = web_context_with("en", &faces, &fetch); + assert!(!draws('ع')); + assert_eq!(fetch.requested(), [ARABIC_URL]); + fetch.answer(ARABIC_URL, Ok(ARABIC)); + assert!(draws('ع')); + + web_fonts("ru", &faces).fetcher(Arc::clone(&fetch) as Arc).install(&ctx); + assert!(draws('ع'), "the fetched face is installed again"); + assert!(fetch.requested().is_empty(), "nothing is fetched again"); +} + +/// Of two served faces that draw Han, the interface language's comes first in the proportional chain, whichever was +/// fetched first. +#[trial] +fn the_interface_languages_served_face_leads() { + const JP_URL: &str = "fonts/noto-sans-cjk-jp/NotoSansCJKjp.otf"; + const SC_URL: &str = "fonts/noto-sans-cjk-sc/NotoSansCJKsc.otf"; + let han = (0x4E00, 0x9FFF); + let faces = [ + ServedFace { + coverage: craft_fonts_build::coverage::encode(&[(0x3040, 0x30FF), han]).leak(), + ..served("Noto Sans CJK JP", "Regular", &["Jpan"], JP_URL, 0) + }, + ServedFace { coverage: craft_fonts_build::coverage::encode(&[han]).leak(), ..served("Noto Sans CJK SC", "Regular", &["Hans"], SC_URL, 0) }, + ]; + let fetch = Arc::new(FakeFetch::default()); + let (ctx, mut draws) = web_context_with("zh-CN", &faces, &fetch); + // Kana only the Japanese face covers, and Han, which the Simplified Chinese face draws first in this UI. + draws('あ'); + draws('中'); + let mut asked = fetch.requested(); + asked.sort_unstable(); + assert_eq!(asked, [JP_URL, SC_URL], "kana asks for the Japanese face, Han for the Simplified Chinese one"); + // The Japanese face arrives first. + fetch.answer(JP_URL, Ok(NOTO_SANS_LATIN)); + draws('あ'); + fetch.answer(SC_URL, Ok(include_bytes!("../../fonts/NotoSansCJKsc-test.otf"))); + draws('中'); + let chain = ctx.fonts(|f| f.definitions().families[&FontFamily::Proportional].clone()); + let at = |name: &str| chain.iter().position(|face| face == name).unwrap_or_else(|| panic!("{name} is in the chain: {chain:?}")); + assert!(at("Noto Sans CJK SC Regular") < at("Noto Sans CJK JP Regular"), "the interface language's face leads: {chain:?}"); +} From faea5d0b1a5c8ac403f543dd17ac1fae5b8f04cc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:49:22 +0000 Subject: [PATCH 7/8] merge-fwd: item 4: Preflight.height is read only by the image resolver; expect dead_code without tree --- crates/svg/src/tree.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 613e298ff..4e2e74516 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -170,6 +170,7 @@ pub struct Preflight<'s> { xml: roxmltree::Document<'s>, depth: usize, /// [`height`]: the nesting usvg converts, references followed. + #[cfg_attr(not(feature = "tree"), expect(dead_code, reason = "only the embedded-image resolver reads it"))] height: usize, } From 2b3056407bc3bce20fa3ac68b5900724982f2bba Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:57:21 +0000 Subject: [PATCH 8/8] merge-fwd: item 5: FW15 trial: wheel to the list's end in steps as its extent grows; the selected filter, the list's lead, is out of view after scrolling up --- crates/layers/tests/it/panel_rows.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/layers/tests/it/panel_rows.rs b/crates/layers/tests/it/panel_rows.rs index c60f81df4..f5acee6e2 100644 --- a/crates/layers/tests/it/panel_rows.rs +++ b/crates/layers/tests/it/panel_rows.rs @@ -422,7 +422,10 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { let list = node(&fixture, "Layers").center(); fixture.frame(vec![pointer::moved(list)]); - fixture.frame(vec![pointer::wheel(-1.0e7)]).settle(); + // The list's extent grows as it measures the rows a wheel brings in, so the end takes a few wheels. + for _ in 0..3 { + fixture.frame(vec![pointer::wheel(-1.0e7)]).settle(); + } for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] { assert!(fixture.by_label(name).is_some(), "{count} layers: scrolled to the bottom, {name:?} shows"); } @@ -431,8 +434,13 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { let selected = Some(LayerRowKey::Filters(smart, Some(0))); assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter is selected"); take(&app); - fixture.frame(vec![pointer::wheel(1.0e7)]).settle(); - assert!(fixture.by_label("Gaussian Blur").is_none(), "{count} layers: scrolled back to the top"); + for _ in 0..3 { + fixture.frame(vec![pointer::wheel(1.0e7)]).settle(); + } + // The selected filter is the list's lead, which stays built out of view. + let view = node(&fixture, "Layers").rect; + let left = fixture.by_label("Gaussian Blur"); + assert!(left.is_none_or(|row| !row.rect.intersects(view)), "{count} layers: scrolled back to the top, the filter is out of view"); assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing"); assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected"); }