diff --git a/crates/host/src/target.rs b/crates/host/src/target.rs index 39ab7ba1f..82dd82774 100644 --- a/crates/host/src/target.rs +++ b/crates/host/src/target.rs @@ -74,11 +74,13 @@ pub enum Backend { } impl Backend { - /// The backend winit opens by default: Wayland when `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set, else X11. An app - /// that forces X11 (XWayland) passes [`Backend::X11`] instead. + /// The backend winit opens by default: on Linux and the BSDs, Wayland when `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is + /// set, else X11; elsewhere X11. An app that forces X11 (XWayland) passes [`Backend::X11`] instead. pub fn from_env() -> Backend { + let unix_desktop = + cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")); let set = |k| std::env::var_os(k).is_some_and(|v| !v.is_empty()); - if set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET") { Backend::Wayland } else { Backend::X11 } + if unix_desktop && (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) { Backend::Wayland } else { Backend::X11 } } } @@ -296,6 +298,12 @@ impl ShellInfo { MenuPlacement::of(self.caps, self.window.chrome) } + /// Whether the platform reports where its windows are on the desktop and moves them there: a native build, except + /// on Wayland, whose compositor keeps window positions to itself. + pub fn window_positions(&self) -> bool { + self.runtime == Runtime::Native && self.backend != Backend::Wayland + } + /// The shell of the running build: the OS, runtime and capabilities this binary has. pub fn current() -> ShellInfo { let os = Os::current(); diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 714144783..79d8901f5 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -75,6 +75,11 @@ impl WindowHost { base_shell(&self.ctx).caps.contains(Caps::VIEWPORTS) && viewports::available(&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() + } + /// Whether the running viewport's window is drawn; a minimized or covered window runs no UI pass, so this reads /// false only from the app's `logic`. pub fn visible(&self) -> bool { diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index aa541ddd0..4d1c349c4 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -71,7 +71,8 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { let mut tools = cx.keep::().clone(); let events = { let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools }; - let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default()); + // The mock app is a preview inside the gallery's page: its floats stay in it. + let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default().native_windows(false)); if let Some(panel) = state.maximized { area = area.maximized(panel); } diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index 8e86ae99e..15be2c00c 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -76,9 +76,9 @@ pub struct DockConfig { /// closes them, for tabs that act as documents. Off: panels close from their menu. Accordion headers and iconic /// columns never show it. pub tab_close_buttons: bool, - /// A floating window the dock model keeps native opens in an OS window of its own where the platform opens - /// windows and its panels allow it (`PanelSpec::allow_native`). Off: every floating window shows in the app - /// window. + /// A floating window opens in an OS window of its own where the window host opens OS windows and reports where + /// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and + /// with this off, it shows in the app window. pub native_windows: bool, } @@ -95,7 +95,7 @@ impl Default for DockConfig { close_menu_items: true, close_button: true, tab_close_buttons: false, - native_windows: false, + native_windows: true, } } } diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 3bb12af63..8c8cd0595 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -11,10 +11,11 @@ use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup}; use crate::contract::{ - Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, Outcome, Overlay, Pad, Pointer as _, Props as _, - Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _, + Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, Outcome, Overlay, Pad, + Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::runtime::env::{Env, Label}; +use crate::runtime::overlay::CloseReason; use crate::runtime::windows::WindowSpec; use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow}; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; @@ -46,8 +47,8 @@ pub struct FloatingGroupOutput { /// The last step of a move or resize this pass, with the rect the caller keeps: while the group is minimized /// the rect has the height the group has when restored. pub placed: Option, - /// The title row's action part taken this pass. Float and Close are the host's: the dock model docks or closes - /// the group. Menu opens the `menu` rows. + /// The title row's action part taken this pass, or Close when the OS asked the group's window to close. Float and + /// Close are the host's: the dock model docks or closes the group. Menu opens the `menu` rows. pub action: Option, /// Whether a double click on the title band asks to minimize the group, or restore it when it is minimized. pub minimized_toggled: bool, @@ -108,6 +109,8 @@ pub struct FloatingGroup<'a> { #[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")] menu: Option>, actions: Vec, + /// Always open: the caller shows the group while its window exists, and a close comes out as the Close action. + open: Bind<'a, bool>, taken: Option, menu_opener: Option, toggled: bool, @@ -144,6 +147,7 @@ impl<'a> FloatingGroup<'a> { native: None, menu: None, actions: ACTIONS.to_vec(), + open: Bind::given(true), taken: None, menu_opener: None, toggled: false, @@ -268,6 +272,16 @@ impl Component for FloatingGroup<'_> { } impl Container for FloatingGroup<'_> { + fn open(&mut self) -> Option> { + Some(self.open.reborrow()) + } + + fn closed(&mut self, why: CloseReason) { + if why == CloseReason::Requested { + self.taken = Some(HeaderAction::Close); + } + } + fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { let shown = TitleRow::new(cx.label()).strength(HeaderStrength::Strong).actions(self.actions.iter().copied()).show(ui); self.taken = shown.action.or(self.taken); diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index ba9ad7ed5..4c53382a9 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -1,8 +1,8 @@ //! Native dock windows: a floating dock group that shows in an OS window of its own. //! //! A native group is a [`FloatingGroup`](super::FloatingGroup) mounted in a viewport. The container does the window -//! work: its title row moves the window, its grips resize it, its limits are the window's, and a close is a -//! `close_requested` report. What is left is policy, in these functions: whether a window of the dock model gets an +//! work: its title row moves the window, its grips resize it, its limits are the window's, and the OS close is the +//! group's Close action. What is left is policy, in these functions: whether a window of the dock model gets an //! OS window, what kind of window it is, where it opens on the connected monitors, and what the dock model records //! when the OS moves or resizes it. `DockArea` and `FloatingGroup` call them. A native window keeps the //! [`Placement`](craft_behavior::placement::Placement) app windows keep, and opens where [`place`] puts it. @@ -32,9 +32,10 @@ pub struct Opening { } /// Whether the groups of panels with `specs` may open OS windows: the dock's `config` turns them on, the platform -/// opens them and every panel allows it. +/// opens them and reports where they are, and every panel allows it. pub(crate) fn allowed(ctx: &Context, config: &DockConfig, specs: &[PanelSpec]) -> bool { - config.native_windows && WindowHost::of(ctx).viewports_available() && specs.iter().all(|spec| spec.allow_native) + let host = WindowHost::of(ctx); + config.native_windows && host.viewports_available() && 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 @@ -43,11 +44,10 @@ pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec { if specs.iter().any(|spec| spec.window_kind == WindowKind::Document) { WindowSpec::document() } else { WindowSpec::tool() } } -/// Where the saved placement of `window` opens on the desktop, in desktop points: [`place`] against the connected +/// 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 opens where its group sits in the main window. `None` for a window that is not native. -pub fn restore

(ctx: &Context, window: &Floating

) -> Option { - let saved = window.native.as_ref()?; +/// position, and one never shown in an OS window, opens where its group sits in the main window. +pub fn restore

(ctx: &Context, window: &Floating

) -> Rect { let host = WindowHost::of(ctx); let monitors = host.monitors(); let main = host.facts(ViewportId::ROOT); @@ -56,19 +56,17 @@ pub fn restore

(ctx: &Context, window: &Floating

) -> Option { let on = monitor_of(&monitors, Rect::from_min_max(outer.min * scale, outer.max * scale))?; monitors.iter().position(|monitor| monitor == on) }); - let placed = place(Some(saved), &monitors, home, &Defaults::new(window.rect.size().into(), [1.0; 2])); + let placed = place(window.native.as_ref(), &monitors, home, &Defaults::new(window.rect.size().into(), [1.0; 2])); let at = placed.position().map(Pos2::from).or_else(|| main.map(|facts| facts.inner.min + window.rect.min.to_vec2())); - Some(Rect::from_min_size(at.unwrap_or(window.rect.min), Vec2::from(placed.normal.size))) + 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 when it is native and `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 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. #[doc(hidden)] pub fn opening

(ctx: &Context, config: &DockConfig, window: &Floating

, specs: &[PanelSpec]) -> Opening { - if allowed(ctx, config, specs) - && let Some(rect) = restore(ctx, window) - { - return Opening { rect, spec: Some(spec_for(specs)) }; + if allowed(ctx, config, specs) { + return Opening { rect: restore(ctx, window), spec: Some(spec_for(specs)) }; } Opening { rect: window.rect, spec: None } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 80a7bac9b..c7ad2b7b8 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -897,7 +897,10 @@ impl Pass<'_, P> { moved = Some((anchor.clone(), change)); } match output.action { - Some(HeaderAction::Close) => self.report.actions.push(Action::close_window(anchor.clone())), + // 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); if let Ok(docked) = move_actions(&commands, &DragUnit::Window(anchor.clone()), DockTo::Docked) { diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 103ee3896..5697d0ab9 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,20 +1,25 @@ -//! Native dock windows: what the dock records when the OS moves its window. +//! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, and the OS close. use craft_behavior::dock::{Action, Floating, Layout, Permissions, Workspace}; use craft_behavior::placement::Placement; +use craft_host::target::{Backend, ShellInfo}; use craft_ui::contract::{Bind, BodyCx}; use craft_ui::docking::{DockConfig, DockPanels, PanelSpec}; use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::InstallSpec; use craft_ui::testing::trial; +use craft_ui::testing::windows::FakeSystem; use craft_ui_test_kit::windows::Windows; -use egui::{Pos2, Rect, Ui, Vec2, ViewportInfo}; +use egui::{Pos2, Rect, Ui, Vec2, ViewportEvent, ViewportId, ViewportInfo}; +use std::sync::Arc; /// The root window and the palette overlap; the palette is the larger. const ROOT_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(300.0, 300.0) }; const PALETTE_AT: Rect = Rect { min: Pos2::new(200.0, 150.0), max: Pos2::new(600.0, 450.0) }; const PALETTE_TITLE: &str = "Tools"; -struct Palettes; +/// Palette panels with the given rights. +struct Palettes(Permissions); impl DockPanels for Palettes { fn spec(&self, _: &u32) -> PanelSpec { @@ -22,7 +27,7 @@ impl DockPanels for Palettes { } fn permissions(&self, _: &u32) -> Permissions { - Permissions::ALL + self.0 } fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} @@ -42,7 +47,7 @@ fn the_dock_records_where_the_os_put_its_native_window() { let mut actions = Vec::new(); windows.frame(vec![], vec![], |ui| { let config = DockConfig::default().native_windows(true); - let shown = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes, config).show(ui); + let shown = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), config).show(ui); actions.extend(shown.actions); }); actions @@ -60,6 +65,66 @@ fn the_dock_records_where_the_os_put_its_native_window() { assert!(after.iter().any(recorded), "the OS move is recorded: {after:?}"); } +/// A float made in the app window, never shown in an OS window: the dock opens it native over its place there, where +/// the host opens OS windows and reports where they are, and records where the OS put it. On Wayland, which reports +/// no positions, it shows in the app window. +#[trial] +fn a_float_opens_an_os_window_where_the_host_reports_window_positions() { + let opened = |windows: Windows| { + windows.root_info(info(true, ROOT_AT)); + windows.child_info(info(true, PALETTE_AT)); + let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let (mut child, mut recorded) = (false, false); + for _ in 0..3 { + let out = windows.frame(vec![], vec![], |ui| { + let shown = + DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + recorded |= shown.actions.iter().any(|action| matches!(action, Action::SetNative { .. })); + }); + child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT); + } + (child, recorded) + }; + assert_eq!(opened(Windows::new()), (true, true), "an OS window opens and its placement is recorded"); + let wayland = ShellInfo::default().backend(Backend::Wayland); + assert_eq!(opened(Windows::with(InstallSpec::new(wayland, Arc::new(FakeSystem::new())))), (false, false), "Wayland: in the app window"); +} + +/// The OS close of a native float closes its window when every panel may close, and leaves it open otherwise. +#[trial] +fn the_os_close_of_a_native_float_closes_it_when_its_panels_may_close() { + let closed = |rights: Permissions| { + let windows = Windows::new(); + windows.root_info(info(true, ROOT_AT)); + windows.child_info(info(true, PALETTE_AT)); + let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let run = |workspace: &mut Workspace| { + let mut actions = Vec::new(); + windows.frame(vec![], vec![], |ui| { + actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(rights), DockConfig::default()).show(ui).actions); + }); + actions.iter().any(|action| matches!(action, Action::CloseWindow { .. })) + }; + for _ in 0..3 { + run(&mut workspace); + } + windows.child_info(ViewportInfo { events: vec![ViewportEvent::Close], ..info(true, PALETTE_AT) }); + let mut closed = run(&mut workspace); + windows.child_info(info(true, PALETTE_AT)); + for _ in 0..2 { + closed |= run(&mut workspace); + } + closed + }; + assert!(closed(Permissions::ALL), "a closable palette's window closes"); + assert!(!closed(Permissions::ALL.closable(false)), "a window with a panel that may not close stays"); +} + +/// A palette float made in the app window. +fn float() -> Floating { + Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) +} + fn info(focused: bool, rect: Rect) -> ViewportInfo { ViewportInfo { focused: Some(focused), diff --git a/crates/ui-shell/src/shell/app.rs b/crates/ui-shell/src/shell/app.rs index aacf0fd09..11decdd80 100644 --- a/crates/ui-shell/src/shell/app.rs +++ b/crates/ui-shell/src/shell/app.rs @@ -7,7 +7,7 @@ use crate::runtime::InstallSpec; use crate::runtime::frame::{FrameInput, FrameOutput, request_repaint_after, set_input, take_output}; use crate::runtime::windows::{self, WindowAction, WindowHost}; use craft_behavior::placement::Defaults; -use craft_host::target::{Os, ShellInfo, WindowState}; +use craft_host::target::{Backend, Os, ShellInfo, WindowState}; use craft_window::desktop::fits; use craft_window::policy::Decision; use craft_window::restore::Store; @@ -36,12 +36,13 @@ pub struct AppSpec { } impl AppSpec { - /// A spec for `app_id` titled `title`, with the running build's shell and an in-memory placement store. + /// A spec for `app_id` titled `title`, with the running build's shell on the backend winit opens by default (the one + /// `run` opens its windows on) and an in-memory placement store. pub fn new(app_id: impl Into, title: impl Into, defaults: Defaults) -> Self { AppSpec { title: title.into(), app_id: app_id.into(), - shell_info: ShellInfo::default(), + shell_info: ShellInfo::default().backend(Backend::from_env()), defaults, placement: Arc::new(Mutex::new(Store::in_memory())), window_system: Arc::new(NoWindows), diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 74f03f8e2..f9b52a9f6 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -87,7 +87,7 @@ The host handles these `DockEvent`s: | `title_bar_docks` | on | Dragging a floating window's title bar onto a target docks the whole window. | | `close_menu_items`, `close_button` | on | Built-in Close items, and the close action on floating windows. | | `tab_close_buttons` | off | Close buttons on tabs (middle click closes too), for tabs that act as documents. | -| `native_windows` | off | Floating windows open as OS windows where the platform and `PanelSpec::allow_native` allow. | +| `native_windows` | on | Floating windows open as OS windows where the window host opens them and reports their positions (not on Wayland) and `PanelSpec::allow_native` allows. | The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords` holds the words. @@ -111,7 +111,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it. With `DockConfig::native_windows`, a floating window opens in its own OS window (`docking::native`). A panel with `allow_native` off keeps its window inside the main window. `window_kind` says whether an OS window is a document or a tool window. +A floating window is a `Floating` in the layout: its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. `window_kind` says whether an OS window is a document or a tool window. ## SplitArea on its own