Native windows: one writer of a window's place at a time

A viewport window's builder carried its caller's rect every pass, and egui sent
each change of it to the window. The caller's rect follows the window's own
reports a pass late (the dock model records the OS place, a saved window reads
its store), so every OS move or resize came back as a command of the place one
pass old. While AppKit moved or live-resized a window the two writers set it to
two places in turn, without end: the title-row drag jittered, and a live resize
stretched the content with black edges.

- The builder carries the place only until the window opens.
- Each window keeps its known place: what its own pass last saw, or what act
  last commanded. A caller's place goes out only where it differs from the
  known place, never while a move gesture runs or the window is minimized,
  maximized or full screen. Placements are recorded from the known place.
- A dock window is fitted to the monitors when it opens; an open one stays at
  the placement the model recorded.
- The windows fixture sends a child the changes of its builder as commands,
  as eframe does, so trials see what an integration would send.
This commit is contained in:
aiongg
2026-11-12 14:32:39 +00:00
parent 6cf7952263
commit 52cc593d40
8 changed files with 186 additions and 24 deletions
@@ -132,6 +132,12 @@ pub(crate) struct Record {
moved_pointer: Option<Pos2>,
/// The `movable` flag last set on the OS window.
movable_applied: Option<bool>,
/// Where a window `show_viewport` opened is as far as its caller knows: its outer top-left corner and inner size,
/// as its own pass last saw them, or as [`act`] last commanded. A caller that records the window's place records
/// this one, so a caller that follows the window places it here and sends it nothing.
known: Option<Rect>,
/// The place the window's own pass last saw.
seen: Option<Rect>,
}
/// Passes between searches for an OS window that was not found.
@@ -194,12 +194,13 @@ impl WindowHost {
Some(WindowFacts { inner: facts.inner?, outer: facts.outer, scale: scale_of(&self.ctx, &facts), state: info.state, focused: facts.focused })
}
/// `previous` (or a new record) updated to where `viewport`'s window is now, recorded as an app window's saved
/// placement is. `None` before the window has reported its rect and scale.
/// `previous` (or a new record) updated to where `viewport`'s window is, recorded as an app window's saved
/// placement is: where it last reported itself, or where the app last sent it. A caller that places the window at
/// this placement sends it nothing. `None` before the window has reported its rect and scale.
#[doc(hidden)]
pub fn placement(&self, viewport: ViewportId, previous: Option<Placement>) -> Option<Placement> {
let facts = PerViewport::<Record>::with(&self.ctx, viewport, |record| record.facts)?;
placement_of(&self.ctx, &facts, previous)
placement_of(&self.ctx, &super::viewport::at_known(&self.ctx, viewport, facts), previous)
}
/// The connected monitors, in desktop pixels; none where the platform does not list them.
@@ -12,7 +12,7 @@ use crate::runtime::frame::PerViewport;
use craft_host::target::{Caps, DoubleClick, WindowState};
use craft_window::native::NativeWindow;
use craft_window::policy::Frame;
use egui::{Context, Pos2, Vec2, ViewportId};
use egui::{Context, Pos2, Rect, Vec2, ViewportId};
use std::sync::Arc;
/// A window command `act` sends.
@@ -115,8 +115,14 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool {
viewports::command(ctx, viewport, egui::ViewportCommand::BeginResize(viewports::resize_direction(edge)));
hand_off(ctx, viewport);
}
WindowAction::SetOuterPosition(pos) => viewports::command(ctx, viewport, egui::ViewportCommand::OuterPosition(pos)),
WindowAction::SetInnerSize(size) => viewports::command(ctx, viewport, egui::ViewportCommand::InnerSize(size)),
WindowAction::SetOuterPosition(pos) => {
viewports::command(ctx, viewport, egui::ViewportCommand::OuterPosition(pos));
PerViewport::<Record>::with(ctx, viewport, |record| record.known = record.known.map(|known| Rect::from_min_size(pos, known.size())));
}
WindowAction::SetInnerSize(size) => {
viewports::command(ctx, viewport, egui::ViewportCommand::InnerSize(size));
PerViewport::<Record>::with(ctx, viewport, |record| record.known = record.known.map(|known| Rect::from_min_size(known.min, size)));
}
WindowAction::SetLevel(level) => {
// A window opened by `show_viewport` gets its level with the next build of its viewport; any other (the
// root) is told now.
@@ -1,6 +1,6 @@
//! Viewport mounts: opening a mount's OS viewport and its close requests.
use super::native::route_hit_test;
use super::native::{WindowAction, act, route_hit_test};
use super::placement::{record_placement, saved_placement};
use super::shell::{os_of, refresh};
use super::spec::{WindowSpec, frame_of_spec};
@@ -8,7 +8,7 @@ use super::{Record, refuse_close_under_modal, shared};
use crate::runtime::egui::viewports;
use crate::runtime::frame::PerViewport;
use craft_host::target::{Os, WindowChrome, WindowKind};
use egui::{Context, Id, Pos2, Ui, Vec2};
use egui::{Context, Id, Pos2, Rect, Ui, Vec2, ViewportId};
/// What a viewport mount asks for.
pub(crate) struct ViewportOpen<'a> {
@@ -32,6 +32,11 @@ pub(crate) struct ViewportOpen<'a> {
/// Opens the OS viewport of a mount and runs `body` once for each pass it gets: with the saved placement, the OS
/// close request turned into a request to the container, and the placement saved after the pass.
///
/// The window opens at the caller's place (saved, placed or measured). From then on the window has two writers, the
/// OS and the caller, and only one writes at a time: a caller's place goes out as a command only where it differs
/// from the place the window is known at ([`keep_placed`]), and the OS's moves and resizes become the known place
/// that the caller records. A caller that follows the window so never sends it its own place back a pass late.
pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: impl FnMut(&mut Ui)) {
let viewport = viewports::viewport_id(open.id);
let saved = open.save.and_then(|key| saved_placement(ctx, key));
@@ -39,6 +44,11 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
Some(placement) => (Some(Vec2::from(placement.normal.size)), placement.position().map(Pos2::from)),
None => (open.size, None),
};
let pos = pos.or(open.position);
let opened = PerViewport::<Record>::with(ctx, viewport, |record| record.seen.is_some());
if opened {
keep_placed(ctx, viewport, pos, size);
}
let spec = open.spec;
let active = !shared(ctx, |shared| shared.away);
let os = os_of(ctx);
@@ -61,8 +71,9 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
});
let opens = viewports::Spec {
title: open.title,
size,
pos: pos.or(open.position),
// The builder carries the place only until the window opens: egui would send each change of it as a command.
size: size.filter(|_| !opened),
pos: pos.filter(|_| !opened),
chrome,
// 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),
@@ -75,7 +86,9 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
};
viewports::show_immediate(ctx, viewport, &opens, |ui| {
let ctx = ui.ctx().clone();
refresh(&ctx, viewport, viewports::current(&ctx));
let facts = viewports::current(&ctx);
refresh(&ctx, viewport, facts);
note_seen(&ctx, viewport, &facts);
if viewports::current(&ctx).close_requested && !refuse_close_under_modal(&ctx) {
viewports::cancel_close(&ctx);
shared(&ctx, |shared| {
@@ -89,7 +102,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
route_hit_test(&ctx, viewport);
}
if let Some(key) = open.save {
record_placement(&ctx, viewport, key, &viewports::current(&ctx));
record_placement(&ctx, viewport, key, &at_known(&ctx, viewport, viewports::current(&ctx)));
}
});
if PerViewport::<Record>::with(ctx, viewport, |record| std::mem::take(&mut record.awaiting_first_paint)) {
@@ -105,3 +118,57 @@ pub(crate) fn take_close_request(ctx: &Context, id: Id) -> bool {
shared.close_requests.len() != before
})
}
/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a
/// placement records the position in pixels.
const ROUNDING: f32 = 0.5;
/// The place of a window with `facts`: its outer top-left corner and its inner size.
fn place_of(facts: &viewports::Facts) -> Option<Rect> {
let inner = facts.inner?;
Some(Rect::from_min_size(facts.outer.unwrap_or(inner).min, inner.size()))
}
/// In the window's own pass: a place the window reports that differs from the one it reported before is its known
/// place, as its caller reads it in this pass.
fn note_seen(ctx: &Context, viewport: ViewportId, facts: &viewports::Facts) {
let Some(place) = place_of(facts) else { return };
PerViewport::<Record>::with(ctx, viewport, |record| {
if record.seen != Some(place) {
record.seen = Some(place);
record.known = Some(place);
}
});
}
/// Sends the window to the caller's position `pos` and inner size `size` where they differ from its known place by
/// more than rounding. Nothing goes out while a move gesture moves the window (it sends the window's place itself),
/// nor while the window is minimized, maximized or full screen, when a caller keeps its normal place.
fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option<Pos2>, size: Option<Vec2>) {
let (known, held) = PerViewport::<Record>::with(ctx, viewport, |record| {
let state = record.facts.is_some_and(|facts| facts.minimized || facts.maximized || facts.fullscreen);
(record.known, state || record.moved_pointer.is_some())
});
let Some(known) = known.filter(|_| !held) else { return };
let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING;
if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) {
act(ctx, viewport, WindowAction::SetOuterPosition(pos));
}
if let Some(size) = size.filter(|size| differs(*size - known.size())) {
act(ctx, viewport, WindowAction::SetInnerSize(size));
}
}
/// `facts` with the window at its known place, where it has one: the place its caller records.
pub(super) fn at_known(ctx: &Context, viewport: ViewportId, facts: viewports::Facts) -> viewports::Facts {
let known = PerViewport::<Record>::with(ctx, viewport, |record| record.known);
let (Some(known), Some(inner)) = (known, facts.inner) else { return facts };
let outer = facts.outer.unwrap_or(inner);
let shift = known.min - outer.min;
let grow = known.size() - inner.size();
viewports::Facts {
inner: Some(Rect::from_min_size(inner.min + shift, known.size())),
outer: facts.outer.map(|outer| Rect::from_min_size(outer.min + shift, outer.size() + grow)),
..facts
}
}
+13 -6
View File
@@ -61,14 +61,21 @@ pub fn restore<P>(ctx: &Context, window: &Floating<P>) -> Rect {
Rect::from_min_size(at.unwrap_or(window.rect.min), Vec2::from(placed.normal.size))
}
/// How `window` shows: in an OS window at its restored rect where `config`, the platform and its panels allow one,
/// else in the app window at its own rect. `specs` are its panels' specs.
/// How `window` shows: in an OS window where `config`, the platform and its panels allow one, else in the app window
/// at its own rect. `specs` are its panels' specs; `group` is the id of the group that shows it. A window that opens
/// opens at its [`restore`]d rect; an open window stays at the placement the dock model recorded for it, so the
/// monitor fit of `restore` never sends back a place the user gave it.
#[doc(hidden)]
pub fn opening<P>(ctx: &Context, config: &DockConfig, window: &Floating<P>, specs: &[PanelSpec]) -> Opening {
if allowed(ctx, config, specs) {
return Opening { rect: restore(ctx, window), spec: Some(spec_for(specs)) };
pub fn opening<P>(ctx: &Context, config: &DockConfig, window: &Floating<P>, specs: &[PanelSpec], group: egui::Id) -> Opening {
if !allowed(ctx, config, specs) {
return Opening { rect: window.rect, spec: None };
}
Opening { rect: window.rect, spec: None }
let open = WindowHost::of(ctx).viewport_of(group).is_some();
let recorded = window.native.as_ref().filter(|_| open).and_then(|native| {
let at = native.position()?;
Some(Rect::from_min_size(Pos2::from(at), Vec2::from(native.normal.size)))
});
Opening { rect: recorded.unwrap_or_else(|| restore(ctx, window)), spec: Some(spec_for(specs)) }
}
/// The action that records where the OS put the native window `window`, shown in `viewport`: its placement, as an
+4 -3
View File
@@ -817,7 +817,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
};
let specs: Vec<PanelSpec> = window.panels().map(|panel| scene.spec(panel)).collect();
let rights: Vec<Permissions> = window.panels().map(|panel| scene.permissions(panel)).collect();
let opening = native::opening(&ctx, scene.config, window, &specs);
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);
@@ -828,7 +830,6 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let (rows, _) = self.menu_rows(body, &active);
let picked = Cell::new(None);
let dropped = RefCell::new(None);
let dock = scene.dock.with(("floating", window.id));
let mut target = DockDropTarget::new(&ctx, dock, scene.layout, &policy);
target.rtl = scene.rtl;
target.space = Some(scene.space);
@@ -847,7 +848,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
.window_of(anchor.clone())
.takes_drops(target, &dropped)
.command_scope(DockCommands::SCOPE)
.id_salt(("floating", window.id));
.id(group_id);
group = match opening.spec.clone() {
Some(window_spec) => group.native(window_spec),
None => group.bounds(scene.bounds),
+49 -1
View File
@@ -129,7 +129,8 @@ fn a_native_float_opens_at_its_own_size() {
sizes.extend(out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, builder)| builder.inner_size));
}
let size = float().rect.size();
assert!(!sizes.is_empty() && sizes.iter().all(|shown| *shown == Some(size)), "{size:?} asked, {sizes:?} opened");
assert_eq!(sizes.first(), Some(&Some(size)), "{size:?} asked, {sizes:?} opened");
assert!(sizes.iter().flatten().all(|shown| *shown == size), "{size:?} asked, {sizes:?} opened");
}
/// The OS close of a native float closes its window when every panel may close, and leaves it open otherwise.
@@ -293,6 +294,53 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_window
assert!(docked, "the button's release docks the whole window");
}
fn placing(commands: &[ViewportCommand]) -> Vec<&ViewportCommand> {
commands.iter().filter(|command| matches!(command, ViewportCommand::OuterPosition(_) | ViewportCommand::InnerSize(_))).collect()
}
/// The OS resizes a native palette live from its edge and then moves it, as AppKit does on macOS, while the dock model
/// records each place a pass after the OS reported it. The app sends the window none of those places back: each would
/// be a pass old, and the two writers would set the window to two places in turn for ever. At rest it stays where the
/// OS left it.
#[trial]
fn a_native_float_the_os_resizes_or_moves_gets_no_place_back() {
let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new()));
let mut sent = Vec::new();
let mut at = FLOAT_AT;
for step in 1..=4 {
at = Rect::from_min_size(FLOAT_AT.min, FLOAT_AT.size() + Vec2::new(2.0, 8.0) * step as f32);
dock.windows.child_info(info(true, at));
sent.extend(dock.frame(vec![]).1);
}
for step in 1..=3 {
at = at.translate(Vec2::new(-30.0, 12.0) * step as f32);
dock.windows.child_info(info(true, at));
sent.extend(dock.frame(vec![]).1);
}
for _ in 0..3 {
sent.extend(dock.frame(vec![]).1);
}
assert!(placing(&sent).is_empty(), "the OS's places come back: {:?}", placing(&sent));
let recorded = dock.workspace.layout.floating[0].native.clone().expect("the model records the window");
assert_eq!(Vec2::from(recorded.normal.size), at.size(), "the model holds the OS's last size");
}
/// An app change of a native palette's place (an undo, a reloaded layout) moves and sizes its window, once.
#[trial]
fn an_app_change_of_a_native_floats_place_moves_its_window_once() {
let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new()));
let to = Rect::from_min_size(Pos2::new(1100.0, 200.0), Vec2::new(320.0, 260.0));
let mut placement = Placement::new(to.size().into(), 1.0);
placement.position_px = Some([to.min.x as i32, to.min.y as i32]);
dock.workspace.apply(Action::set_native(1, Some(placement)), false, |_| Permissions::ALL).expect("the model takes the place");
let mut sent = Vec::new();
for _ in 0..3 {
sent.extend(dock.frame(vec![]).1);
}
let placing = placing(&sent);
assert_eq!(placing, [&ViewportCommand::OuterPosition(to.min), &ViewportCommand::InnerSize(to.size())], "one move and one size");
}
/// A palette float made in the app window.
fn float() -> Floating<u32> {
Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0)))
+28 -2
View File
@@ -1,6 +1,6 @@
//! A frame driver for trials with child viewports: the context opens OS viewports (not embedded), and a renderer
//! like eframe's runs each child's pass nested inside its parent's UI closure, with events and window facts
//! the trial gives it.
//! like eframe's runs each child's pass nested inside its parent's UI closure, with events and window facts the trial
//! gives it. As an integration does, the window gets what changed in its builder as commands before the pass.
use craft_host::target::ShellInfo;
use craft_ui::runtime::InstallSpec;
@@ -32,6 +32,9 @@ thread_local! {
static TREES: RefCell<Vec<(ViewportId, AccessTree)>> = const { RefCell::new(Vec::new()) };
/// The time every pass of the frame runs at.
static NOW: Cell<f64> = const { Cell::new(0.0) };
/// Each child's builder as its window has it: a later builder patches it, and what changed goes to the window as
/// commands, as an integration sends them.
static BUILDERS: RefCell<Vec<(ViewportId, ViewportBuilder)>> = const { RefCell::new(Vec::new()) };
}
/// Seconds between two frames.
@@ -81,7 +84,29 @@ fn all_viewports(child: ViewportInfo) -> egui::ViewportIdMap<ViewportInfo> {
all
}
/// Patches the window of `id` with `builder`, as an integration does before the child's pass: the fields that
/// changed go to the window as commands. The first builder opens the window.
fn patch_window(id: ViewportId, builder: ViewportBuilder) {
let commands = BUILDERS.with(|kept| {
let mut kept = kept.borrow_mut();
match kept.iter_mut().find(|(held, _)| *held == id) {
Some((_, window)) => window.patch(builder).0,
None => {
kept.push((id, builder));
Vec::new()
}
}
});
COMMANDS.with(|kept| {
for command in commands {
os_applies(id, &command);
kept.borrow_mut().push((id, command));
}
});
}
fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) {
patch_window(viewport.ids.this, viewport.builder);
let mut callback = viewport.viewport_ui_cb;
let events = CHILD_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut()));
let mut info = CHILD_INFO.with(|info| info.borrow().clone());
@@ -143,6 +168,7 @@ impl Windows {
CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default());
CHILDREN.with(|children| children.borrow_mut().clear());
COMMANDS.with(|kept| kept.borrow_mut().clear());
BUILDERS.with(|kept| kept.borrow_mut().clear());
NOW.with(|now| now.set(0.0));
Windows { ctx, root_info: RefCell::new(ViewportInfo::default()) }
}