diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 8429d5025..179ff8a17 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -60,7 +60,9 @@ impl ActionsSettings { /// The Actions panel's persisted section: Button Mode and the collapsed sets. /// Selection and expansion are not persisted. -#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ActionsSettings { @@ -72,7 +74,7 @@ pub struct ActionsSettings { /// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at /// a time) and the list's key. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ActionSelection { /// The set header of this name. @@ -89,7 +91,7 @@ pub enum ActionSelection { /// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder) /// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the /// app clears `selected` (the panel cannot tell which rows the delete removed). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ActionsPanelState { /// The persisted section. diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 22a624530..1326059f6 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,19 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +141,19 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +203,9 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index fbca9ff8a..2f428b0f3 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -398,7 +398,7 @@ struct Scene { /// the selected anchors or the picked handle (⌥ alone); Delete and Backspace report /// [`delete`](BezierOutput::delete) under the tools that delete anchors (Direct, Convert, Curvature, Add Anchor, /// Delete Anchor), Insert [`insert`](BezierOutput::insert) halfway along the segment leaving the picked anchor; -/// Escape deselects. +/// Escape leaves the selection and goes to the window. /// - The anchor tools ([`BezierTool::AddAnchor`], [`BezierTool::DeleteAnchor`], [`BezierTool::AutoAddDelete`]) and /// [`BezierTool::Curvature`] take only a press that hits what they edit, and draw the [`HitMark`] of what a press /// would take under the pointer. [`segment_mark`](Self::segment_mark), [`anchors`](Self::anchors) and @@ -1121,9 +1121,6 @@ impl<'a> BezierOverlay<'a> { self.report.delete = Some(AnchorDelete::new(path, self.selection.anchors.clone(), true)); } } - if keyed && cx.gesture().is_none() && cx.intents().take(Intent::Cancel) && *self.selection != PathSelection::default() { - self.report.select = Some(PathSelection::default()); - } } /// The path ⌘A selects: the selection's, else the picked part's, else the only one. diff --git a/crates/draw/src/ui/pen/bezier/tools.rs b/crates/draw/src/ui/pen/bezier/tools.rs index 6297be197..e2753753c 100644 --- a/crates/draw/src/ui/pen/bezier/tools.rs +++ b/crates/draw/src/ui/pen/bezier/tools.rs @@ -57,7 +57,7 @@ impl BezierTool { matches!(self, BezierTool::AddAnchor | BezierTool::DeleteAnchor | BezierTool::AutoAddDelete) } - /// Whether the tool has the arrow, ⌘A and Esc keys: Direct, Convert and Curvature. Add and Delete have Delete + /// Whether the tool has the arrow and ⌘A keys: Direct, Convert and Curvature. Add and Delete have Delete /// only, Auto Add/Delete none. pub(super) fn keyed(self) -> bool { matches!(self, BezierTool::Direct | BezierTool::Convert | BezierTool::Curvature) diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index b7fe52b2a..57f21a504 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -421,7 +421,7 @@ fn hit_test_matches_the_overlays_press_priority() { // ---- the anchor tools and the Curvature tool ---- -// Arrows, select all and Escape belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none. +// Arrows and select all belong to Direct, Convert and Curvature; Add, Delete and Auto Add/Delete have none. #[trial] fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_no_part() { @@ -1202,6 +1202,23 @@ fn arrow_keys_nudge_the_selected_anchors_and_shift_nudges_farther() { assert_eq!(h.state.borrow().changes.len(), 2, "one edit per press"); } +// Escape on a focused anchor leaves the anchor selection and the targeted path under Direct, Convert and Curvature; it +// goes on to the window. A key still reaches the overlay afterwards. +#[trial] +fn escape_on_a_focused_anchor_keeps_the_selection() { + for tool in [BezierTool::Direct, BezierTool::Convert, BezierTool::Curvature] { + let mut h = two_paths(); + h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)]))); + h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let before = h.state.borrow().selection.clone(); + assert!(before != PathSelection::default(), "{tool:?}: an anchor is selected"); + h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle(); + assert_eq!(h.state.borrow().selection, before, "{tool:?}: Escape keeps the selection"); + h.fixture.key(egui::Key::ArrowRight, egui::Modifiers::NONE).settle(); + assert!(h.last_change().is_some(), "{tool:?}: the overlay still has the keys"); + } +} + // A press belongs to the tool it began under: switching the host's tool in the middle of a drag leaves the drag its // own, and it commits as that tool's edit. #[trial] diff --git a/crates/imaging/src/ui/histogram/data.rs b/crates/imaging/src/ui/histogram/data.rs index 6588b6aa6..a8521da70 100644 --- a/crates/imaging/src/ui/histogram/data.rs +++ b/crates/imaging/src/ui/histogram/data.rs @@ -207,7 +207,7 @@ impl HistogramData { } /// A range of whole levels (bin positions) a plot has selected, both ends included. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct LevelRange { /// The first level. diff --git a/crates/imaging/src/ui/scopes/panel/settings.rs b/crates/imaging/src/ui/scopes/panel/settings.rs index 6d14f3fb4..a61305622 100644 --- a/crates/imaging/src/ui/scopes/panel/settings.rs +++ b/crates/imaging/src/ui/scopes/panel/settings.rs @@ -4,7 +4,19 @@ use crate::ui::histogram::LevelRange; use crate::ui::scopes::clipping::{ClippingDiagnostic, ClippingMode, ClippingWarnings}; /// The panel's view (its menu's Compact, Expanded and All Channels View). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ScopeView { @@ -20,7 +32,7 @@ pub enum ScopeView { /// The scope panel's persisted section: the app keeps it with its preferences (PhotoCraft's /// `histogramPanel` and `filter.cameraRaw.scope`). Unknown fields are ignored, missing ones take /// their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ScopeSettings { @@ -93,7 +105,7 @@ impl ScopeSettings { /// What the panel keeps for the app between passes: the persisted settings and the selected /// level range (not persisted). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ScopePanelState { /// The persisted section. diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index 74e144b32..8709aba62 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -31,9 +31,10 @@ pub(in crate::ui::panel) struct DisplayRow { /// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A /// change of any of them builds the rows again; nothing else does. #[derive(MemoProps)] -pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> { +pub(in crate::ui::panel) struct RowsKey<'a, Id> { pub(in crate::ui::panel) tree: Revision, pub(in crate::ui::panel) filter: &'a LayerFilter, + #[memo_props(hash = "tree ids are plain model ids (LayerTree::Id: PlainData); Hash covers them")] pub(in crate::ui::panel) opened: &'a [Id], } diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index d8f10d5cd..b73560a0e 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -11,7 +11,7 @@ use std::hash::Hash; use craft_behavior::IconId; use craft_keymap::Mods; use craft_theme::LabelColor; -use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove}; +use craft_ui::contract::{Entry, PlainData, ReorderMove}; use craft_ui::list::ThumbTarget; use super::filter::{EffectKind, LayerFilter, SmartSource}; @@ -22,6 +22,9 @@ use super::panel::MenuTarget; /// the panel derives from the tree. /// /// ```ignore +/// #[derive(Clone, PartialEq, Eq, Hash, Debug, PlainData)] +/// struct LayerId(u64); +/// /// #[derive(PlainData)] /// struct PhotoLayers { layers: LayerIndex, open: HashSet } /// impl LayerTree for PhotoLayers { @@ -36,9 +39,10 @@ use super::panel::MenuTarget; /// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the /// tracked revision, the filter or a reveal's opens changed. pub trait LayerTree: PlainData { - /// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the - /// display order when a reveal opens groups. - type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static; + /// The app's layer id: the key of a row, of its thumbnails and of every event. It is plain model data + /// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order + /// when a reveal opens groups. + type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the /// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text. diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index 1064277b1..766015568 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -97,10 +97,10 @@ pub use theme::{ pub use token_group::{GroupValues, TokenGroup}; pub use tokens::{ AccentColors, BarSizes, CaptionColors, ColorToken, ColorTokens, ControlSizes, DataColors, DialogSizes, DockColumnSizes, Edge, EdgeColors, - ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LineColors, Motion, MotionTokens, - OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StateColors, Status, - StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, TypeTokens, WellShape, - WindowSizes, + ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LetterCase, LineColors, Motion, + MotionTokens, OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, + StateColors, Status, StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, + TypeTokens, WellShape, WindowSizes, }; pub use values::ColorSource; pub use variant::{CustomVariant, Emphasis, RadiusStep, Variant, VariantLook}; diff --git a/crates/theme/src/tokens/type_motion.rs b/crates/theme/src/tokens/type_motion.rs index c83a5f79a..c03244af8 100644 --- a/crates/theme/src/tokens/type_motion.rs +++ b/crates/theme/src/tokens/type_motion.rs @@ -30,6 +30,8 @@ pub struct TypeStyle { pub enum TypeRole { /// Small print, badges. Caption, + /// A heading over a group of fields or cards: the caption's size and font, set in capitals. + SectionCaption, /// Control labels. Label, /// Body text. @@ -48,6 +50,26 @@ pub enum TypeRole { Display, } +/// How a type role sets its letters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum LetterCase { + /// As written. + #[default] + AsWritten, + /// In capitals; the stored text stays as written. + Upper, +} + +impl TypeRole { + /// How the role sets its letters. + pub fn letter_case(self) -> LetterCase { + match self { + TypeRole::SectionCaption => LetterCase::Upper, + _ => LetterCase::AsWritten, + } + } +} + /// Every type role. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct TypeTokens { @@ -75,7 +97,7 @@ impl TypeTokens { /// The style of `role`. pub fn get(&self, role: TypeRole) -> TypeStyle { match role { - TypeRole::Caption => self.caption, + TypeRole::Caption | TypeRole::SectionCaption => self.caption, TypeRole::Label => self.label, TypeRole::Body => self.body, TypeRole::BodyStrong => self.body_strong, diff --git a/crates/ui-canvas/src/canvas_controls/task_bar.rs b/crates/ui-canvas/src/canvas_controls/task_bar.rs index d76711327..1e45fbeb6 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar.rs @@ -20,7 +20,7 @@ use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; use craft_behavior::kurbo::Point; use craft_behavior::overlay::{Align, Side}; -use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense}; +use craft_behavior::{EditEvent, GesturePhase, IconId, Metrics, Mixed, Sense}; use egui::{Pos2, Rect, Response, Ui}; use std::sync::Arc; @@ -245,8 +245,7 @@ impl<'a> TaskBar<'a> { let rect = shown.output.response.rect; let pick = menu.pick; if shows && kind == TaskBarKind::Task { - let moved = shown.output.moved.filter(|moved| moved.min != rect.min); - let next = settled(held, rect, area, moved, pick); + let next = settled(held, rect, area, shown.output.moved, pick); if next != held { let word = match pick { Some(MenuPick::Reset) => &words.task_bar_reset, @@ -303,8 +302,8 @@ fn layer_overlay(held: &TaskBarPlace, hang: Option, area: Rect, side: Side } } -/// The place after a pass that showed the bar at `shown`. A move (`moved`, a rect other than `shown`) keeps the bar -/// where it was dropped; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A +/// The place after a pass that showed the bar at `shown`. A move that ended (`moved`, where it was dropped) keeps the +/// bar there; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A /// non-finite place is cleared. With no move and no pick, the place stays unchanged; the overlay host keeps the layer /// inside the area. fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option, pick: Option) -> TaskBarPlace { @@ -333,7 +332,7 @@ pub struct TaskBarLayerStyle { metrics: Metrics, } -/// What the task bar's layer reports: its response, the last move of this pass and why it closed. +/// What the task bar's layer reports: its response, the move that ended in this pass and why it closed. #[derive(Debug)] struct TaskBarLayerOutput { response: Response, @@ -361,6 +360,8 @@ struct TaskBarLayer { props: ContainerProps, /// Open while the bar shows; the caller shows the bar again each pass it wants it. open: Bind<'static, bool>, + /// Where a move by the grip ended in this pass. The layer host shows the bar under the pointer while the move + /// runs, so the place is written once, on the drop. moved: Option, /// Why the layer closed, once it has. closed: Option, @@ -411,7 +412,7 @@ impl Container for TaskBarLayer { } fn placement_changed(&mut self, change: &PlacementChange) { - if change.kind == PlacementKind::Move { + if change.kind == PlacementKind::Move && change.phase == GesturePhase::Commit { self.moved = Some(change.rect); } } diff --git a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs index 0fa97a336..417e2ab86 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs @@ -6,6 +6,7 @@ use craft_ui::buttons::Button; use craft_ui::canvas_controls::{TaskBar, TaskBarDismiss, TaskBarPlace}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::testing::canvas_story::on_canvas; +use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Vec2}; use std::cell::RefCell; @@ -272,3 +273,39 @@ fn the_grip_sits_on_the_members_line() { let dropped = seen(&scene); assert!((dropped.rect.min - (bar.min + by)).length() < 2.0 * SLACK, "a drag on the grip moves the bar: {:?}", dropped.rect); } + +/// A drag of the grip moves the bar under the pointer in the frame of each step, in one pass, and writes its place +/// once, on the drop: one edit for the whole move. +#[trial] +fn a_dragged_task_bar_stands_under_the_pointer_in_each_frame_and_writes_its_place_on_the_drop() { + let scene = Rc::new(RefCell::new(Scene { + anchor: frame(DocVec::ZERO), + place: TaskBarPlace::default(), + bounds: Rect::NOTHING, + area: Rect::NOTHING, + rect: Rect::NOTHING, + })); + let mut fixture = fixture(&scene); + fixture.settle(); + let start = seen(&scene).rect; + let from = fixture.by_label("Move bar").expect("the grip is named").center(); + fixture.frame(vec![moved(from)]); + fixture.frame(vec![press(from)]); + let step = Vec2::new(-30.0, 15.0); + for n in 1..=4 { + let to = start.min + step * n as f32; + fixture.frame(vec![moved(from + step * n as f32)]); + let now = seen(&scene); + assert!((now.rect.min - to).length() < SLACK, "step {n}: the bar stands under the pointer in its frame: {:?}, wanted {to:?}", now.rect); + assert_eq!(fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(now.place, TaskBarPlace::default(), "step {n}: the place is not written while the drag runs"); + } + let dropped_at = start.min + step * 4.0; + fixture.frame(vec![release(from + step * 4.0)]); + let dropped = seen(&scene); + assert!((dropped.rect.min - dropped_at).length() < SLACK, "the bar stays where it was dropped: {:?}", dropped.rect); + let at = dropped.place.at.map(|at| dropped.area.min + Vec2::from(at)); + assert!(at.is_some_and(|at| (at - dropped_at).length() < SLACK), "the drop writes the place: {:?}", dropped.place); + fixture.settle(); + assert!((seen(&scene).rect.min - dropped_at).length() < SLACK, "the written place keeps the bar there: {:?}", seen(&scene).rect); +} diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 6533a5127..e03be55cb 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> { /// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent /// flow showed it this run: its own measuring run shows its content in a flow of its own. in_column: bool, + /// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it + /// this run: a rule above its header is not drawn, so two rules never follow each other. + after_rule: bool, /// A bottom-anchored region is following the end of its content. follows_end: bool, } @@ -242,6 +245,7 @@ impl<'b> BodyHooks<'b> { held: false, across: false, in_column: true, + after_rule: false, follows_end: false, } } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 0f9f07641..70f69657c 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -5,7 +5,7 @@ use super::open::open_now; use super::placement::{Placement, measure_layer, overlay_of, shown_placement}; use super::regions::{ LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under, - gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, + gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, }; use super::reorder::REORDER_BAND; use super::scroll::{ @@ -68,7 +68,9 @@ impl ShapeHooks for BodyHooks<'_> { } fn host(&mut self, comp: &C, at: crate::contract::run::HostCx<'_>) -> Box { - let mounted = crate::contract::mount::host(comp.props(Internal::new()), &at, self.open, at.label); + let props = comp.props(Internal::new()); + let moving = overlay_of(props).filter(|overlay| overlay.movable).and_then(|_| self.mode.running_move(at.ui.ctx(), at.id)); + let mounted = crate::contract::mount::host(props, &at, self.open, at.label, moving); if mounted.exiting { self.exiting = true; self.open = true; @@ -157,7 +159,8 @@ impl ShapeHooks for BodyHooks<'_> { self.region_gap = gap_of(&env.tokens, Gap::Tight); self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(props, &env.tokens); - self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx)); + self.after_rule = layout::flow_start(&ctx, env) == Some(true); + self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx), self.after_rule); self.least_width = least_of(&env.tokens, props.least_width); let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx); if !matches!(props.mount, Mount::Inline | Mount::Pane(_)) @@ -185,7 +188,7 @@ impl ShapeHooks for BodyHooks<'_> { 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); - shown_placement(&ctx, id, save.as_ref(), overlay, screen, env.tokens.space.inset.screen) + shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) }); // A layer the user sized takes that size, at its saved position or where its anchor places it. placement.size.is_some() @@ -1305,12 +1308,12 @@ impl BodyHooks<'_> { && env.values.get::() == label::LabelScheme::Inspector; let (room, content_column, scroll, beside, label_width) = (plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x); - let first_body = plan.first.1; + let (first_body, layout_id) = (plan.first.1, plan.layout_id); // The slot of a footer the body places takes the size the measuring run's footer took. let footer_slot = footer_in_body(props) .then(|| FooterSlotOf { owner: id, size: if real { self.measured_footer } else { self.footer_size.unwrap_or(Vec2::ZERO) } }); plan.body_env = Some(plan.line_env.derive_local(|scoped| { - self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside }); + self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside, layout: layout_id }); scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held); scoped.cell_fills = cell_fills; if footer_slot.is_some() { @@ -1569,6 +1572,12 @@ impl BodyHooks<'_> { /// size counts the label column. fn after_body(&mut self, ui: &mut Ui, env: &Env, plan: &mut BodyPlan<'_>) { let (props, ctx, real) = (plan.props, &plan.ctx, plan.real); + if let Some(bracket) = props.bracket { + let took = layout::take_bracket(ctx, plan.layout_id); + if let (true, crate::contract::Bracket::Linked, Some(took)) = (real, bracket, took) { + paint_bracket(ui, env, &took, plan.rtl); + } + } // A measuring run decided the label before the control reported its minimum width: it decides again // from the minimum this run recorded, so the extent it measures is the one the real run lays out. if let (false, Some(input)) = (real, plan.label_input.as_mut()) { @@ -1580,6 +1589,12 @@ impl BodyHooks<'_> { plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl); } if let Some(size) = &mut self.body_size { + // A labelled row of a bracketed row reports where its control lies: the bracket runs from it. + if let (Some(row), Some(_)) = (env.bracket, props.label.as_ref()) { + let body = plan.body_rect; + let left = if plan.rtl { body.max.x - size.x } else { body.min.x }; + layout::report_bracket_control(ctx, row, Rect::from_min_size(egui::pos2(left, body.min.y), *size), plan.rtl); + } let label_extra = plan.label_extra; // A body beside its label in a content-sized column of rows reports how far it reaches past the label // column, so that column's container measures its rows at the widest label. @@ -1801,7 +1816,8 @@ impl BodyHooks<'_> { self.region_gap = gap_of(&at.env.tokens, Gap::Tight); self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(&props, &at.env.tokens); - self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx())); + self.after_rule = layout::flow_start(at.ui.ctx(), at.env) == Some(true); + self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()), self.after_rule); self.least_width = least_of(&at.env.tokens, props.least_width); self.room = match at.width { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 660e5ebc8..8669cc8f0 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -19,6 +19,8 @@ pub(super) struct BodyScope { pub(super) label_width: f32, /// The width the regions beside the body take on its line (`Regions::beside`). pub(super) beside: f32, + /// The id the body's layout runs under (`BodyPlan::layout_id`). + pub(super) layout: Id, } /// The surface a container paints under its regions: its props' surface, else its style's in its current state. @@ -96,10 +98,23 @@ impl BodyHooks<'_> { /// What the body inherits on top of the line's env: arena, transform, the room it is offered and its scroll axes. pub(super) fn scope_body(&self, scoped: &mut Scoped, props: &ContainerProps, id: Id, body: BodyScope) { - let BodyScope { room, real, content_column, scroll, label_width, beside } = body; + let BodyScope { room, real, content_column, scroll, label_width, beside, layout } = body; if props.arena { scoped.arena = Some(ArenaId::new(id)); } + // The body's flow starts after a rule when the container draws one under its header, or when the container + // draws nothing of its own (no header, surface or mount) and itself started after a rule. + scoped.after_rule = props.header.is_some_and(|header| header.rule && !header.inline) + || (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule); + scoped.flow_body = None; + scoped.column_row = + self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); + // A bracketed row's rows report to it up to the first labelled container, whose body is its own control. + if props.bracket.is_some() { + scoped.bracket = Some(layout); + } else if props.label.is_some() { + scoped.bracket = None; + } scoped.transform = props.transform; scoped.content_column = content_column; scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack); diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index 4f885be80..311fe446b 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -28,8 +28,7 @@ impl Placement { /// The placement the caller of `overlay` gives, when it places the layer. fn given(overlay: &crate::contract::Overlay) -> Option { - let kept = |rect: Rect| overlay.bounds.map_or(rect, |bounds| super::window::keep_inside(rect, bounds)); - overlay.placed.map(|rect| Placement::at(kept(rect))).or_else(|| overlay.placed_at.map(Placement::at_pos)) + overlay.placed.map(|rect| Placement::at(super::window::kept_in(rect, overlay.bounds))).or_else(|| overlay.placed_at.map(Placement::at_pos)) } /// The rect it names, taking the position and size it lacks from `rect`. @@ -46,7 +45,9 @@ pub(crate) fn placement_id(id: Id) -> Id { /// is `placed` has the caller's rect instead: the slot reads it and writes nothing, since the caller owns the /// placement and learns of the user's changes from `PlacementChange` reports. A layer hung from its anchor keeps only /// its size, whether or not the user can move it: each opening places it from its anchor at that size, and a caller -/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. +/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. While the +/// user drags the move band, the layer host shows the layer at the drag's rect whatever the slot holds +/// ([`shown_placement`]), so a caller places it from the drag's `Commit` alone. pub(super) struct PlacementSlot<'s> { stage: &'s mut MemoryStage, id: Id, @@ -96,7 +97,28 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement { /// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on /// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with /// no position places an anchored layer from its anchor at that size. +/// +/// While a drag of the layer's move band runs, `moving` is the rect it puts the layer at in this pass +/// (`WindowMode::running_move`): the layer shows there, within its bounds, at the size the placement gives. The +/// caller's place, the stored one or the anchor applies again once the drag ends. pub(crate) fn shown_placement( + ctx: &Context, + id: Id, + save: Option<&SaveKey>, + overlay: &crate::contract::Overlay, + moving: Option, + screen: Rect, + screen_inset: f32, +) -> Placement { + let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset); + if let Some(moving) = moving { + placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into()); + } + placement +} + +/// The placement a layer is shown at while no drag moves it ([`shown_placement`]). +fn resting_placement( ctx: &Context, id: Id, save: Option<&SaveKey>, diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 24c1ff5c3..6383347dd 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -11,7 +11,7 @@ use crate::runtime::egui::{alloc, child, style}; use crate::runtime::env::{Env, RowLine}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; -use crate::style::{RuleKind, UiTokens, rule_look}; +use crate::style::{RuleKind, RuleLook, RuleWidth, UiTokens, rule_look}; use egui::{Align, Id, Layout, Pos2, Rect, Ui, UiBuilder, Vec2}; /// The slots of a container's own header parts at the edges of the header's line (`Container::header_parts`). @@ -84,12 +84,13 @@ pub(super) struct RuleBands { } impl RuleBands { - /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. - pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32) -> Self { + /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. A rule above separates the + /// container from what precedes it in flow: right after a rule (`after_rule`) there is none. + pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32, after_rule: bool) -> Self { let width = rule_look(tokens, RuleKind::Divider).width.points(pixels_per_point); let on = |rule: bool| if rule { width } else { 0.0 }; RuleBands { - above: on(props.header.is_some_and(|header| header.rule_above)), + above: on(!after_rule && props.header.is_some_and(|header| header.rule_above)), under: on(props.header.is_some_and(|header| header.rule && !header.inline)), footer: on(props.footer.is_some_and(|footer| footer.rule)), end: on(props.end.is_some_and(|end| end.rule)), @@ -217,6 +218,30 @@ pub(super) fn paint_rules(ui: &mut Ui, env: &Env, regions: &Regions) { } } +/// The bracket of a linked `Row` (`Bracket::Linked`) from what its rows reported in `took`: a tick from the end of the +/// first and the last row's controls, `space.gap.tight` past them, to the middle child's centre line, and a stroke +/// along that line from each tick to the middle child's edge. `text.muted`, `stroke.thin` wide. +pub(super) fn paint_bracket(ui: &mut Ui, env: &Env, took: &crate::layout::BracketTook, rtl: bool) { + let (Some(first), Some(last), Some(end), Some(middle)) = (took.first, took.last, took.end, took.middle) else { return }; + if last <= first { + return; + } + let tokens = &env.tokens; + let tight = tokens.tokens().space.gap.tight; + let look = RuleLook { color: crate::style::rgba_color(tokens.color.text.muted), width: RuleWidth::Points(tokens.stroke.thin) }; + let ppp = ui.ctx().pixels_per_point(); + let (start, line) = if rtl { (-end - tight, middle.center().x) } else { (end + tight, middle.center().x) }; + let painter = ui.painter(); + for (from, to) in [ + (Pos2::new(start, first), Pos2::new(line, first)), + (Pos2::new(start, last), Pos2::new(line, last)), + (Pos2::new(line, first), Pos2::new(line, middle.top().max(first))), + (Pos2::new(line, middle.bottom().min(last)), Pos2::new(line, last)), + ] { + painter.extend(Rule::shapes(&look, from, to, ppp)); + } +} + impl BodyHooks<'_> { /// The footer's rect and how far its left edge lies past the container's, under the control column of a /// label-scoped container; along an axis the room leaves unbounded, the footer follows the body and the end region. @@ -610,7 +635,11 @@ fn own_labels(ui: &mut Ui, id: Id, (room, seed): (f32, Option), foun group.offer(room); body(ui) }); - (found.extent, found.unsettled) = (scoped.extent, scoped.unsettled); + found.extent = scoped.extent; + // A later sweep of the same run may take a row's measure from the earlier sweep without reading the column again + // (a stack's sweep at the width its first sweep found): that measure is still the one taken at the narrower + // column, so the rows run again whenever any sweep found one. + found.unsettled = scoped.unsettled.or(found.unsettled.take()); result } diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 1c0392f89..ca7587876 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,6 +29,9 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, + /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule + /// just before it (a rule above its header is not drawn). + flow: (bool, bool), } /// The props a body was measured under, compared on the fields its measure reads. @@ -92,6 +95,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), + flow: (self.in_column, self.after_rule), } } diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 7976228fe..bc1af97e6 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -124,6 +124,9 @@ pub(super) struct WindowMode { kind: Option, restore: Placement, began: Option, + /// The rect the layer had when a press went down on its move band or a grip, until the press ends: a drag that + /// starts from the press runs from it. + pressed: Option, moving: Option, sizing: Option, /// The index in `GRIPS` of the grip a drag holds, from its `DragStart` to its release: `move_parts` keeps it @@ -136,6 +139,23 @@ impl WindowMode { pub(super) fn held(&self) -> Option { self.held } + + /// The rect a drag of the move band of the layer `id` puts the layer at in this pass, before the bounds keep it: + /// the rect the layer had when the press went down, moved by the pointer's travel since. `window_drag` reports the + /// same rect for the step. `None` while no move by the band runs. The layer host shows the layer there + /// (`shown_placement`) before the container's pass runs, so the layer stands under the pointer in the frame of + /// each step, whoever owns its placement. + pub(super) fn running_move(&self, ctx: &Context, id: Id) -> Option { + if self.pressed.is_none() && self.began.is_none() { + return None; + } + let (began, start, pos) = match crate::primitives::sensing::part_press(ctx, id, MOVE_BAND.into()).press.phase { + PressPhase::DragStart { start, pos, .. } => (self.pressed?, start, pos), + PressPhase::Drag { start, pos, .. } | PressPhase::Release { start, pos, .. } => (self.began?, start, pos), + _ => return None, + }; + Some(began.translate(pos - start.origin)) + } } /// A move of a viewport mount's OS window that the app runs (`Overlay::moved_by_app`), from its Begin to its Commit @@ -200,6 +220,11 @@ pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y))) } +/// `rect` kept inside `bounds`, when the layer has bounds. +pub(super) fn kept_in(rect: Rect, bounds: Option) -> Rect { + bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) +} + /// What every change of a layer's rect keeps to: the least and most size, and the rect it stays inside. struct Limits { min: Vec2, @@ -214,8 +239,7 @@ impl Limits { /// `rect` moved by `delta`, kept inside the bounds. fn moved(&self, rect: Rect, delta: Vec2) -> Rect { - let rect = rect.translate(delta); - self.bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) + kept_in(rect.translate(delta), self.bounds) } /// `rect` with the edges `dx` and `dy` (-1: low edge, 1: high edge, 0: none) moved by `delta`, within the size @@ -377,14 +401,7 @@ impl BodyHooks<'_> { if mode.kind == Some(kind) { mode = WindowMode::default(); } else { - mode = WindowMode { - kind: Some(kind), - restore: current.clone(), - began: Some(current.rect_over(rect)), - moving: None, - sizing: None, - held: None, - }; + mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), ..WindowMode::default() }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -436,7 +453,8 @@ impl BodyHooks<'_> { } /// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the - /// limits, and each step is reported. Escape, which cancels the press, restores the placement from before. + /// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape, + /// which cancels the press, restores the placement from before. pub(super) fn window_drag(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { let Some(overlay) = overlay_of(props) else { return }; // A band that moves the window below starts the OS move of the window the layer is shown in. @@ -455,9 +473,11 @@ impl BodyHooks<'_> { let mut pressed = vec![(None, phase((MOVE_BAND, None)))]; pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64)))))); let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? { - phase @ (PressPhase::DragStart { .. } | PressPhase::Drag { .. } | PressPhase::Release { .. } | PressPhase::Cancel { .. }) => { - Some((grip, phase)) - } + phase @ (PressPhase::Down { .. } + | PressPhase::DragStart { .. } + | PressPhase::Drag { .. } + | PressPhase::Release { .. } + | PressPhase::Cancel { .. }) => Some((grip, phase)), _ => None, }) else { return; @@ -465,8 +485,14 @@ impl BodyHooks<'_> { let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); let (origin, pos, gesture) = match phase { + PressPhase::Down { .. } => { + self.mode.pressed = Some(current.rect_over(rect)); + return; + } PressPhase::DragStart { start, pos, .. } => { - self.mode.began = Some(current.rect_over(rect)); + // The layer host shows this pass at the step's rect already (`running_move`): the drag runs from where + // the layer stood at the press. + self.mode.began = Some(self.mode.pressed.unwrap_or_else(|| current.rect_over(rect))); self.mode.restore = current.clone(); self.mode.held = grip; (start.origin, Some(pos), GesturePhase::Begin) @@ -476,6 +502,9 @@ impl BodyHooks<'_> { PressPhase::Cancel { start, .. } => (start.origin, None, GesturePhase::Cancel), _ => return, }; + if matches!(gesture, GesturePhase::Commit | GesturePhase::Cancel) { + self.mode.pressed = None; + } let Some(began) = self.mode.began else { return }; let (dx, dy, _) = grip.map_or((0, 0, CursorIcon::Grab), |index| GRIPS[index]); let kind = if grip.is_some() { PlacementKind::Size(edge_of(dx, dy)) } else { PlacementKind::Move }; diff --git a/crates/ui-contract/src/contract/collection.rs b/crates/ui-contract/src/contract/collection.rs index 754053cdc..623ac6612 100644 --- a/crates/ui-contract/src/contract/collection.rs +++ b/crates/ui-contract/src/contract/collection.rs @@ -12,7 +12,8 @@ pub use events::{ CollectionEvent, ColumnEvent, ColumnRequest, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit, }; pub use props::{ - ActivateOn, CollectionProps, DragPayload, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, RowState, SelectMode, SpaceAction, + ActivateOn, CollectionProps, DragPayload, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, RowState, SelectMode, + SpaceAction, }; pub(crate) use response::Gestures; pub(crate) use response::ItemsOut; diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 3c464e0b4..db45f0d04 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -119,6 +119,21 @@ pub enum LeadOnOpen { First, } +/// What the pointer moving over the rows changes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum HoverLead { + /// Nothing: only a press moves the lead. + #[default] + Off, + /// The lead moves to the row under the pointer; the selection stays until a pick (click, Enter, or a key move): + /// option lists, where the selection is the chosen value. + Lead, + /// The lead moves and picks the row, as the arrow keys do: menus and the undo list, where the hover range is + /// the point. + LeadAndSelection, +} + /// How tall a collection's rows are. Read-only display tables (a metadata table) take text rows; lists the user picks /// from or navigates keep control-high rows, a pointer target as tall as a control. A row with a thumbnail or a /// detail line is as tall as those need either way. @@ -173,9 +188,8 @@ pub struct CollectionProps { pub allow_empty: bool, /// Where the lead starts. pub lead_on_open: LeadOnOpen, - /// The lead, and the selection with it as for the arrow keys, moves to the row under the pointer when the pointer - /// moves: menus, popup lists and the undo list. - pub lead_follows_hover: bool, + /// What the pointer moving over the rows changes: the lead, and for some lists the selection too. + pub hover_lead: HoverLead, /// The arrow keys select the row they move the lead to. Off: they move the lead only, and Space, Enter or a click /// selects it (a swatch table, a tab strip, a preset browser); Enter then activates it as well. pub arrows_select: bool, @@ -299,7 +313,7 @@ impl CollectionProps { striped: false, allow_empty: false, lead_on_open: LeadOnOpen::Selected, - lead_follows_hover: false, + hover_lead: HoverLead::Off, arrows_select: true, focus_on_press: true, rows_stamp: None, @@ -434,10 +448,10 @@ impl CollectionProps { self } - /// The lead follows the pointer over the rows. + /// What the pointer moving over the rows changes. #[must_use] - pub const fn lead_follows_hover(mut self, on: bool) -> Self { - self.lead_follows_hover = on; + pub const fn hover_lead(mut self, hover: HoverLead) -> Self { + self.hover_lead = hover; self } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 142677f22..b7a8f1da8 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -727,6 +727,19 @@ impl EnvValue for InMenu { } } +/// The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and +/// height to their chain): a tick from each of the first and the last row's controls to the middle child's centre +/// line, joined along that line. The middle child sits halfway between the two controls. The value is the link's +/// state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Bracket { + /// The rows are linked: the bracket is drawn. + Linked, + /// The rows are not linked: the middle child keeps its place, with no bracket. + Unlinked, +} + /// What a container or collection adds to `Common`. A builder added here is added to the forwarder list in /// `crates/ui-macros/src/props.rs` too. /// @@ -820,6 +833,9 @@ pub struct ContainerProps { pub label_column: bool, /// How the labelled rows under the container show their labels; `None` keeps the scheme of the scope. pub labels: Option, + /// The bracket an unwrapped `Row` placed from its start draws from its first child's labelled rows to the child + /// after them; any other body draws none. + pub bracket: Option, /// The component whose memory holds the container's shown memory and its layer's bookkeeping, when it is another: /// the body of a popup an `overlay` hook shows belongs to the component that shows it. pub(crate) owner: Option, @@ -860,6 +876,7 @@ impl ContainerProps { && self.outer_edit == other.outer_edit && self.collection_body == other.collection_body && self.labels == other.labels + && self.bracket == other.bracket } /// Props with every field at its default. @@ -901,6 +918,7 @@ impl ContainerProps { collection_body: false, label_column: false, labels: None, + bracket: None, owner: None, } } @@ -1122,6 +1140,12 @@ impl ContainerProps { self } + /// The bracket of a `Row` from its first child's labelled rows to the child after them ([`bracket`](Self::bracket)). + pub const fn bracket(mut self, bracket: Bracket) -> Self { + self.bracket = Some(bracket); + self + } + /// The labelled rows under the container show their labels in `scheme`: its regions, its body and every container /// inside, until one sets a scheme of its own. pub const fn labels(mut self, scheme: LabelScheme) -> Self { diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index a3b6225fd..40671bf6f 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -8,7 +8,7 @@ use super::{Held, ITEM_NODE, ItemsHooks, LastLayout, Lead, Placement, Renaming, use super::{request, rows}; use crate::contract::ValueOf; use crate::contract::collection::{ - CollectionEvent, ColumnLayout, ContextMenuRequest, DropAt, Gestures, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow, + CollectionEvent, ColumnLayout, ContextMenuRequest, DropAt, Gestures, HoverLead, ItemsOut, OpenChange, PendingDrop, Rename, RowState, ShownRow, }; use crate::contract::cx::{BodyCx, CxCore, Pointer as _}; use crate::contract::run::{Measuring, ShapeHooks, ShowAt}; @@ -277,8 +277,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let seen = Placement { offset: ScrollPos { x: self.offset_x_at_read, y: self.offset_at_read }, ..at }; self.edge_step(cx); self.press_step(comp, cx, &props, &layout, seen); - if props.lead_follows_hover { - self.hover_lead(comp, cx, &layout, seen); + if props.hover_lead != HoverLead::Off { + self.hover_lead(comp, cx, &layout, seen, props.hover_lead); } if props.select_under_drag { self.drag_select(comp, cx, &layout, seen); diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index 88e069872..6d69fd2ea 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -1,7 +1,7 @@ //! The lead and the selection: picks, ranges, and where the lead starts and follows. use super::{ItemsHooks, Placement}; -use crate::contract::collection::{CollectionEvent, LeadOnOpen, LeadSource, ListDrag, SelectMode}; +use crate::contract::collection::{CollectionEvent, HoverLead, LeadOnOpen, LeadSource, ListDrag, SelectMode}; use crate::contract::{Collection, Cx}; use craft_behavior::{Flow, ItemLayout, PointerEvent, SelectionChange, SelectionModel}; use egui::{Pos2, Rect, Vec2}; @@ -135,10 +135,10 @@ impl ItemsHooks<'_, '_, C> { layout.hit(local, offset).filter(|&row| self.source.enabled(row) && !self.source.is_section(row) && layout.shown(row)) } - /// The lead follows a moving pointer over the rows, and the selection follows the lead the way it does for the - /// arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead + /// The lead follows a moving pointer over the rows; with `HoverLead::LeadAndSelection` the selection follows the + /// lead the way it does for the arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead /// with no movement to measure, and a modifier change under a resting pointer leaves the lead where the keys put it. - pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement, hover: HoverLead) { let moved = crate::runtime::pointer::with_pass_raw(&cx.core.ctx, |pass| pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. }))); if !moved { @@ -147,7 +147,9 @@ impl ItemsHooks<'_, '_, C> { let Some(row) = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)) else { return }; if self.lead.key.as_ref() != Some(&self.source.key(row)) { self.move_lead(row, LeadSource::Pointer); - self.pick(comp, row, false, false); + if hover == HoverLead::LeadAndSelection { + self.pick(comp, row, false, false); + } } } diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index e49a5c280..b2c5f1b18 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -116,6 +116,8 @@ impl LeafPlaced { pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { let scope = sub(at.id, "field"); let enabled = at.under.enabled; + // Read before the child measures: nothing it does there may count as a child placed in flow. + let in_column = in_column(ui); let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; let input = LabelIn { scope, @@ -131,7 +133,7 @@ pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: & size: at.under.size, control_min, leaf: true, - in_column: in_column(ui), + in_column, claims: C::LABELLED_AFTER, status: false, trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size), @@ -227,9 +229,15 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< placed } -/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. +/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an +/// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start, +/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. pub(crate) fn in_column(flow: &Ui) -> bool { - !flow.layout().is_horizontal() + if !flow.layout().is_horizontal() { + return true; + } + let env = Env::of(flow); + env.column_row && crate::layout::at_flow_start(flow.ctx(), &env) } /// A control with its label after it that the label step moved into the control column (its `control` starts past diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 41d5b40d5..b2c263953 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -177,6 +177,7 @@ impl Lazy { if memo { place_view(ui, rect); } else { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } if view.is_some() || memo { @@ -269,6 +270,7 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { /// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. fn place_view(ui: &mut Ui, rect: Rect) -> Rect { if take_cell(ui, rect.size()).is_none() { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } rect diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 14ea466f7..7b44688d6 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -60,16 +60,17 @@ pub use body::{STRIP_BACK, STRIP_FORWARD}; pub use collection::{ ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove, ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest, - ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, RowState, - SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, + HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, + RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, }; #[doc(hidden)] pub use container::InBar; #[doc(hidden)] pub use container::InMenu; pub use container::{ - BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth, - Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth, + BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, + LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, + WrapWidth, }; pub use craft_tracked::{PlainData, Revision, Tracked}; pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 54fee68fb..34137bf9a 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -26,7 +26,8 @@ pub(super) struct Mounted { } /// The host for `props.mount`. A layer-like mount of a closed container shows nothing once its exit fade ended. -pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label) -> Mounted { +/// `moving` is the rect a running drag of the container's move band puts its layer at in this pass. +pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label, moving: Option) -> Mounted { let ctx = at.ui.ctx(); let layer = |overlay: &Overlay| { let presence = if at.ui.is_sizing_pass() { @@ -46,7 +47,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false }, Mount::Window { .. } => Mounted { host: Box::new(WindowContentHost), exiting: false }, Mount::Layer(overlay) => match layer(overlay) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size, moving)), exiting }, (None, _) => closed(), }, Mount::FullWindow => full_window(props.focus), @@ -57,7 +58,9 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & full_window(fallback.focus) } else if !viewports { match layer(fallback) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => { + Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size, moving)), exiting } + } (None, _) => closed(), } } else if open { @@ -196,12 +199,14 @@ struct LayerHost { fade: f32, /// The size the container measured for this pass. size: Vec2, + /// The rect a running drag of the move band puts the layer at in this pass, in screen space. + moving: Option, dismissed: Option, } impl LayerHost { - fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2) -> Self { - LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, dismissed: None } + fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2, moving: Option) -> Self { + LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, moving, dismissed: None } } } @@ -227,7 +232,7 @@ impl Host for LayerHost { overlay = mapped; } let screen = overlay::screen_for(&ctx, env, &overlay); - let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, screen, env.tokens.space.inset.screen); + let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen); // An anchored resizable layer has no position to seed: its default size is held as its minimum until the // user resizes it. if overlay.fit == overlay::OverlayFit::Resizable 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 2b1ae4b38..e2c8379e3 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::primary_press(ctx) else { diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 6fcec39a9..1fffe99f1 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); @@ -260,6 +268,150 @@ 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 mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // The layer's root node, made before its `Area` shows, as in `host`. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, 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 spec.root.is_some() && layer.exiting { + access::hide_exiting_content(&ctx, ui.unique_id()); + } + // 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 && overlay.rank.is_modal() { + access::report_modal(&ctx, layer.id); + } + 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/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f7e3aab2d..f495e805f 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1609,8 +1609,11 @@ fn extent_step( let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); let env = begun.env(); // A body root with parts steps its press machine before its measuring run, so the body reads this pass's part - // presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8. - if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) { + // presses in both runs (`BodyCx::part_press`) and its host reads them before it places the body. Step 8 finds the + // outcome. A member of another arena senses at step 8. A root its host shows on a layer of its own (not in flow) + // senses in its own arena: its steps 6 to 16 run in the layer's env, which is outside its opener's arena. + let own_arena = t.arena() || facts.text() || env.arena.is_none() || !t.in_flow(); + if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && own_arena { sensing::sense_early(ctx, id, resolved.enabled); } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 0be4e115f..956401601 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -546,6 +546,7 @@ pub(crate) fn show_container_taking( body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); + crate::layout::close_flow_start_in(ui); crate::runtime::egui::alloc::advance_past(ui, rect); shown } diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index de37411f3..8a6b9b170 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -71,6 +71,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); + super::close_flow_start_in(ui); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index c32bee2cb..39aef7f2b 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -211,6 +211,79 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { }); } +/// The bodies whose flow has placed nothing yet in the sweep or run under way, by body id, each with whether a rule +/// precedes the body's start (`Scoped::after_rule`). +#[derive(Default)] +pub(crate) struct FlowStarts(IdMap); + +/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed +/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); +/// `None` once a child took room there, and outside a body. +pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { + let body = env.flow_body?; + pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) +} + +/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). +pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { + flow_start(ctx, env).is_some() +} + +/// A child took room in the flow of the body that places the children under `env`: its flow start closes. +pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { + if let Some(body) = env.flow_body { + pass_state::with::(ctx, |starts| starts.0.remove(&body)); + } +} + +/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. +pub(crate) fn close_flow_start_in(ui: &Ui) { + close_flow_start(ui.ctx(), &Env::of(ui)); +} + +/// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or +/// run under way, and the rect of the row's last child in flow, by the row's layout id. +#[derive(Default)] +pub(crate) struct Brackets(IdMap); + +/// The controls of a bracket's rows and the child after them. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct BracketTook { + /// The centre line of the first row's control. + pub(crate) first: Option, + /// The centre line of the last row's control. + pub(crate) last: Option, + /// How far the rows' controls reach toward the row's end edge, at most: right, or left under right-to-left. + pub(crate) end: Option, + /// The rect of the row's last child placed in flow: the control in the bracket's middle. + pub(crate) middle: Option, +} + +impl BracketTook { + /// The centre line between the first and the last row's controls, once two rows reported. + pub(crate) fn centre(&self) -> Option { + self.first.zip(self.last).filter(|(first, last)| last > first).map(|(first, last)| (first + last) / 2.0) + } +} + +/// Reports the `control` rect of a labelled row to the bracketed row `row`, its end edge `rtl`-aware. +pub(crate) fn report_bracket_control(ctx: &egui::Context, row: Id, control: Rect, rtl: bool) { + pass_state::with::(ctx, |brackets| { + if let Some(took) = brackets.0.get_mut(&row) { + let centre = control.center().y; + took.first.get_or_insert(centre); + took.last = Some(centre); + let end = if rtl { -control.min.x } else { control.max.x }; + took.end = Some(took.end.map_or(end, |was: f32| was.max(end))); + } + }); +} + +/// What the rows of the bracketed row `row` reported in the run that just ended; `None` outside a bracketed row. +pub(crate) fn take_bracket(ctx: &egui::Context, row: Id) -> Option { + pass_state::with::(ctx, |brackets| brackets.0.remove(&row)) +} + /// How a child that fills the main axis of the body it sits in sizes along it. enum MainFill { /// The body is being measured: the child takes no room along the axis and is counted. @@ -1115,9 +1188,16 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); let (line, target) = (env.row_line, env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; - let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); + // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its + // rows reported before it. + let bracket = line.filter(|line| env.bracket == Some(line.body)).and_then(|line| { + let took = pass_state::with::(ui.ctx(), |brackets| brackets.0.get(&line.body).copied())?; + Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) + }); + let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, env.grid, slot); + let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { rect } else { @@ -1130,6 +1210,9 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) }; + if let Some((row, _)) = bracket { + pass_state::with::(ui.ctx(), |brackets| brackets.0.get_mut(&row).map(|took| took.middle = Some(placed))); + } if measure::active(ui.ctx()) { if let Some(line) = line { pass_state::with::(ui.ctx(), |rows| { @@ -1148,7 +1231,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, Env::of(ui).grid, size) + take_in(ui, &Env::of(ui), size) } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1158,13 +1241,15 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, grid, Vec2::ZERO); + take_in(ui, &env, Vec2::ZERO); } } -/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself. -fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { - match cell_in(ui, grid, size) { +/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start +/// closes. +fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1173,7 +1258,12 @@ fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { /// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { - cell_in(ui, Env::of(ui).grid, size) + let env = Env::of(ui); + let cell = cell_in(ui, env.grid, size); + if cell.is_some() { + close_flow_start(ui.ctx(), &env); + } + cell } fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { @@ -1324,6 +1414,7 @@ fn run_grid( scoped.derive_local(|scoped| { scoped.grid = Some(id); scoped.grid_top = cells == CellAlign::Top; + scoped.flow_body = Some(id); }), ); let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body); @@ -1598,8 +1689,14 @@ pub(crate) fn run_body_measured( // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); + // Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh. + let (after_rule, bracket) = (env.after_rule, env.bracket == Some(id)); let body = |ui: &mut Ui| { open_sweep(&ctx, target, row); + pass_state::with::(&ctx, |starts| starts.0.insert(id, after_rule)); + if bracket { + pass_state::with::(&ctx, |brackets| brackets.0.insert(id, BracketTook::default())); + } body(ui) }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. @@ -1627,7 +1724,10 @@ struct RowIn { /// A `Stack` body: each leaf shows at most the stack's room, never below its least. fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); - let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); + let env = env.derive_local(|scoped| { + scoped.shrink = Some(Shrink::Fit); + scoped.flow_body = Some(at.id); + }); let installed = Env::install_for(ui, env.clone()); // A held child of a column whose own room is unbounded keeps the width it measured at. let inner = if env.content_column && flow_room(ui).x.is_finite() { @@ -1652,6 +1752,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m scoped.grid_top = false; scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_spread(ui, id, gap.x, rtl, &mut body); @@ -1675,6 +1776,7 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu scoped.row_room = Some(room.width()); scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_shrinking(ui, id, &mut body); @@ -1724,6 +1826,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; + scoped.flow_body = Some(id); if line.is_some() { scoped.first_line = None; } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 4f2654e97..b5fbb0c2e 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column, - leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, - shares_y, shrink_cap, take_cell, take_in_flow, view_room, + BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, + flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, + report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, + view_room, }; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 9b36826d8..d09cc6ea9 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -5,7 +5,7 @@ use crate::runtime::egui::memory; use crate::runtime::egui::text_layout; pub use crate::style::Span; use crate::style::text_measure::{paragraph_job, span_format}; -use crate::style::{StyleColor, TypeRole, UiTokens}; +use crate::style::{LetterCase, StyleColor, TypeRole, UiTokens}; use craft_i18n::Direction; use egui::epaint::text::FontCacheRevision; use egui::text::{LayoutJob, TextWrapping}; @@ -118,6 +118,11 @@ impl<'a> TextRun<'a> { /// Sets the type role. pub fn role(mut self, role: TypeRole) -> Self { self.role = role; + if role.letter_case() == LetterCase::Upper { + for span in &mut self.spans { + span.text = Cow::Owned(span.text.to_uppercase()); + } + } self } diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 65f0231d6..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); } @@ -74,9 +84,9 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, ctx.show_viewport_immediate(id, builder, |ui, _| body(ui)) } -/// Makes the hidden viewport `id` visible. -pub(crate) fn show(ctx: &Context, id: ViewportId) { - ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(true)); +/// Shows or hides the window of viewport `id`. +pub(crate) fn set_visible(ctx: &Context, id: ViewportId, visible: bool) { + ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(visible)); } /// The viewport id of the container `id`. @@ -168,6 +178,16 @@ pub(crate) fn raise(ctx: &Context, viewport: ViewportId) { ctx.request_repaint_of(viewport); } +/// Brings `viewport`'s window in front of the app's other windows without giving it focus, by standing it above every +/// window and then back at `level`, its own level. egui-winit ignores `Focus` for a window that has focus, and the +/// window holding a modal usually has it; on Windows the level change also puts the window in front of the ordinary +/// windows that were made ordinary before it. A Wayland compositor gives clients no stacking control. +pub(crate) fn raise_above(ctx: &Context, viewport: ViewportId, level: WindowLevel) { + command(ctx, viewport, ViewportCommand::WindowLevel(WindowLevel::AlwaysOnTop)); + command(ctx, viewport, ViewportCommand::WindowLevel(level)); + ctx.request_repaint_of(viewport); +} + /// Cancels an OS close request of the running viewport so the owner can decide. pub(crate) fn cancel_close(ctx: &Context) { ctx.send_viewport_cmd(ViewportCommand::CancelClose); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index c0f132239..2e0794919 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -138,6 +138,18 @@ pub struct Scoped { /// Where the first child the scope places in flow reports its first line: a container's header or body /// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself. pub(crate) first_line: Option, + /// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`) + /// and the one a child placed in flow closes. + pub(crate) flow_body: Option, + /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws + /// nothing of its own and itself follows one. The body's layout opens its flow start with it. + pub(crate) after_rule: bool, + /// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first + /// child in flow starts where the rows of that flow start (`label::in_column`). + pub(crate) column_row: bool, + /// The layout of the bracketed `Row` body (`ContainerProps::bracket`) whose labelled rows report their controls to + /// it: set for the row's body and kept through the containers inside it up to a labelled one. + pub(crate) bracket: Option, /// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a /// `FooterSlot` shown under it takes that size and is where the footer is drawn. pub(crate) footer_slot: Option, @@ -358,6 +370,7 @@ impl Scoped { /// layer is no line of a bar it was opened from. A layer's content measures and runs in this. pub(crate) fn start_layer(&mut self) { self.start_room(); + self.bracket = None; self.measure = None; self.arena = None; self.roving = None; @@ -387,6 +400,8 @@ impl Scoped { self.row_room = None; self.row_line = None; self.first_line = None; + self.flow_body = None; + self.column_row = false; self.fill_body = None; self.fill_share = None; self.shrink = None; @@ -568,6 +583,10 @@ impl Env { row_room: None, row_line: None, first_line: None, + flow_body: None, + after_rule: false, + column_row: false, + bracket: None, footer_slot: None, fill_body: None, fill_share: None, @@ -657,6 +676,7 @@ impl Env { pub(crate) fn new_room(&self) -> Env { self.derive_local(|scoped| { scoped.start_room(); + scoped.bracket = None; scoped.lazy = None; scoped.measure = None; // A pane opened from a bar is not the bar's line. diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 072ab185f..57b6b3b11 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/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 5c5b630dc..3894fd46b 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1239,6 +1239,11 @@ pub(crate) mod guard { ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), + ( + "layout::body::FlowStarts", + "flow starts: opened by each sweep of the body and closed by its first child in flow; a child reads its body's at its own start, and its measure key holds what it read", + ), + ("layout::body::Brackets", "bracket reports: opened by each sweep of the bracketed row and taken after its body"), ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index be4d8185a..ea79ef4d5 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -76,7 +76,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 { .. }) } @@ -153,6 +153,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. @@ -202,6 +206,7 @@ impl OpenEntry { scoped: false, absorbs: false, window: false, + popup: false, region: None, place: None, dialog: None, @@ -211,7 +216,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. @@ -560,11 +565,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)); @@ -853,7 +885,7 @@ pub(crate) fn end_pass(ctx: &Context) { } fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool { - pass::live_viewports(ctx).into_iter().filter(|viewport| *viewport != running).any(|viewport| with_persist(ctx, viewport, |persist| persist.modal)) + modal_viewport(ctx, running).is_some() } /// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook @@ -929,9 +961,19 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option) { (root.is_some() || modal_in_other_viewports(ctx, viewport), root) } +/// The live viewports with a modal layer open as of their last finished pass. +fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { + pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal)) +} + /// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises. pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option { - pass::live_viewports(ctx).into_iter().filter(|other| *other != viewport).find(|other| with_persist(ctx, *other, |persist| persist.modal)) + modal_viewports(ctx).find(|other| *other != viewport) +} + +/// A viewport that has a modal layer open: the window that blocks the app's other windows. +pub(crate) fn app_modal_viewport(ctx: &Context) -> Option { + modal_viewports(ctx).next() } /// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index def4d3915..d616909a5 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -96,6 +96,8 @@ pass_state! { held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, + flow_starts: crate::layout::body::FlowStarts, + brackets: crate::layout::body::Brackets, cursors: crate::layout::body::Cursors, footer_slots: crate::contract::footer_slot::Slots, column_groups: crate::layout::column_group::Open, diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index a5d117b24..42409d37c 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -48,9 +48,9 @@ pub use shell::shell_of; use shell::{refresh, window_info}; #[cfg(feature = "testing")] pub(crate) use shell::{set_chrome, set_os}; -use spec::chrome_of; +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; @@ -86,11 +86,17 @@ pub(crate) struct Shared { desktop: Option, /// Whether the root window had focus in the last root pass. root_focused: bool, - /// Whether no window of the app had focus when the last frame's windows had all reported. - away: bool, + /// The app's state when the last frame's windows had all reported, which its palettes follow. + app: AppState, + /// Whether a palette window stood lowered under an app-modal layer in this frame. + lowered: bool, + /// Where the raise of the modal's window above the palettes it lowered stands. + raise: Raise, /// 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. @@ -105,8 +111,10 @@ pub(crate) struct Record { chrome: Option, /// The caption buttons the app draws in this window. captions: Option, - /// The level the window was opened with or last set to; a palette's egui level follows the app's activity. + /// The level the window was opened with or last set to; a palette's egui level follows the app's state. level: Option, + /// Whether the window is hidden because the app's state hides it (a palette while the main window is minimized). + hidden: bool, /// H4: whether the primary button is down as the viewport's events left the input hook. primary_down: bool, /// Whether the user can resize the window; unknown for a window not opened by `show_viewport`. @@ -146,6 +154,22 @@ 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 +/// frame after a palette was built lowered: a raise in the same frame may reach the OS before the palette's new level +/// does, and the palette, made an ordinary window after it, would stand in front again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Raise { + /// No palette has stood lowered under the open modal yet, or no modal is open. + #[default] + Waiting, + /// A palette stood lowered in the last frame: the modal's window is raised in this one. + Due, + /// The modal's window was raised. + Done, } /// Passes between searches for an OS window that was not found. @@ -294,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 } @@ -350,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 { @@ -465,12 +565,14 @@ fn flush_store(ctx: &Context) { } } -/// Keeps the app's activity and the stacking order of its windows current from the windows' focus. A palette's -/// window level follows the activity: the mounts build their viewports with the level of the moment, and a change +/// Keeps the app's state and the stacking order of its windows current from the windows' facts. A palette's window +/// level and visibility follow the state: the mounts build their viewports with the state of the moment, and a change /// asks for the next frame. Runs at the end of the root pass, inside which every child window's pass of the frame /// has run, so each window's focus is the one its own pass reported after its input batch. The root input's list of /// windows holds each child as of its previous pass, so it is not read for focus. The app is inactive when no /// window reports focus: the batch that took focus from one window gave it to no other. +/// +/// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal. fn follow_activity(ctx: &Context) { let windows = viewports::reported(ctx); let focused: Vec = windows @@ -478,13 +580,27 @@ fn follow_activity(ctx: &Context) { .map(|(viewport, _)| *viewport) .filter(|viewport| PerViewport::::with(ctx, *viewport, |record| record.facts.is_some_and(|facts| facts.focused))) .collect(); - let changed = shared(ctx, |shared| { + let modal = overlay::app_modal_viewport(ctx); + let minimized = viewports::current(ctx).minimized; + let (repaint, raise) = shared(ctx, |shared| { shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport)); shared.stacking.extend(&focused); - let away = focused.is_empty(); - std::mem::replace(&mut shared.away, away) != away + let app = AppState { away: focused.is_empty(), modal, minimized }; + let lowered = std::mem::take(&mut shared.lowered); + let (step, raise) = match shared.raise { + _ if app.modal != shared.app.modal => (Raise::Waiting, None), + Raise::Waiting if lowered => (Raise::Due, None), + Raise::Due => (Raise::Done, app.modal), + step => (step, None), + }; + shared.raise = step; + let changed = std::mem::replace(&mut shared.app, app) != app; + (changed || step == Raise::Due, raise) }); - if changed { + if let Some(modal) = raise { + act(ctx, modal, WindowAction::Raise); + } + if repaint { ctx.request_repaint(); } } 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/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index b13db3737..9974910df 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -5,7 +5,7 @@ use super::host::scale_of; #[cfg(doc)] use super::logic; use super::shell::{base_shell, os_of, window_info}; -use super::spec::WindowLevel; +use super::spec::{Standing, WindowLevel}; use super::{HandOff, Record, SEARCH_EVERY, shared}; use crate::runtime::egui::{pass, viewports}; use crate::runtime::frame::{PerViewport, Stored}; @@ -40,6 +40,9 @@ pub enum WindowAction { SetMaximized(bool), /// Raises the window and gives it OS focus. Focus, + /// Brings the window in front of the app's other windows without giving it focus, as the window holding an + /// app-modal layer comes in front of the palettes the modal lowered. + Raise, /// The OS starts moving the window with the pointer. StartMove, /// The OS starts resizing the window from `edge`. @@ -100,7 +103,8 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { | WindowAction::Restore | WindowAction::SetMinInnerSize(_) | WindowAction::SetLevel(_) - | WindowAction::SetTitle(_) => commands, + | WindowAction::SetTitle(_) + | WindowAction::Raise => commands, WindowAction::SetOpacity(_) => false, }; if !allowed { @@ -109,6 +113,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { match action { WindowAction::Close => viewports::close(ctx, viewport), WindowAction::Focus => viewports::raise(ctx, viewport), + WindowAction::Raise => viewports::raise_above(ctx, viewport, standing(ctx, viewport, level_of(ctx, viewport)).level), WindowAction::Minimize => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(true)), WindowAction::ToggleMaximize => viewports::command(ctx, viewport, egui::ViewportCommand::Maximized(window.state != WindowState::Maximized)), WindowAction::ToggleFullscreen => { @@ -147,8 +152,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { if opened { ctx.request_repaint_of(viewport); } else { - let active = !shared(ctx, |shared| shared.away); - viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(level.for_egui(active, os_of(ctx)))); + viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(standing(ctx, viewport, level).level)); } } WindowAction::SetTitle(title) => { @@ -172,6 +176,16 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { true } +/// The level `viewport`'s window was opened with or last set to. +fn level_of(ctx: &Context, viewport: ViewportId) -> WindowLevel { + PerViewport::::with(ctx, viewport, |record| record.level.unwrap_or_default()) +} + +/// How `viewport`'s window at `level` stands in the app's current state. +fn standing(ctx: &Context, viewport: ViewportId, level: WindowLevel) -> Standing { + level.standing(viewport, shared(ctx, |shared| shared.app), os_of(ctx)) +} + /// Applies `opacity` to the OS window. A faded window is told again in every pass, because the window system's own /// style changes can drop the layered style; an opaque one only when it was faded. Returns whether the platform applied /// it now. diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index cb8277a54..af9e889e6 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -4,7 +4,7 @@ use super::shared; use super::shell::{base_shell, os_of}; use craft_host::target::{Os, WindowChrome, WindowKind}; use craft_window::policy::{CaptionFamily, Captions, Frame, MacInset, tool_frame}; -use egui::Context; +use egui::{Context, ViewportId}; /// Where a window stands in the stack of windows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -13,26 +13,53 @@ pub enum WindowLevel { /// An ordinary window. #[default] Normal, - /// A palette: above the app's other windows while the app is active, and an ordinary window (behind other - /// apps' windows on Windows) once none of the app's windows has focus, so it stays shown without covering - /// other apps. + /// A palette: above the app's other windows while the app is active, an ordinary window while an app-modal layer + /// in another window blocks it, and an ordinary window (behind other apps' windows on Windows) once none of the + /// app's windows has focus, so it stays shown without covering other apps or the modal. Hidden while the main + /// window is minimized, except on macOS, where the app stays active and its palettes stay. Palette, /// Above every other window. AlwaysOnTop, } +/// The app's state that its palettes follow, as its windows reported it in the last frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct AppState { + /// No window of the app has focus. + pub away: bool, + /// The window that holds an app-modal layer, which blocks the app's other windows. + pub modal: Option, + /// The main window is minimized. + pub minimized: bool, +} + +/// How a window stands among the windows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Standing { + /// The level egui is given. + pub level: egui::WindowLevel, + /// Whether the window is shown. + pub shown: bool, + /// Whether the window stands as an ordinary window because an app-modal layer in another window blocks it. + pub lowered: bool, +} + impl WindowLevel { - /// The level egui is given while the app is `active` or not, on `os`. An inactive app's palette goes behind - /// other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the - /// activated app's included, so the palette goes to the bottom. - pub(super) fn for_egui(self, active: bool, os: Os) -> egui::WindowLevel { - match self { + /// How `viewport`'s window at this level stands while the app is in `app`, on `os`. An inactive app's palette goes + /// behind other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the + /// activated app's included, so the palette goes to the bottom. A palette blocked by a modal stands as an ordinary + /// window, so the modal's window can be raised above it. + pub(super) fn standing(self, viewport: ViewportId, app: AppState, os: Os) -> Standing { + let palette = self == WindowLevel::Palette; + let lowered = palette && !app.away && app.modal.is_some_and(|modal| modal != viewport); + let level = match self { WindowLevel::Normal => egui::WindowLevel::Normal, WindowLevel::AlwaysOnTop => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if active => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, - WindowLevel::Palette => egui::WindowLevel::Normal, - } + WindowLevel::Palette if app.away && os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, + WindowLevel::Palette if app.away || lowered => egui::WindowLevel::Normal, + WindowLevel::Palette => egui::WindowLevel::AlwaysOnTop, + }; + Standing { level, shown: !(palette && app.minimized && os != Os::Mac), lowered } } } @@ -58,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 { @@ -67,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() } @@ -81,6 +119,8 @@ impl WindowSpec { level: WindowLevel::Normal, taskbar: true, shown_after_first_paint: false, + takes_focus: true, + passes_pointer: false, } } @@ -130,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 a037488a7..b621430c3 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -54,10 +54,10 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size)); } let spec = open.spec; - let active = !shared(ctx, |shared| shared.away); + let state = shared(ctx, |shared| shared.app); let os = os_of(ctx); let (chrome, captions) = frame_of_spec(ctx, spec); - let level = PerViewport::::with(ctx, viewport, |record| { + let standing = PerViewport::::with(ctx, viewport, |record| { record.kind = Some(spec.kind); record.chrome = Some(chrome); record.captions = captions.clone(); @@ -73,8 +73,11 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record.searched = None; } } - record.level.get_or_insert(spec.level).for_egui(active, os) + record.level.get_or_insert(spec.level).standing(viewport, state, os) }); + if standing.lowered { + shared(ctx, |shared| shared.lowered = true); + } let app = app_id(ctx); let opens = viewports::Spec { title: open.title, @@ -88,10 +91,12 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im // egui sends a limit only when it has one: an open window always carries its maximum, unbounded when the // caller has none, so a lifted maximum reaches the OS. max_size: open.limits.1.or(opened.then_some(Vec2::INFINITY)), - level, + level: standing.level, 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| { @@ -115,8 +120,77 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record_placement(&ctx, viewport, key, &at_known(&ctx, viewport, viewports::current(&ctx))); } }); - if PerViewport::::with(ctx, viewport, |record| std::mem::take(&mut record.awaiting_first_paint)) { - viewports::show(ctx, viewport); + // A window opened hidden appears once its first pass ran; a window the app's state hides goes and comes back with + // it. The builder's visibility only opens the window: egui sends no change of it once the window is open. + let hidden = !standing.shown; + let (reveal, changed) = PerViewport::::with(ctx, viewport, |record| { + let first = std::mem::take(&mut record.awaiting_first_paint); + let changed = std::mem::replace(&mut record.hidden, hidden) != hidden; + (first || changed, changed) + }); + if hidden && changed { + viewports::set_visible(ctx, viewport, false); + } else if !hidden && reveal { + viewports::set_visible(ctx, viewport, true); + } +} + +/// 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); + if known.is_none_or(|known| differs(ctx, viewport, rect.min - known.min)) { + act(ctx, viewport, WindowAction::SetOuterPosition(rect.min)); + } + if known.is_none_or(|known| differs(ctx, viewport, 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); } } @@ -151,9 +225,17 @@ pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool { && PerViewport::::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none()) } -/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a -/// placement records the position in pixels. -const ROUNDING: f32 = 0.5; +/// How far a caller's place may differ from the known place before it is a change, in physical pixels of the window's +/// display: the OS rounds to pixels, and a placement records the position in pixels. +const ROUNDING_PX: f32 = 0.5; + +/// Whether `delta`, in points, moves the window `viewport` by more than rounding on its display: a whole pixel on +/// a 2x display is half a point. +fn differs(ctx: &Context, viewport: ViewportId, delta: Vec2) -> bool { + let facts = PerViewport::::with(ctx, viewport, |record| record.facts); + let scale = facts.and_then(|facts| super::host::scale_of(ctx, &facts)).unwrap_or(1.0); + delta.x.abs() * scale > ROUNDING_PX || delta.y.abs() * scale > ROUNDING_PX +} /// The place of a window with `facts`: its outer top-left corner and its inner size. fn place_of(facts: &viewports::Facts) -> Option { @@ -182,11 +264,10 @@ fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option, size: Opt (record.known, state || record.moved_pointer.is_some()) }); let Some(known) = known.filter(|_| !held) else { return }; - let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; - if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) { + if let Some(pos) = pos.filter(|pos| differs(ctx, viewport, *pos - known.min)) { act(ctx, viewport, WindowAction::SetOuterPosition(pos)); } - if let Some(size) = size.filter(|size| differs(*size - known.size())) { + if let Some(size) = size.filter(|size| differs(ctx, viewport, *size - known.size())) { act(ctx, viewport, WindowAction::SetInnerSize(size)); } } diff --git a/crates/ui-contract/src/style/mod.rs b/crates/ui-contract/src/style/mod.rs index dc5783d61..a2fd71549 100644 --- a/crates/ui-contract/src/style/mod.rs +++ b/crates/ui-contract/src/style/mod.rs @@ -18,6 +18,7 @@ pub use cache::{Accepted, accepted_variant}; pub use craft_behavior::{ControlMetrics, Insets, Metrics}; #[doc(hidden)] pub use craft_theme::GroupValues; +pub use craft_theme::LetterCase; pub use craft_theme::{FlagMask, Flags, Mix, Resolve, State, StateMix, Stateful, States, TokenGroup, Tokens, TypeRole, Variant}; pub use craft_ui_macros::{ComponentStyle, TokenGroup}; pub(crate) use cx::control_metrics; diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 924eed4d6..6b86efe0f 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1,8 +1,8 @@ //! `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 (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, a repeated injected press, the window that has the -//! keys, and `act`. +//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a +//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus +//! loss, non-finite injected points, a repeated injected press, the window that has the keys, and `act`. use craft_behavior::{Cursor, CursorIcon, PointerButton}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -302,6 +302,81 @@ fn a_palette_drops_its_level_while_the_app_is_inactive() { assert_eq!(frame(true, false), on_top, "the frame after the main window took focus again"); } +/// A palette stands as an ordinary window while an app-modal layer in the main window blocks it, so the modal is never +/// behind a palette: the frame after the modal opens builds the palette's window at the ordinary level, a later frame +/// raises the main window above it once, by its level (egui ignores `Focus` for a window that has focus), and the +/// palette stands above the app's windows again once the modal closes. +#[trial] +fn a_palette_stands_behind_the_window_that_holds_a_modal() { + let windows = Windows::new(); + windows.root_info(ViewportInfo { focused: Some(true), ..ViewportInfo::default() }); + let frame = |modal: bool| { + let out = windows.frame(vec![], vec![], |ui| { + windows.child_info(ViewportInfo { focused: Some(false), ..ViewportInfo::default() }); + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + if modal { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("save prompt").show(ui, |_, _| {}); + } + }); + let raise: Vec = out + .commands + .iter() + .filter(|(id, command)| *id == ViewportId::ROOT && matches!(command, ViewportCommand::WindowLevel(_) | ViewportCommand::Focus)) + .map(|(_, command)| command.clone()) + .collect(); + (builder_titled(&out, "tool").1.window_level, raise) + }; + let (on_top, normal) = (Some(egui::WindowLevel::AlwaysOnTop), Some(egui::WindowLevel::Normal)); + assert_eq!(frame(false), (on_top, vec![]), "no modal: the palette stands above the main window"); + let frames: Vec<_> = (0..4).map(|_| frame(true)).collect(); + assert_eq!(frames.last().map(|(level, _)| *level), Some(normal), "the modal open: the palette is an ordinary window"); + let raises: Vec = frames.iter().enumerate().filter(|(_, (_, raise))| !raise.is_empty()).map(|(at, _)| at).collect(); + let lowered = frames.iter().position(|(level, _)| *level == normal); + assert_eq!(raises.len(), 1, "the main window is raised once: {frames:?}"); + assert!(lowered.is_some_and(|lowered| raises[0] > lowered), "the raise follows the frame that lowered the palette: {frames:?}"); + let level = |level| ViewportCommand::WindowLevel(level); + assert_eq!( + frames[raises[0]].1, + vec![level(egui::WindowLevel::AlwaysOnTop), level(egui::WindowLevel::Normal)], + "the raise stands the main window above every window and back, without focus" + ); + frame(false); + assert_eq!(frame(false), (on_top, vec![]), "the modal closed: the palette stands above again"); +} + +/// A palette's window is hidden while the main window is minimized and shown again at its place when the main window +/// is restored, on Windows and Linux; a document window stays. On macOS a minimized main window leaves the app active, +/// and its palettes stay. +#[trial] +fn palettes_hide_while_the_main_window_is_minimized() { + for os in [Os::Windows, Os::Linux, Os::Mac] { + let windows = Windows::with(InstallSpec::new(ShellInfo::default().os(os).caps(Caps::native(os)), Arc::new(FakeSystem::new()))); + let frame = |minimized: bool| { + windows.root_info(ViewportInfo { minimized: Some(minimized), ..ViewportInfo::default() }); + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + Palette::new("doc", Some(WindowSpec::document())).show(ui, |_, _| {}); + }) + }; + let first = frame(false); + let (tool, doc) = (builder_titled(&first, "tool").0, builder_titled(&first, "doc").0); + frame(false); + let commands = |minimized: bool| -> Vec<(ViewportId, ViewportCommand)> { (0..3).flat_map(|_| frame(minimized).commands).collect() }; + let sent = |commands: &[(ViewportId, ViewportCommand)], to: ViewportId| -> Vec { + commands.iter().filter(|(id, _)| *id == to).map(|(_, command)| command.clone()).collect() + }; + let (minimized, restored) = (commands(true), commands(false)); + let hides = os != Os::Mac; + let visible = |on: bool| if hides { vec![ViewportCommand::Visible(on)] } else { vec![] }; + let (tool_minimized, doc_minimized) = (sent(&minimized, tool), sent(&minimized, doc)); + let (tool_restored, doc_restored) = (sent(&restored, tool), sent(&restored, doc)); + assert_eq!(tool_minimized, visible(false), "{os:?}: the main window minimized: the palette is hidden, and nothing else is sent"); + assert_eq!(tool_restored, visible(true), "{os:?}: the main window restored: the palette is shown where it was"); + assert_eq!((doc_minimized, doc_restored), (vec![], vec![]), "{os:?}: a document window is left as it is"); + } +} + /// A full-window container mounted in its own window opens a resizable OS window titled as the container where /// viewports are available, and covers the main window's content where they are not. #[trial] diff --git a/crates/ui-macros/src/props.rs b/crates/ui-macros/src/props.rs index 158382be1..e334f26f8 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -175,7 +175,7 @@ const COLLECTION: &[Forwarded] = &[ ("striped", "bool", "Odd rows are tinted: the item reads `ItemCx::row.striped`."), ("allow_empty", "bool", "A press on the empty space below the rows empties the selection."), ("lead_on_open", "$ui::contract::LeadOnOpen", "Where the lead lands when rows first show."), - ("lead_follows_hover", "bool", "The lead, and the selection with it, moves to the row under the pointer when the pointer moves."), + ("hover_lead", "$ui::contract::HoverLead", "What the pointer moving over the rows changes: nothing, the lead, or the lead and the selection."), ("arrows_select", "bool", "The arrow keys select the row they move the lead to; off, they move the lead only."), ("arrows_wrap", "bool", "The arrow keys wrap from the last item to the first and back."), ("type_ahead", "bool", "Typed letters move the lead to the next item whose text starts with them; off, they stay shortcut candidates."), diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 1980e15bd..fc6369b3b 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -9,7 +9,7 @@ use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; -use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; +use super::{DockDropTarget, DockDropped, DockSizes, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges}; @@ -53,14 +53,21 @@ pub struct FloatingGroupStyle { /// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's /// double arrow at the end on `edge`, and a collapsed column shows against that edge of the window's rect. +/// +/// A column whose content fixes its height ([`held`](Self::held)) shows at that height whatever the rect's, and the +/// rect keeps its own height for when the content no longer fixes it: a column collapsed to icons, and one whose +/// every group is minimized. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct WindowColumn { /// The edge of the float area, in reading order, that the window keeps to: the dock model's `Floating::edge`, /// else the one nearer the window. pub edge: DockEdge, - /// The size of the collapsed column under the title row; `None` while the column is expanded. - pub collapsed: Option, + /// The height of the column under the title row when its content fixes it: a collapsed column's icons, or the + /// tab strips of a column whose every group is minimized. `None` while the rect gives the height. + pub held: Option, + /// The width of the collapsed column; `None` while the column is expanded, and the rect gives the width. + pub collapsed: Option, /// The least and most width the sides of a collapsed column's window resize it to /// ([`DockSizes::iconic_bounds`](super::DockSizes::iconic_bounds)); unbounded while the column is expanded. pub widths: (f32, f32), @@ -74,20 +81,27 @@ pub struct WindowColumn { impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. The window's sides resize its /// width within `widths`, as a docked collapsed column's inner edge does; its height stays `size`'s. pub fn collapsed(edge: DockEdge, size: Vec2, widths: (f32, f32)) -> Self { - WindowColumn { edge, collapsed: Some(size), widths, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: Some(size.y), collapsed: Some(size.x), widths, fitted: None, arrow: ColumnArrow::Collapse } + } + + /// An expanded column whose every group is minimized, their strips `height` under the title row, that keeps to + /// `edge`. The window shows at its rect's place and width and that height; its sides resize the width, and the + /// rect keeps its height, which the window takes back once a group is restored. + pub fn minimized(edge: DockEdge, height: f32) -> Self { + WindowColumn { edge, held: Some(height), collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's /// steps, and a move keeps the rect's size. pub fn fitted(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } } /// The column with the double arrow `arrow` ([`ColumnArrow::of`]). @@ -96,20 +110,25 @@ impl WindowColumn { self } - /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under the window's - /// chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect` and against the edge the window keeps - /// to. `None` while the column is expanded. + /// Where a window that keeps `rect` shows while its content fixes its height ([`Self::held`]): the column under + /// the window's chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect`, as wide as a collapsed + /// column or else as `rect`, and against the edge the window keeps to. `None` while the rect gives the height. pub fn shown(self, rect: Rect, chrome: f32, rtl: bool) -> Option { - let size = self.collapsed? + Vec2::new(0.0, chrome); + let size = Vec2::new(self.collapsed.unwrap_or(rect.width()), self.held? + chrome); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; Some(Rect::from_min_size(Pos2::new(left, rect.top()), size)) } - /// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the - /// collapsed column ([`Self::shown`]) so that the column's side on the edge the window keeps to stays on that side - /// of `rect`, whatever width the column shows at; `rect` keeps its expanded size. While expanded, `shown`. + /// The rect a window that keeps `rect` keeps when it shows at `shown`, so that it keeps its height while its + /// content fixes the shown one ([`Self::shown`]). While collapsed, `rect` moved with the collapsed column so that + /// the column's side on the edge the window keeps to stays on that side of `rect`, whatever width the column shows + /// at; `rect` keeps its expanded size. While every group is minimized, `shown`'s place and width with `rect`'s + /// height. Otherwise `shown`. pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect { let Some(at) = self.shown(rect, chrome, rtl) else { return shown }; + if self.collapsed.is_none() { + return Rect::from_min_size(shown.min, Vec2::new(shown.width(), rect.height())); + } let dx = if at_left(self.edge, rtl) { shown.left() - at.left() } else { shown.right() - at.right() }; rect.translate(Vec2::new(dx, shown.top() - at.top())) } @@ -126,7 +145,8 @@ impl WindowColumn { /// at the same place against that edge ([`Self::around_strip`]); an expanded window keeps `rect`, and the edge /// nearer it (`None`). pub fn dropped(self, rect: Rect, bounds: Rect, rtl: bool) -> (Rect, Option) { - let Some(size) = self.collapsed else { return (rect, None) }; + let (Some(width), Some(height)) = (self.collapsed, self.held) else { return (rect, None) }; + let size = Vec2::new(width, height); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; let (rect, edge) = Self::around_strip(Rect::from_min_size(Pos2::new(left, rect.top()), size), rect.size(), bounds, rtl); (rect, Some(edge)) @@ -199,7 +219,8 @@ impl Outcome for FloatingGroupOutput { /// in [`FloatingGroupOutput::collapsed_width`]) while its height stays the icons', and the rect keeps its size. A /// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are /// reported as the user makes them, and in an OS window the app runs them, so the window takes only the size the -/// host gives it. +/// host gives it. A column whose every group is minimized ([`WindowColumn::minimized`]) shows at the rect's place +/// and width and its strips' height; its sides resize the width, and the rect keeps its height. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -256,6 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, + /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the + /// running window's. + scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, /// Takes the drops released on the group, on the group's own layer. @@ -302,6 +326,7 @@ impl<'a> FloatingGroup<'a> { rtl: false, placed: None, collapsed_width: None, + scale: None, start_drag: None, take_drop: None, moving: false, @@ -338,6 +363,14 @@ impl<'a> FloatingGroup<'a> { self } + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome is sized at that scale. + #[must_use] + pub fn scale(mut self, pixels_per_point: f32) -> Self { + self.scale = Some(pixels_per_point); + self + } + /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { @@ -348,11 +381,11 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); - let header = title_row(&env.tokens); // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top - // grip; an OS window's grips lie over its title row. - let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 }; - (self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl()); + // grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own. + let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env)); + let sizes = self.scale.map_or(sizes, |scale| sizes.at_scale(scale)); + (self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl()); let mount = self.mount(); self.props = self.props.mount(mount); let minimized = self.minimized; @@ -367,10 +400,15 @@ impl<'a> FloatingGroup<'a> { fn mount(&self) -> Mount { // The frame's limits are the body's with the chrome on top. let frame = self.limits.around(Vec2::new(0.0, self.chrome)); - let collapsed = self.collapsed_rect().zip(self.column.map(|column| column.widths)); + // A collapsed column's width stays within its own bounds, a minimized one's within the panels' limits. + let widths = self.column.map(|column| match column.collapsed { + Some(_) => column.widths, + None => (frame.min.x, frame.max.map_or(f32::INFINITY, |max| max.x)), + }); + let held = self.held_rect().zip(widths); let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false); - overlay = if let Some((shown, (least, most))) = collapsed { - // The sides resize a collapsed column's width; its height is its icons'. + overlay = if let Some((shown, (least, most))) = held { + // The sides resize the column's width; its content fixes its height. let height = shown.height(); let edges = if self.minimized { ResizeEdges::NONE } else { ResizeEdges::LEFT.union(ResizeEdges::RIGHT) }; overlay.placed(shown).resize_edges(edges).size_limits(SizeLimits::new(Vec2::new(least, height), Vec2::new(most.max(least), height))) @@ -399,9 +437,9 @@ impl<'a> FloatingGroup<'a> { } } - /// Where the group shows while its column is collapsed: the collapsed column under the chrome, at the top of the - /// rect and against its edge the window keeps to. `None` while the column is expanded. - fn collapsed_rect(&self) -> Option { + /// Where the group shows while its column's content fixes its height ([`WindowColumn::shown`]). `None` while the + /// rect gives the height. + fn held_rect(&self) -> Option { self.column?.shown(self.rect, self.chrome, self.rtl) } @@ -524,14 +562,15 @@ impl Container for FloatingGroup<'_> { fn placement_changed(&mut self, change: &PlacementChange) { let mut change = *change; let fitted = self.column.is_some_and(|column| column.fitted.is_some()); - if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) { - // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. + if let Some(column) = self.column.filter(|column| column.held.is_some()) { + // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. A minimized + // window's rect takes the width and keeps its height. let resized = match change.kind { PlacementKind::Size(_) => true, - PlacementKind::Keyboard => self.collapsed_rect().is_some_and(|shown| change.rect.width() != shown.width()), + PlacementKind::Keyboard => self.held_rect().is_some_and(|shown| change.rect.width() != shown.width()), _ => false, }; - if resized { + if resized && column.collapsed.is_some() { self.collapsed_width = Some(change.rect.width()); } change.rect = column.kept(change.rect, self.rect, self.chrome, self.rtl); 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-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 568e3d011..4ef261889 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -46,6 +46,12 @@ pub fn opens_os_windows(ctx: &Context, config: &DockConfig) -> bool { config.native_windows && host.opens_windows() && host.positions_reported() } +/// The display scale the OS window `viewport` lays out at: its monitor's scale with the app's zoom, as the window +/// reported it (`WindowHost::facts`). `None` before it reported one. +pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option { + WindowHost::of(ctx).facts(viewport)?.scale.map(|scale| scale * ctx.zoom_factor()) +} + /// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool /// window (a palette level, no taskbar entry). pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 15a9f1c79..ab44830f8 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -7,7 +7,7 @@ use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; -use crate::style::StyleCx; +use crate::style::{RuleKind, RuleWidth, StyleCx}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; @@ -53,6 +53,12 @@ pub struct DockSizes { pub bar: f32, /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, + /// The divider rule a floating window draws under its title row, which the container lays out in a band of its + /// own: the rule's width in whole physical pixels on the window's display ([`Self::pixels_per_point`]). + pub title_rule: RuleWidth, + /// The display scale the sizes that depend on it are for: the running window's, or with [`Self::at_scale`] an OS + /// window's own. + pub pixels_per_point: f32, /// The band a floating window in the app window keeps clear over its title row for its top grip /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's /// height less its chrome ([`Self::window_chrome`]). @@ -107,6 +113,8 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), + title_rule: cx.rule(RuleKind::Divider).width, + pixels_per_point: cx.frame_ctx().pixels_per_point(), top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, @@ -119,10 +127,23 @@ impl DockSizes { } } - /// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the - /// band over it. + /// The height above a floating window's body: its title row, the rule under it and, for a window in the app + /// window (`in_app`), the band over it. pub fn window_chrome(&self, in_app: bool) -> f32 { - self.title_row + if in_app { self.top_band } else { 0.0 } + self.title_row + self.title_rule.points(self.pixels_per_point) + if in_app { self.top_band } else { 0.0 } + } + + /// The sizes for a window on a display of `pixels_per_point`: an OS window lays out at its own monitor's scale. + #[must_use] + pub fn at_scale(mut self, pixels_per_point: f32) -> Self { + self.pixels_per_point = pixels_per_point; + self + } + + /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` + /// while a group is open. + pub fn minimized_height

(&self, column: &Column

) -> Option { + column.groups.iter().all(|group| group.minimized).then_some(self.strip * column.groups.len() as f32) } /// The width bounds of an expanded column from the limits of its panels. diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 5d3c00ca7..954fc901f 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -187,7 +187,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { struct AreaMemory

{ /// The open flyout when the host binds none. open: Option

, - /// The running move or resize of a floating window. + /// The running resize or keyboard move of a floating window. moving: Option>, /// The least window id above every id the workspaces this area showed held: an undo that brings back an older /// workspace keeps its new windows above it ([`Workspace::raise_window_floor`]). @@ -1270,6 +1270,10 @@ impl Pass<'_, P> { /// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records /// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]). /// + /// A window whose every group is minimized shows its title row and their strips at its rect's place and width + /// ([`WindowColumn::minimized`]): its sides resize its width, and its placement keeps its expanded height, so a + /// restore shows it at that height again. + /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps @@ -1297,6 +1301,14 @@ impl Pass<'_, P> { let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); let opening = native::opening(&ctx, scene.config, window, &specs, group_id); + // An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the + // main window's. + let scale = opening + .spec + .as_ref() + .and_then(|_| WindowHost::of(&ctx).viewport_of(group_id)) + .and_then(|viewport| native::pixels_per_point(&ctx, viewport)); + let window_sizes = scale.map_or(scene.sizes, |scale| scene.sizes.at_scale(scale)); let movable = rights.iter().all(|rights| rights.movable); // The title row is the column's bar: its double arrow and Close; the menu opens from a context request on // its band. @@ -1330,6 +1342,8 @@ impl Pass<'_, P> { WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of)) } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { WindowColumn::fitted(edge, Vec2::new(width, content)) + } else if let Some(strips) = scene.sizes.minimized_height(&window.column) { + WindowColumn::minimized(edge, strips) } else { WindowColumn::expanded(edge) } @@ -1343,6 +1357,9 @@ impl Pass<'_, P> { .takes_drops(target, &dropped) .command_scope(DockCommands::SCOPE) .id(group_id); + if let Some(scale) = scale { + group = group.scale(scale); + } group = match opening.spec.clone() { Some(window_spec) => group.native(window_spec), None => group.bounds(scene.bounds), @@ -1363,7 +1380,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; @@ -1373,8 +1393,9 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } - // The height above the window's body: the title row, and in the app window the band over it. - let chrome = scene.sizes.window_chrome(opening.spec.is_none()); + // The height above the window's body at its scale: the title row, the rule under it, and in the app window + // the band over it. + let chrome = window_sizes.window_chrome(opening.spec.is_none()); // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. let resized = output .placed @@ -1406,8 +1427,11 @@ impl Pass<'_, P> { let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); self.report.actions.extend(reported); } - } else if let Some(mut change) = output.placed { - // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. + } else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit) + { + // The layer host shows a window its title row moves under the pointer, so the move reaches the workspace + // once, when it ends: one edit. A collapsed window keeps its edge until then, and the move ends where its + // strip was dropped. let mut keeps = shape.collapsed.map(|_| edge); if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); @@ -1470,8 +1494,9 @@ fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> /// The workspace edit of a floating window's move or resize, the step `phase` of a gesture that `action` /// (`Action::MoveFloating`) places the window by: the gesture runs from the window's `Begin` to its `Commit`, so one -/// drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the panels' -/// permissions with the lock applied, which refuse the move of a locked workspace. +/// drag is one undo step. A move by the title row arrives only as its `Commit`, which sets the place. `moving` holds +/// the gesture and the workspace it began on; `rights` are the panels' permissions with the lock applied, which refuse +/// the move of a locked workspace. fn window_edit( ctx: &Context, current: &Arc>, diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index 4a5d2abeb..0c2a31a27 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -96,38 +96,45 @@ impl DockPanels for Demo { } /// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the -/// end, with one floating group and one floating window collapsed to icons. -fn workspace() -> Arc> { +/// end, with one floating group, `minimized` or not, and one floating window collapsed to icons. +fn workspace(minimized: bool) -> Arc> { let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1); let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE); let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE); icons.iconic = true; let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre); - let window = Floating::single(1, vec![HISTORY], 0, WINDOW); + let mut window = Floating::single(1, vec![HISTORY], 0, WINDOW); + window.column.groups[0].minimized = minimized; let mut collapsed = Floating::single(2, vec![NAVIGATOR], 0, COLLAPSED_WINDOW); collapsed.column.iconic = true; Arc::new(Workspace::new(Layout::new(Some(root), vec![window, collapsed]))) } -fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { +fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> StoryOutput { /// One spec model for every story, so its revision stays put across frames. static SPECS: LazyLock> = LazyLock::new(|| Tracked::new(DemoSpecs)); - let (workspace, workspace_at) = data.value_at("workspace", workspace()); + let (workspace, workspace_at) = data.value_at("workspace", workspace(minimized)); DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn docked_columns_a_floating_group_and_a_flyout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn a_canvas_group_the_host_draws(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn host_rows_above_the_dock_rows_in_a_panel_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }, false) +} + +/// The floating group minimized: its window shows the title row and the tab strip at its width. +#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] +fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, true) } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export.rs b/crates/ui-patterns/src/patterns/form_dialogs/export.rs index 8cb0d5fbd..00c5e6431 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export.rs @@ -388,7 +388,7 @@ const MIN_SIDE: f64 = 1.0; impl ExportOptions { /// The options as the controls can hold them for a document of size `source`: a format the list has (the first - /// when not), a resample method of `methods` (the first when not; any method when `methods` is empty), a quality + /// when not), a resample method of `methods` (Automatic when listed, else the first; any method when `methods` is empty), a quality /// of 1 to 100, and a size the document can take. A linked pixel width keeps its width and /// takes the height from this document (the last export's proportions would stretch another shape); unlinked /// pixels stay as asked when in range; anything out of range becomes 100 percent. @@ -399,10 +399,8 @@ impl ExportOptions { { self.format = first.id.to_owned(); } - if let Some(first) = Resample::ALL.iter().find(|method| methods.contains(method)) - && !methods.contains(&self.resample) - { - self.resample = *first; + if !methods.is_empty() && !methods.contains(&self.resample) { + self.resample = if methods.contains(&default_resample()) { default_resample() } else { methods[0] }; } self.quality = self.quality.clamp(*QUALITY.start(), *QUALITY.end()); let in_range = |side: u32| (MIN_SIDE..=MAX_DOCUMENT_SIDE).contains(&f64::from(side)); 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 160b92a3f..39c003b1b 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 @@ -140,8 +140,8 @@ pub struct ExportAsDialog<'a> { /// The formats the list offers. #[prop(into)] formats: Vec, - /// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty. A method the - /// list lacks, remembered or from a preset, opens as the first listed one. + /// The resample methods the list offers, in the order given; all of them when empty. A method the list lacks, + /// remembered or from a preset, opens as Automatic when listed, else as the first listed one. #[prop] methods: Vec, /// The dialog's title in place of "Export As" ("Export As: Layer 1"). @@ -451,7 +451,7 @@ impl HostedExportAs { self } - /// The resample methods the list offers, in the order of [`Resample::ALL`]; all of them when empty + /// The resample methods the list offers, in the order given; all of them when empty /// ([`ExportAsDialog::methods`]). #[must_use] pub fn methods(mut self, methods: Vec) -> Self { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs index f4d9282bd..6f2417c35 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs @@ -8,7 +8,7 @@ use crate::display::{Shade, Text}; use crate::list::{List, ListRow, ThumbAspect}; use crate::patterns::presets::PresetId; use crate::primitives::{ContentPainterCx, StrokeWidth}; -use crate::runtime::env::{Env, Label, UnitKind}; +use crate::runtime::env::{Label, UnitKind}; use crate::style::TypeRole; use crate::tabs::{Tab, TabKind, TabStrip}; use crate::tile_grid::{Tile, TileGrid}; @@ -171,7 +171,7 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea } else { let count = read.units.number(cards.len() as f64, 0..=0); let heading = Label::from(words.presets_heading.fill(&[("n", &count)])); - Text::new(Env::of(ui).view().resolve(&heading).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + Text::new(heading).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); let shown = TileGrid::::new(words.cards.clone()) .card_columns(CARD_COLUMNS) .card() diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs index b1f23fd8c..dfdb6a893 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs @@ -5,7 +5,7 @@ use super::presets::{ BackgroundContents, ColorMode, DocumentOptions, MAX_NAME, MAX_SAVED, Orientation, PIXEL_ASPECTS, RESOLUTION_UNITS, SIZE_UNITS, SQUARE_PIXELS, }; use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label}; -use crate::buttons::Button; +use crate::buttons::{Button, IconButton}; use crate::choice::{Checkbox, Segmented, Swatch}; use crate::contract::{Bind, Entry, FieldLayout, Gap, MemoProps, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked}; use crate::display::{Shade, Text}; @@ -123,16 +123,29 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti PIXEL_ASPECTS.iter().map(|(id, _)| Entry::new((*id).to_owned(), pixel_aspect_label(words, id).clone())).collect(); pixel_aspects.extend(setup.custom_pixel_aspects.iter().map(|(id, name)| Entry::new(id.clone(), name.clone()))); - Text::new(Env::of(ui).view().resolve(&words.preset_details).as_str().to_uppercase()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + Text::new(words.preset_details.clone()).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); FieldGroup::new(words.preset_details.clone()).gap(Gap::Tight).show(ui, |ui, _| { Field::new(words.name.clone()).layout(FieldLayout::Above).id_salt("name").show(ui, |ui, _| { - let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())).limit(MAX_NAME).select_on_focus().show(ui); - if let Some(name) = shown.value().cloned() { - values.name = name; - } - if std::mem::take(&mut session.focus_name) { - focus::request(ui.ctx(), FocusTarget::Id(shown.response.id)); - } + Row::new().show(ui, |ui, _| { + let shown = TextField::new(words.name.clone(), Bind::given(values.name.clone())) + .limit(MAX_NAME) + .select_on_focus() + .sizing(Sizing::FillWidth) + .show(ui); + if let Some(name) = shown.value().cloned() { + values.name = name; + } + if std::mem::take(&mut session.focus_name) { + focus::request(ui.ctx(), FocusTarget::Id(shown.response.id)); + } + let title = words.save_preset_title.clone(); + let save = IconButton::new(IconId::new("square_plus")).label(title.clone()).tooltip(title).id_salt("save-preset").show(ui); + if clicked(&save) { + session.naming = Some(proposed_name(read)); + session.name_tried = false; + session.focus_preset_name = true; + } + }); }); let dimension = |ui: &mut Ui, session: &mut Session, side: Side| { @@ -229,22 +242,6 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti } }); }); - Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { - let current = values.profile.clone().filter(|profile| others.contains(&profile)); - let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); - if let Some(profile) = shown.value().cloned() { - values.profile = profile; - } - }); - Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { - let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); - let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; - let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); - if let Some(id) = shown.value().cloned() { - values.pixel_aspect = id; - } - }); - Field::new(words.background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let kind = BackgroundKind::of(values.background); @@ -265,15 +262,23 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti } }); }); + Field::new(words.profile.clone()).layout(FieldLayout::Above).id_salt("profile").show(ui, |ui, _| { + let current = values.profile.clone().filter(|profile| others.contains(&profile)); + let shown = Select::new(words.profile.clone(), Bind::given(current), &profiles).sizing(Sizing::FillWidth).show(ui); + if let Some(profile) = shown.value().cloned() { + values.profile = profile; + } + }); + Field::new(words.pixel_aspect.clone()).layout(FieldLayout::Above).id_salt("pixel-aspect").show(ui, |ui, _| { + let listed = pixel_aspects.iter().any(|entry| entry.value() == Some(&values.pixel_aspect)); + let current = if listed { values.pixel_aspect.clone() } else { SQUARE_PIXELS.to_owned() }; + let shown = Select::new(words.pixel_aspect.clone(), Bind::given(current), &pixel_aspects).sizing(Sizing::FillWidth).show(ui); + if let Some(id) = shown.value().cloned() { + values.pixel_aspect = id; + } + }); }); - let save = Button::new(words.save_preset_title.clone()).painted(words.save_preset.clone()).id_salt("save-preset").show(ui); - if clicked(&save) { - session.naming = Some(proposed_name(read)); - session.name_tried = false; - session.focus_preset_name = true; - } - let fitted = values.clone().fitted(); if fitted != *values { *values = fitted; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs index 6de918a89..84e82f056 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs @@ -3,7 +3,7 @@ use super::FormDialog; use super::size_model::{LinkedSize, MAX_DOCUMENT_SIDE}; -use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _}; +use crate::contract::{Bind, Bracket, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; use crate::dialog::{DialogResult, FieldRefusal, HeldAnswer}; use crate::display::Text; use crate::form::{Field, FieldGroup}; @@ -138,11 +138,11 @@ impl Resample { } } - /// The list entries of the methods in `allowed`, in the order of [`Resample::ALL`]; all of them when `allowed` names - /// none. + /// The list entries of the methods in `allowed`, in the order given; all of them in the order of + /// [`Resample::ALL`] when `allowed` names none. pub fn entries(words: &SizingWords, allowed: &[Resample]) -> Vec> { - let listed = |method: &Resample| allowed.is_empty() || allowed.contains(method); - Resample::ALL.iter().copied().filter(listed).map(|method| Entry::new(method, method.label(words))).collect() + let methods = if allowed.is_empty() { &Resample::ALL[..] } else { allowed }; + methods.iter().map(|&method| Entry::new(method, method.label(words))).collect() } } @@ -412,10 +412,11 @@ impl Kit { } } - /// The width and height rows, with the chain beside them when the model draws one. + /// The width and height rows, with the chain bracketed to them when the model draws one. pub(super) fn sides(&self, ui: &mut Ui, size: &mut LinkedSize) { let chain = size.has_chain(); - Row::new().show(ui, |ui, _| { + let row = if chain { Row::new().bracket(if size.is_linked() { Bracket::Linked } else { Bracket::Unlinked }) } else { Row::new() }; + row.show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { self.row(ui, size, Dimension::Width); self.row(ui, size, Dimension::Height); @@ -465,6 +466,7 @@ impl Kit { .range(range.clone()) .unit_label(unit_name.clone()) .number_enabled(editable) + .sizing(Sizing::Content) .id_salt("field") .show(ui); if let Some(number) = shown.edit.value().copied().flatten() { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs index 2f518ac4a..5b571c966 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs @@ -4,7 +4,7 @@ use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, set_size_json, sh use crate::choice::Checkbox; use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; -use crate::form::Field; +use crate::layout_components::Row; use crate::pickers::Select; use crate::runtime::env::{ColumnSize, Label, UnitKind}; use crate::runtime::{keys, overlay}; @@ -155,7 +155,7 @@ pub struct ImageSize<'a> { /// Binds the open state to `open`. #[prop(name = "opened")] open: Option>, - /// The methods the list offers, in the order of [`Resample::ALL`]; all of them when empty. + /// The methods the list offers, in the order given; all of them when empty. #[prop] methods: Vec, /// The bytes one pixel of the flat image takes, for the file size readout: the mode's colour channels at the @@ -220,18 +220,19 @@ impl<'a> ImageSize<'a> { } } } - let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); - if let Some(on) = on.value().copied() { - state.size.resampling(on); - } - if state.size.is_resampling() { - Field::new(words.resample_method.clone()).id_salt("method").show(ui, |ui, _| { - let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).show(ui); + // Resample and its method share a row that starts in the control column. + Row::new().id_salt("resample-row").show(ui, |ui, _| { + let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); + if let Some(on) = on.value().copied() { + state.size.resampling(on); + } + if state.size.is_resampling() { + let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).id_salt("method").show(ui); if let Some(method) = picked.value().copied() { state.method = method; } - }); - } + } + }); let styles = Checkbox::new(Bind::given(state.scale_styles)) .label(words.scale_styles.clone()) .id_salt("scale-styles") diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 60704d765..c10dbad28 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -65,6 +65,10 @@ struct Bed { } fn bed(layout: Layout) -> Bed { + bed_with(layout, DockConfig::default()) +} + +fn bed_with(layout: Layout, config: DockConfig) -> Bed { let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); @@ -77,7 +81,7 @@ fn bed(layout: Layout) -> Bed { let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); let mut panels = Panels; - let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, config.clone()).show(ui); *held.borrow_mut() = workspace; seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { @@ -138,15 +142,13 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { assert!(window.panels().any(|panel| *panel == SECOND), "the tab joined the window: {:?}", bed.actions.borrow()); } -/// A window's move is the area's own edit, written each pass, and keeps its drag; a host that replaces the workspace -/// ends the drag, and the release drops nothing. +/// A host that replaces the workspace while a window's move runs ends the drag, and the release drops nothing. #[trial] -fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() { +fn a_replaced_workspace_ends_a_window_drag() { let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let by = Vec2::new(-40.0, 30.0); press_and_move(&mut bed.fixture, window_title(), by); - let moved_to = bed.workspace.borrow().layout().floating[0].rect; - assert!(dragging(&bed) && moved_to != WINDOW_AT, "the window moves under its drag: {moved_to:?}"); + assert!(dragging(&bed), "the window's drag runs"); Arc::make_mut(&mut bed.workspace.borrow_mut()).replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))))); bed.fixture.frame(vec![moved(window_title() + by * 1.25)]); assert!(!dragging(&bed), "the replacement ended the drag"); @@ -175,7 +177,7 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let mut fixture = Fixture::new(move |ui| { let given = held.borrow().clone(); let mut panels = Requesting; - let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default().title_bar_docks(false)).show(ui); Arc::make_mut(&mut held.borrow_mut()).apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply"); seen.borrow_mut().extend(out.requested); }); @@ -185,11 +187,40 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let own = |action: &Action| *action == Action::activate(DOCKED) || *action == Action::activate(WINDOW); assert!(!asked.is_empty() && asked.iter().all(own), "each body's request came back: {asked:?}"); assert_eq!(workspace.borrow().layout().floating[0].rect, WINDOW_AT, "nothing moved yet"); - press_and_move(&mut fixture, window_title(), Vec2::new(-40.0, 30.0)); + let by = Vec2::new(-40.0, 30.0); + press_and_move(&mut fixture, window_title(), by); + fixture.frame(vec![release(window_title() + by)]); + fixture.settle(); let moved_to = workspace.borrow().layout().floating[0].rect; assert!(moved_to != WINDOW_AT, "the host's copy took the window's move: {moved_to:?}"); } +/// A drag of a floating window's title row shows the window under the pointer in the frame of each step, in one pass; +/// the workspace takes the move once, on the drop. +#[trial] +fn a_dragged_floating_window_stands_under_the_pointer_in_each_frame_and_moves_on_the_drop() { + let mut bed = bed(with_window(None)); + let from = window_title(); + let step = Vec2::new(-10.0, 8.0); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for n in 1..=4 { + let to = WINDOW_AT.translate(step * n as f32); + bed.fixture.frame(vec![moved(from + step * n as f32)]); + let shown = layer_rects(bed.fixture.ctx()); + assert!( + shown.iter().any(|rect| (rect.min - to.min).length() < SLACK && (rect.size() - to.size()).length() < SLACK), + "step {n}: the window stands under the pointer in its frame: {shown:?}, wanted {to:?}" + ); + assert_eq!(bed.fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "step {n}: the workspace is not written while the move runs"); + } + bed.fixture.frame(vec![release(from + step * 4.0)]); + bed.fixture.settle(); + let rect = bed.workspace.borrow().layout().floating.first().map(|window| window.rect); + assert!(rect.is_some_and(|rect| (rect.min - (WINDOW_AT.min + step * 4.0)).length() < SLACK), "the drop moves the window: {rect:?}"); +} + /// A dock area's first pass leaves a drag running in another area alone. #[trial] fn an_areas_first_pass_keeps_a_running_drag() { @@ -247,11 +278,14 @@ fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by() ); } -/// The window's rect while a press at `from` drags by `by`, before the release, which would dock a window moved over -/// the docked group. +/// The window's rect after a press at `from` drags by `by` and releases, in an area whose title-row drags only move a +/// window, so the release docks nothing. fn dragged_from(from: Pos2, by: Vec2) -> Rect { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); + let config = DockConfig::default().title_bar_docks(false); + let mut bed = bed_with(with_window(Some(Node::tabs(vec![DOCKED], 0))), config); press_and_move(&mut bed.fixture, from, by); + bed.fixture.frame(vec![release(from + by)]); + bed.fixture.settle(); bed.workspace.borrow().layout().floating[0].rect } @@ -520,6 +554,52 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); } +/// A floating window whose every group is minimized shows its title row and tab strip at its place and width. Its free +/// side resizes its width and not its height, and its rect keeps the expanded height, which the window shows at again +/// once the group is restored. +#[trial] +fn a_window_whose_groups_are_all_minimized_shows_its_strip_and_comes_back_at_its_height() { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); + let window_layer = |bed: &Bed| { + let layers = layer_rects(bed.fixture.ctx()).into_iter().filter(|rect| rect.contains(window_title())); + layers.min_by(|a, b| a.area().total_cmp(&b.area())).expect("the window's layer holds its title row") + }; + let strip = |bed: &Bed| { + let lists = bed.fixture.by_role(Role::TAB_LIST).into_iter().filter(|list| WINDOW_AT.expand(SLACK).contains_rect(list.rect)); + lists.map(|list| list.rect).next().expect("the window shows its tab strip") + }; + Arc::make_mut(&mut bed.workspace.borrow_mut()) + .apply(Action::set_minimized(WINDOW, true), false, |_| Permissions::ALL) + .expect("the group minimizes"); + bed.fixture.settle(); + let shown = window_layer(&bed); + assert!((shown.bottom() - strip(&bed).bottom()).abs() <= SLACK, "the window ends at its strip: {shown:?}, {:?}", strip(&bed)); + assert!((shown.min - WINDOW_AT.min).length() <= SLACK && (shown.width() - WINDOW_AT.width()).abs() <= SLACK, "at its place and width: {shown:?}"); + + // The window keeps to the end edge; its start side is free, and a press just inside it holds the side's grip. + let side = Pos2::new(shown.left() + 2.0, shown.center().y); + let by = Vec2::new(-40.0, 10.0); + press_and_move(&mut bed.fixture, side, by); + bed.fixture.frame(vec![release(side + by)]); + bed.fixture.settle(); + let resized = window_layer(&bed); + let rect = bed.workspace.borrow().layout().floating[0].rect; + assert!((resized.width() - (shown.width() - by.x)).abs() <= SLACK, "the side resizes the width: {shown:?}, then {resized:?}"); + assert!((resized.height() - shown.height()).abs() <= SLACK, "the height stays the strip's: {resized:?}"); + assert!( + (rect.width() - resized.width()).abs() <= SLACK && rect.height() == WINDOW_AT.height(), + "the rect takes the width and keeps its height: {rect:?}" + ); + + Arc::make_mut(&mut bed.workspace.borrow_mut()) + .apply(Action::set_minimized(WINDOW, false), false, |_| Permissions::ALL) + .expect("the group restores"); + bed.fixture.settle(); + let restored = window_layer(&bed); + assert!((restored.height() - WINDOW_AT.height()).abs() <= SLACK, "restored, the window shows at its height: {restored:?}"); + assert!((restored.width() - resized.width()).abs() <= SLACK, "at the width the side gave it: {restored:?}"); +} + /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. #[trial] fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 8e0fd047e..2cc0dd9c8 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, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs}; @@ -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; @@ -257,6 +259,10 @@ 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, + /// The tree the palette window's pass produced in the last frame. + palette_tree: Option, } impl NativeDock { @@ -278,7 +284,7 @@ impl NativeDock { windows.child_info(info(true, FLOAT_AT)); let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]))); let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped }); - let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None }; + let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -300,7 +306,12 @@ impl NativeDock { let out = self.windows.frame(root, child, |ui| { actions.extend(DockArea::new("Native dock", Bind::bound(workspace), specs, &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; + self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { let _ = kept.patch(builder); @@ -308,7 +319,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) } } @@ -717,6 +728,68 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() assert_eq!(at.width(), width, "the window keeps the width the OS gave it"); } +/// A native palette whose every group is minimized shrinks to its title row and tab strip at its place and width. +/// The OS resizes its width and never its height: AppKit takes the height as fixed, and the app sends no size back +/// for the width the OS gave it. The model keeps the expanded height throughout, and restored, the window takes that +/// height back at the width it was given. +#[trial] +fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_height() { + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); + let expanded = FLOAT_AT.size(); + let mut at = FLOAT_AT; + // The OS follows the window commands of each frame, within the limits in force, and the window reports where it is. + let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { + let mut sent = Vec::new(); + for _ in 0..frames { + let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let commands = dock.frame(vec![]).1; + for command in &commands { + match command { + ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))), + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + sent.extend(commands); + } + sent + }; + let recorded = + |dock: &NativeDock| Vec2::from(dock.workspace.layout().floating[0].native.clone().expect("the model records the window").normal.size); + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, true), false, |_| Permissions::ALL).expect("the group minimizes"); + follow(&mut dock, &mut at, 3); + let strips = at; + assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}"); + if let Err(fit) = fits_exactly(dock.palette_tree.as_ref().expect("the palette ran a pass"), strips.size(), Role::TAB_LIST) { + panic!("{os:?}: the minimized window fits its title row and strip: {fit}"); + } + assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width"); + assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size"); + let builder = dock.builder.clone().expect("the palette's window opened"); + let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size")); + assert!(least.y == most.y && (least.y - strips.height()).abs() <= 0.5, "{os:?}: the height is fixed: {least:?}..{most:?}, {strips:?}"); + assert!(least.x < most.x, "{os:?}: the width resizes: {least:?}..{most:?}"); + if os == Os::Mac { + assert_eq!(builder.resizable, Some(true), "AppKit resizes the minimized window"); + } + + // The OS widens the window. + let width = expanded.x + 60.0; + at = Rect::from_min_size(at.min, Vec2::new(width, at.height())); + dock.windows.child_info(info(true, at)); + let sent = follow(&mut dock, &mut at, 3); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "{os:?}: no size goes back: {sent:?}"); + assert_eq!(recorded(&dock), Vec2::new(width, expanded.y), "{os:?}: the model takes the width and keeps the expanded height"); + + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, false), false, |_| Permissions::ALL).expect("the group restores"); + follow(&mut dock, &mut at, 3); + assert_eq!(at, Rect::from_min_size(FLOAT_AT.min, Vec2::new(width, expanded.y)), "{os:?}: restored, the window takes its height back"); + } +} + /// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its /// column, and the OS window takes its expanded size. #[trial] @@ -751,6 +824,246 @@ 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 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())); + // Both windows report the display at 125 % before the column collapses. + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + 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 specs = &dock.specs; + let out = dock.windows.frame(root, child, |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), specs, &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)) +} + +/// How far a node's edge may stray from the window's for float rounding: far under a pixel at any scale. +const FIT_ROUNDING: f32 = 0.05; + +/// Whether a window `size` big fits what its pass shows in `tree` exactly: every node lies inside it, and the lowest +/// node of `role` ends at its bottom, within float rounding. +fn fits_exactly(tree: &AccessTree, size: Vec2, role: Role) -> Result<(), String> { + let window = Rect::from_min_size(Pos2::ZERO, size); + let outside: Vec = + tree.keys().into_iter().filter_map(|key| tree.bounds_of(key)).filter(|rect| !window.expand(FIT_ROUNDING).contains_rect(*rect)).collect(); + let bottom = tree.with_role(role).into_iter().filter_map(|key| tree.bounds_of(key)).map(|rect| rect.max.y).fold(f32::MIN, f32::max); + if !outside.is_empty() { + return Err(format!("nodes past the {size:?} window: {outside:?}")); + } + if (bottom - size.y).abs() > FIT_ROUNDING { + return Err(format!("the content ends at {bottom}, the {size:?} window at {}", size.y)); + } + Ok(()) +} + +/// 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, and the +/// window fits the title row, its rule and the icons exactly. +#[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"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons: {fit}"); + } +} + +/// A native palette on a monitor at 1x while the main window is on one at 2x (a laptop with an external display): +/// collapsed to icons, its window fits the title row, the rule under it and the icons exactly at its own scale. +#[trial] +fn a_collapsed_native_palette_on_a_1x_monitor_beside_a_2x_main_window_fits_its_icons_exactly() { + let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, 2.0)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, 1.0)); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + let commands = dock.frame(vec![]).1; + at = placed_by(&commands, at); + dock.windows.child_info(scaled(true, at, 1.0)); + } + let tree = dock.palette_tree.as_ref().expect("the palette ran a pass"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons at its own scale: {fit}"); + } +} + +/// 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-patterns/tests/it/form_dialogs/export.rs b/crates/ui-patterns/tests/it/form_dialogs/export.rs index 9e8c91f79..b27455b9f 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/export.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/export.rs @@ -8,6 +8,7 @@ use craft_ui::patterns::form_dialogs::{ HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate, }; use craft_ui::runtime::requests::PathRequest; +use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; @@ -281,6 +282,36 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones() assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows"); } +/// Export As lists the app's resample methods in the order it gives, and an unlisted opening method opens as Automatic +/// when listed, else as the first listed one. +#[trial] +fn export_as_lists_resample_methods_in_the_hosts_order() { + let methods = vec![Resample::Bicubic, Resample::BicubicSmoother, Resample::NearestNeighbor, Resample::PreserveDetails]; + let host = Rc::new(RefCell::new(DialogHost::new())); + 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 mut start = ExportOptions::default(); + start.resample = Resample::Lanczos; + host.borrow_mut().open(HostedExportAs::new("Poster", document(), start).methods(methods.clone())); + fixture.idle(10); + let opened = host.borrow_mut().get_mut::().map(|dialog| dialog.options().resample).expect("the dialog is open"); + assert_eq!(opened, Resample::Bicubic, "without Automatic in the list, the first listed method opens"); + + let select = fixture.by_label("Resample").expect("the resample select"); + fixture.access(AccessActionKind::Focus, &select).idle(2); + fixture.key(Key::Space, Modifiers::NONE).idle(3); + let mut options = fixture.by_role(Role::LIST_BOX_OPTION); + options.sort_by(|a, b| a.center().y.total_cmp(&b.center().y)); + let names: Vec = options.iter().map(|option| fixture.tree().name_of(option.node).expect("the option has a name").to_owned()).collect(); + assert_eq!(names.len(), methods.len(), "the list offers the listed methods only"); + assert_eq!( + names, + ["Bicubic (smooth gradients)", "Bicubic Smoother (enlargement)", "Nearest Neighbor (hard edges)", "Preserve Details"], + "the list keeps the host's order" + ); +} + /// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed /// one, and automation cannot set an unlisted one. #[trial] diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 91004c210..74646a479 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -464,3 +464,120 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() { alt_digit(&mut fixture, Key::Num7, "7", alt); assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method"); } + +/// Opens a dialog on a host. +type Opener = fn(&mut DialogHost); + +/// Image Size's and Canvas Size's Width and Height rows (a stack of fields beside the link) show as they measured, at +/// 1x and 1.25x (#15483, #15538): each label sits beside its field, each field and unit select is as tall as a direct +/// row's control (`reference`), and Height's label starts under Width's controls. +#[trial] +fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() { + for scale in [1.0, 1.25] { + let opens: [(Opener, &str); 2] = [ + ( + |host| { + host.open(image_size()); + }, + "Resolution", + ), + ( + |host| { + host.open(canvas_size()); + }, + "Canvas extension color", + ), + ]; + for (open, reference) in opens { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + fixture.pixels_per_point(scale); + open(&mut host.borrow_mut()); + fixture.settle(); + let rect = |name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let label_of = |name: &str| { + // The field's label names the unit select's group, the number field's parent. + let tree = fixture.tree(); + let mut node = fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).node; + let label = loop { + if let Some(label) = tree.labelled_by_key(node).into_iter().next() { + break label; + } + node = tree.parent_of_key(node).unwrap_or_else(|| panic!("{name} is labelled")); + }; + tree.bounds_of(label).unwrap_or_else(|| panic!("{name}'s label is shown")) + }; + let full = rect(reference).height(); + for name in ["Width", "Height"] { + let (label, field) = (label_of(name), rect(name)); + for part in [field, rect(&format!("{name} unit"))] { + assert!(part.height() >= full - 0.5, "{name}'s controls are a full row tall at {scale}x ({reference}): {part:?} {full}"); + } + assert!(label.max.x <= field.min.x + 0.5, "{name}'s label sits before its field at {scale}x ({reference}): {label:?} {field:?}"); + assert!( + label.min.y < field.max.y && label.max.y > field.min.y, + "{name}'s label is on its field's line at {scale}x: {label:?} {field:?}" + ); + } + let (width, height) = (rect("Width").union(rect("Width unit")), label_of("Height")); + assert!(height.min.y >= width.max.y - 0.5, "Height's row starts under Width's at {scale}x ({reference}): {height:?} {width:?}"); + } + } +} + +/// The horizontal line segments one frame of `fixture` paints, as (y, from x, to x). +fn horizontal_lines(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < 0.5 => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// Image Size as 0.23.1 lays it out: the chain sits halfway between Width's and Height's controls with the bracket +/// drawn from each control to it, and Resample starts in the control column with the method on its line. +#[trial] +fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_column() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(image_size()); + fixture.settle(); + let rect = |fixture: &Fixture, name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let (width, height, link) = (rect(&fixture, "Width unit"), rect(&fixture, "Height unit"), rect(&fixture, "Maintain aspect ratio")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= 0.5, "the chain sits halfway between Width and Height: {link:?} {middle}"); + let lines = horizontal_lines(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + assert!( + lines.iter().any(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0), + "a tick runs from {name}'s control to the chain: {lines:?}" + ); + } + let (number, check, method) = (rect(&fixture, "Width"), rect(&fixture, "Resample"), rect(&fixture, "Resample method")); + assert!((check.min.x - number.min.x).abs() <= 0.5, "Resample starts at the control column: {check:?} {number:?}"); + assert!( + method.min.x >= check.max.x - 0.5 && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows Resample on its line: {method:?} {check:?}" + ); +} + +/// Canvas Size draws one rule between its title and Current Size, the title's: the first section's rule above would +/// stand right under it. The rule between the two sections stays. +#[trial] +fn canvas_size_draws_one_rule_under_its_title() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(canvas_size()); + fixture.settle(); + let text = |fixture: &Fixture, text: &str| { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")) + }; + let (title, current, new) = (text(&fixture, "Canvas Size"), text(&fixture, "Current Size"), text(&fixture, "New Size")); + let lines = horizontal_lines(&mut fixture); + let across = |top: f32, bottom: f32| lines.iter().filter(|(y, from, to)| *y > top && *y < bottom && to - from > current.width()).count(); + assert_eq!(across(title.max.y, current.min.y), 1, "one rule between the title and Current Size: {lines:?}"); + assert_eq!(across(current.max.y, new.min.y), 1, "a rule between Current Size and New Size: {lines:?}"); +} diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 81066b702..760b341b0 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -10,7 +10,7 @@ use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; use std::rc::Rc; -/// Opens the Save Document Preset pane with the button below the fields, types `name` over the proposed one and saves. +/// Opens the Save Document Preset pane with the icon on the Name row, types `name` over the proposed one and saves. fn save_preset(fixture: &mut Fixture, name: &str) { let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button"); fixture.click(&save).idle(10); @@ -266,5 +266,38 @@ fn the_new_document_layout_places_presets_and_details_below_the_tabs() { assert!(recent.bottom() <= mode.top(), "tabs go above the details"); assert!((mode.top() - depth.top()).abs() < 1.0, "color mode and depth share a row"); assert!(mode.right() <= depth.left(), "depth follows color mode"); - assert!(mode.bottom() <= save.top() && save.bottom() <= create.top(), "Save Preset is between the fields and the footer"); + assert!(save.bottom() <= create.top(), "Save Preset is above the footer"); +} + +/// The fields run Name, size, Color Mode, Background Contents, then the advanced Color Profile and Pixel Aspect Ratio; the +/// save icon (no text) sits at the end of the Name row. +#[trial] +fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits_on_the_name_row() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let top = |fixture: &Fixture, label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")).rect.top(); + let (mode, background) = (top(&fixture, "Color Mode"), top(&fixture, "Background Contents")); + let (profile, aspect) = (top(&fixture, "Color Profile"), top(&fixture, "Pixel Aspect Ratio")); + assert!(mode < background && background < profile && profile < aspect, "Background Contents comes before the advanced fields"); + + let name = fixture.by_label("Name").expect("the Name field").rect; + let save = fixture.by_label("Save Document Preset").expect("the save action").rect; + assert!(save.top() < name.bottom() && name.top() < save.bottom(), "the save icon shares the Name row"); + assert!(name.right() <= save.left(), "the save icon is at the end of the Name field"); + assert!(!fixture.texts().iter().any(|run| run.text.starts_with("Save ")), "the save control is an icon, with no text"); +} + +/// The caption role sets its text in capitals when it paints; the label stays as written. +#[trial] +fn section_captions_paint_in_capitals_and_keep_their_text() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + assert!(shows(&fixture, "PRESET DETAILS"), "the caption paints in capitals"); + assert!(fixture.by_label("Preset Details").is_some(), "the accessible name keeps the text as written"); } diff --git a/crates/ui-shell/src/shell/document_window.rs b/crates/ui-shell/src/shell/document_window.rs index 1bc55a73d..edab6e6fa 100644 --- a/crates/ui-shell/src/shell/document_window.rs +++ b/crates/ui-shell/src/shell/document_window.rs @@ -84,6 +84,8 @@ impl Outcome for DocumentWindowOutput { /// - **Title and focus.** The title is the label given to `new`; it follows the document while the app changes it. /// [`raise`](DocumentWindow::raise) brings the window forward in the pass it is set. With /// [`in_list`](DocumentWindow::in_list) the window makes itself the list's active window when it gains OS focus. +/// - **Body.** The body is laid out in the window's room and never scrolls, in the OS window and on the fallback +/// layer alike; an app that wants scrolling puts a scroll region in the body. /// - **Fallback.** Where OS windows are unavailable the document shows on a movable, resizable layer with a title row. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container)] @@ -138,7 +140,7 @@ impl<'a> DocumentWindow<'a> { /// A window titled `title`, resizable, with the installed decision's frame. pub fn new(title: impl Into