From ce33666294c993f1f3b067dad10d08e0db511d43 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:23:23 +0000 Subject: [PATCH] Layers opened from a palette window open in popup OS windows A collapsed floating window is 40 pt wide, so its flyouts, the double arrow's tooltip and the panel menu could not show inside it: the tooltip wrapped one letter per line ("E x") and the flyouts opened outside the window (#15861). Every layer the overlay host shows from a palette window (a dock window or a popup window, at WindowLevel::Palette) now shows in a popup window of its own (WindowSpec::popup), placed in desktop points within the work area around the palette (windows::popup_room, overlay::layer_room). Layers from the main window stay in it; full-window layers cover their own window. - The popup's pass shows the layer and records it in the popup's stack, with its focus scope and Escape/Enter/activation dismissal. The opener's pass records an entry standing for the window (OpenEntry::popup), so family closes, the anchor and outside presses in the opener work as before; family closes also reach the layers in popup windows. - A press in another app window closes an outside-closing popup, and a popup closes when the app loses focus. - Popups that take keys take the OS focus and hand it back to their opener on close; tooltips take no focus and let the pointer through. - A layer without a measured size (a tooltip) is laid out in the popup's pass, in the work-area room, and placed by the size it took there. - A palette column passes no main-window bounds to its flyouts. - The test kit keeps facts per popup window. --- crates/ui-contract/src/contract/overlay.rs | 2 +- .../src/contract/overlay/dismissal.rs | 21 ++ .../ui-contract/src/contract/overlay/host.rs | 149 +++++++++++- .../src/contract/overlay/placement.rs | 12 +- crates/ui-contract/src/contract/overlay/ui.rs | 4 +- .../ui-contract/src/runtime/egui/viewports.rs | 12 +- crates/ui-contract/src/runtime/frame.rs | 12 + crates/ui-contract/src/runtime/overlay.rs | 38 +++- crates/ui-contract/src/runtime/windows.rs | 82 ++++++- .../ui-contract/src/runtime/windows/host.rs | 2 +- .../ui-contract/src/runtime/windows/spec.rs | 27 +++ .../src/runtime/windows/viewport.rs | 62 +++++ crates/ui-panels/src/docking/iconic.rs | 6 +- crates/ui-patterns/src/patterns/dock/area.rs | 5 +- crates/ui-patterns/tests/it/docking/native.rs | 213 +++++++++++++++++- crates/ui-test-kit/src/windows.rs | 77 +++++-- 16 files changed, 687 insertions(+), 37 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index 7622c5596..215f7a0e7 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -23,7 +23,7 @@ pub(crate) use host::{Layer, forget_layer, host, host_window}; pub(crate) use opener::{LayerFloor, anchor_floor}; pub use opener::{Opener, Trigger}; pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; -pub use placement::PopupRegion; +pub use placement::{PopupRegion, layer_room}; pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for}; pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index b6790cd12..8ce555ead 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -73,6 +73,27 @@ pub(super) fn dismissal( None } +/// The dismissal of a layer shown in the popup window `popup`, decided in its opener's pass, beside what the popup's +/// own pass decides: a layer that closes on outside presses closes on one in the opener outside it and its anchor +/// (absorbed or not, as its rule says), and on one in any other window of the app; a popup also closes once the app +/// has no focus. An absorbing layer can't keep a press in another OS window from reaching that window. +pub(super) fn popup_dismissal( + ctx: &Context, + layer: &Layer<'_>, + rect: Rect, + anchor: Rect, + popup: egui::ViewportId, + appears: bool, +) -> Option { + let here = match layer.overlay.dismiss.outside { + Outside::Keep => return None, + Outside::Absorb => overlay::absorbed_press(ctx).is_some(), + Outside::Close => press_outside(ctx, layer, rect, anchor), + }; + let away = layer.overlay.rank == Rank::Popup && crate::runtime::windows::app_away(ctx); + (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. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 9c2ab20fc..a37aa15b5 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -1,6 +1,6 @@ //! The overlay host: shows a layer on an egui layer, remembers it while shown and closes its family. -use super::dismissal::dismissal; +use super::dismissal::{dismissal, popup_dismissal}; use super::opener::{Opening, Trigger}; use super::place::{OverlayFit, Place}; use super::placement::{anchor_rect, opened_overlay, placement}; @@ -13,6 +13,7 @@ use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::motion::{self, Driver}; use crate::runtime::overlay::{self, Backdrop, CloseReason, OpenEntry, Rank}; +use crate::runtime::windows::{self, PopupOpen, PopupRoom, WindowSpec}; use craft_behavior::{MotionKind, Playback}; use egui::{Context, Id, Pos2, Rect, Ui, Vec2}; @@ -90,6 +91,7 @@ pub(crate) fn forget_layer(ctx: &Context, id: Id, owner: Id) { if taken.is_some_and(|memory| !memory.family_closed) { overlay::close_descendants(ctx, id); } + windows::close_popup(ctx, id); } /// Asks the layers opened from inside `layer` to close once the layer closes or starts to fade out, in the pass that @@ -106,8 +108,14 @@ fn area_id(id: Id) -> Id { sub(id, "area") } -/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. +/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. A layer opened in a palette +/// window shows in a popup window of its own ([`host_in_popup`]); a full-window layer covers its own window. pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + if !layer.overlay.is_full_window() + && let Some(popup) = windows::popup_room(ctx) + { + return host_in_popup(ctx, layer, popup, body); + } // A layer that appears starts with nothing it remembered while shown before, also when it opens again during its // exit fade or its host never saw it hide: the focus that was inside it does not close it as `focus_left`. let appears = overlay::appears(ctx, layer.id, layer.exiting); @@ -248,6 +256,143 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U LayerOut { dismissed } } +/// A layer opened in a palette window, shown in a popup window of its own (`WindowSpec::popup`): placed in the +/// opener's points within the work area around it, the window at that place in desktop points. +/// +/// The layer's bookkeeping is split between the two windows. The popup's pass shows the layer at the window's origin +/// and records it in the popup's stack, with its focus scope and the dismissal its own input decides (Escape, Enter, +/// activations, focus, timeout). The opener's pass records an entry that stands for the window (`OpenEntry::popup`), +/// so its family, its anchor and the presses in the opener are judged where they happen; a press in any other window +/// of the app, and for a popup the app losing focus, close it too ([`popup_dismissal`]). +/// +/// A layer whose size its container measured is placed before the window opens. A layer without one (a tooltip) is +/// laid out in the popup's pass first, in the room its unplaced form has, and placed by the size it took there. +/// A popup that takes keys (a menu, a flyout) takes the OS focus; a tooltip takes none and lets the pointer through. +fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + let appears = overlay::appears(ctx, layer.id, layer.exiting); + let mut memory = if appears { LayerMemory::default() } else { recall(layer, ctx) }; + let opened = opened_overlay(ctx, layer.overlay, memory.opening); + if let Some((_, opening)) = &opened { + memory.opening.get_or_insert(*opening); + } + // The popup window lies outside any region of the opener: the work area is its room. + let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer }; + let overlay = layer.overlay; + let bounds = popup.room; + let anchor = anchor_rect(ctx, layer, bounds, &mut memory); + let min_width = overlay.least_width(anchor.width()); + let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y)); + let unplaced = placement(ctx, layer, measured, bounds, anchor); + let parent = overlay::drawing_parent(ctx); + let tier = overlay::layer_tier(ctx, overlay.rank); + let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); + if overlay.rank.is_modal() && appears { + overlay::close_popups_outside(ctx, &[layer.id]); + } + // The body reports in its parent's space: the popup's points are the opener's screen less the layer's place. + let to_parent = overlay::parent_space(ctx, layer.id); + let tooltip = overlay.rank == Rank::Tooltip; + let spec = WindowSpec::popup().takes_focus(!tooltip && (scope.is_some() || overlay.rank.takes_keys())).passes_pointer(tooltip); + let known = measured.map(|size| Rect::from_min_size(unplaced.at, size)); + let open = PopupOpen { id: layer.id, spec: &spec, rect: known.map(|rect| rect.translate(popup.origin.to_vec2())) }; + let mut shown = None; + windows::show_popup(ctx, &open, |ui| { + let at = unplaced.at.to_vec2(); + overlay::note_parent_space(ui.ctx(), layer.id, egui::emath::TSTransform::from_translation(-at) * to_parent); + shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body)); + }); + let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None)); + let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) }; + let rect = Rect::from_min_size(placed.at, size); + if known.is_none() { + windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2())); + } + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(tier, area_id(layer.id))); + entry.parent = parent; + entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.scoped = scope.is_some(); + entry.absorbs = overlay.dismiss.outside == Outside::Absorb; + entry.window = true; + entry.popup = true; + overlay::record(ctx, entry); + let viewport = crate::runtime::egui::viewports::viewport_id(layer.id); + let dismissed = if layer.exiting { None } else { dismissed.or_else(|| popup_dismissal(ctx, layer, rect, anchor, viewport, appears)) }; + close_family(ctx, layer, layer.exiting || dismissed.is_some(), &mut memory); + remember(layer, ctx, memory); + LayerOut { dismissed } +} + +/// The popup window's pass of [`host_in_popup`]: the layer at the window's origin, offered the room `placed` leaves, +/// its entry in the popup's stack and the dismissal the popup's own input decides. Returns the size the layer took +/// and that dismissal. +fn show_in_popup( + ui: &mut Ui, + layer: &Layer<'_>, + placed: &super::placement::Placed, + min_width: f32, + scope: Option, + memory: &mut LayerMemory, + body: &mut dyn FnMut(&mut Ui), +) -> (Vec2, Option) { + let ctx = ui.ctx().clone(); + let overlay = layer.overlay; + let window = ctx.content_rect(); + let area = area_id(layer.id); + let tier = overlay::layer_tier(&ctx, overlay.rank); + let cover = match overlay.rank { + Rank::Modal { backdrop } => { + let scrim = match backdrop { + Backdrop::Scrim => crate::style::scrim_color(&layer.env.tokens).gamma_multiply(layer.fade), + Backdrop::None => egui::Color32::TRANSPARENT, + }; + let cover_id = sub(layer.id, "cover"); + let through = crate::runtime::sampler::through(&ctx, crate::runtime::egui::pass::current_viewport(&ctx), layer.id); + areas::show_cover_layer(&ctx, areas::CoverLayer { id: cover_id, tier, screen: window, scrim, through, absorbs: !layer.exiting }); + Some(areas::layer_of(tier, cover_id)) + } + _ => None, + }; + // The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts. + let opener = layer.env.capture().env(); + let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root)); + let spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side); + let shown = areas::show_layer(&ctx, &spec, |ui| { + areas::fade(ui, layer.fade * overlay.opacity); + let installed = Env::install_for(ui, env.clone()); + let real = !ui.is_sizing_pass(); + if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { + access::report_layer(&ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + } + // The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus + // back when the popup closes (`windows::close_popup`). + if real { + let entering = !std::mem::replace(&mut memory.scope_entered, true); + focus::push_scope_from(&ctx, layer.id, overlay.focus, None, None, layer.exiting, Some(entering)); + } + areas::bound(ui, placed.room, min_width.min(placed.room.x)); + if overlay.fit == OverlayFit::Resizable { + ui.set_min_size(overlay.size_limits.min.min(placed.room)); + } + access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui))); + if real { + focus::pop_scope(&ctx); + } + Env::restore(&ctx, installed); + }); + overlay::end_layer(&ctx); + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, shown.rect, shown.layer); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.cover = cover; + entry.scoped = scope.is_some(); + overlay::record(&ctx, entry); + let dismissed = if layer.exiting { None } else { dismissal(&ctx, layer, shown.rect, Rect::NOTHING, scope, memory) }; + (shown.rect.size(), dismissed) +} + /// The motion slot of a layer's nudge, under the layer's id. // PLAN: the decision names a `NUDGE_SPEC`; `MotionSpec::new` (`runtime/motion.rs:39`) is a private `const fn` of a file outside this set, so // the nudge runs on `spec::OPEN_FADE` (a fade, which reduced motion still runs) over the open token's duration. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index c4100569e..526a2fdda 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -82,10 +82,16 @@ pub(crate) fn region_for(env: &Env, overlay: &Overlay) -> Option { } } -/// The screen rect a layer of `overlay` opened in `env` keeps inside: the safe rect, or the part of it a contained -/// layer's region leaves. +/// The room a layer opened in the running viewport may take, in its points: the work area around a palette window, +/// whose layers show in popup windows of their own (`windows::popup_room`), else the window's safe rect. +pub fn layer_room(ctx: &Context) -> Rect { + crate::runtime::windows::popup_room(ctx).map_or_else(|| areas::safe_rect(ctx), |popup| popup.room) +} + +/// The screen rect a layer of `overlay` opened in `env` keeps inside: the layer room ([`layer_room`]), or the part +/// of it a contained layer's region leaves. pub(crate) fn screen_for(ctx: &Context, env: &Env, overlay: &Overlay) -> Rect { - let safe = areas::safe_rect(ctx); + let safe = layer_room(ctx); region_for(env, overlay).map_or(safe, |region| region.intersect(safe)) } diff --git a/crates/ui-contract/src/contract/overlay/ui.rs b/crates/ui-contract/src/contract/overlay/ui.rs index 34728c9f3..4f428911d 100644 --- a/crates/ui-contract/src/contract/overlay/ui.rs +++ b/crates/ui-contract/src/contract/overlay/ui.rs @@ -76,10 +76,10 @@ impl<'a> OverlayUi<'a> { } /// Keeps the popups this component shows from here on, and every popup opened from them, below the component: - /// inside the safe rect less the part above the component's bottom edge. A menu bar's menus and their submenus + /// inside the layer room less the part above the component's bottom edge. A menu bar's menus and their submenus /// never cover the bar. pub fn contain_popups_below(&mut self) { - let safe = areas::safe_rect(self.ctx); + let safe = super::layer_room(self.ctx); let top = (self.to_screen * self.anchor).bottom().clamp(safe.top(), safe.bottom()); let region = Rect::from_min_max(egui::pos2(safe.left(), top), safe.max); self.env = self.env.derive(|scoped| { diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 36b162ca7..e20acbb1e 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -35,8 +35,12 @@ pub(crate) struct Spec<'a> { pub resizable: bool, /// Whether the window has a taskbar or Dock entry. pub taskbar: bool, - /// Whether the window opens hidden; [`show`] reveals it. + /// Whether the window opens hidden; [`set_visible`] reveals it. pub hidden: bool, + /// Whether the window takes OS focus when it opens. + pub active: bool, + /// Whether pointer input passes through the window. + pub passes_pointer: bool, /// The app id the OS window carries (dock icon, Wayland compositor rules); empty carries none. pub app_id: &'a str, } @@ -48,6 +52,12 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, if spec.hidden { builder = builder.with_visible(false); } + if !spec.active { + builder = builder.with_active(false); + } + if spec.passes_pointer { + builder = builder.with_mouse_passthrough(true); + } if !spec.app_id.is_empty() { builder = builder.with_app_id(spec.app_id); } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index b6804a2b8..3efa412a9 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -197,6 +197,13 @@ pub struct Stamped { value: T, } +impl Stamped { + /// The record as its viewport's latest pass left it. + pub(crate) fn value(&self) -> &T { + &self.value + } +} + impl PerViewport { fn record(&mut self, viewport: ViewportId) -> &mut T { let at = match self.records.iter().position(|(id, _)| *id == viewport) { @@ -257,6 +264,11 @@ impl PerViewport { } } + /// Runs `f` on the record of `viewport` when it has one; creates none. + pub(crate) fn with_existing(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut T) -> R) -> Option { + T::records(ctx, |records| records.records.iter_mut().find(|(id, _)| *id == viewport).map(|(_, record)| f(record))) + } + /// Runs `f` on the record of every viewport that has one. pub(crate) fn each(ctx: &Context, mut f: impl FnMut(&mut T)) { T::records(ctx, |records| records.records.iter_mut().for_each(|(_, record)| f(record))); diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 894bbd4f6..015651a50 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -75,7 +75,7 @@ impl Rank { /// Whether a layer of this rank takes keys without a focus scope. Modal chrome takes none: Cancel and Enter stay /// with the modal under it. - const fn takes_keys(self) -> bool { + pub(crate) const fn takes_keys(self) -> bool { matches!(self, Rank::Popup | Rank::Modal { .. }) } @@ -152,6 +152,10 @@ pub struct OpenEntry { /// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui /// layer is shown for it. pub(crate) window: bool, + /// The entry stands in its opener's stack for a layer shown in a popup window of its own (with `window`): the + /// family, the anchor and the presses in the opener's window are judged here, and the popup's own stack holds the + /// layer, so the entry blocks nothing here. + pub(crate) popup: bool, /// The screen rect the layer is contained in: its scrim, placement, clip and input blocking stop at it. pub(crate) region: Option, /// The layer's place on its dialog stack (`stack_place`): the modal families of one stack stack in its order. @@ -178,6 +182,7 @@ impl OpenEntry { scoped: false, absorbs: false, window: false, + popup: false, region: None, place: None, dialog: None, @@ -187,7 +192,7 @@ impl OpenEntry { /// Whether the layer is a modal over its whole window: a modal contained in a region blocks only inside it, and the /// window's keys, commands and hits stay with the rest. pub(crate) fn blocks_window(&self) -> bool { - self.rank.is_modal() && self.region.is_none() + self.rank.is_modal() && self.region.is_none() && !self.popup } /// Whether the layer takes keys: the layers `top` can name. A layer with a focus scope takes keys whatever its rank. @@ -535,11 +540,38 @@ pub fn opening(ctx: &Context, id: Id) -> bool { /// not outlive it. The closes are carried: with no motion the layer's body hides in the same frame, so the owner of /// a popup in it runs again only when the layer reopens, and takes the close then. pub(crate) fn close_descendants(ctx: &Context, id: Id) { - for descendant in family(ctx, id).into_iter().filter(|member| *member != id) { + let mut members: Vec = family(ctx, id).into_vec(); + // A member shown in a popup window keeps the layers opened from inside it in that window's stack. + let mut at = 0; + while at < members.len() { + let member = members[at]; + for inner in family_in(ctx, crate::runtime::egui::viewports::viewport_id(member), member) { + if !members.contains(&inner) { + members.push(inner); + } + } + at += 1; + } + for descendant in members.into_iter().filter(|member| *member != id) { push_close(ctx, descendant, CloseReason::Requested, true); } } +/// `id` and everything opened from inside it, as `viewport`'s latest pass showed them (a popup window's: its pass of +/// this frame, or its last one once it is no longer shown); none for a viewport that has no stack. +fn family_in(ctx: &Context, viewport: ViewportId, id: Id) -> Vec { + let Some(last) = PerViewport::>::with_existing(ctx, viewport, |pass| pass.value().current.clone()) else { + return Vec::new(); + }; + let mut out: Vec = last.iter().filter(|entry| entry.id == id).map(|entry| entry.id).collect(); + for entry in &last { + if entry.parent.is_some_and(|parent| out.contains(&parent)) && !out.contains(&entry.id) { + out.push(entry.id); + } + } + out +} + /// Records that a primary press landed outside the layer `id`, its anchor and its family in this pass. pub(crate) fn note_pressed_outside(ctx: &Context, id: Id) { with_pass(ctx, |pass| pass.pressed_outside.push(id)); diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index dfe5a8d90..42409d37c 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -50,7 +50,7 @@ use shell::{refresh, window_info}; pub(crate) use shell::{set_chrome, set_os}; use spec::{AppState, chrome_of}; pub use spec::{WindowLevel, WindowSpec}; -pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request, unplaced}; +pub(crate) use viewport::{PopupOpen, ViewportOpen, close_popup, place_popup, show_popup, show_viewport, take_close_request, unplaced}; /// Seconds between writes of a changed placement store. const FLUSH_SECONDS: f64 = 1.0; @@ -95,6 +95,8 @@ pub(crate) struct Shared { /// The app's windows from the one focused longest ago to the one focused last: the stacking order of /// overlapping windows. stacking: Vec, + /// The windows that got a primary press, each with the root frame of the press, in this root frame and the last. + presses: Vec<(ViewportId, u64)>, } /// One viewport's window record. @@ -152,6 +154,8 @@ pub(crate) struct Record { seen: Option, /// The smallest inner size its caller asks for, as the window's builder carries it. min_size: Option, + /// For a popup window ([`show_popup`]): the window its layer was opened from, while the layer shows. + opener: Option, } /// The raise of the window holding an app-modal layer above the palettes the modal lowered. The raise goes out in the @@ -314,6 +318,15 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { if handed_off && tracked == Some(viewport) { shared(ctx, |shared| shared.tracked_move = None); } + let pressed = + input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })); + if pressed { + let frame = pass::root_frame_nr(ctx); + shared(ctx, |shared| { + shared.presses.retain(|(_, at)| at + 1 >= frame); + shared.presses.push((viewport, frame)); + }); + } released } @@ -370,6 +383,73 @@ fn opens_over(ctx: &Context, opener: ViewportId) -> bool { !covers } +/// Where the layers opened in a palette window show: in popup windows of their own, placed in desktop points. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PopupRoom { + /// The palette window's inner top-left corner in desktop points: the origin of its viewport's points. + pub origin: Pos2, + /// The room its layers may take, in its viewport's points: the work area of the monitor the window is on, or where + /// no monitor is listed, the area the app's windows other than popups span. + pub room: Rect, +} + +/// The room of the layers opened in the running viewport when it is a palette window (a dock window or a popup +/// window, both at [`WindowLevel::Palette`]) that opens OS windows ([`opens_over`]) where the platform places them: +/// every such layer shows in a popup window of its own. `None` in every other window, whose layers stay in it. +pub(crate) fn popup_room(ctx: &Context) -> Option { + let viewport = pass::current_viewport(ctx); + if !base_shell(ctx).window_positions() || !opens_over(ctx, viewport) { + return None; + } + let facts = PerViewport::::with_existing(ctx, viewport, |record| record.facts.filter(|_| record.level == Some(WindowLevel::Palette)))??; + let origin = facts.inner?.min; + let scale = host::scale_of(ctx, &facts).unwrap_or(1.0).max(f32::EPSILON); + let work = host::monitor_of(ctx, &facts).map(|monitor| { + let (pos, size) = monitor.work_px.unwrap_or((monitor.pos_px, monitor.size_px)); + let min = Pos2::new(pos[0] as f32, pos[1] as f32) / scale; + Rect::from_min_size(min, Vec2::new(size[0] as f32, size[1] as f32) / scale) + }); + // The popup windows themselves don't count: a popup's room never depends on where a popup stands. + let spanned = || { + let popup = |viewport: ViewportId| PerViewport::::with_existing(ctx, viewport, |record| record.opener.is_some()).unwrap_or(false); + viewports::reported(ctx) + .iter() + .filter(|(viewport, _)| !popup(*viewport)) + .filter_map(|(_, facts)| facts.inner) + .fold(Rect::NOTHING, Rect::union) + }; + let room = work.unwrap_or_else(spanned).translate(-origin.to_vec2()); + Some(PopupRoom { origin, room }) +} + +/// Whether a primary press landed, in this root frame (or in the last one, unless the popup window `popup` just +/// `appeared`), in a window of the app other than the running viewport (the popup's opener, whose own presses its +/// layer stack judges) and the popup window and the popup windows opened from it. +pub(crate) fn pressed_elsewhere(ctx: &Context, popup: ViewportId, appeared: bool) -> bool { + let opener = pass::current_viewport(ctx); + let frame = pass::root_frame_nr(ctx); + let presses = shared(ctx, |shared| shared.presses.clone()); + presses.into_iter().filter(|(_, at)| *at == frame || (!appeared && at + 1 == frame)).any(|(viewport, _)| { + if viewport == opener { + return false; + } + // A press in a popup window opened from the popup, at any depth, is inside its family. + let mut at = Some(viewport); + while let Some(window) = at { + if window == popup { + return false; + } + at = PerViewport::::with_existing(ctx, window, |record| record.opener).flatten(); + } + true + }) +} + +/// Whether no window of the app has focus, as the last frame's windows reported. +pub(crate) fn app_away(ctx: &Context) -> bool { + shared(ctx, |shared| shared.app.away) +} + /// 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/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 5e15aac8d..84ed27cde 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -421,7 +421,7 @@ pub(super) fn monitors(ctx: &Context) -> Vec { /// The monitor the top-left corner of a window with `facts` lies on. A corner is on a monitor when its pixel position /// at that monitor's scale is inside the monitor. -fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { +pub(super) fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { let corner = facts.outer.or(facts.inner)?.min; monitors(ctx).into_iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale)) } diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index cfecdfdd5..af9e889e6 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -85,6 +85,10 @@ pub struct WindowSpec { pub taskbar: bool, /// Whether the window opens hidden and appears once its first pass has been laid out and painted. pub shown_after_first_paint: bool, + /// Whether the window takes OS focus when it opens. + pub takes_focus: bool, + /// Whether pointer input passes through the window to the window below it. + pub passes_pointer: bool, } impl WindowSpec { @@ -94,6 +98,13 @@ impl WindowSpec { WindowSpec { kind: WindowKind::Tool, level: WindowLevel::Palette, taskbar: false, ..Self::dialog() } } + /// A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It + /// has no frame, no taskbar entry and a palette level, and appears once its first pass ran, at the size and place + /// its layer took in that pass. + pub fn popup() -> Self { + WindowSpec { chrome: Some(WindowChrome::Integrated), shown_after_first_paint: true, ..Self::tool() } + } + /// A document window with the installed decision's frame. pub fn document() -> Self { WindowSpec { kind: WindowKind::Document, ..Self::dialog() } @@ -108,6 +119,8 @@ impl WindowSpec { level: WindowLevel::Normal, taskbar: true, shown_after_first_paint: false, + takes_focus: true, + passes_pointer: false, } } @@ -157,6 +170,20 @@ impl WindowSpec { self } + /// Sets whether the window takes OS focus when it opens. + #[must_use] + pub fn takes_focus(mut self, takes_focus: bool) -> Self { + self.takes_focus = takes_focus; + self + } + + /// Sets whether pointer input passes through the window to the window below it (a tooltip's). + #[must_use] + pub fn passes_pointer(mut self, passes_pointer: bool) -> Self { + self.passes_pointer = passes_pointer; + self + } + /// Sets whether the window opens hidden and appears after its first paint, so a window that shows a capture or /// other content that must be ready does not flash an empty frame. #[must_use] diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index 844fd716f..cc337a081 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -95,6 +95,8 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im resizable: open.resizable, taskbar: spec.taskbar, hidden: PerViewport::::with(ctx, viewport, |record| record.awaiting_first_paint), + active: spec.takes_focus, + passes_pointer: spec.passes_pointer, app_id: &app, }; viewports::show_immediate(ctx, viewport, &opens, |ui| { @@ -133,6 +135,66 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im } } +/// What a layer shown in a popup window asks for ([`show_popup`]). +pub(crate) struct PopupOpen<'a> { + /// The layer's id; the popup's viewport derives from it. + pub id: Id, + /// How the window opens: a [`WindowSpec::popup`]. + pub spec: &'a WindowSpec, + /// The window's place in desktop points (outer top-left corner and inner size) when the layer's size is known + /// before its pass; otherwise the caller places it after the pass ([`place_popup`]). + pub rect: Option, +} + +/// Opens the popup window of a layer opened in the running viewport (its opener) and runs `body` in its pass. The +/// window is a viewport mount without a container: it opens at `open.rect` and follows it, and the opener gets the OS +/// focus back when it closes ([`close_popup`]). +pub(crate) fn show_popup(ctx: &Context, open: &PopupOpen<'_>, body: impl FnMut(&mut Ui)) { + let opener = crate::runtime::egui::pass::current_viewport(ctx); + PerViewport::::with(ctx, viewports::viewport_id(open.id), |record| record.opener = Some(opener)); + let mount = ViewportOpen { + id: open.id, + title: "", + size: open.rect.map(|rect| rect.size()), + follows_size: true, + save: None, + spec: open.spec, + limits: (None, None), + position: open.rect.map(|rect| rect.min), + resizable: false, + moved_by_app: false, + }; + show_viewport(ctx, &mount, body); +} + +/// Sends the popup window of layer `id` to `rect` (desktop points) where it is not there already: a layer whose size +/// its pass measured is placed once that pass ran. +pub(crate) fn place_popup(ctx: &Context, id: Id, rect: Rect) { + let viewport = viewports::viewport_id(id); + let known = PerViewport::::with(ctx, viewport, |record| record.known); + let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; + if known.is_none_or(|known| differs(rect.min - known.min)) { + act(ctx, viewport, WindowAction::SetOuterPosition(rect.min)); + } + if known.is_none_or(|known| differs(rect.size() - known.size())) { + act(ctx, viewport, WindowAction::SetInnerSize(rect.size())); + } + PerViewport::::with(ctx, viewport, |record| record.known = Some(rect)); +} + +/// The layer `id` is hidden: when it showed in a popup window that still has the OS focus, the window it was opened +/// from takes the focus back. Once per close; a layer that never showed in a popup does nothing. +pub(crate) fn close_popup(ctx: &Context, id: Id) { + let viewport = viewports::viewport_id(id); + let closed = PerViewport::::with_existing(ctx, viewport, |record| { + let focused = record.facts.is_some_and(|facts| facts.focus_reported); + record.opener.take().filter(|_| focused) + }); + if let Some(opener) = closed.flatten() { + act(ctx, opener, WindowAction::Focus); + } +} + /// Fits saved geometry to the current display layout once, before the viewport opens. fn saved_geometry(ctx: &Context, open: &ViewportOpen<'_>, opened: bool) -> Option<(Vec2, Option)> { let saved = saved_placement(ctx, open.save?)?.repaired()?; diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 4971991ec..6ab02daf3 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -205,7 +205,9 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// Whether Auto-Collapse Iconic Panels is on. #[prop] auto_collapse: bool, - /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. + /// The rect the dock may grow within, which bounds how wide its inner edge can make the column, and the rect its + /// flyouts open in. Unset, the flyouts take the room layers opened there have (`overlay::layer_room`): around a + /// palette window, the work area. #[prop] within: Rect, open: Bind<'a, Option

>, @@ -617,7 +619,7 @@ impl Component for IconicColumn<'_, P> { let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect); // The screen side the flyouts open on, mirrored in a right-to-left layout. let right = (opens == Side::End) != cx.flow.is_rtl(); - let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() }; + let within = if self.within.is_positive() { self.within } else { crate::contract::overlay::layer_room(&cx.core.ctx) }; // The column side of the bounds stops at the column, so a saved width wider than the room keeps that side. let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) }; if !bounds.is_positive() { diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 1e7cd429b..4ace220ce 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1290,7 +1290,10 @@ impl Pass<'_, P> { while let Some((command, _)) = body.take_command::() { commands.push(command); } - let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() }; + // An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an + // in-app window's stay in the float area. + let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() }; self.column(ui, body, &window.column, at); }); self.dock = area_dock; diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 1ed545c30..21860735c 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -4,6 +4,7 @@ use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; +use craft_ui::contract::Role; use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _, SizeLimits}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec}; @@ -11,11 +12,12 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::drag; +use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; -use craft_ui_test_kit::windows::Windows; +use craft_ui_test_kit::windows::{Out, Windows}; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -246,6 +248,8 @@ struct NativeDock { /// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the /// window only the limits a builder carries. builder: Option, + /// The palette's window: the first child window the dock opened. + palette: Option, } impl NativeDock { @@ -266,7 +270,7 @@ impl NativeDock { windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])); - let mut dock = NativeDock { windows, workspace, stepped, builder: None }; + let mut dock = NativeDock { windows, workspace, stepped, builder: None, palette: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -287,7 +291,11 @@ impl NativeDock { let out = self.windows.frame(root, child, |ui| { actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions); }); - for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) { + if self.palette.is_none() { + self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT); + } + let palette = self.palette; + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { let _ = kept.patch(builder); @@ -295,7 +303,7 @@ impl NativeDock { None => self.builder = Some(builder), } } - let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); + let commands = out.commands.into_iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command).collect(); (actions, commands) } } @@ -797,6 +805,203 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size"); } +/// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in. +#[derive(Default)] +struct BodyProbe(Vec); + +impl DockPanels for BodyProbe { + fn spec(&self, _: &u32) -> PanelSpec { + PanelSpec::new(PALETTE_TITLE) + } + + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + let ctx = ui.ctx(); + if *panel == 1 && !craft_ui::testing::is_measuring(ctx) { + self.0.push(ctx.viewport_id()); + } + } +} + +/// The scale of the display the collapsed palette trials run on: Windows at 125 %, where the issue was reported. +const COLLAPSED_SCALE: f32 = 1.25; + +/// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at. +fn collapsed_palette() -> (NativeDock, Rect) { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + let mut at = FLOAT_AT; + for _ in 0..4 { + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + } + (dock, at) +} + +/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window, +/// whose OS window follows its commands at `at`: the frame's output. +fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect, root: Vec, child: Vec) -> Out { + let workspace = &mut dock.workspace; + let out = dock.windows.frame(root, child, |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui); + }); + let palette = dock.palette; + let commands: Vec = + out.commands.iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command.clone()).collect(); + *at = placed_by(&commands, *at); + dock.windows.child_info(scaled(true, *at, COLLAPSED_SCALE)); + out +} + +/// The windows the frame showed other than the main window and the palette's: its popup windows. +fn popups(dock: &NativeDock, out: &Out) -> Vec { + out.builders.iter().map(|(viewport, _)| *viewport).filter(|viewport| *viewport != ViewportId::ROOT && Some(*viewport) != dock.palette).collect() +} + +/// The rect of `viewport`'s window in desktop points, as the window system reports it. +fn window_rect(dock: &NativeDock, viewport: ViewportId) -> Rect { + dock.windows.facts(viewport).inner_rect.expect("the window reports its rect") +} + +/// The rect, in its window's points, of the node of `tree` named `name` whose role is `role`. +fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option { + tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key)) +} + +/// The role and name of each named node of `tree`. +fn nodes(tree: &AccessTree) -> Vec<(Option, String)> { + let mut nodes: Vec<(Option, String)> = + tree.keys().into_iter().filter_map(|key| tree.name_of(key).map(|name| (tree.role_of(key), name.to_owned()))).collect(); + nodes.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + nodes +} + +/// The tree the frame's pass of `viewport` produced. +fn tree_of_viewport(out: &Out, viewport: ViewportId) -> &AccessTree { + &out.trees.iter().find(|(shown, _)| *shown == viewport).expect("the viewport ran a pass").1 +} + +/// Opens the flyout of the collapsed palette's panel by a click on its icon; returns the flyout's popup window. +fn open_flyout(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect) -> ViewportId { + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let icon = node_rect(tree_of_viewport(&out, palette), PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon").center(); + for events in [vec![moved(icon)], vec![press(icon)], vec![release(icon)]] { + collapsed_frame(dock, panels, at, vec![], events); + } + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let opened = popups(dock, &out); + assert_eq!(opened.len(), 1, "the click opens one popup window: {opened:?}"); + opened[0] +} + +/// A click on the icon of a native palette collapsed to icons opens the panel's flyout in a popup OS window of its +/// own, beside the strip against its side away from the edge it keeps to, in desktop points: a palette-level window +/// with no taskbar entry that takes the focus. The flyout's body runs in the popup's pass only, as often in each +/// frame, never in the palette's. +#[trial] +fn a_click_on_an_icon_of_a_collapsed_native_palette_opens_its_flyout_in_an_os_window_beside_it() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let palette = dock.palette.expect("the palette's window opened"); + let strip = nodes(tree_of_viewport(&collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]), palette)); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let flyout = window_rect(&dock, popup); + let end = at.max.x >= FLOAT_AT.max.x - 1.0; + let outer = if end { (flyout.max.x - at.min.x).abs() } else { (flyout.min.x - at.max.x).abs() }; + assert!(outer <= 0.5, "the flyout stands against the strip's side away from its edge: {flyout:?} beside {at:?}"); + assert!(flyout.min.y >= at.min.y - 0.5 && flyout.min.y < at.max.y, "the flyout's top is level with the strip: {flyout:?}, {at:?}"); + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == popup).expect("the popup shows").1; + assert_eq!(builder.window_level, Some(egui::WindowLevel::AlwaysOnTop), "the popup stands as a palette of the active app"); + assert_eq!(builder.taskbar, Some(false), "the popup has no taskbar entry"); + assert_ne!(builder.active, Some(false), "the flyout takes the focus"); + assert_eq!(nodes(tree_of_viewport(&out, palette)), strip, "the palette's window shows none of the flyout"); + assert!(!tree_of_viewport(&out, popup).keys().is_empty(), "the popup window shows the flyout"); + let runs = |probe: &mut BodyProbe, dock: &mut NativeDock, at: &mut Rect| { + probe.0.clear(); + collapsed_frame(dock, probe, at, vec![], vec![]); + std::mem::take(&mut probe.0) + }; + let (first, second) = (runs(&mut probe, &mut dock, &mut at), runs(&mut probe, &mut dock, &mut at)); + assert!(!first.is_empty() && first.iter().all(|viewport| *viewport == popup), "the body runs in the popup's pass: {first:?}"); + assert_eq!(first.len(), second.len(), "the body runs as often in each frame"); +} + +/// The pointer rests on the double arrow of a collapsed native palette past the tooltip delay: the frame that follows. +fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) { + let end = at.max.x >= FLOAT_AT.max.x - 1.0 && at.min.x > FLOAT_AT.min.x + 1.0; + let arrow = Pos2::new(if end { at.width() - 4.0 } else { 4.0 }, 4.0); + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![moved(arrow)]); + // The tooltip shows after its delay, at 60 frames a second. + let frames = (craft_ui::contract::tooltip::DELAY * 60.0).ceil() as usize + 2; + for _ in 0..frames { + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + } + let out = collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let name = tree_of_viewport(&out, palette).keys().into_iter().find_map(|key| { + let tree = tree_of_viewport(&out, palette); + tree.name_of(key) + .filter(|name| name.starts_with("Expand")) + .filter(|_| tree.role_of(key) == Some(Role::BUTTON)) + .and_then(|_| tree.bounds_of(key)) + }); + let arrow_rect = name.expect("the title row shows the double arrow"); + (out, arrow_rect) +} + +/// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the +/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it. +#[trial] +fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { + let (mut dock, mut at) = collapsed_palette(); + let (out, _) = hovered_arrow(&mut dock, &mut at); + let palette = dock.palette.expect("the palette's window opened"); + let tree = tree_of_viewport(&out, palette); + let window = Rect::from_min_size(Pos2::ZERO, at.size()); + let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon"); + assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}"); + assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip"); +} + +/// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop +/// points, on one line: the window takes no focus and lets the pointer through to the palette. +#[trial] +fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() { + let (mut dock, mut at) = collapsed_palette(); + let (out, arrow) = hovered_arrow(&mut dock, &mut at); + let shown = popups(&dock, &out); + let tip = shown + .iter() + .copied() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::TOOLTIP).is_empty()) + .expect("the tooltip shows in a popup window"); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == tip).expect("the popup shows").1; + assert_eq!(builder.active, Some(false), "the tooltip's window takes no focus"); + assert_eq!(builder.mouse_passthrough, Some(true), "the pointer passes through the tooltip's window"); + let rect = window_rect(&dock, tip); + assert!(rect.min.y >= at.min.y + arrow.max.y - 0.5, "the tooltip stands below the arrow: {rect:?}, arrow {arrow:?} in {at:?}"); + assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}"); +} + +/// A press in the main window closes the flyout a collapsed native palette opened in a popup window. +#[trial] +fn a_press_in_the_main_window_closes_a_native_palettes_flyout() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let over = OVER_GROUP - MAIN_AT.min.to_vec2(); + for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] { + collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]); + } + // The flyout fades out, then its window closes. + let closed = (0..60).any(|_| { + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + !popups(&dock, &out).contains(&popup) + }); + assert!(closed, "the flyout's window closed"); +} + /// Palettes no smaller than `PALETTE_LEAST`. struct Least; diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index 300940877..01fd11af2 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -22,8 +22,11 @@ thread_local! { static CHILD_EVENTS: RefCell> = const { RefCell::new(Vec::new()) }; /// The files hovering over and dropped on the child's window in the next child pass. static CHILD_FILES: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; - /// The window facts every child pass reports. + /// The window facts every child opened from the root reports. static CHILD_INFO: RefCell = RefCell::new(ViewportInfo::default()); + /// The window facts of each child opened from another child (a popup window): it opens where its builder puts it + /// and follows its own commands. + static OWN_INFO: RefCell> = const { RefCell::new(Vec::new()) }; /// The window facts the root reports. static ROOT_INFO: RefCell = RefCell::new(ViewportInfo::default()); /// The children whose windows are open: those that ran a pass and are still shown. Like an integration, every pass's @@ -43,14 +46,30 @@ thread_local! { /// Seconds between two frames. const FRAME_SECONDS: f64 = 1.0 / 60.0; +/// Runs `f` on the facts `id` reports: its own for a child opened from another child, else the ones every child +/// opened from the root shares. +fn with_facts(id: ViewportId, f: impl FnOnce(&mut ViewportInfo) -> R) -> R { + let own = OWN_INFO.with(|own| { + let mut own = own.borrow_mut(); + own.iter().position(|(held, _)| *held == id).map(|at| own.swap_remove(at)) + }); + match own { + Some((_, mut info)) => { + let out = f(&mut info); + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + out + } + None => CHILD_INFO.with(|info| f(&mut info.borrow_mut())), + } +} + /// The window system's answer to a move or a resize: the children's facts follow the commands (the fake window -/// has no decoration, so its inner and outer rects are one). Every child shares one set of facts. +/// has no decoration, so its inner and outer rects are one). The children opened from the root share one set of facts. fn os_applies(id: ViewportId, command: &ViewportCommand) { if id == ViewportId::ROOT { return; } - CHILD_INFO.with(|info| { - let mut info = info.borrow_mut(); + with_facts(id, |info| { let current = info.outer_rect.or(info.inner_rect).unwrap_or_else(|| Rect::from_min_size(Pos2::ZERO, CHILD_SIZE)); let moved = match command { ViewportCommand::OuterPosition(pos) => Rect::from_min_size(*pos, current.size()), @@ -75,26 +94,40 @@ fn keep_commands(output: &FullOutput) { } /// The window facts of every window the integration knows: the root and the children that ran, each with the -/// facts the trial gave it. -fn all_viewports(child: ViewportInfo) -> egui::ViewportIdMap { +/// facts the trial gave it or its own. +fn all_viewports() -> egui::ViewportIdMap { let mut all = egui::ViewportIdMap::default(); all.insert(ViewportId::ROOT, ROOT_INFO.with(|info| info.borrow().clone())); CHILDREN.with(|children| { for id in children.borrow().iter() { - all.insert(*id, child.clone()); + all.insert(*id, with_facts(*id, |info| info.clone())); } }); all } -/// Patches the window of `id` with `builder`, as an integration does before the child's pass: the fields that -/// changed go to the window as commands. The first builder opens the window. -fn patch_window(id: ViewportId, builder: ViewportBuilder) { +/// Patches the window of `ids.this` with `builder`, as an integration does before the child's pass: the fields that +/// changed go to the window as commands. The first builder opens the window; a window opened from another child opens +/// where the builder puts it, with focus unless the builder opens it inactive. +fn patch_window(ids: egui::ViewportIdPair, builder: ViewportBuilder) { + let id = ids.this; let commands = BUILDERS.with(|kept| { let mut kept = kept.borrow_mut(); match kept.iter_mut().find(|(held, _)| *held == id) { Some((_, window)) => window.patch(builder).0, None => { + if ids.parent != ViewportId::ROOT { + let rect = Rect::from_min_size(builder.position.unwrap_or(Pos2::ZERO), builder.inner_size.unwrap_or(CHILD_SIZE)); + let scale = CHILD_INFO.with(|info| info.borrow().native_pixels_per_point); + let info = ViewportInfo { + focused: Some(builder.active.unwrap_or(true)), + inner_rect: Some(rect), + outer_rect: Some(rect), + native_pixels_per_point: scale, + ..ViewportInfo::default() + }; + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + } kept.push((id, builder)); Vec::new() } @@ -129,12 +162,12 @@ impl egui::DroppedFile for DroppedPath { } fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { - patch_window(viewport.ids.this, viewport.builder); + patch_window(viewport.ids, viewport.builder); let mut callback = viewport.viewport_ui_cb; let events = CHILD_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut())); let (hovered_files, dropped) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut())); let dropped_files = dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); - let mut info = CHILD_INFO.with(|info| info.borrow().clone()); + let mut info = with_facts(viewport.ids.this, |info| info.clone()); info.parent = Some(viewport.ids.parent); let mut input = RawInput { viewport_id: viewport.ids.this, @@ -152,7 +185,8 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { children.push(viewport.ids.this); } }); - input.viewports = all_viewports(info); + input.viewports = all_viewports(); + input.viewports.insert(viewport.ids.this, info); let mut output = ctx.run_ui(input, |ui| callback(ui)); output.textures_delta.clear(); keep_commands(&output); @@ -205,6 +239,7 @@ impl Windows { CHILD_EVENTS.with(|events| events.borrow_mut().clear()); CHILD_FILES.with(|files| *files.borrow_mut() = Default::default()); CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default()); + OWN_INFO.with(|own| own.borrow_mut().clear()); CHILDREN.with(|children| children.borrow_mut().clear()); COMMANDS.with(|kept| kept.borrow_mut().clear()); BUILDERS.with(|kept| kept.borrow_mut().clear()); @@ -217,6 +252,12 @@ impl Windows { CHILD_INFO.with(|kept| *kept.borrow_mut() = info); } + /// The window facts `viewport` reports: its own for a child opened from another child, else those + /// [`child_info`](Self::child_info) gave. + pub fn facts(&self, viewport: ViewportId) -> ViewportInfo { + with_facts(viewport, |info| info.clone()) + } + /// The window facts the root viewport reports from now on. pub fn root_info(&self, info: ViewportInfo) { *self.root_info.borrow_mut() = info; @@ -258,11 +299,15 @@ impl Windows { now.get() })); ROOT_INFO.with(|info| *info.borrow_mut() = self.root_info.borrow().clone()); - input.viewports = all_viewports(CHILD_INFO.with(|info| info.borrow().clone())); + input.viewports = all_viewports(); let mut output = self.ctx.run_ui(input, ui); // A child the frame no longer shows has closed: like an integration, the kit drops its window, so later inputs - // stop listing it (and what its last pass left, such as a modal, stops counting). - CHILDREN.with(|children| children.borrow_mut().retain(|id| output.viewport_output.contains_key(id))); + // stop listing it (and what its last pass left, such as a modal, stops counting), and a window opened again + // opens anew. + let shown = |id: &ViewportId| output.viewport_output.contains_key(id); + CHILDREN.with(|children| children.borrow_mut().retain(shown)); + OWN_INFO.with(|own| own.borrow_mut().retain(|(id, _)| shown(id))); + BUILDERS.with(|kept| kept.borrow_mut().retain(|(id, _)| shown(id))); output.textures_delta.clear(); keep_commands(&output); keep_tree(&mut output, ViewportId::ROOT);