Merge pull request #3446

This commit is contained in:
autocraft-bot[bot] committed 2026-11-28 18:35:45 +00:00
commit 604941c4ba
27 files changed
+755 -105

No files matched your search

@@ -657,7 +657,7 @@ impl 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, None, screen, env.tokens.space.inset.screen)
shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, &env.tokens)
});
// A layer the user sized takes that size, at its saved position or where its anchor places it.
placement.size.is_some()
@@ -5,6 +5,7 @@ use crate::contract::{ContainerProps, Mount};
use crate::runtime::egui::areas;
use crate::runtime::memory::{MemoryStage, SaveKey, sub};
use crate::runtime::windows::{self};
use crate::style::UiTokens;
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
use serde::{Deserialize, Serialize};
@@ -94,9 +95,11 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement {
}
/// The placement a layer is shown at: the caller's `placed` rect or `placed_at` position, else the saved or session placement, else for a
/// 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.
/// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less the tokens'
/// `space.inset.screen` on each side, centred or at the overlay's float position and kept as `Overlay::drag_bounds`
/// says. A saved size and position win over the default, and are kept as the rule says too, so a layer the user moved
/// or resized past an edge keeps what the rule keeps of it inside. 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
@@ -108,9 +111,9 @@ pub(crate) fn shown_placement(
overlay: &crate::contract::Overlay,
moving: Option<Rect>,
screen: Rect,
screen_inset: f32,
tokens: &UiTokens,
) -> Placement {
let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset);
let mut placement = resting_placement(ctx, id, save, overlay, screen, tokens);
if let Some(moving) = moving {
placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into());
}
@@ -124,26 +127,33 @@ fn resting_placement(
save: Option<&SaveKey>,
overlay: &crate::contract::Overlay,
screen: Rect,
screen_inset: f32,
tokens: &UiTokens,
) -> Placement {
if let Some(given) = Placement::given(overlay) {
return given;
}
let mut placement = placement_of(ctx, id, save);
// The layer centres, and is kept, inside the screen cut to `bounds`; bounds that miss the screen leave it whole.
let region = overlay.bounds.map(|bounds| screen.intersect(bounds)).filter(|region| region.is_positive()).unwrap_or(screen);
if let Some(size) = placement.size {
// A size already stored is the one the layer took (a resize by the user): the keep rule still holds the part of
// it the rule keeps inside, as it does while the user moves the layer, so a place a drag left past an edge puts
// back what the rule keeps. A layer hung from its anchor keeps no place, so the rule has nothing to keep there.
if let (Some(pos), Place::Float(_)) = (placement.pos, &overlay.place) {
let rect = Rect::from_min_size(Pos2::from(pos), Vec2::from(size));
placement.pos = Some(overlay.drag_bounds.keep(rect, region, tokens).min.into());
}
return placement;
}
let (Some(default), Place::Float(float), true) = (overlay.size, &overlay.place, overlay.fit == OverlayFit::Resizable) else {
return placement;
};
if placement.size.is_some() {
return placement;
}
let room = (screen.size() - Vec2::splat(2.0 * screen_inset)).max(Vec2::ZERO);
let room = (screen.size() - Vec2::splat(2.0 * tokens.space.inset.screen)).max(Vec2::ZERO);
let least = overlay.size_limits.min.min(room);
let size = default.max(least).min(overlay.size_limits.max.unwrap_or(Vec2::INFINITY)).min(room);
// The layer centres, and is kept, inside the screen cut to `bounds`; bounds that miss the screen leave it whole.
let region = overlay.bounds.map(|bounds| screen.intersect(bounds)).filter(|region| region.is_positive()).unwrap_or(screen);
// The saved position is the layer's top left; the float's is where its corner sits.
let pos = placement.pos.map(Pos2::from).or_else(|| float.top_left(size)).unwrap_or_else(|| region.center() - size / 2.0);
let pos = super::window::keep_inside(Rect::from_min_size(pos, size), region).min;
let pos = overlay.drag_bounds.keep(Rect::from_min_size(pos, size), region, tokens).min;
placement.pos = Some(pos.into());
placement.size = Some(size.into());
placement
@@ -163,12 +173,8 @@ pub(super) fn measure_layer(props: &ContainerProps, id: Id, ui: &Ui) -> areas::L
let area = sub(id, "area");
match &props.mount {
Mount::Viewport { .. } if windows::mount_window(ui.ctx(), id) => ui.layer_id(),
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => {
areas::layer_of(crate::runtime::overlay::layer_tier(ui.ctx(), overlay.rank), area)
}
Mount::FullWindow => {
areas::layer_of(crate::runtime::overlay::layer_tier(ui.ctx(), crate::contract::Overlay::full_window(props.focus).rank), area)
}
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => areas::layer_of(overlay.tier(ui.ctx()), area),
Mount::FullWindow => areas::layer_of(crate::contract::Overlay::full_window(props.focus).tier(ui.ctx()), area),
_ => ui.layer_id(),
}
}
@@ -19,7 +19,7 @@ use craft_host::target::{Caps, WindowChrome, WindowState};
use craft_keymap::{Chord, Key, Mods};
use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId};
pub(crate) const MOVE_BAND: PartKey = PartKey::new("move_band");
pub(crate) use crate::runtime::pointer::MOVE_BAND;
const GRIP: PartKey = PartKey::new("resize_grip");
@@ -213,7 +213,8 @@ fn resized_edge(before: Rect, after: Rect) -> Option<ResizeEdge> {
}
/// `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's
/// bounds, whether the user moves the layer or the host places it. On an axis where it is longer than the bounds, its
/// bounds, whether the user moves the layer or the host places it, and the window's under the default
/// [`DragBounds::Inside`](crate::contract::overlay::DragBounds::Inside). On an axis where it is longer than the bounds, its
/// low edge sits on theirs.
pub fn keep_inside(rect: Rect, bounds: Rect) -> Rect {
let keep = |low: f32, high: f32, bounds_low: f32, bounds_high: f32| low.min(bounds_high - (high - low)).max(bounds_low) - low;
@@ -509,15 +510,18 @@ impl BodyHooks<'_> {
};
let mut slot = PlacementSlot::new(&mut *core.memory, id, self.save.as_ref(), overlay);
let current = slot.read();
// Where the layer stands: at the placement's size, where it is shown, which the window's keep rule
// (`Overlay::drag_bounds`) may have moved from the stored position a drag past the window's edge left.
let shown = Rect::from_min_size(rect.min, current.rect_over(rect).size());
let (start, pos, gesture) = match phase {
PressPhase::Down { .. } => {
self.mode.pressed = Some(current.rect_over(rect));
self.mode.pressed = Some(shown);
return;
}
PressPhase::DragStart { start, pos, .. } => {
// 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.began = Some(self.mode.pressed.unwrap_or(shown));
self.mode.restore = current.clone();
self.mode.held = grip;
(start, Some(pos), GesturePhase::Begin)
+1 -1
View File
@@ -243,7 +243,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, self.moving, screen, env.tokens.space.inset.screen);
let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, &env.tokens);
// 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
+1 -1
View File
@@ -22,7 +22,7 @@ pub use host::paint_frame_layers;
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 place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
pub use placement::{PopupRegion, layer_room};
pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for};
pub(crate) use popups::dwell;
@@ -170,7 +170,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
if let Some(nudge) = &nudge {
placed.at += nudge.offset();
}
let tier = overlay::layer_tier(ctx, overlay.rank);
let tier = overlay.tier(ctx);
// A toast or a tooltip shows first at its room, never in egui's hidden sizing pass; a container's layer starts its
// `Area` at its measured size (`LayerSpec::size`).
if sized && areas::layer_rect(ctx, area).is_none() {
@@ -270,6 +270,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
entry.exiting = layer.exiting;
entry.cover = cover;
entry.region = layer.region;
entry.among_windows = overlay.among_windows;
entry.scoped = scope.is_some();
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
entry.closes_on_commands = overlay.dismiss.commands;
@@ -319,7 +320,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y));
let unplaced = placement(ctx, layer, covers, measured, bounds, anchor);
let parent = overlay::drawing_parent(ctx);
let tier = overlay::layer_tier(ctx, overlay.rank);
let tier = overlay.tier(ctx);
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
if overlay.rank.is_modal() && appears {
overlay::close_popups_outside(ctx, &[layer.id]);
@@ -378,7 +379,7 @@ fn show_in_popup(
let overlay = layer.overlay;
let window = ctx.content_rect();
let area = area_id(layer.id);
let tier = overlay::layer_tier(&ctx, overlay.rank);
let tier = overlay.tier(&ctx);
let cover = match overlay.rank {
Rank::Modal { backdrop } => {
let scrim = match backdrop {
@@ -546,8 +547,13 @@ pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> Layer
let overlay = layer.overlay;
let mut memory = recall(layer, ctx);
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
let mut entry =
OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(overlay::layer_tier(ctx, overlay.rank), area_id(layer.id)));
let mut entry = OpenEntry::new(
layer.id,
overlay.rank,
overlay.keys,
rect,
areas::layer_of(overlay::layer_tier(ctx, overlay.rank, overlay.among_windows), area_id(layer.id)),
);
entry.role = overlay.role;
entry.scoped = scope.is_some();
entry.window = true;
@@ -1,5 +1,6 @@
//! Where a layer sits and how it sizes: anchors, places, viewport shares, fit, resize and size limits.
use crate::style::UiTokens;
use craft_behavior::overlay::{Align, Side};
use egui::{Align2, Pos2, Rect, Vec2};
@@ -60,6 +61,39 @@ impl FloatPlace {
}
}
/// How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title.
///
/// It holds while the user moves the layer, when the layer is placed at a position, and when it shows at the placement
/// a pass stored: the window's safe rect, cut to the overlay's [`bounds`](super::Overlay::bounds) when it sets them.
/// Bounds of the overlay's own still hold the whole layer while the user moves it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragBounds {
/// The whole layer: a move stops where an edge of the layer meets the window's.
#[default]
Inside,
/// A strip of its title: its top edge stays at or below the window's top, and at least `size.bar.title` of its
/// height and `size.dialog.button` of its width stay inside, so the user takes it back by its title band. The rest
/// may go past the window's edges: a dialog moved mostly aside shows what lies behind it, as InDesign's do. A layer
/// smaller than the strip on an axis stays whole inside on that axis.
TitleVisible,
}
impl DragBounds {
/// `rect` moved, at its size, the least distance that keeps what this rule keeps of it inside `bounds`.
pub(crate) fn keep(self, rect: Rect, bounds: Rect, tokens: &UiTokens) -> Rect {
match self {
DragBounds::Inside => crate::contract::body::keep_inside(rect, bounds),
DragBounds::TitleVisible => {
let strip = Vec2::new(tokens.size.dialog.button, tokens.size.bar.title).min(rect.size());
let x = rect.min.x.min(bounds.max.x - strip.x).max(bounds.min.x + strip.x - rect.width());
let y = rect.min.y.min(bounds.max.y - strip.y).max(bounds.min.y);
rect.translate(Pos2::new(x, y) - rect.min)
}
}
}
}
/// Where an egui layer sits.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
@@ -267,12 +267,14 @@ pub(super) struct Placed {
}
/// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect
/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its
/// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side
/// while it stays open, asks for the same side, and the content fits there or that side is the larger. A layer that `covers` its anchor
/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor.
/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so
/// the size it measures decides the side.
/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow (`Overlay::drag_bounds`). A float that
/// keeps only its title strip inside has the room it would have with the whole of it inside, so a move past an edge
/// leaves its size as it was. An anchored layer takes its side by its size: below its anchor, above when the room below
/// is too short and the room above is larger, and keeps that side while it stays open, asks for the same side, and the
/// content fits there or that side is the larger. A layer that `covers` its anchor ([`layer_covers_anchor`]) and fits
/// neither side keeps its height within the bounds and slides over the anchor. Before its size is known (a popup's
/// first, hidden pass) it takes no side and its body is offered `content_room`, so the size it measures decides the
/// side.
pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Option<egui::Vec2>, bounds: Rect, anchor: Rect) -> Placed {
let rtl = layer.env.layer_direction().is_rtl();
let cap = cap(layer.overlay, bounds, anchor);
@@ -306,8 +308,10 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op
let kept = within_bounds(layer.overlay, bounds);
let size = size.unwrap_or(egui::Vec2::ZERO);
let min = float.top_left(size).unwrap_or_else(|| kept.center() - size / 2.0);
let at = crate::contract::body::keep_inside(Rect::from_min_size(min, size), kept).min;
Placed { at, side: None, asked: None, room: (kept.max - at).max(egui::Vec2::ZERO).min(cap) }
let rect = Rect::from_min_size(min, size);
let at = layer.overlay.drag_bounds.keep(rect, kept, &layer.env.tokens).min;
let inside = crate::contract::body::keep_inside(rect, kept).min;
Placed { at, side: None, asked: None, room: (kept.max - inside).max(egui::Vec2::ZERO).min(cap) }
}
}
}
@@ -1,7 +1,7 @@
//! The `Overlay` data, its presets and builders, its dismissal rules and the placement changes it reports.
use super::opener::{Opener, Trigger};
use super::place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
use super::place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
use crate::runtime::access::PopupKind;
use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::motion::{MotionSpec, spec};
@@ -10,7 +10,7 @@ use crate::runtime::windows::ResizeEdge;
use craft_behavior::overlay::{Align, MinWidth, Side};
use craft_behavior::{GesturePhase, OwnerClass};
use egui::emath::TSTransform;
use egui::{Align2, Id, Pos2, Rect, Response, Vec2};
use egui::{Align2, Context, Id, Pos2, Rect, Response, Vec2};
use std::borrow::Cow;
/// What a press outside the layer and its anchor does.
@@ -109,6 +109,9 @@ pub struct Overlay {
pub min_width: MinWidth,
/// Whether the user may move it.
pub movable: bool,
/// How much of it stays inside the window when the user moves it or it floats at a position (default
/// [`DragBounds::Inside`]).
pub drag_bounds: DragBounds,
/// How the user may resize it.
pub resize: Resize,
/// Its rank.
@@ -159,6 +162,10 @@ pub struct Overlay {
pub continue_move: Option<Vec2>,
/// What the layer is for; a progress window is left out of `any_open`.
pub role: LayerRole,
/// The layer stands among the floating windows, in the order egui keeps for them, whatever its rank: the last of
/// them shown, pressed or raised is on top, and the app's own egui windows stack with it. Unset, a `Rank::Popup`
/// stands above every window instead; a collapsed dock column's flyout sets it.
pub among_windows: bool,
/// Set only by [`Overlay::full_window`].
full_window: bool,
}
@@ -180,6 +187,7 @@ impl Overlay {
fit,
min_width: MinWidth::None,
movable: false,
drag_bounds: DragBounds::Inside,
resize: Resize::NONE,
rank,
keys,
@@ -199,6 +207,7 @@ impl Overlay {
moved_by_app: false,
continue_move: None,
role: LayerRole::default(),
among_windows: false,
full_window: false,
}
}
@@ -461,12 +470,31 @@ impl Overlay {
self
}
/// Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]):
/// [`DragBounds::TitleVisible`] lets a dialog go past the window's edges with its title band left to grab.
pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay {
self.drag_bounds = bounds;
self
}
/// Sets what the layer is for ([`Overlay::role`]).
pub fn role(mut self, role: LayerRole) -> Overlay {
self.role = role;
self
}
/// Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]).
pub fn among_windows(mut self, on: bool) -> Overlay {
self.among_windows = on;
self
}
/// The egui tier the layer opened now shows in: its rank's, raised to that of the layer it is opened inside, and
/// the floating windows' for a layer that stands among them.
pub(crate) fn tier(&self, ctx: &Context) -> crate::runtime::egui::areas::Tier {
crate::runtime::overlay::layer_tier(ctx, self.rank, self.among_windows)
}
/// Sets whether the move band moves the OS window the layer is shown in, in place of the layer.
pub fn moves_window(mut self, on: bool) -> Overlay {
self.moves_window = on;
+1 -1
View File
@@ -225,7 +225,7 @@ pub type LayerKey = egui::LayerId;
/// How an overlay layer ranks among egui's orders, bottom to top: the one place the runtime chooses an `Order`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Tier {
/// Floating windows and panels.
/// Floating windows and panels, and the popups that stand among them.
Window,
/// Toasts, popups, modals and their chrome.
Foreground,
@@ -250,11 +250,15 @@ fn movable_id(viewport: ViewportId) -> egui::Id {
/// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands
/// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go
/// to the band), else what the app wrote with [`write_movable`], else true.
/// to the band), else what the app wrote with [`write_movable`], else true. Read between passes (by an integration or
/// a test after the frame), it answers for the viewport's last pass: egui counts a pass when it ends, so there the
/// pass number has already moved past the pass that wrote the flag.
#[doc(hidden)]
pub fn movable(ctx: &Context) -> bool {
match movable_record(ctx) {
Some((pass, movable)) if pass == pass_number(ctx) => movable,
let number = pass_number(ctx);
let latest = if crate::runtime::frame::running(ctx).is_some() { Some(number) } else { number.checked_sub(1) };
match (movable_record(ctx), latest) {
(Some((pass, movable)), Some(latest)) if pass == latest => movable,
_ => true,
}
}
+45 -18
View File
@@ -26,7 +26,8 @@ pub enum Backdrop {
Scrim,
}
/// An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen.
/// An overlay's place in the order. `Rank` chooses a layer's egui order; a popup that stands among the floating
/// windows (an iconic column's flyout) shares theirs.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Rank {
@@ -186,6 +187,9 @@ pub struct OpenEntry {
pub(crate) place: Option<usize>,
/// The dialog of a dialog host the layer shows for (`stack_place`).
dialog: Option<Id>,
/// A popup that stands among the floating windows (`Overlay::among_windows`, a dock column's flyout): left to
/// egui's area order with them, so the last of them opened or pressed is on top.
pub(crate) among_windows: bool,
}
/// A replay moves the entry's screen rects with its record; the rest stays.
@@ -236,6 +240,7 @@ impl OpenEntry {
region: None,
place: None,
dialog: None,
among_windows: false,
}
}
@@ -546,10 +551,15 @@ pub fn drawing_parent(ctx: &Context) -> Option<Id> {
/// The tier a layer of `rank` opened now shows in: the higher of its rank's and that of the layer whose body is
/// running. egui sorts layers by tier before the family order, so a floating window opened inside a modal's family
/// shows in the modal's tier, above its parent, and takes input.
pub(crate) fn layer_tier(ctx: &Context, rank: Rank) -> Tier {
/// shows in the modal's tier, above its parent, and takes input. A layer that stands among the floating windows
/// (`among_windows`) shows in their tier, so it joins their order wherever it is opened.
pub(crate) fn layer_tier(ctx: &Context, rank: Rank, among_windows: bool) -> Tier {
let parent = with_pass(ctx, |pass| pass.drawing.last().map(|(_, tier)| *tier));
parent.map_or(rank.tier(), |parent| parent.max(rank.tier()))
let own = if among_windows { Tier::Window } else { rank.tier() };
match parent {
None => own,
Some(parent) => parent.max(own),
}
}
/// Whether the layer `id`, open in this pass, faded out in the last one: it opens anew.
@@ -890,13 +900,16 @@ fn families(entries: &[OpenEntry], raised: &IdMap<u64>) -> Vec<Vec<OpenEntry>> {
groups.into_iter().map(|(_, members)| members).collect()
}
/// The end hook: raises the families that appeared, were pressed or were asked to (`raise`), hands egui the order of
/// every layer above the floating windows (which keep egui's own area order, where an asked raise moves them to the
/// top), and records the open-modal fact.
/// The end hook: raises the families that appeared, also one that reopened during its own exit fade, those that were
/// pressed and those that were asked to (`raise`), hands egui the order of every layer above the floating windows
/// (which keep egui's own area order, where an asked raise moves them to the top), and records the open-modal fact.
/// A family that stands in the floating windows' order is raised there when it reopens during its fade: egui showed its
/// area in the pass before, so egui raises none.
pub(crate) fn end_pass(ctx: &Context) {
let viewport = pass::current_viewport(ctx);
let (current, last_ids, raise) =
with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::<Vec<_>>(), pass.raise.clone()));
let (current, last, raise) = with_pass(ctx, |pass| {
(pass.current.clone(), pass.last.iter().map(|entry| (entry.id, entry.exiting)).collect::<Vec<_>>(), pass.raise.clone())
});
let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin);
let now = pass::root_frame_nr(ctx);
let (order, to_top, floats, asked) = with_persist(ctx, viewport, |persist| {
@@ -911,12 +924,23 @@ pub(crate) fn end_pass(ctx: &Context) {
.filter(|entry| entry.parent.is_none_or(|parent| !current.iter().any(|other| other.id == parent)))
.map(|entry| entry.id)
.collect();
let mut asked: Vec<Id> = Vec::new();
for root in &roots {
if !last_ids.contains(root) {
stamp(*root, persist);
let shown = current.iter().find(|entry| entry.id == *root);
// A root the last pass did not have appears, and so does one that faded out then and is open again
// (`reopened`): it shows over whatever the fade let over it.
let kept = last.iter().any(|(id, _)| id == root);
let reopened = last.iter().any(|(id, exiting)| id == root && *exiting) && shown.is_none_or(|entry| !entry.exiting);
if kept && !reopened {
continue;
}
stamp(*root, persist);
// A root that reopens during its own fade is raised in egui's area order as a press raises it: egui showed
// its area in the pass before, so it raises none. A root that first shows there is raised by egui itself.
if reopened && shown.is_some_and(|entry| !entry.window && (entry.rank == Rank::Window || entry.among_windows)) {
asked.push(*root);
}
}
let mut asked: Vec<Id> = Vec::new();
for id in raise {
let mut at = current.iter().find(|entry| entry.id == id);
while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) {
@@ -947,13 +971,16 @@ pub(crate) fn end_pass(ctx: &Context) {
persist.stack.clear();
for members in &families {
for member in members {
// A floating window or panel (`Rank::Window`) is left to egui's own area order, which raises a layer
// when it first shows and when it is pressed: the app's own egui windows stack with it in that one
// order, so a dialog the app opens later shows above it. Listed layers would go above every unlisted
// layer of their egui order, so a float opened from a listed layer (a panel floated from a full-window
// container) is listed too, above its parent. An OS window has no egui layer here.
// A floating window or panel (`Rank::Window`), and a popup that stands among them (an iconic column's
// flyout), are left to egui's own area order, which raises a layer when it first shows and when it is
// pressed: the app's own egui windows stack with them in that one order, so a dialog the app opens
// later shows above them, and opening a flyout or pressing it raises it as a window is raised. Listed
// layers would go above every unlisted layer of their egui order, so a window opened from a listed
// layer (a panel floated from a full-window container) is listed too, above its parent, and so is the
// flyout of a column inside it. An OS window has no egui layer here.
let over_listed = member.parent.is_some_and(|parent| listed.contains(&parent));
if !member.window && (member.rank != Rank::Window || over_listed) {
let windows_order = member.rank == Rank::Window || member.among_windows;
if !member.window && (!windows_order || over_listed) {
order.extend(member.cover);
order.push(member.layer);
listed.push(member.id);
+15 -7
View File
@@ -11,8 +11,8 @@ use crate::runtime::inputs::{self, Input};
use crate::runtime::sampler;
use craft_behavior::press::{MULTI_TAP_SLOP, MULTI_TAP_TIME};
use craft_behavior::{
Buttons, MultiTap, MultiTouch, PartRef, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressStart, ResolveFor, Shape,
Winner, count_clicks, resolve,
Buttons, MultiTap, MultiTouch, PartKey, PartRef, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressStart, ResolveFor,
Shape, Winner, count_clicks, resolve,
};
use craft_keymap::Mods;
use craft_theme::HitSizes;
@@ -21,6 +21,10 @@ use smallvec::SmallVec;
use std::collections::HashMap;
use std::sync::Arc;
/// The key of a container's move band, the part a press-drag moves its layer or window by (the body step declares
/// it). The press winners give it no drag from under a control over it ([`PressWinners`]).
pub(crate) const MOVE_BAND: PartKey = PartKey::new("move_band");
/// Points one wheel line adds to `PointerFrame.scroll`; scroll owners apply their own notch (the wheel service).
pub(crate) const WHEEL_LINE_POINTS: f32 = 40.0;
@@ -1005,8 +1009,9 @@ pub(crate) fn made_lookups(ctx: &Context, viewport: ViewportId) -> u32 {
/// their winning shapes' place in the pass's paint order, top first. The top one takes every kind of press its shape
/// senses. Under a top shape that only drags (a window's resize grip), the click goes to the first root below whose
/// shape clicks; under one that only clicks (a button), the drag goes to the first root below whose shape drags, when
/// that root takes no click anywhere. Under a top shape that clicks and passes its drag (`Sense::PASSES_DRAG`), the
/// drag goes to the next shape under it that drags: its own root's, else the first root's below.
/// that root takes no click anywhere and that shape is no move band (`MOVE_BAND`). Under a top shape that clicks and
/// passes its drag (`Sense::PASSES_DRAG`), the drag goes to the next shape under it that drags: its own root's, else the
/// first root's below.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PressWinners {
pub click: Option<(Winner<Id>, Id)>,
@@ -1370,12 +1375,15 @@ fn winners_of(mut ranked: Vec<Ranked>) -> PressWinners {
}
}
// Under a top shape that only clicks, the first root below whose shape drags takes the drag, unless the
// root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. Under a top
// shape that passes its drag, the next shape that drags takes it, in the same root or one below.
// root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. A move band
// is not: a press on a control over the band (a title bar's Home, a menu title, a caption button) never
// moves the window, and its double click never zooms it. Under a top shape that passes its drag, the next
// shape that drags takes it, in the same root or one below, a move band too.
(true, false) => {
let passes = winners.click.is_some_and(|(top, _)| top.sense.contains(craft_behavior::Sense::PASSES_DRAG));
let root_target = winners.click.is_some_and(|(top, owner)| top.drag_to_root && root != owner);
if drags && !root_target && (passes || !(clicks || root_clicks)) {
let band = winner.part.is_some_and(|part| part.key == MOVE_BAND);
if drags && !root_target && (passes || !(clicks || root_clicks || band)) {
winners.drag = Some((winner, root));
}
break;
+102 -1
View File
@@ -4,7 +4,8 @@
use craft_behavior::overlay::{Align, Side};
use craft_behavior::{GesturePhase, Sense};
use craft_ui::contract::overlay::{Anchor, FloatPlace, Place, PlacementChange, PlacementKind};
use craft_theme::{Contrast, Mode};
use craft_ui::contract::overlay::{Anchor, DragBounds, FloatPlace, Place, PlacementChange, PlacementKind};
use craft_ui::contract::{
BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MemoProps, MemoView, Mount, Overlay, Props as _, Role,
Show as _, ShowContainer as _, Sizing,
@@ -145,6 +146,106 @@ fn a_placed_layer_reports_its_move_and_keeps_no_placement_of_its_own() {
assert!((caller.rect.get().min - commit.rect.min).abs().max_elem() > SLACK, "no placement was stored: {:?}", caller.rect.get());
}
/// A movable float dragged by its header far toward the window's bottom right corner: under the default
/// `DragBounds::Inside` it stops with the whole of it inside the window. Under `DragBounds::TitleVisible` it goes past
/// the right and bottom edges at its own size with its header still inside, and a second drag of the header moves it
/// back by the pointer's travel.
#[trial]
fn a_layer_that_keeps_its_title_strip_inside_moves_past_the_window_edges() {
for bounds in [DragBounds::Inside, DragBounds::TitleVisible] {
let (shown, log, seen) = (Cell::new(Rect::NOTHING), RefCell::new(Vec::new()), RefCell::new(Seen::default()));
let mut show = |ui: &mut Ui| {
let overlay = Overlay::floating().movable(true).drag_bounds(bounds);
let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content).header(HeaderRegion::new().band(DragBand::Move));
let out = Pane { common: Common::new(), props, log: &log }.id_salt("aside").show(ui, |ui, _| {
Probe::new(&seen).size(BODY).show(ui);
});
shown.set(out.output.rect);
};
let mut frames = Frames::new();
frames.idle(4, &mut show);
let window = frames.ctx.content_rect();
let start = shown.get();
assert!(start.is_positive() && window.contains_rect(start), "{bounds:?}: the layer opens inside {window:?}: {start:?}");
// The pointer ends just inside the window's corner; the layer's own corner would end far past it.
let grab = header_of(start);
pointer::drag(&mut frames, grab, window.right_bottom() - Vec2::splat(4.0) - grab, &mut show);
frames.idle(3, &mut show);
let moved = shown.get();
assert!((moved.size() - start.size()).abs().max_elem() < SLACK, "{bounds:?}: the layer keeps its size: {start:?} -> {moved:?}");
if bounds == DragBounds::Inside {
assert!(window.expand(SLACK).contains_rect(moved), "{bounds:?}: the layer stays inside {window:?}: {moved:?}");
continue;
}
assert!(moved.right() > window.right() + SLACK, "the layer goes past the right edge of {window:?}: {moved:?}");
assert!(moved.bottom() > window.bottom() + SLACK, "the layer goes past the bottom edge of {window:?}: {moved:?}");
// The part of the header left inside the window takes the next drag.
let title = Pos2::new((moved.left() + window.right()) / 2.0, moved.top() + 8.0);
assert!(window.contains(title) && moved.contains(title), "the header stays inside {window:?}: {moved:?}");
let back = Vec2::new(-200.0, -200.0);
pointer::drag(&mut frames, title, back, &mut show);
frames.idle(3, &mut show);
let returned = shown.get();
assert!((returned.min - (moved.min + back)).abs().max_elem() < SLACK, "a drag of the header moves it back: {moved:?} -> {returned:?}");
assert!(window.contains_rect(returned), "the layer is back inside {window:?}: {returned:?}");
}
}
/// A resizable dialog under `DragBounds::TitleVisible`, its placement kept in shown memory: the user resizes it by its
/// bottom right grip, which leaves a size in that placement, then drags it by its header far past the window's right
/// and bottom edges. It goes past them at its resized size, and the strip of its title the rule keeps stays inside: its
/// top left, where its title row starts, and the band there. A drag that pushes further leaves it where it is, so the
/// user takes it back by the band rather than losing it off the window.
#[trial]
fn a_resized_layer_keeps_its_title_strip_inside_a_drag_past_the_window_edges() {
let tokens = craft_ui::testing::style::tokens(Mode::Dark, Contrast::Standard);
let strip = Vec2::new(tokens.size.dialog.button, tokens.size.bar.title);
let (shown, log, seen) = (Cell::new(Rect::NOTHING), RefCell::new(Vec::new()), RefCell::new(Seen::default()));
let mut show = |ui: &mut Ui| {
let overlay = Overlay::dialog().modeless().resizable(true).drag_bounds(DragBounds::TitleVisible);
let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content).header(HeaderRegion::new().band(DragBand::Move));
let out = Pane { common: Common::new(), props, log: &log }.id_salt("kept dialog").show(ui, |ui, _| {
Probe::new(&seen).size(BODY).show(ui);
});
shown.set(out.output.rect);
};
let mut frames = Frames::new();
frames.idle(4, &mut show);
let window = frames.ctx.content_rect();
let opened = shown.get();
assert!(opened.is_positive() && window.contains_rect(opened), "the dialog opens inside {window:?}: {opened:?}");
// The bottom right grip sizes it, so the placement keeps a size the user gave it.
pointer::drag(&mut frames, opened.right_bottom() - Vec2::splat(3.0), Vec2::new(140.0, 80.0), &mut show);
frames.idle(3, &mut show);
let resized = shown.get();
assert!(
resized.width() > opened.width() + SLACK && resized.height() > opened.height() + SLACK,
"the grip gives the dialog a size of its own: {opened:?} -> {resized:?}"
);
// The pointer ends well past the window's corner: without the keep, the title row's start ends outside the window.
let grab = header_of(resized);
pointer::drag(&mut frames, grab, window.right_bottom() + Vec2::splat(300.0) - grab, &mut show);
frames.idle(3, &mut show);
let moved = shown.get();
assert!((moved.size() - resized.size()).abs().max_elem() < SLACK, "the move keeps the resized size: {resized:?} -> {moved:?}");
assert!(window.contains(moved.min), "the title row's start stays inside {window:?}: {moved:?}");
assert!(moved.left() + strip.x <= window.right() + SLACK, "the title strip ends inside {window:?}: {moved:?}");
assert!(moved.top() + strip.y <= window.bottom() + SLACK, "the title strip reaches no lower than {window:?}: {moved:?}");
assert!(
moved.right() > window.right() + SLACK && moved.bottom() > window.bottom() + SLACK,
"the dialog goes past the window's edges at its size: {moved:?} in {window:?}"
);
// The band is what the rule keeps: a drag from the part of the header still inside pushes no further.
let again = Pos2::new(window.right() - 8.0, moved.top() + 8.0);
pointer::drag(&mut frames, again, Vec2::new(300.0, 200.0), &mut show);
frames.idle(3, &mut show);
let further = shown.get();
assert!((further.min - moved.min).abs().max_elem() < SLACK, "the dialog stays where the rule keeps it: {moved:?} -> {further:?}");
}
/// Where the layers of the Size trial hang from: with room above it and before it.
const ANCHOR: Rect = Rect { min: Pos2::new(400.0, 300.0), max: Pos2::new(430.0, 320.0) };
+9 -1
View File
@@ -3,7 +3,7 @@
use super::frame::{self, DialogOutput, FOOTER, FooterCx, FooterFn, FooterHooks, HEADER, SIDE_BUTTONS};
use crate::contract::Remember as _;
use crate::contract::overlay::{FloatPlace, OverlayFit, Place};
use crate::contract::overlay::{DragBounds, FloatPlace, OverlayFit, Place};
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, FooterPlace, FooterRegion, HeaderRegion, Mount, Overlay, Pad,
Props as _, Role, SaveKey, Show as _, ShowContainer as _,
@@ -196,6 +196,14 @@ impl<'a> Dialog<'a> {
self.overlay(Overlay::modeless)
}
/// How much of the dialog stays inside the window when the user moves it by its title band: the whole dialog
/// ([`DragBounds::Inside`], the default), or only a strip of its title ([`DragBounds::TitleVisible`]), so a dialog
/// that previews its change in the document behind it moves mostly aside and is taken back by its title.
#[must_use]
pub fn drag_bounds(self, bounds: DragBounds) -> Self {
self.overlay(|overlay| overlay.drag_bounds(bounds))
}
/// What is drawn behind a modal dialog.
#[must_use]
pub fn backdrop(self, backdrop: Backdrop) -> Self {
+6 -1
View File
@@ -60,6 +60,10 @@ impl Outcome for FlyoutOutput {
/// The user resizes it by its top and bottom edges, the edge away from the column and the two corners there; the
/// column side stays. The flyout keeps no rect of its own: each step comes back in [`FlyoutShown::placed`] and the
/// caller places the next pass from it.
///
/// It stands among the floating windows, in their order: a flyout opened after a window is drawn over it and takes
/// the presses there, and pressing the window brings it back in front. The menus opened from a flyout stand above
/// every window.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(container, unregistered)]
pub struct Flyout {
@@ -120,7 +124,8 @@ impl Flyout {
.focus_left(self.auto_collapse)
.commands(false),
)
.body_scroll(false);
.body_scroll(false)
.among_windows(true);
if bounded { overlay.bounds(self.within) } else { overlay }
}
+12 -6
View File
@@ -6,7 +6,9 @@ use super::dock_column::{
register_edges, show_bar,
};
use super::group::GripMarks;
use super::{CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag};
use super::{
CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag,
};
use crate::buttons::{ActiveLook, IconButton};
use crate::contract::overlay::Anchor;
use crate::contract::{
@@ -210,9 +212,10 @@ pub struct IconicColumnStyle {
/// column registers its drop spots with the dock `dock` as an expanded column does: its edges, the seams between its
/// icon groups, the top and bottom of the stack and each icon group's cells, which join its tabs. The flyout shows
/// its group through the `view` of [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the
/// group within the room and at least the height of its panels' default heights; a group the user sized keeps that
/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`;
/// a flyout taller than the room below that top moves up by what it overflows and no further.
/// group within the room and at least the height of its panels' default heights, which a panel whose
/// [`FlyoutHeight`] is `Content` leaves to its group docked in a column; a group the user sized keeps that size. The
/// flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`; a flyout
/// taller than the room below that top moves up by what it overflows and no further.
/// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in
/// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`).
///
@@ -490,12 +493,15 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> {
Plan { bar, cells, names, grips, groups, body }
}
/// The height of the flyout of `group`: the group's own height, else what its panels ask for, else the least.
/// The height of the flyout of `group`: the group's own height, else the docked default heights of its panels
/// whose flyout takes them ([`FlyoutHeight::Docked`]), else the least.
fn flyout_height(&self, group: &Group<P>, sizes: &DockSizes) -> f32 {
let content = group
.panels
.iter()
.filter_map(|panel| (self.spec)(panel).heights.filter(|heights| heights.valid()))
.map(|panel| (self.spec)(panel))
.filter(|spec| spec.flyout_height == FlyoutHeight::Docked)
.filter_map(|spec| spec.heights.filter(|heights| heights.valid()))
.map(|heights| heights.default + sizes.strip)
.fold(sizes.strip + sizes.least, f32::max);
group.height.filter(|height| height.is_finite() && *height > 0.0).unwrap_or(content).max(sizes.strip + sizes.least)
+76 -3
View File
@@ -1,5 +1,5 @@
//! Trials of `IconicColumn`: the letter of a panel without an icon, the names a wide column shows, the grips of its
//! groups, the resizes of its flyouts, and a flyout that a command leaves open.
//! groups, the heights and resizes of its flyouts, and a flyout that a command leaves open.
#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")]
use super::{CELL, GRIP};
@@ -8,8 +8,8 @@ use crate::contract::overlay::{self, OpenFilter};
use crate::contract::{Bind, Show as _, ShowContainer as _};
use crate::docking::group::GRIP_ABOVE;
use crate::docking::{
DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupDrag, GroupGrip, IconGroupSeparator, IconicColumn, PanelKey,
PanelSpec,
DockColumn, DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutHeight, FlyoutResize, GroupAt, GroupDrag, GroupGrip,
IconGroupSeparator, IconicColumn, PanelKey, PanelSpec,
};
use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, Scope};
use crate::runtime::drag;
@@ -422,6 +422,79 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt
}
}
/// The body height a panel asks for docked in a column, well above what its one-line body measures.
const DOCKED: f32 = 260.0;
/// A panel with a one-line body that asks for [`DOCKED`] in a dock column, its flyout `height` tall; the other panel
/// asks for no height.
fn docked_tall(height: FlyoutHeight) -> impl Fn(&u8) -> PanelSpec {
move |panel| match panel {
0 => PanelSpec::new("Swatches").heights(DockHeights::new(DOCKED)).flyout_height(height),
_ => PanelSpec::new("Brushes"),
}
}
/// What a group with a one-line body measures in the trials: its strip, the body's padding and a line, four strips.
fn one_line(sizes: &DockSizes) -> f32 {
sizes.strip * 4.0
}
/// The height of the flyout of the [`docked_tall`] panel at `height`, whose group measures [`one_line`], and the dock
/// sizes it showed in.
fn flyout_height_of(height: FlyoutHeight) -> (f32, DockSizes) {
let shown = Rc::new(Cell::new(None));
let (seen, open) = (Rc::clone(&shown), Cell::new(None));
let spec = docked_tall(height);
let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y));
let mut fixture = Fixture::new(move |ui| {
let column = Column::new(vec![Group::new(vec![0], 0)]);
let measured = one_line(&StyleCx::with_root(ui.ctx(), DockSizes::style));
let mut now = open.get();
IconicColumn::new("Panels", global("iconic column", "flyout height"), &column, Bind::bound(&mut now), &spec)
.within(screen())
.show_flyouts_at(ui, place, |_, at, _, _| match at {
GroupAt::Measure(_) => Some(measured),
GroupAt::Show(rect) => {
seen.set(Some(rect));
None
}
});
open.set(now);
});
fixture.room(SCREEN).settle();
let icon = fixture.by_label("Swatches").expect("the Swatches icon").rect.center();
fixture.click_at(icon).settle();
(shown.get().expect("the flyout is open").height(), StyleCx::with_root(fixture.ctx(), DockSizes::style))
}
/// A panel that asks for a tall docked height opens a flyout at least that tall by default; with
/// `FlyoutHeight::Content` its flyout is as tall as its one-line body measures, while docked in a column its group
/// keeps the docked height.
#[trial]
fn a_content_tall_flyout_ignores_the_docked_height_that_its_docked_group_keeps() {
let (by_default, sizes) = flyout_height_of(FlyoutHeight::Docked);
let (docked, measured) = (DOCKED + sizes.strip, one_line(&sizes));
assert!(measured < docked && measured > sizes.strip + sizes.least, "the body measures between the least and the docked height");
assert!(near(by_default, docked), "by default the flyout takes the docked height: {by_default} for {docked}");
let (content, _) = flyout_height_of(FlyoutHeight::Content);
assert!(near(content, measured), "a content-tall flyout is as tall as its body measures: {content} for {measured}");
let rects = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&rects);
let spec = docked_tall(FlyoutHeight::Content);
let mut fixture = Fixture::new(move |ui| {
let column = Column::new(vec![Group::new(vec![0], 0), Group::new(vec![1], 0)]);
let mut shown = Vec::new();
DockColumn::new("Panels", global("dock column", "flyout height"), &column, &spec).show_groups(ui, |group, rect, _, _| {
shown.push((group.panels.first().copied(), rect));
});
*seen.borrow_mut() = shown;
});
fixture.room(SCREEN).settle();
let group = rects.borrow().iter().find(|(panel, _)| *panel == Some(0)).map(|(_, rect)| *rect).expect("the docked group shows");
assert!(near(group.height(), docked), "docked in a column the group keeps its docked height: {group:?} for {docked}");
}
/// The names of the panels of the tall-body trials, which set no heights.
const TALL: [&str; 8] = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
/// What the body of a flyout in the tall-body trial measures.
+1 -1
View File
@@ -45,7 +45,7 @@ pub use panels::{close_requests, open_requests};
pub use placed::{Placing, placed_rect, with_area_rules};
pub use root::{DockRoot, DockRootOutput, DockRootStyle};
pub use sources::{DividerKind, DockSource, SourceKind};
pub use spec::{DockGrid, DockHeights, PanelDocument, PanelSpec};
pub use spec::{DockGrid, DockHeights, FlyoutHeight, PanelDocument, PanelSpec};
pub use splitter::{Splitter, SplitterStyle};
pub use targets::{CardInset, ColumnCards, DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule};
pub use words::DockWords;
+26 -2
View File
@@ -52,6 +52,19 @@ impl DockHeights {
}
}
/// How tall the flyout of a panel in a column collapsed to icons opens while the user has not resized its group. Either
/// way the flyout is at least as tall as its body measures, within the room below its top.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FlyoutHeight {
/// At least the panel's [`DockHeights::default`], the height its group takes docked in a column.
#[default]
Docked,
/// As tall as the body measures, at least the dock's least group height: the panel's [`DockHeights`] size its
/// group docked in a column only.
Content,
}
/// How a panel that lays its content in a grid of equal columns (a toolbar) sizes its dock column. The column is a
/// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as
/// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag
@@ -211,9 +224,12 @@ pub struct PanelSpec {
pub icon: Option<IconSpec<'static>>,
/// Body size limits.
pub limits: SizeLimits,
/// How the panel's group sizes itself in a dock column until the user resizes it. `None` shares the column's
/// free height with the column's last open group, which fills it, and with the other groups that have none.
/// How the panel's group sizes itself in a dock column until the user resizes it, and under
/// [`FlyoutHeight::Docked`] the least height of its flyout. `None` shares the column's free height with the
/// column's last open group, which fills it, and with the other groups that have none.
pub heights: Option<DockHeights>,
/// How tall the panel's flyout opens: at least its docked default height, or as tall as its body measures.
pub flyout_height: FlyoutHeight,
/// The size the panel floats at: its width and the most height it takes. `None`: the size of the group it floats
/// out of, else `FloatSpace`'s default size.
pub float_size: Option<Vec2>,
@@ -266,6 +282,7 @@ impl PanelSpec {
icon: None,
limits: SizeLimits::default(),
heights: None,
flyout_height: FlyoutHeight::Docked,
float_size: None,
allow_native: true,
allow_float_resize: true,
@@ -352,6 +369,13 @@ impl PanelSpec {
self
}
/// How tall the panel's flyout opens.
#[must_use]
pub fn flyout_height(mut self, height: FlyoutHeight) -> Self {
self.flyout_height = height;
self
}
/// The size the panel floats at.
#[must_use]
pub fn float_size(mut self, size: Vec2) -> Self {
+1 -1
View File
@@ -1941,7 +1941,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
DockTargets::<P>::register_room(ui.ctx(), dock, cell);
}
let opens = if edge == DockEdge::Start { Side::End } else { Side::Start };
// Only a docked column's icons are a rail; a floating window's open flyouts.
// Only a docked column's icons are a rail; a floating window's open flyouts, which stand in the windows' order.
let mode = if in_window { IconicMode::Flyouts } else { scene.config.iconic_mode };
// The width the user gives a column by its inner edge leaves out its card's inset.
let inset = card.map_or(0.0, |place| scene.sizes.inset(place));
@@ -3,6 +3,7 @@
use craft_behavior::Axis;
use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at};
use craft_theme::{AppSizes, SizeValue};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, BodyCx, PlainData, Role, Show as _, SizeLimits, Tracked};
use craft_ui::display::Text;
use craft_ui::docking::{
@@ -422,6 +423,163 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses
assert!(!shown(&fixture, "Alpha body"), "and its panel no longer shows");
}
/// How tall the flyout of [`UnderWindow`]'s Alpha group measures.
const FLYOUT_HEIGHT: f32 = 300.0;
/// The frames a flyout closed in a pass still shows its group over: its 150 ms `motion.open` exit fade at 1/60 s, which
/// is nine, and a few to spare. A `settle` runs four.
const FLYOUT_FADE_FRAMES: usize = 12;
/// Panels for a docked flyout under a floating window: Alpha's group, in the flyout, is a view that measures
/// [`FLYOUT_HEIGHT`] and records the rect it shows in, this pass; Beta, in the window, shows a button that counts its
/// clicks.
struct UnderWindow {
flyout: Rc<Cell<Option<Rect>>>,
clicks: Rc<Cell<u32>>,
}
impl DockPanels<u32> for UnderWindow {
fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
if *panel == 11 {
self.clicks.set(self.clicks.get() + Button::new("Beta button").show(ui).clicks);
}
}
fn group_view(&mut self, panels: &[u32], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
if !panels.contains(&10) {
return None;
}
Some(match at {
GroupAt::Measure(_) => FLYOUT_HEIGHT,
GroupAt::Show(rect) => {
self.flyout.set(Some(rect));
rect.height()
}
})
}
}
/// A start dock whose column, collapsed to icons, holds Alpha, beside the canvas, and a floating window holding Beta
/// at `window`.
fn flyout_dock(window: Option<Rect>) -> Arc<Workspace<u32>> {
let side = Column::new(vec![Group::new(vec![10], 0)]).with_iconic(true);
let root = Node::split(Axis::X, SplitSize::Ratio(0.4), Node::dock(DockEdge::Start, vec![side]), Node::tabs(vec![1], 0));
let windows = window.map(|at| Floating::new(100, Column::new(vec![Group::new(vec![11], 0)]), at)).into_iter().collect();
Arc::new(Workspace::new(Layout::new(Some(root), windows)))
}
/// The rect of the floating window of [`flyout_dock`] over the flyout at `flyout`: it starts 40 points inside the
/// flyout, so the window's button lies over it, and it reaches past the flyout's foot; at the flyout's own width, the
/// dock's column, its end edge meets the flyout's, so the window's foot alone lies clear of the flyout.
fn window_over(flyout: Rect) -> Rect {
Rect::from_min_size(flyout.min + Vec2::new(40.0, 30.0), Vec2::new(300.0, 360.0))
}
/// A collapsed column's flyout stands among the floating windows, for every app, in the order egui keeps for them: a
/// flyout opened after a window is drawn over it and takes the presses where they overlap, and a press on the window
/// then brings the window back in front of the flyout. The flyout stays open throughout, and its own presses raise it.
#[trial]
fn a_flyout_stands_among_the_floating_windows_in_their_order() {
let workspace = Rc::new(RefCell::new(flyout_dock(None)));
let (flyout, clicks) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(0)));
let mut panels = UnderWindow { flyout: Rc::clone(&flyout), clicks: Rc::clone(&clicks) };
let (held, specs, pass_rect) = (Rc::clone(&workspace), Tracked::new(Sides), Rc::clone(&flyout));
let mut fixture = Fixture::new(move |ui| {
// The cell holds this pass's flyout rect, so a flyout that does not show reads as `None`.
pass_rect.set(None);
let config = DockConfig::default().native_windows(false);
let shown = Bind::given(Arc::clone(&held.borrow()));
DockArea::new("Flyout dock", shown, &specs, &mut panels, config).show(ui);
});
fixture.room(Vec2::new(900.0, 600.0)).settle();
let icon = fixture.by_label("Alpha").expect("Alpha's icon").rect.center();
fixture.click_at(icon).settle();
let open = flyout.get().expect("Alpha's flyout shows its group");
// The floating window shows over the flyout. It is raised as the newest layer while the flyout stands there; the
// flyout is then closed and opened again, so it is the one opened after the window.
let window = window_over(open);
*workspace.borrow_mut() = flyout_dock(Some(window));
fixture.settle();
// The window is there and the flyout too; a point of the window's foot, below the flyout's foot, names the window's
// layer. The flyout opens as wide as the dock's column, while the window starts 40 points inside it and is 300
// wide, so the window's end edge meets the flyout's: of the window, only its foot lies clear of the flyout.
let clear = Pos2::new(open.center().x, open.bottom() + 24.0);
assert!(
window.contains(clear) && !open.contains(clear),
"the window's foot lies in the window and clear of the flyout: {clear:?} in {window:?}, clear of {open:?}"
);
let ctx = fixture.ctx().clone();
let window_layer = ctx.layer_id_at(clear).expect("the floating window shows");
let flyout_layer = ctx.layer_id_at(Pos2::new(open.left() + 8.0, open.center().y)).expect("the flyout shows beside the window");
assert_ne!(flyout_layer, window_layer, "the flyout and the window are layers of their own: {flyout_layer:?}");
// Closed and opened again, the flyout is the one opened after the window. A closed flyout keeps showing over the
// frames of its exit fade, more than a settle runs, so the icon is clicked again once they have run.
fixture.click_at(icon);
for _ in 0..FLYOUT_FADE_FRAMES {
if flyout.get().is_none() {
break;
}
fixture.frame(Vec::new());
}
assert!(flyout.get().is_none(), "the icon of the open panel closes its flyout");
fixture.click_at(icon).settle();
let open = flyout.get().expect("the flyout is open again");
let button = fixture.by_label("Beta button").expect("the floating window shows Beta's button").center();
assert!(open.contains(button), "the window's button lies over the open flyout: {button:?} in {open:?}");
assert_eq!(ctx.layer_id_at(button), Some(flyout_layer), "the flyout opened after the window is on top where they overlap");
fixture.click_at(button).settle();
assert_eq!(clicks.get(), 0, "and the press there does not reach the window's button");
// A press on the window where the flyout does not reach raises the window, as a press raises any floating window.
assert!(!open.contains(clear), "the window's foot lies clear of the reopened flyout: {clear:?} in {open:?}");
fixture.frame(vec![pointer::moved(clear)]).frame(vec![pointer::press(clear)]).frame(vec![pointer::release(clear)]).settle();
assert!(flyout.get().is_some(), "the flyout stays open: Auto-Collapse Iconic Panels is off");
assert_eq!(ctx.layer_id_at(button), Some(window_layer), "the pressed window is in front of the flyout");
fixture.click_at(button).settle();
assert_eq!(clicks.get(), 1, "and a press at the button now reaches it");
}
/// A flyout closed and opened again while its exit fade runs is raised over the window the fade let in front of it. A
/// flyout stands in the floating windows' order, where egui raises a layer when it first shows and when it is pressed,
/// and it does neither for a layer that shows again while its area is still up.
#[trial]
fn a_flyout_opened_again_during_its_fade_is_above_the_window_over_it() {
let workspace = Rc::new(RefCell::new(flyout_dock(None)));
let flyout = Rc::new(Cell::new(None));
let mut panels = UnderWindow { flyout: Rc::clone(&flyout), clicks: Rc::new(Cell::new(0)) };
let (held, specs, pass_rect) = (Rc::clone(&workspace), Tracked::new(Sides), Rc::clone(&flyout));
let mut fixture = Fixture::new(move |ui| {
// The cell holds this pass's flyout rect, so a flyout that does not show reads as `None`.
pass_rect.set(None);
let config = DockConfig::default().native_windows(false);
let shown = Bind::given(Arc::clone(&held.borrow()));
DockArea::new("Flyout dock", shown, &specs, &mut panels, config).show(ui);
});
fixture.room(Vec2::new(900.0, 600.0)).settle();
let icon = fixture.by_label("Alpha").expect("Alpha's icon").rect.center();
fixture.click_at(icon).settle();
let open = flyout.get().expect("Alpha's flyout shows its group");
// A point of the flyout's own top that the floating window covers too.
let tab = Pos2::new(open.left() + 60.0, open.top() + 40.0);
let ctx = fixture.ctx().clone();
let flyout_layer = ctx.layer_id_at(tab).expect("the flyout shows at its tab");
// The floating window shows over the flyout, as the newest layer, so it is on top where they overlap.
*workspace.borrow_mut() = flyout_dock(Some(window_over(open)));
fixture.settle();
let window_layer = ctx.layer_id_at(tab).expect("the window over the flyout shows");
assert_ne!(window_layer, flyout_layer, "the window over the flyout is the layer on top at its tab");
// Closed, the flyout fades out over the nine frames of its 150 ms fade at 1/60 s rather than at once.
fixture.frame(vec![pointer::moved(icon)]).frame(vec![pointer::press(icon)]).frame(vec![pointer::release(icon)]);
assert!(flyout.get().is_some(), "the closed flyout still shows while its exit fade runs");
// Opened again in the fade, the flyout is the newer layer and takes the top back.
fixture.frame(vec![pointer::moved(icon)]).frame(vec![pointer::press(icon)]).frame(vec![pointer::release(icon)]).frame(Vec::new());
assert!(flyout.get().is_some(), "the icon opens the flyout again while it fades");
assert_eq!(ctx.layer_id_at(tab), Some(flyout_layer), "the flyout opened again during its fade is above the window over it");
}
#[derive(PlainData)]
struct RailWithMenu;
+31 -4
View File
@@ -8,6 +8,7 @@ use craft_ui::docking::GroupDrag;
use craft_ui::patterns::dock::{PaneArea, PaneCommands, PaneContent, PaneEdges, PanePlace, PaneRequest, PaneSpec, PaneState};
use craft_ui::runtime::commands::{FireSource, fire};
use craft_ui::runtime::{drag, keys};
use craft_ui::testing::layout::allocate;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::style::tokens;
use craft_ui::testing::{Fixture, trial};
@@ -18,8 +19,15 @@ use std::rc::Rc;
const ROOM: Vec2 = Vec2::new(900.0, 600.0);
/// The floating frame a pane starts in, clear of every edge band.
const FLOAT: Rect = Rect { min: Pos2::new(300.0, 200.0), max: Pos2::new(540.0, 360.0) };
/// A point on a floating frame's title row, clear of the action parts at its end.
/// Where a floating frame's title row is first tried from its corner; [`Bed::title`] steps past any button there.
const TITLE_AT: Vec2 = Vec2::new(24.0, 10.0);
/// The content of the pane's body. A pane's window sizes to its content: with an empty body its title row, and the
/// move band under it, would be only as wide as the row's Float and Close buttons, so no point of the band would be
/// free of a button, and a press on a button over the band is the button's and never moves the window. A body half as
/// wide and high as the frame, as a real pane has content, leaves the band free room before the buttons at its end.
const BODY: Vec2 = Vec2::new(120.0, 80.0);
/// How far past a button's bounds [`Bed::title`] steps, clear of the button's part.
const PAST_BUTTON: f32 = 8.0;
/// The app's one pane: it docks at `edges` and the app keeps its state by applying the area's requests.
struct Panes {
@@ -38,7 +46,9 @@ impl PaneContent<u32> for Panes {
Some(self.state.get())
}
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
allocate(ui, BODY);
}
}
/// A pane area of one pane starting at `start`, with what the app saw.
@@ -89,9 +99,26 @@ impl Bed {
.collect()
}
/// The point on the floating pane's title row.
/// A point on the floating pane's title row where the window's move band takes the press: clear of the row's
/// buttons (Float and Close). A press on a button over the band is the button's and never moves the window, so the
/// point steps past any button at the fixed corner offset; the pane's body ([`BODY`]) keeps the band wider than the
/// buttons.
fn title(&self) -> Pos2 {
self.state.get().float_rect.unwrap_or(FLOAT).min + TITLE_AT
let frame = self.state.get().float_rect.unwrap_or(FLOAT);
let y = frame.min.y + TITLE_AT.y;
let buttons: Vec<Rect> = self
.fixture
.by_role(Role::BUTTON)
.into_iter()
.map(|button| button.rect)
.filter(|button| frame.contains(button.center()) && button.y_range().contains(y))
.collect();
let mut x = frame.min.x + TITLE_AT.x;
while let Some(button) = buttons.iter().find(|button| button.expand(PAST_BUTTON / 2.0).x_range().contains(x)) {
x = button.max.x + PAST_BUTTON;
}
assert!(x < frame.max.x, "the title row keeps a free point of its band: buttons {buttons:?} in {frame:?}");
Pos2::new(x, y)
}
/// Presses the floating pane's title and moves it to `to` in steps, leaving the button down.
+2 -1
View File
@@ -7,7 +7,8 @@ use egui::Context;
/// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands
/// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go
/// to the band), else what the app wrote with [`set_window_movable`], else true. The runtime sets macOS's
/// `NSWindow.movable` from it at the end of each window's pass.
/// `NSWindow.movable` from it at the end of each window's pass. Read between passes, it answers for the window's last
/// pass.
pub fn window_movable(ctx: &Context) -> bool {
viewports::movable(ctx)
}
+127 -3
View File
@@ -94,6 +94,129 @@ fn a_title_bar_in_an_embedded_shell_acts_on_no_window() {
assert!(!commands.is_empty(), "the window's bar acts on the window");
}
/// The window commands a title bar with a Home button in its leading content sends for each step list of `gestures`,
/// in order, given the Home button's centre and a free point of the band.
fn home_bar_sent(gestures: impl Fn(Pos2, Pos2) -> Vec<Vec<Vec<Event>>>) -> Vec<Vec<ViewportCommand>> {
use craft_ui::buttons::Button;
use craft_ui::contract::Show as _;
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout });
let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None };
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop }));
let bar = Cell::new(Rect::NOTHING);
let frame = |events: Vec<Event>| {
windows.frame(events, vec![], |ui| {
let shown = TitleBar::new().show_titled(
ui,
Title::new("Landscape.psd"),
|ui, _| {
Button::new("Home").show(ui);
},
|_, _| {},
);
bar.set(shown.response.rect);
})
};
frame(vec![]);
let settled = frame(vec![]);
let tree = &settled.trees.iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1;
let home = tree
.with_role(Role::BUTTON)
.into_iter()
.find(|key| tree.name_of(*key) == Some("Home"))
.and_then(|key| tree.bounds_of(key))
.expect("the bar shows its Home button")
.center();
// The title is no control: the band lies under it.
let band = bar.get().center();
gestures(home, band)
.into_iter()
.map(|steps| {
steps
.into_iter()
.flat_map(|events| frame(events).commands)
.map(|(_, command)| command)
.filter(|command| matches!(command, ViewportCommand::StartDrag | ViewportCommand::Maximized(_) | ViewportCommand::OuterPosition(_)))
.collect()
})
.collect()
}
/// A press on a control over the band is the control's: a press-drag that starts on the bar's Home button neither
/// moves the window nor drags, and a double click on it does not maximize the window. The band used to take the drag
/// under the button, as a drag-only root under a button in it does, so the drag moved the window and the double click
/// zoomed it. The free band still moves the window, and its double click still maximizes it.
#[trial]
fn a_press_on_a_control_over_the_band_never_moves_or_zooms_the_window() {
let sent = home_bar_sent(|home, band| {
let drag = |at: Pos2| vec![vec![moved(at)], vec![press(at)], vec![moved(at + vec2(40.0, 0.0))], vec![release(at + vec2(40.0, 0.0))], vec![]];
let double = |at: Pos2| vec![vec![moved(at)], vec![press(at)], vec![release(at)], vec![press(at)], vec![release(at)], vec![]];
vec![drag(home), double(home), drag(band), double(band)]
});
let [home_drag, home_double, band_drag, band_double] = &sent[..] else { panic!("four gestures ran: {sent:?}") };
assert!(home_drag.is_empty(), "a drag from Home does not move the window: {home_drag:?}");
assert!(home_double.is_empty(), "a double click on Home does not maximize the window: {home_double:?}");
assert!(band_drag.contains(&ViewportCommand::StartDrag), "a drag of the free band moves the window: {band_drag:?}");
assert!(band_double.contains(&ViewportCommand::Maximized(true)), "a double click on the free band maximizes the window: {band_double:?}");
}
/// The OS may move the window (macOS `NSWindow.movable`) only where a press would go to the bar's free band: not over
/// the bar's Home button, over the free band yes. The bar runs in a measuring run before its drawn run, as in a
/// measured container, and the flag reads the same in the pass and after it. Read after the pass, it used to say the
/// window was movable everywhere: egui had counted the pass by then, so the flag the pass wrote looked stale.
#[trial]
fn the_window_is_movable_from_the_free_band_and_not_from_a_control_over_it() {
use craft_ui::buttons::Button;
use craft_ui::contract::Show as _;
use craft_ui::runtime::measure;
use craft_ui::shell::title_bar::window_movable;
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout });
let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None };
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop }));
let (bar, in_pass) = (Cell::new(Rect::NOTHING), Cell::new(None));
let show = |ui: &mut Ui| {
TitleBar::new()
.show_titled(
ui,
Title::new("Landscape.psd"),
|ui, _| {
Button::new("Home").show(ui);
},
|_, _| {},
)
.response
.rect
};
let frame = |events: Vec<Event>| {
windows.frame(events, vec![], |ui| {
let ctx = ui.ctx().clone();
let builder = egui::UiBuilder::new().sizing_pass().invisible();
measure::run(&ctx, || ui.scope_builder(builder, show));
bar.set(show(ui));
in_pass.set(Some(window_movable(&ctx)));
})
};
frame(vec![]);
let settled = frame(vec![]);
let tree = &settled.trees.iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1;
let home = tree
.with_role(Role::BUTTON)
.into_iter()
.find(|key| tree.name_of(*key) == Some("Home"))
.and_then(|key| tree.bounds_of(key))
.expect("the bar shows its Home button")
.center();
// The title is no control: the band lies under it.
let band = bar.get().center();
for (at, movable, what) in [(home, false, "over Home"), (band, true, "over the free band"), (home, false, "over Home again")] {
frame(vec![moved(at)]);
frame(vec![]);
assert_eq!(in_pass.get(), Some(movable), "{what}, read in the pass");
assert_eq!(window_movable(&windows.ctx), movable, "{what}, read after the pass");
}
}
/// The shell sends the window title once after a change and not again while the viewport reports it; an embedded shell
/// sends none.
#[trial]
@@ -410,14 +533,15 @@ fn cursors_over_the_bar(look: craft_ui::contract::MoveBandCursor) -> (Option<cra
(over(file.center()), over(Pos2::new(help.right() + 40.0, help.center().y)))
}
/// A title bar's move band shows the open hand by default, also through the menu titles on it, which sense clicks
/// only; under `MoveBandCursor::Arrow` the band and the titles show the arrow, as an OS title bar does.
/// A title bar's move band shows the open hand by default over its free band, not over the menu titles on it, which
/// take the press (they sense clicks only); under `MoveBandCursor::Arrow` the band shows the arrow too, as an OS title
/// bar does.
#[trial]
fn a_move_band_shows_the_arrow_when_the_app_asks() {
use craft_behavior::{Cursor, CursorIcon};
use craft_ui::contract::MoveBandCursor;
let grab = Some(Cursor::System(CursorIcon::Grab));
assert_eq!(cursors_over_the_bar(MoveBandCursor::Hand), (grab.clone(), grab), "the hand over the band and the titles on it");
assert_eq!(cursors_over_the_bar(MoveBandCursor::Hand), (None, grab), "the hand over the free band and not the titles on it");
assert_eq!(cursors_over_the_bar(MoveBandCursor::Arrow), (None, None), "the arrow over the band and the titles on it");
}
+10 -9
View File
@@ -2448,7 +2448,6 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component.
- `pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<std::sync::Arc<ResolvedCommand>>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above
- `pub fn column_room(&self) -> Option<f32>`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the
- `pub fn in_row(&self) -> bool`. Whether the component is a direct child of a `Row` body, a bar's included. A component that could wrap into
- `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes
- `pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2`. The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect):
- `pub fn label(&self) -> Label`. The label as given.
@@ -2504,7 +2503,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `fn unshown(response: Response) -> Option<Self> where Self: Sized,`. The output of a layer-like container that shows nothing this pass (closed, past its exit fade): `response` is
- `fn value_text(&self) -> Option<&str>`. The shown value as the component words it to assistive technology; `None` for a component that gives none.
- `fn story_facts(&self) -> crate::testing::StoryOutput`. The facts a story reports about this output: its id, click, edit kinds, collection kinds and visible range.
- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option<Opener>, pub popup: PopupKind, pub size: Option<Vec2>, pub size_limits: SizeLimits, pub placed: Option<Rect>, pub placed_at: Option<Pos2>, pub bounds: Option<Rect>, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option<Vec2>, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields.
- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option<Opener>, pub popup: PopupKind, pub size: Option<Vec2>, pub size_limits: SizeLimits, pub placed: Option<Rect>, pub placed_at: Option<Pos2>, pub bounds: Option<Rect>, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option<Vec2>, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields.
- `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window,
- `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It
- `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further.
@@ -2534,7 +2533,9 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn opacity(mut self, opacity: f32) -> Overlay`. Sets the layer's opacity, from 0 (invisible) to 1.
- `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width.
- `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it.
- `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]):
- `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]).
- `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]).
- `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer.
- `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]).
- `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer
@@ -2835,6 +2836,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the
- `pub const fn on_activate(mut self, on: bool) -> Self`. Closes when a component inside is activated, except an opener toggling its popup.
- `pub const fn commands(mut self, on: bool) -> Self`. Closes when a key, a native menu pick or the palette runs a command from outside it; off for a layer its host
- `pub const fn timeout(mut self, seconds: Option<f32>) -> Self`. Closes after `seconds`.
- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title.
- `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option<Pos2>, pub corner: Align2 }`. Where a floating layer sits.
- `pub const fn centred() -> Self`. Centred in the viewport.
- `pub const fn at(pos: Pos2) -> Self`. With its left-top at `pos`.
@@ -2844,7 +2846,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the
- `craft_ui::contract::overlay::OpenFilter`: re-export of `craft_ui::runtime::overlay::OpenFilter`.
- `craft_ui::contract::overlay::Opener`: `pub struct Opener { pub id: Id, pub rect: Rect, pub layer: areas::Layer, pub trigger: Trigger, pub enabled: bool, pub anchor: Option<Anchor>, pub others: Vec<Opener> }`. A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its
- `craft_ui::contract::overlay::Outside`: `pub enum Outside { Close, Keep, Absorb }`. What a press outside the layer and its anchor does.
- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option<Opener>, pub popup: PopupKind, pub size: Option<Vec2>, pub size_limits: SizeLimits, pub placed: Option<Rect>, pub placed_at: Option<Pos2>, pub bounds: Option<Rect>, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option<Vec2>, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields.
- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option<Opener>, pub popup: PopupKind, pub size: Option<Vec2>, pub size_limits: SizeLimits, pub placed: Option<Rect>, pub placed_at: Option<Pos2>, pub bounds: Option<Rect>, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option<Vec2>, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields.
- `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window,
- `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It
- `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further.
@@ -2874,7 +2876,9 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the
- `pub fn opacity(mut self, opacity: f32) -> Overlay`. Sets the layer's opacity, from 0 (invisible) to 1.
- `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width.
- `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it.
- `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]):
- `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]).
- `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]).
- `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer.
- `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]).
- `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer
@@ -4029,7 +4033,7 @@ One-shot screenshot slots and the facts a screenshot is measured against.
- `pub const fn points_per_inch(self) -> f64`. How many points make an inch.
- `craft_ui::runtime::env::ResolvedRoot`: `pub struct ResolvedRoot { pub mode: Mode, pub contrast: Contrast, pub motion: MotionMode }`. The mode, contrast and motion of a pass, with `System` resolved.
- `craft_ui::runtime::env::RevealEdge`: `pub enum RevealEdge { Top, Start, End }`. An edge of the window whose slots a pointer at the edge reveals in body-only mode. The bottom edge and the centre
- `craft_ui::runtime::env::RootEnv`: `pub struct RootEnv { pub sizes: Arc<AppSizes>, pub text_size: TextSize, pub direction: Direction, pub motion: MotionChoice, pub mode: ModeChoice, pub contrast: ContrastChoice, pub density: Size, pub scale: Scale, pub tab_all_controls: bool, pub tab_toggles_chrome: bool, pub escape_leaves_fields: bool, pub shortcuts_repeat: bool, pub dialog_tab: TabReach, pub canvas_pattern: bool, pub cursor_follows_zoom: bool, pub tooltips: bool, pub values: AppValues, pub today: Option<CalendarDate>, pub wheel: WheelSpeed, pub pointer_scoped_field_wheel: bool, pub alt_codes: AltCodePages, pub ctrl_wheel_pinch: bool }`. The app's root values each frame.
- `craft_ui::runtime::env::RootEnv`: `pub struct RootEnv { pub sizes: Arc<AppSizes>, pub text_size: TextSize, pub direction: Direction, pub motion: MotionChoice, pub mode: ModeChoice, pub contrast: ContrastChoice, pub density: Size, pub scale: Scale, pub tab_all_controls: bool, pub tab_toggles_chrome: bool, pub escape_leaves_fields: bool, pub shortcuts_repeat: bool, pub dialog_tab: TabReach, pub canvas_pattern: bool, pub cursor_follows_zoom: bool, pub tooltips: bool, pub values: AppValues, pub today: Option<CalendarDate>, pub wheel: WheelSpeed, pub alt_codes: AltCodePages, pub ctrl_wheel_pinch: bool }`. The app's root values each frame.
- `pub fn new() -> Self`. A root with every value at its default.
- `pub fn scale(mut self, scale: Scale) -> Self`. Sets the interface scale.
- `pub fn direction(mut self, direction: Direction) -> Self`. Sets the layout direction.
@@ -4051,7 +4055,6 @@ One-shot screenshot slots and the facts a screenshot is measured against.
- `pub fn component_set(&self) -> ComponentSet`. The component set the root's values carry.
- `pub fn today(mut self, date: CalendarDate) -> Self`. Sets today's date, as the host's clock and time zone give it.
- `pub fn wheel_speed(mut self, speed: WheelSpeed) -> Self`. Sets this frame's wheel speed.
- `pub fn pointer_scoped_field_wheel(mut self, enabled: bool) -> Self`. Sends the wheel to a focused field only while the pointer is over it when enabled.
- `pub fn alt_code_pages(mut self, pages: AltCodePages) -> Self`. Sets the code pages that decode Alt+numpad codes.
- `pub fn ctrl_wheel_pinch(mut self, pinch: bool) -> Self`. Sets whether a fractional Ctrl+wheel arrives as a pinch (`ctrl_wheel_pinch`).
- `craft_ui::runtime::env::RowPressed`: `pub enum RowPressed { Row, Cell(ColumnKey), Part { was_lead: bool } }`. Where the collection holds a primary press on a row, within slop, or the press a part of the row holds.
@@ -4094,7 +4097,7 @@ One-shot screenshot slots and the facts a screenshot is measured against.
- `pub fn mode(mut self, mode: Mode) -> Self`. Resolves in `mode`: a plot that is dark in every theme, a preview of the other mode.
- `pub fn contrast(mut self, contrast: Contrast) -> Self`. Resolves under `contrast`.
- `pub fn density(mut self, density: Size) -> Self`. Resolves at the density preset `density`.
- `craft_ui::runtime::env::UnitKind`: `pub enum UnitKind { Pixels, Percent, Degrees, Points, Times, Inches, Centimetres, Millimetres, Picas, PixelsPerInch, PixelsPerCentimetre, Minutes, Columns, LinesPerInch, LinesPerCentimetre, Feet, Yards, Metres, Q, Ha, Letters, Hyphens, PerInch, Milliseconds }`. What a number counts.
- `craft_ui::runtime::env::UnitKind`: `pub enum UnitKind { Pixels, Percent, Degrees, Points, Times, Inches, Centimetres, Millimetres, Picas, PixelsPerInch, PixelsPerCentimetre, Minutes, Columns, LinesPerInch, LinesPerCentimetre, Feet, Yards, Metres, Q, Ha, Letters, Hyphens, PerInch }`. What a number counts.
- `pub const LENGTHS: [UnitKind; 5]`. The lengths a unit choice offers. [`per_inch`](Self::per_inch) answers for more kinds (feet, yards, metres, Q,
- `pub const fn decimals(self) -> RangeInclusive<usize>`. The digits after the decimal mark a number of this kind shows by default, at most.
- `pub const fn step(self) -> f64`. What one arrow press, wheel notch or scrub point changes a number of this kind by, where the control that shows
@@ -4361,11 +4364,9 @@ The key stage (spec 9.1, 9.2, 9.3, 9.7): the input hook strips the keys the runt
Layout memory: sizes one pass measures and the next pass places by, the one discard pass a change asks for, what
- `craft_ui::runtime::layout_memory::emit_text`: `pub fn emit_text(ctx: &Context, id: Id, text: Option<&str>)`. Hands forward a text a run found under `id` that content outside the body it runs in shows, as `emit_record`
- `craft_ui::runtime::layout_memory::emit_width`: `pub fn emit_width(ctx: &Context, id: Id, width: f32)`. Hands forward a width a run measured under `id` that a step outside the content that measured it sizes by, as
- `craft_ui::runtime::layout_memory::forget_kept`: `pub fn forget_kept(ctx: &Context)`. Drops every kept measurement, so the next pass measures each body as a first pass would.
- `craft_ui::runtime::layout_memory::kept_leaves`: `pub fn kept_leaves(ctx: &Context) -> usize`. How many component entries the valid kept measurements hold, each body counting only the components directly in
- `craft_ui::runtime::layout_memory::text`: `pub fn text(ctx: &Context, id: Id) -> Option<Arc<str>>`. The text a run of this pass handed forward under `id` ([`emit_text`]), or a kept transcript gave this pass.
- `craft_ui::runtime::layout_memory::width`: `pub fn width(ctx: &Context, id: Id) -> Option<f32>`. The width a run of this pass handed forward under `id` ([`emit_width`]), or a kept transcript gave this pass.
## `craft_ui::runtime::memory`
@@ -4448,7 +4449,7 @@ The layer stack (15.2): the record of the egui layers shown, their order and the
- `craft_ui::runtime::overlay::CloseReason`: `pub enum CloseReason { Requested, Escape, Outside, FocusLeft(crate::runtime::focus::FocusMove), Activated, Enter, Timeout, AnchorGone }`. Why a layer closes.
- `craft_ui::runtime::overlay::LayerRole`: `pub enum LayerRole { Plain, Progress, InPlaceEditor }`. What a layer is for, beyond its rank.
- `craft_ui::runtime::overlay::OpenFilter`: `pub enum OpenFilter { Any, Modal, Keys, Asks }`. What `any_open` counts.
- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen.
- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` chooses a layer's egui order; a popup that stands among the floating
- `pub const fn modal(backdrop: Backdrop) -> Rank`. A modal rank with `backdrop`.
- `craft_ui::runtime::overlay::any_open`: `pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool`. Whether any layer of the running viewport that `filter` counts was shown last frame.
- `craft_ui::runtime::overlay::close_popups`: `pub fn close_popups(ctx: &Context)`. Queues a close of every popup layer of the running viewport shown last frame that a command closes
+3 -2
View File
@@ -56,7 +56,7 @@ The host keeps its panels' specs in a plain-data model that implements `PanelSpe
| Method | Does |
| --- | --- |
| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`, `host_body`, `count`, `caption`, `swatch` (a data colour before the tab's name; `Some(None)` is the theme's empty swatch) and `documents`. |
| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, `FlyoutHeight`, float size, `allow_native`, `window_kind`, `canvas`, `grid`, `host_body`, `count`, `caption`, `swatch` (a data colour before the tab's name; `Some(None)` is the theme's empty swatch) and `documents`. |
| `permissions` | The panel's `Permissions` (default `ALL`). |
A panel's `documents` (`PanelDocument`: id, label, swatch, `closable`, `shown`) are tabs of its group's strip after the panel tabs, whichever panel the group shows: one fit and one overflow menu for both. The tab of the shown panel's `shown` document is the selected tab. A pick reports `DockEvent::DocumentPicked` and activates the panel; a close button or middle click reports `DockEvent::DocumentClosed`. The host opens, shows and closes documents by editing the spec. Document tabs do not drag and take no tab drop.
@@ -128,9 +128,10 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords
- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives.
- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window.
- A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group.
- A flyout is as tall as its group measures, within the room below its top, and at least the `DockHeights::default` of each of its panels whose `PanelSpec::flyout_height` is `FlyoutHeight::Docked`, the default. A panel with `FlyoutHeight::Content` opens a flyout as tall as its body measures, while its `DockHeights` still size its group docked in a column. A group the user sized keeps that height.
- Split handles are Tab stops, and the arrow keys move them. A pointer press or drag on a handle leaves key focus where it was, so the arrows after a drag still reach the app; only a handle reached by Tab takes them. A divider drag is one gesture in `DockAreaOutput::edit`.
- A pointer press on a panel tab (a click, a drag's press, the tab menu's secondary press) leaves key focus where it was, so the document's keys keep working; Tab still reaches the tab row.
- Floating windows stack with the app's own egui windows in egui's area order: the one shown, pressed or raised last (`FloatingGroup::raise`, which the host's `DockArea::focus` request sets on the window holding the panel) is on top, so a dialog the app opens over a floating panel shows above it.
- Floating windows stack with the app's own egui windows in egui's area order: the one shown, pressed or raised last (`FloatingGroup::raise`, which the host's `DockArea::focus` request sets on the window holding the panel) is on top, so a dialog the app opens over a floating panel shows above it. A collapsed column's flyout stands in that order too: one opened after a window is over it, and a press on either brings it in front, while the menus opened from a flyout stand above every window.
- A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s.
## Commands and workspaces