Merge branch 'fx/float' into fx/all-1117

# Conflicts:
#	crates/ui-patterns/tests/it/docking/native.rs
This commit is contained in:
aiongg
2026-11-17 14:46:20 +00:00
11 changed files with 288 additions and 69 deletions
+5 -4
View File
@@ -356,11 +356,12 @@ impl Host for ViewportHost {
let open = ViewportOpen {
id,
title: title.as_str(),
// A placed rect is the caller's size for the window, then a resizable fallback's default size, as the layer
// takes it; the measured size is for a window sized by content: what its body took in the window, recorded
// once the window reported its place (`steps::record_body_size`).
// A placed rect is the caller's size for the window, within the window's limits, which the OS would clamp it
// to; then a resizable fallback's default size, as the layer takes it; the measured size is for a window
// sized by content: what its body took in the window, recorded once the window reported its place
// (`steps::record_body_size`).
size: placed
.map(|rect| rect.size())
.map(|rect| self.overlay.size_limits.clamp(rect.size()))
.or(self.overlay.size.filter(|_| self.overlay.fit == overlay::OverlayFit::Resizable))
.or_else(measured),
// A resizable window takes its default or content size to open; from then on its size is the user's.
@@ -196,6 +196,11 @@ impl SizeLimits {
SizeLimits { min: self.min + extra, max: self.max.map(|max| max + extra) }
}
/// `size` within these limits; the minimum wins over a smaller maximum.
pub fn clamp(self, size: Vec2) -> Vec2 {
size.min(self.max.unwrap_or(Vec2::INFINITY)).max(self.min)
}
/// Whether every value is finite and non-negative, the maximum is no less than the minimum and no value is
/// above [`Self::BOUND`].
pub fn valid(self) -> bool {
@@ -27,7 +27,7 @@ pub(crate) struct Spec<'a> {
pub os_buttons: bool,
/// The smallest inner size.
pub min_size: Option<Vec2>,
/// The largest inner size.
/// The largest inner size; `Vec2::INFINITY` lifts an earlier one.
pub max_size: Option<Vec2>,
/// The window level.
pub level: WindowLevel,
+8 -2
View File
@@ -310,11 +310,17 @@ pub(crate) fn blocking_modal(ctx: &Context) -> Option<ViewportId> {
/// It reads only this pass's facts, so the mount, the body (which runs inside the child's pass) and the window steps
/// agree within a pass.
pub(crate) fn mount_window(ctx: &Context, id: Id) -> bool {
let current = pass::current_viewport(ctx);
let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current };
opens_over(ctx, opener)
}
/// Whether a viewport mount opened from `opener`'s window shows in an OS window of its own: the rule of
/// [`mount_window`].
fn opens_over(ctx: &Context, opener: ViewportId) -> bool {
if !WindowHost::of(ctx).viewports_available() {
return false;
}
let current = pass::current_viewport(ctx);
let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current };
let shell = shell_of(ctx, opener);
let covers = match shell.window.state {
WindowState::Fullscreen => true,
@@ -77,6 +77,13 @@ impl WindowHost {
base_shell(&self.ctx).caps.contains(Caps::VIEWPORTS) && viewports::available(&self.ctx)
}
/// Whether a viewport mount opened in the running viewport's pass shows in an OS window of its own, and not in
/// its fallback layer: OS viewports are available and the running window is neither full screen nor, on Wayland,
/// maximized.
pub fn opens_windows(&self) -> bool {
super::opens_over(&self.ctx, pass::current_viewport(&self.ctx))
}
/// Whether the platform reports where windows are on the desktop and moves them there; false on Wayland.
pub fn positions_reported(&self) -> bool {
base_shell(&self.ctx).window_positions()
@@ -83,7 +83,9 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
// A tool window has no OS caption buttons; its panel's title row carries a close action.
os_buttons: !(spec.kind == WindowKind::Tool && captions.is_none() && chrome != WindowChrome::Native),
min_size: open.limits.0,
max_size: open.limits.1,
// egui sends a limit only when it has one: an open window always carries its maximum, unbounded when the
// caller has none, so a lifted maximum reaches the OS.
max_size: open.limits.1.or(opened.then_some(Vec2::INFINITY)),
level,
resizable: open.resizable,
taskbar: spec.taskbar,
+26 -12
View File
@@ -2,8 +2,9 @@
//!
//! The group is a movable, resizable container on a layer (or in an OS window) whose rect the caller owns: the
//! caller places it with the rect the dock model keeps and takes the rect the output reports after each step of
//! a gesture. The title row carries the active panel's title and the Menu, Float and Close actions; the Menu action
//! opens the `menu` rows. The body step supplies the move band, the edge grips and the keyboard Move and Size modes.
//! a gesture. The title row carries the Close action; a context request on its band opens the `menu` rows, as the
//! Menu action does where `actions` asks for one. The body step supplies the move band, the edge grips and the
//! keyboard Move and Size modes.
//! A dock window's title row is also the bar of the column the window holds, with the column's double arrow.
use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron};
@@ -38,8 +39,9 @@ pub(crate) fn title_row(tokens: &UiTokens) -> f32 {
tokens.size.panel_header
}
/// The actions a floating group's title row shows unless `actions` says otherwise.
const ACTIONS: [HeaderAction; 3] = [HeaderAction::Menu, HeaderAction::Float, HeaderAction::Close];
/// The actions a floating group's title row shows unless `actions` says otherwise: Close alone, as a floating panel's
/// title bar has beside its double arrow; the menu opens from the band.
const ACTIONS: [HeaderAction; 1] = [HeaderAction::Close];
/// The style of a floating group: the surface and padding come from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
@@ -90,6 +92,21 @@ impl WindowColumn {
self
}
/// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under a title row
/// `header` tall, at the top of `rect` and against the edge the window keeps to. `None` while the column is
/// expanded.
pub fn shown(self, rect: Rect, header: f32, rtl: bool) -> Option<Rect> {
let size = self.collapsed? + Vec2::new(0.0, header);
let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x };
Some(Rect::from_min_size(Pos2::new(left, rect.top()), size))
}
/// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the
/// collapsed column ([`Self::shown`]), so it keeps its expanded size; while expanded, `shown`.
pub fn kept(self, shown: Rect, rect: Rect, header: f32, rtl: bool) -> Rect {
self.shown(rect, header, rtl).map_or(shown, |at| rect.translate(shown.min - at.min))
}
/// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is
/// in the half of the bounds there or `bounds` is empty.
pub fn nearer_edge(rect: Rect, bounds: Rect, rtl: bool) -> DockEdge {
@@ -205,7 +222,7 @@ pub struct FloatingGroup<'a> {
/// Opens the group in an OS window of this kind.
#[prop]
native: Option<WindowSpec>,
/// The rows of the menu the Menu action opens.
/// The rows of the menu a context request on the title row, or the Menu action, opens.
#[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")]
menu: Option<MenuRows<'a>>,
actions: Vec<HeaderAction>,
@@ -236,7 +253,7 @@ type StartDrag<'a> = Box<dyn for<'b, 'c> FnOnce(&'b mut Cx<'c, FloatingGroup<'a>
type TakeDrop<'a> = Box<dyn for<'b, 'c> FnMut(&'b mut Cx<'c, FloatingGroup<'a>>) + 'a>;
impl<'a> FloatingGroup<'a> {
/// A floating group titled `title` at `rect`, with the Menu, Float and Close actions.
/// A floating group titled `title` at `rect`, with the Close action.
pub fn new(title: impl Into<Label>, rect: Rect) -> Self {
let props = ContainerProps::new()
.surface(SurfaceKind::Floating)
@@ -356,10 +373,7 @@ impl<'a> FloatingGroup<'a> {
/// Where the group shows while its column is collapsed: the collapsed column under the title row, at the top of
/// the rect and against its edge the window keeps to. `None` while the column is expanded.
fn collapsed_rect(&self) -> Option<Rect> {
let column = self.column?;
let size = column.collapsed? + Vec2::new(0.0, self.header);
let left = if at_left(column.edge, self.rtl) { self.rect.left() } else { self.rect.right() - size.x };
Some(Rect::from_min_size(Pos2::new(left, self.rect.top()), size))
self.column?.shown(self.rect, self.header, self.rtl)
}
/// The double arrow's square at the end of the title row the window keeps to.
@@ -483,9 +497,9 @@ impl Container for FloatingGroup<'_> {
fn placement_changed(&mut self, change: &PlacementChange) {
let mut change = *change;
let fitted = self.column.is_some_and(|column| column.fitted.is_some());
if let Some(shown) = self.collapsed_rect() {
if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) {
// The collapsed window moves; the rect keeps its expanded size.
change.rect = self.rect.translate(change.rect.min - shown.min);
change.rect = column.kept(change.rect, self.rect, self.header, self.rtl);
} else if fitted && change.kind == PlacementKind::Move {
// A window its content sizes moves; the rect keeps its size.
change.rect = Rect::from_min_size(change.rect.min, self.rect.size());
+24 -7
View File
@@ -31,11 +31,12 @@ pub struct Opening {
pub spec: Option<WindowSpec>,
}
/// Whether the groups of panels with `specs` may open OS windows: the dock's `config` turns them on, the platform
/// opens them and reports where they are, and every panel allows it.
/// Whether the groups of panels with `specs` open OS windows: the dock's `config` turns them on, the platform opens
/// them over the dock's window this pass (the rule the group's mount falls back to a layer by) and reports where they
/// are, and every panel allows it.
pub(crate) fn allowed(ctx: &Context, config: &DockConfig, specs: &[PanelSpec]) -> bool {
let host = WindowHost::of(ctx);
config.native_windows && host.viewports_available() && host.positions_reported() && specs.iter().all(|spec| spec.allow_native)
config.native_windows && host.opens_windows() && host.positions_reported() && specs.iter().all(|spec| spec.allow_native)
}
/// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool
@@ -44,6 +45,14 @@ pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec {
if specs.iter().any(|spec| spec.window_kind == WindowKind::Document) { WindowSpec::document() } else { WindowSpec::tool() }
}
/// The rect in the main window's points of `desktop`, a rect in desktop points: where a window at `desktop` would sit
/// in the app window, as [`restore`] opens a window from its rect there. `None` while the main window has not
/// reported its place.
pub fn in_app(ctx: &Context, desktop: Rect) -> Option<Rect> {
let main = WindowHost::of(ctx).facts(ViewportId::ROOT)?;
Some(desktop.translate(-main.inner.min.to_vec2()))
}
/// Where `window` opens on the desktop, in desktop points: its saved placement [`place`]d against the connected
/// monitors, with the main window's monitor as the home of a window whose position is unknown. A window with no
/// position, and one never shown in an OS window, opens where its group sits in the main window.
@@ -79,12 +88,20 @@ pub fn opening<P>(ctx: &Context, config: &DockConfig, window: &Floating<P>, spec
}
/// The action that records where the OS put the native window `window`, shown in `viewport`: its placement, as an
/// app window's is recorded. `None` while the model already holds what the OS reports, so a window at rest costs no
/// action.
/// app window's is recorded, with the rect `kept` gives for the rect the OS shows the window at (outer top-left corner
/// and inner size, in desktop points), so a collapsed window keeps its expanded rect
/// ([`WindowColumn::kept`](super::WindowColumn::kept)). `None` while the model already holds what the OS reports, so a
/// window at rest costs no action.
#[doc(hidden)]
pub fn reported<P: Clone>(ctx: &Context, window: &Floating<P>, viewport: ViewportId) -> Option<Action<P>> {
pub fn reported<P: Clone>(ctx: &Context, window: &Floating<P>, viewport: ViewportId, kept: impl FnOnce(Rect) -> Rect) -> Option<Action<P>> {
let panel = window.panels().next()?;
let next = WindowHost::of(ctx).placement(viewport, window.native.clone())?;
let mut next = WindowHost::of(ctx).placement(viewport, window.native.clone())?;
if let (false, false, Some(at)) = (next.maximized, next.fullscreen, next.position()) {
let rect = kept(Rect::from_min_size(Pos2::from(at), Vec2::from(next.normal.size)));
next.normal.size = rect.size().into();
next.normal.pos = rect.min.into();
next.position_px = Some([(rect.min.x * next.scale).round() as i32, (rect.min.y * next.scale).round() as i32]);
}
let settled = window.native.as_ref().is_some_and(|saved| {
let near = (0..2).all(|i| (saved.normal.size[i] - next.normal.size[i]).abs() <= SETTLED);
let mut next = next.clone();
+29 -19
View File
@@ -1113,7 +1113,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
/// double arrow sits at that end, and its collapsed column shows against that edge of its rect. A move or resize
/// keeps the edge the window had when it began, so nothing jumps while the window crosses the middle. A collapsed
/// window's move ends at the edge nearer the strip where it was dropped, with the rect that shows the strip there
/// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect.
/// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. An OS window is measured
/// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records
/// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]).
///
/// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that
/// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or
@@ -1141,10 +1143,10 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let dock = scene.dock.with(("floating", window.id));
let group_id = dock.with("window");
let opening = native::opening(&ctx, scene.config, window, &specs, group_id);
let mut actions = vec![HeaderAction::Menu];
if rights.iter().all(|rights| rights.movable) {
actions.push(HeaderAction::Float);
}
let movable = rights.iter().all(|rights| rights.movable);
// The title row is the column's bar: its double arrow and Close; the menu opens from a context request on
// its band.
let mut actions = Vec::new();
if scene.config.close_button && rights.iter().all(|rights| rights.closable) {
actions.push(HeaderAction::Close);
}
@@ -1162,7 +1164,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let mut commands = Vec::new();
let spec = scene.spec(&active);
let began = started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id));
let (began_rect, began_edge) = began.map_or((opening.rect, window.edge), |began| (began.rect, began.edge));
// The window's rect in the app window: for an OS window, where it would sit there.
let in_app = opening.spec.as_ref().and_then(|_| native::in_app(&ctx, opening.rect)).unwrap_or(opening.rect);
let (began_rect, began_edge) = began.map_or((in_app, window.edge), |began| (began.rect, began.edge));
let edge = began_edge.unwrap_or_else(|| WindowColumn::nearer_edge(began_rect, scene.bounds, scene.rtl));
let width = scene.sizes.expanded_width(&window.column, &spec_of);
let shape = if window.column.iconic {
@@ -1226,7 +1230,22 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
native::place(&ctx, viewport, opening.rect, rect);
}
self.report.windows.push((anchor.clone(), viewport));
self.report.actions.extend(native::reported(&ctx, window, viewport));
// A move or resize that ends records where the window would sit in the app window, and the edge it
// keeps to: a collapsed window's the edge nearer its strip where it was dropped, as for a window
// in the app window ([`WindowColumn::dropped`]). The window's placement keeps the rect the
// collapsed column shows against that edge.
let mut kept = shape;
if movable
&& let Some(change) = output.placed.filter(|change| change.phase == GesturePhase::Commit)
&& let Some(rect) = native::in_app(&ctx, change.rect)
{
let (rect, keeps) = shape.dropped(rect, scene.bounds, scene.rtl);
kept.edge = keeps.unwrap_or(kept.edge);
self.report.actions.push(Action::move_floating_with_edge(anchor.clone(), rect, keeps));
}
let title_row = scene.sizes.title_row;
let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, title_row, scene.rtl));
self.report.actions.extend(reported);
}
} else if let Some(mut change) = output.placed {
// A collapsed window keeps the edge its move began with until the move ends where its strip was dropped.
@@ -1243,18 +1262,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
}
moved = Some((anchor.clone(), change, keeps));
}
match output.action {
// The OS close of a native window arrives here as well, also where the title row offers no Close.
Some(HeaderAction::Close) if rights.iter().all(|rights| rights.closable) => {
self.report.actions.push(Action::close_window(anchor.clone()));
}
Some(HeaderAction::Float) => {
let commands = DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated);
if let Ok(docked) = move_actions(&commands, &DragUnit::Window(anchor.clone()), DockTo::Docked) {
self.report.actions.extend(docked);
}
}
_ => {}
// The OS close of a native window arrives here as well, also where the title row offers no Close.
if output.action == Some(HeaderAction::Close) && rights.iter().all(|rights| rights.closable) {
self.report.actions.push(Action::close_window(anchor.clone()));
}
if let Some(item) = picked.get() {
self.pick(&active, item);
@@ -437,26 +437,32 @@ fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column()
assert!(!bed.workspace.borrow().layout.floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow());
}
/// A collapsed floating window's title row is its column's bar alone: a context request on its band opens the
/// window's menu, whose Close entry closes the window.
/// A floating window's title row is its column's bar, with the double arrow and Close and no menu button: a context
/// request on its band opens the window's menu, collapsed or expanded, and the menu's Close entry closes the window.
#[trial]
fn a_context_request_on_a_collapsed_windows_band_opens_its_menu_and_close_closes_it() {
let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL);
let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon");
let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0);
bed.fixture.frame(vec![moved(band)]);
bed.fixture.frame(vec![secondary(band, true)]);
bed.fixture.frame(vec![secondary(band, false)]);
bed.fixture.settle();
let tree = bed.fixture.tree();
let items: Vec<_> =
bed.fixture.by_role(Role::MENU_ITEM).into_iter().map(|item| (craft_ui::testing::access::name(tree, item.node), item)).collect();
let names: Vec<_> = items.iter().map(|(name, _)| *name).collect();
let close = items.iter().find(|(name, _)| name.is_some_and(|name| name.starts_with("Close"))).map(|(_, item)| *item);
let close = close.unwrap_or_else(|| panic!("the band's context request opens the window's menu with a Close entry: {names:?}"));
bed.fixture.click(&close);
bed.fixture.settle();
assert!(bed.workspace.borrow().layout.floating.is_empty(), "Close closed the window: {:?}", bed.actions.borrow());
fn a_context_request_on_a_windows_band_opens_its_menu_and_close_closes_it() {
for collapsed in [true, false] {
let mut bed = if collapsed { bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL) } else { bed(with_window(None), |_| Permissions::ALL) };
let band = if collapsed {
let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon");
Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0)
} else {
window_title()
};
bed.fixture.frame(vec![moved(band)]);
bed.fixture.frame(vec![secondary(band, true)]);
bed.fixture.frame(vec![secondary(band, false)]);
bed.fixture.settle();
let tree = bed.fixture.tree();
let items: Vec<_> =
bed.fixture.by_role(Role::MENU_ITEM).into_iter().map(|item| (craft_ui::testing::access::name(tree, item.node), item)).collect();
let names: Vec<_> = items.iter().map(|(name, _)| *name).collect();
let close = items.iter().find(|(name, _)| name.is_some_and(|name| name.starts_with("Close"))).map(|(_, item)| *item);
let close = close.unwrap_or_else(|| panic!("collapsed {collapsed}: the band's context request opens the window's menu: {names:?}"));
bed.fixture.click(&close);
bed.fixture.settle();
assert!(bed.workspace.borrow().layout.floating.is_empty(), "collapsed {collapsed}: Close closed the window: {:?}", bed.actions.borrow());
}
}
/// Nothing goes beside a floating window: a tab dragged over the start side of its group marks the join of the
+155 -4
View File
@@ -1,10 +1,10 @@
//! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and
//! docking the whole window by dragging its title row.
use craft_behavior::dock::{Action, Column, Floating, Group, Layout, Node, Permissions, Workspace};
use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace};
use craft_behavior::placement::Placement;
use craft_host::target::{Backend, Caps, Os, ShellInfo};
use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _, SizeLimits};
use craft_ui::display::Text;
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec};
use craft_ui::patterns::dock::DockArea;
@@ -16,7 +16,7 @@ use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::trial;
use craft_ui::testing::windows::FakeSystem;
use craft_ui_test_kit::windows::Windows;
use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use std::sync::Arc;
/// The root window and the palette overlap; the palette is the larger.
@@ -203,6 +203,9 @@ struct NativeDock {
windows: Windows,
workspace: Workspace<u32>,
stepped: bool,
/// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the
/// window only the limits a builder carries.
builder: Option<ViewportBuilder>,
}
impl NativeDock {
@@ -222,7 +225,8 @@ impl NativeDock {
let windows = Windows::with(InstallSpec::new(shell, system));
windows.root_info(info(true, MAIN_AT));
windows.child_info(info(true, FLOAT_AT));
let mut dock = NativeDock { windows, workspace: Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])), stepped };
let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]));
let mut dock = NativeDock { windows, workspace, stepped, builder: None };
for _ in 0..3 {
dock.frame(vec![]);
}
@@ -243,6 +247,14 @@ impl NativeDock {
let out = self.windows.frame(root, child, |ui| {
actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions);
});
for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) {
match self.builder.as_mut() {
Some(kept) => {
let _ = kept.patch(builder);
}
None => self.builder = Some(builder),
}
}
let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect();
(actions, commands)
}
@@ -486,6 +498,145 @@ fn an_app_change_of_a_native_floats_place_moves_its_window_once() {
assert_eq!(placing, [&ViewportCommand::OuterPosition(to.min), &ViewportCommand::InnerSize(to.size())], "one move and one size");
}
/// The size and place an OS window takes from `commands`, starting at `at`.
fn placed_by(commands: &[ViewportCommand], at: Rect) -> Rect {
commands.iter().fold(at, |at, command| match command {
ViewportCommand::OuterPosition(to) => Rect::from_min_size(*to, at.size()),
ViewportCommand::InnerSize(size) => Rect::from_min_size(at.min, *size),
_ => at,
})
}
/// A native palette collapsed to icons keeps its expanded size in the model while its OS window shows the strip of
/// icons. Moved across the main window, the strip stays where it was dropped and keeps to the edge nearer it. Expanded
/// again, the window takes its expanded size back and the OS lets it: the strip's size limits are lifted.
#[trial]
fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() {
let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new()));
let expanded = FLOAT_AT.size();
// The OS follows the window commands of each frame, and the window reports where it is.
let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| {
let mut sent = Vec::new();
for _ in 0..frames {
let commands = dock.frame(vec![]).1;
*at = placed_by(&commands, *at);
dock.windows.child_info(info(true, *at));
sent.extend(commands);
}
sent
};
let mut at = FLOAT_AT;
dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses");
follow(&mut dock, &mut at, 3);
let strip = at;
assert!(strip.width() < expanded.x, "the OS window shows the strip: {strip:?}");
let recorded = |dock: &NativeDock| dock.workspace.layout.floating[0].native.clone().expect("the model records the window");
assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "collapsed, the model keeps the expanded size");
// The OS moves the strip over the start half of the main window.
let dropped = Rect::from_min_size(Pos2::new(MAIN_AT.min.x + 50.0, strip.min.y), strip.size());
at = dropped;
dock.windows.child_info(info(true, at));
let sent = follow(&mut dock, &mut at, 4);
assert!(placing(&sent).is_empty(), "the strip stays where it was dropped: {:?}", placing(&sent));
assert_eq!(at, dropped);
assert_eq!(dock.workspace.layout.floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip");
assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "moved, the model keeps the expanded size");
dock.workspace.apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands");
let sent = follow(&mut dock, &mut at, 3);
assert!(sent.contains(&ViewportCommand::InnerSize(expanded)), "the window takes its expanded size back: {:?}", placing(&sent));
assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge");
let max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size);
assert!(max.is_none_or(|max| max.x >= expanded.x && max.y >= expanded.y), "the OS lets it take that size: max {max:?}");
}
/// Palettes no smaller than `PALETTE_LEAST`.
struct Least;
const PALETTE_LEAST: Vec2 = Vec2::new(240.0, 160.0);
impl DockPanels<u32> for Least {
fn spec(&self, _: &u32) -> PanelSpec {
PanelSpec::new(PALETTE_TITLE).limits(SizeLimits::at_least(PALETTE_LEAST))
}
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
}
/// A model place smaller than the palette's limits sizes its OS window within them: the window is never asked for a
/// size the OS would clamp, so the size the model records is the one the window has.
#[trial]
fn a_native_palette_is_never_sized_below_its_limits() {
let windows = Windows::new();
windows.root_info(info(true, MAIN_AT));
windows.child_info(info(true, FLOAT_AT));
let mut window = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size()));
let mut saved = Placement::new(FLOAT_AT.size().into(), 1.0);
saved.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]);
window.native = Some(saved);
let mut workspace = Workspace::new(Layout::new(None, vec![window]));
let mut run = |workspace: &mut Workspace<u32>| {
let out = windows.frame(vec![], vec![], |ui| {
let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Least, DockConfig::default().native_windows(true)).show(ui);
});
out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect::<Vec<_>>()
};
for _ in 0..3 {
run(&mut workspace);
}
let mut small = Placement::new([80.0, 60.0], 1.0);
small.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]);
workspace.apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place");
let mut sent = Vec::new();
for _ in 0..3 {
sent.extend(run(&mut workspace));
}
let sizes: Vec<Vec2> =
sent.iter().filter_map(|command| if let ViewportCommand::InnerSize(size) = command { Some(*size) } else { None }).collect();
assert!(!sizes.is_empty(), "the window is sized to the model's place");
assert!(sizes.iter().all(|size| size.x >= PALETTE_LEAST.x && size.y >= PALETTE_LEAST.y), "within the limits: {sizes:?}");
}
/// While the main window is full screen, an OS window opened over it would cover it, so a float shows in the app
/// window instead, at its own rect there, and a drag of its title row moves it.
#[trial]
fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_screen() {
let windows = Windows::new();
windows.root_info(ViewportInfo { fullscreen: Some(true), ..info(true, MAIN_AT) });
windows.child_info(info(true, FLOAT_AT));
let start = float().rect;
let mut workspace = Workspace::new(Layout::new(None, vec![float()]));
let mut child = false;
let mut run = |workspace: &mut Workspace<u32>, events: Vec<Event>| {
let out = windows.frame(events, vec![], |ui| {
let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui);
});
child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT);
};
for _ in 0..3 {
run(&mut workspace, vec![]);
}
let row = start.min + ROW_AT.to_vec2();
let by = Vec2::new(60.0, 40.0);
run(&mut workspace, vec![moved(row)]);
run(&mut workspace, vec![press(row)]);
for step in 1..=3 {
run(&mut workspace, vec![moved(row + by * step as f32 / 3.0)]);
}
run(&mut workspace, vec![release(row + by)]);
for _ in 0..2 {
run(&mut workspace, vec![]);
}
assert!(!child, "no OS window opens over the full-screen window");
let moved_to = workspace.layout.floating[0].rect.min;
assert!(
(moved_to - (start.min + by)).length() <= by.length() / 2.0,
"the drag moved the float with the pointer: {moved_to:?} from {:?}",
start.min
);
}
/// Palettes whose body is a veil over the window: a target inside the window that takes dropped files.
struct Veiled;