diff --git a/apps/photocraft/src/cursor.rs b/apps/photocraft/src/cursor.rs index 72548ca638..786166e29b 100644 --- a/apps/photocraft/src/cursor.rs +++ b/apps/photocraft/src/cursor.rs @@ -13,10 +13,15 @@ //! [`service`] builds the pointer-position service for the app's window, `None` where it can't //! be read. -pub use platform::service; +pub use platform::{primary_down_service, service}; #[cfg(target_os = "macos")] mod platform { + /// Not read here: the title-bar move of a floating document window reaches the app as a press and a release. + pub fn primary_down_service() -> Option { + None + } + use objc2::MainThreadMarker; use objc2_app_kit::{NSApplication, NSEvent, NSWindow}; use photocraft_ui_egui::CursorPosFn; @@ -45,6 +50,11 @@ mod platform { #[cfg(target_os = "linux")] mod platform { + /// Not read here: the title-bar move of a floating document window reaches the app as a press and a release. + pub fn primary_down_service() -> Option { + None + } + use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; use photocraft_ui_egui::CursorPosFn; use x11rb::protocol::xproto::ConnectionExt; @@ -81,7 +91,17 @@ mod platform { #[cfg(target_os = "windows")] mod platform { - use photocraft_ui_egui::CursorPosFn; + use photocraft_ui_egui::{CursorPosFn, PrimaryDownFn}; + + /// The physical left button (`GetAsyncKeyState`): a floating document window's title-bar move runs in the OS, which + /// tells the app nothing when it ends (#16415). + pub fn primary_down_service() -> Option { + // `GetAsyncKeyState` reads the physical button: with the buttons swapped, the primary one is the right. + Some(Box::new(|| { + let swapped = winsafe::GetSystemMetrics(winsafe::co::SM::SWAPBUTTON) != 0; + winsafe::GetAsyncKeyState(if swapped { winsafe::co::VK::RBUTTON } else { winsafe::co::VK::LBUTTON }) + })) + } pub fn service(_cc: &eframe::CreationContext<'_>) -> Option { Some(Box::new(|ctx: &egui::Context| { @@ -104,6 +124,11 @@ fn client_points(screen_px: egui::Pos2, inner_min: egui::Pos2, ppp: f32) -> egui #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] mod platform { + /// Not read here: the title-bar move of a floating document window reaches the app as a press and a release. + pub fn primary_down_service() -> Option { + None + } + use photocraft_ui_egui::CursorPosFn; pub fn service(_cc: &eframe::CreationContext<'_>) -> Option { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 9145a00a76..845b94bdc0 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -713,6 +713,8 @@ fn main() -> eframe::Result { } // Where file drags and drops are (winit 0.30 doesn't say). app.services.cursor_pos = cursor::service(cc); + // The physical primary button: it ends a floating document window's OS move by its title bar (#16415). + app.services.primary_down = cursor::primary_down_service(); // The custom title bar's undecorated window must stay borderless, or its caption and // border offset the content and the pointer on some Windows systems (#2246). app.services.window_frame = window_frame::service(cc, integrated_frame); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e21d0713d6..47cf6e3885 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -99,6 +99,7 @@ impl PhotocraftApp { last_canvas_layer: egui::LayerId::background(), ppp: 1.0, drop_canvas_rect: None, + dock_drop_rect: None, ctx, frame_preview: None, drop_places: Default::default(), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e441ae2f6a..ad09929d65 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -239,6 +239,9 @@ mod tabs_tests; #[cfg(test)] mod doc_window_dialog_tests; +#[cfg(test)] +mod document_window_title_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/document_area.rs b/crates/ui-egui/src/canvas/document_area.rs index bfc1345247..0d1920b0fe 100644 --- a/crates/ui-egui/src/canvas/document_area.rs +++ b/crates/ui-egui/src/canvas/document_area.rs @@ -25,6 +25,8 @@ use super::{PhotocraftApp, canvas_view}; /// document (`layer_transfer`). pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if crate::jobs_ui::batch_preview(app, ui) { + // The preview replaces the tabs: a floating window dropped meanwhile docks nowhere (#16415). + app.dock_drop_rect = None; return; } crate::distort_ui::drop_foreign(app, ui.ctx()); @@ -130,13 +132,23 @@ pub(crate) fn apply_arranged(app: &mut PhotocraftApp, arranged: Arranged) { } } +/// The height of the band at the top of the document area that takes a floating window's drop where no tab strip +/// shows: a tab's height. +const DOCK_BAND: f32 = 32.0; + fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The web build's drop path reads where the canvas is (`file_open::target_at`); set again when one shows. app.drop_canvas_rect = None; + // A floating window's title bar docks on the tab strip (`tabs::strip` sets its rect); where no strip shows, on a + // band of a tab's height at the top of the area, where the strip would be. + let area = ui.max_rect(); + app.dock_drop_rect = Some(Rect::from_min_size(area.min, egui::vec2(area.width(), DOCK_BAND.min(area.height())))); retain_gpu_documents(app); publish_shown(app); crate::cas_transform::tick(app, ui.ctx()); if app.home_screen_up() { + // The Home screen hides the tabs: a floating window dropped on it docks nowhere (#16415). + app.dock_drop_rect = None; start_screen(app, ui); return; } diff --git a/crates/ui-egui/src/canvas/document_window_title_tests.rs b/crates/ui-egui/src/canvas/document_window_title_tests.rs new file mode 100644 index 0000000000..67ab197a56 --- /dev/null +++ b/crates/ui-egui/src/canvas/document_window_title_tests.rs @@ -0,0 +1,343 @@ +//! #16415: a document floated into an OS window of its own, with the app-drawn frame, has a title bar: the window +//! can be told apart, moved, and closed from it. A stand-in for the window system runs each OS window's pass on the +//! harness's context with its own input, as eframe does. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::rc::Rc; + +use egui::accesskit::{Node, NodeId, Role}; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, ViewportId, pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; + +/// Where the floating window opens on the desktop. +fn window_rect() -> Rect { + Rect::from_min_size(pos2(100.0, 80.0), vec2(500.0, 400.0)) +} + +/// The OS windows the app opened: each one's input for its next pass and its access tree as of its last pass. +#[derive(Default)] +struct Host { + events: HashMap>, + nodes: HashMap>, + commands: Vec<(ViewportId, egui::ViewportCommand)>, + time: f64, + /// Where the OS has the floating window, once it moved from where it opened. + moved: Option, + /// The height of a system title bar over the floating window: its outer rect reaches that far above its inner rect. + decorated: f32, +} + +impl Host { + /// The floating window's outer rect on the desktop, as the OS reports it. + fn window_rect(&self) -> Rect { + self.moved.unwrap_or_else(window_rect) + } + + /// The window facts of the main window and the floating window `id`, the floating one with the keyboard. + fn infos(&self, id: ViewportId) -> egui::ViewportIdMap { + let info = |rect: Rect, focused: bool| egui::ViewportInfo { + inner_rect: Some(rect), + outer_rect: Some(rect), + focused: Some(focused), + native_pixels_per_point: Some(1.0), + ..Default::default() + }; + let mut window = info(self.window_rect(), true); + window.outer_rect = window.inner_rect.map(|inner| Rect::from_min_max(inner.min - vec2(0.0, self.decorated), inner.max)); + [(ViewportId::ROOT, info(Rect::from_min_size(Pos2::ZERO, vec2(900.0, 700.0)), false)), (id, window)].into_iter().collect() + } + + fn render(host: &RefCell, ctx: &egui::Context, mut viewport: egui::ImmediateViewport<'_>) { + let id = viewport.ids.this; + let size = viewport.builder.inner_size.unwrap_or(window_rect().size()); + let (events, time) = { + let mut host = host.borrow_mut(); + host.time += 1.0 / 60.0; + (host.events.remove(&id).unwrap_or_default(), host.time) + }; + let viewports = host.borrow().infos(id); + let input = egui::RawInput { + viewport_id: id, + viewports, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), + events, + focused: true, + time: Some(time), + ..Default::default() + }; + let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); + full.textures_delta.clear(); + let mut host = host.borrow_mut(); + if let Some(update) = full.platform_output.accesskit_update.take() { + host.nodes.entry(id).or_default().extend(update.nodes); + } + let commands = full.viewport_output.get(&id).map(|output| output.commands.clone()).unwrap_or_default(); + // The OS follows a move the app asks for. + for command in &commands { + if let egui::ViewportCommand::OuterPosition(pos) = command { + let size = host.window_rect().size(); + host.moved = Some(Rect::from_min_size(*pos, size)); + } + } + host.commands.extend(commands.into_iter().map(|command| (id, command))); + } +} + +type App = Box; + +/// The whole app with its one document floated, the frame decided as at launch with the app's own title bar, and +/// OS windows on the stand-in host. +fn desktop() -> (Harness<'static, App>, Rc>) { + let host = Rc::new(RefCell::new(Host::default())); + let shared = host.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, viewport| Host::render(&shared, ctx, viewport)); + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + // The app's own frame with Windows' captions, whatever the OS or `PHOTOCRAFT_TITLEBAR`: the bar these tests drive + // has Minimize, Maximize and Close. + use craft::window::policy::{CaptionFamily, Captions, Decision, Desktop, DesktopKind, Frame}; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout: craft::window::Layout::default() }); + let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None }; + let decision = Decision { frame, overridden: None, desktop }; + PhotocraftApp::setup_window(&cc.egui_ctx, crate::theme::AppTheme::pro(), decision); + cc.egui_ctx.set_embed_viewports(false); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 200, "height": 150, "name": "floated.png"})).unwrap(); + app.sync_views(); + let document = app.session.documents()[0].doc.id; + assert!(app.ui.document_windows.float(&document, window_rect()).is_some(), "the document floats"); + app + }); + h.run_steps(4); + (h, host) +} + +/// The one OS window the app opened. +fn window(host: &RefCell) -> ViewportId { + let host = host.borrow(); + assert_eq!(host.nodes.len(), 1, "one document window"); + *host.nodes.keys().next().unwrap() +} + +/// The bounds of every node in `id`'s window whose role is `role` and whose name contains `name`. +fn nodes_bounds(host: &RefCell, id: ViewportId, role: Role, name: &str) -> Vec { + let host = host.borrow(); + let Some(nodes) = host.nodes.get(&id) else { return Vec::new() }; + nodes + .values() + .filter(|n| n.role() == role && n.label().is_some_and(|l| l.contains(name))) + .filter_map(|n| n.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))) + .collect() +} + +/// The window's Close caption button. +fn close_button(host: &RefCell, id: ViewportId) -> Option { + nodes_bounds(host, id, Role::Button, "Close").into_iter().next() +} + +/// The window's title bar: a group named after the document, a bar's height at the window's top. The canvas groups +/// carry the same name but fill the window. +fn title_bar(host: &RefCell, id: ViewportId) -> Option { + nodes_bounds(host, id, Role::Group, "floated.png").into_iter().find(|r| r.top() <= 1.0 && r.height() < 60.0) +} + +#[test] +fn a_floating_document_window_has_a_title_bar_at_its_top() { + let (_h, host) = desktop(); + let id = window(&host); + let bar = title_bar(&host, id).expect("the floating window has a title bar named after its document"); + + assert!(close_button(&host, id).is_some_and(|c| bar.contains(c.center())), "the bar has a Close button"); +} + +/// Runs `n` frames with the OS windows listed in the main window's input, the floating one with the keyboard, as an +/// integration reports them. +fn steps(h: &mut Harness<'static, App>, host: &RefCell, id: ViewportId, n: usize) { + for _ in 0..n { + let infos = host.borrow().infos(id); + let input = h.input_mut(); + input.viewports = infos; + input.focused = false; + h.step(); + } +} + +/// Clicks the floating window's title-bar Close. +fn click_close(h: &mut Harness<'static, App>, host: &RefCell, id: ViewportId) { + let close = close_button(host, id).expect("the bar has a Close button").center(); + let press = |pressed| Event::PointerButton { pos: close, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for events in [vec![Event::PointerMoved(close)], vec![press(true)], vec![press(false)]] { + host.borrow_mut().events.insert(id, events); + steps(h, host, id, 1); + } + steps(h, host, id, 2); +} + +/// Close in a floating window's title bar closes its document, as in the reference application: a saved one at once, +/// with the window; one with unsaved changes asks first, and the window stays while it asks. +#[test] +fn the_title_bar_close_closes_the_floating_document() { + let (mut h, host) = desktop(); + let id = window(&host); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + steps(&mut h, &host, id, 2); + click_close(&mut h, &host, id); + assert!(h.state().dialog_open(), "a document with unsaved changes asks before it closes"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays while the prompt asks"); + assert_eq!(h.state().ui.document_windows.floating.len(), 1, "and so does its window"); + + let (mut h, host) = desktop(); + let id = window(&host); + click_close(&mut h, &host, id); + assert!(h.state().session.documents().is_empty(), "a saved document closes"); + assert!(h.state().ui.document_windows.floating.is_empty(), "its window goes with it"); +} + +#[test] +fn dragging_the_title_bar_moves_the_floating_window() { + let (mut h, host) = desktop(); + let id = window(&host); + let bar = title_bar(&host, id).expect("the floating window has a title bar"); + // Left of the centred title: the free band, no control. + let band = bar.left_center() + vec2(40.0, 0.0); + let press = |pressed, pos| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + host.borrow_mut().commands.clear(); + for events in [ + vec![Event::PointerMoved(band)], + vec![press(true, band)], + vec![Event::PointerMoved(band + vec2(40.0, 0.0))], + vec![press(false, band + vec2(40.0, 0.0))], + ] { + host.borrow_mut().events.insert(id, events); + steps(&mut h, &host, id, 1); + } + let started = host.borrow().commands.iter().any(|(viewport, command)| *viewport == id && *command == egui::ViewportCommand::StartDrag) + || h.output().viewport_output.get(&id).is_some_and(|out| out.commands.contains(&egui::ViewportCommand::StartDrag)); + assert!(started, "a drag on the bar's free band moves the window: {:?}", host.borrow().commands); +} + +/// A move of the floating window (the title bar's OS drag, or the OS itself) stays: the app does not put the window +/// back where it opened. +#[test] +fn a_moved_floating_window_stays_where_it_was_moved() { + let (mut h, host) = desktop(); + let id = window(&host); + steps(&mut h, &host, id, 2); + let moved = window_rect().translate(vec2(150.0, 60.0)); + host.borrow_mut().moved = Some(moved); + steps(&mut h, &host, id, 4); + assert_eq!(host.borrow().window_rect(), moved, "the window stays where the OS moved it"); + let placed = h.state().ui.document_windows.floating.first().map(|(_, rect)| *rect); + assert_eq!(placed, Some(moved), "the app keeps the window's new place"); +} + +/// Presses the floating window's title bar at its middle-left, lets the OS move the window to `to` (outer rect on the +/// desktop) and releases there, as an OS move by the title bar does (the runtime adds the release when it ends). +fn move_by_title_bar(h: &mut Harness<'static, App>, host: &RefCell, id: ViewportId, to: Option) { + let bar = title_bar(host, id).expect("the floating window has a title bar"); + let at = bar.left_center() + vec2(40.0, 0.0); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + host.borrow_mut().events.insert(id, vec![Event::PointerMoved(at), press(true)]); + steps(h, host, id, 1); + if let Some(to) = to { + host.borrow_mut().moved = Some(to); + steps(h, host, id, 1); + } + host.borrow_mut().events.insert(id, vec![press(false)]); + steps(h, host, id, 3); +} + +/// #16415: a floating document window dropped by its title bar on the main window's document tabs goes back into +/// them; dropped elsewhere it stays where it went, and a click on its bar docks nothing. +#[test] +fn a_floating_window_dropped_on_the_main_windows_tabs_docks_again() { + let (mut h, host) = desktop(); + let id = window(&host); + steps(&mut h, &host, id, 2); + // A click, no move: the window stays. + move_by_title_bar(&mut h, &host, id, None); + assert_eq!(h.state().ui.document_windows.floating.len(), 1, "a click on the bar docks nothing"); + // Dropped far off the main window: it stays floating there. + let away = Rect::from_min_size(pos2(2000.0, 1200.0), window_rect().size()); + move_by_title_bar(&mut h, &host, id, Some(away)); + assert_eq!(h.state().ui.document_windows.floating.len(), 1, "dropped off the main window it keeps floating"); + // Dropped with the pointer on the main window's tab area: it docks, its document in front. + let target = h.state().dock_drop_rect.expect("the main window has a place to dock"); + let bar = title_bar(&host, id).expect("the bar"); + let grab = bar.left_center() + vec2(40.0, 0.0); + let over = Rect::from_min_size(target.center() - grab.to_vec2(), window_rect().size()); + move_by_title_bar(&mut h, &host, id, Some(over)); + assert!(h.state().ui.document_windows.floating.is_empty(), "dropped on the tabs the window docks"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays open"); + assert_eq!(h.state().session.active_index(), Some(0), "the docked document is in front"); +} + +/// #16415, Windows: the OS runs a title-bar move of the floating window (its hit test answers the caption), so the app +/// sees no press and no release. The window moving while the physical button is down, then the button going up with the +/// OS pointer on the bar over the main window's tabs, docks it; the same end with the pointer elsewhere keeps it. +#[test] +fn an_os_move_of_the_floating_window_ending_over_the_tabs_docks_it() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut h, host) = desktop(); + let id = window(&host); + let down = Arc::new(AtomicBool::new(false)); + let pointer = Rc::new(Cell::new(None::)); + { + let (down, pointer) = (Arc::clone(&down), Rc::clone(&pointer)); + let app = h.state_mut(); + app.services.primary_down = Some(Box::new(move || down.load(Ordering::SeqCst))); + app.services.cursor_pos = Some(Box::new(move |_| pointer.get())); + } + steps(&mut h, &host, id, 2); + let bar = title_bar(&host, id).expect("the bar"); + let grab = bar.left_center() + vec2(40.0, 0.0); + // The OS moves the window with the button held, then the button goes up: off the tabs, nothing docks. + let os_move = |h: &mut Harness<'static, App>, to: Rect| { + down.store(true, Ordering::SeqCst); + host.borrow_mut().moved = Some(to); + pointer.set(Some(to.min + grab.to_vec2())); + steps(h, &host, id, 2); + down.store(false, Ordering::SeqCst); + steps(h, &host, id, 2); + h.state().ui.document_windows.floating.len() + }; + let away = Rect::from_min_size(pos2(500.0, 400.0), window_rect().size()); + assert_eq!(os_move(&mut h, away), 1, "an OS move ending off the tabs keeps it floating"); + let target = h.state().dock_drop_rect.expect("the main window has a place to dock"); + let over = Rect::from_min_size(target.center() - grab.to_vec2(), window_rect().size()); + assert_eq!(os_move(&mut h, over), 0, "an OS move ending on the tabs docks it"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays open"); +} + +/// #16415: a floating document window has a status bar along its bottom with its own document's readout, as the +/// reference application's floating windows do: the zoom and, by default, the document's dimensions. +#[test] +fn a_floating_document_window_has_a_status_bar_with_its_documents_readout() { + let (_h, host) = desktop(); + let id = window(&host); + let host = host.borrow(); + let nodes = host.nodes.get(&id).expect("the window's access tree"); + let labels: Vec<&str> = nodes.values().filter_map(|n| n.label()).collect(); + let dims = labels.iter().find(|l| l.contains("200") && l.contains("150")).copied(); + assert!(dims.is_some(), "the status bar names the document's 200 x 150 size: {labels:?}"); + let zoom = nodes.values().any(|n| n.label().is_some_and(|l| l.contains('%')) || n.value().is_some_and(|v| v.contains('%'))); + assert!(zoom, "the status bar has the zoom: {labels:?}"); +} + +/// #16415: a floating window with the system's title bar (its outer rect taller than its inner one) keeps its size: the +/// app records the outer origin with the inner size, which the framework applies as the inner size again. +#[test] +fn a_decorated_floating_window_keeps_its_size() { + let (mut h, host) = desktop(); + let id = window(&host); + host.borrow_mut().decorated = 30.0; + steps(&mut h, &host, id, 6); + let placed = h.state().ui.document_windows.floating.first().map(|(_, rect)| *rect).expect("the window floats"); + assert!((placed.size() - window_rect().size()).length() < 0.5, "the stored size stays the inner size: {placed:?}"); + assert!((placed.min.y - (window_rect().min.y - 30.0)).abs() < 0.5, "at the outer origin: {placed:?}"); +} diff --git a/crates/ui-egui/src/canvas/document_windows.rs b/crates/ui-egui/src/canvas/document_windows.rs index df2c5070e9..ee480bb0ed 100644 --- a/crates/ui-egui/src/canvas/document_windows.rs +++ b/crates/ui-egui/src/canvas/document_windows.rs @@ -4,9 +4,12 @@ use craft::behavior::canvas::zoom::wrapped_canvas; use craft::behavior::kurbo::Size; +use craft::host::target::WindowState; use craft::ui::canvas::ToolHost; use craft::ui::contract::{ShowContainer as _, SizeLimits}; -use craft::ui::shell::{DocumentWindow, Wrapped}; +use craft::ui::runtime::windows::WindowHost; +use craft::ui::shell::{DocumentWindow, Title, TitleBar, Wrapped}; +use craft::window::policy::Frame; use egui::{Rect, Vec2, vec2}; use photocraft_doc::DocId; @@ -60,6 +63,8 @@ pub(crate) fn sync_documents(app: &mut PhotocraftApp, ids: &[DocId]) { pub fn extra_windows(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let windows: Vec<(u64, Rect)> = app.ui.document_windows.floating.iter().map(|(g, rect)| (g.id, *rect)).collect(); let mut closed = Vec::new(); + let mut docked = Vec::new(); + let dock_target = app.dock_drop_rect; for (id, rect) in windows { let shown = app.ui.document_windows.floating.iter().find(|(g, _)| g.id == id).and_then(|(g, _)| g.shown.or_else(|| g.documents.first().copied())); let Some(doc) = shown.and_then(|d| crate::canvas::tabs::document_index(app, d)) else { continue }; @@ -74,13 +79,39 @@ pub fn extra_windows(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let size = app.session.documents()[doc].doc.size; let doc_size = Size::new(f64::from(size.width), f64::from(size.height)); let focused = app.session.active_index() == Some(doc); + let bar_title = { + let text = crate::canvas::tabs::tab_title_at(app, doc, start.zoom * 100.0); + if app.session.documents()[doc].is_dirty() { Title::unsaved(text) } else { Title::new(text) } + }; let mut view = start.clone(); + let mut dock = false; + let mut bar_rect = None; let inner = DocumentWindow::new(title).first_placed(rect).overlay(|o| o.size_limits(SizeLimits::at_least(MIN_SIZE))).show(ui, |ui, cx| { + if let Some(bar) = window_title_bar(ui, bar_title.clone()) { + if bar.close { + cx.request_close(); + } + dock |= dropped_on_main(ui, id, bar.rect, dock_target); + bar_rect = Some(bar.rect); + } + // The window's status bar along its bottom, before the canvas takes the rest; a zoom typed into it applies + // to the view the canvas draws this pass. + let host = CanvasHost { idx: doc, window: Some(id) }; + let shown = ToolHost::shown_space(ui.ctx(), host.canvas_id()).map(|space| space.view); + let edited = egui::Panel::bottom(egui::IdSalt::new(("floating document status", id))) + .resizable(false) + .frame(egui::Frame::NONE) + .show(ui, |ui| crate::panels::document_window_status(app, ui, doc, shown)) + .inner; + if let Some(edited) = edited { + // The window's own scale, which its canvas builds its view with: it may sit on another display. + let ppp = ui.ctx().pixels_per_point(); + view.set_from(&edited, ppp); + } // A second run of the body in one pass continues from the first run's view; the wrap rule // compares with the view the window started the pass with, so both runs file the same ask. let (after, canvas) = document_window_canvas(app, ui, id, doc, view.clone(), focused); // The view the window's canvas showed this pass, kept by the tool host that ran in it. - let host = CanvasHost { idx: doc, window: Some(id) }; if wants_wrap(preference, &start, &after) && let Some(drawn) = ToolHost::shown_space(ui.ctx(), host.canvas_id()).map(|space| space.view) { @@ -89,8 +120,23 @@ pub fn extra_windows(app: &mut PhotocraftApp, ui: &mut egui::Ui) { view = after; }); let output = inner.output; + dock |= os_move_dropped(app, ui.ctx(), id, output.response.id, bar_rect, dock_target); + if dock { + docked.push((id, doc)); + continue; + } + follow_os_window(app, ui.ctx(), id, output.response.id); if output.close_requested.is_some() { - closed.push(id); + if own { + // A New Window for Document is a second view: closing it leaves the document open. + closed.push(id); + } else { + // Closing a floating document closes the document, as in the reference application, through the + // guarded close the tab's × takes: a document with unsaved changes asks first, and the window stays + // until it is answered (#16415). The window goes with the document. + let doc_id = app.session.documents()[doc].doc.id; + super::tabs::close_document(app, ui.ctx(), doc_id); + } } if output.focus_gained && app.session.active_index() != Some(doc) { app.session.set_active(doc); @@ -111,6 +157,118 @@ pub fn extra_windows(app: &mut PhotocraftApp, ui: &mut egui::Ui) { for id in closed { close_window(app, id); } + // A window whose title bar was dropped on the main window's tabs goes back into them, its document in front. + for (id, doc) in docked { + close_window(app, id); + app.session.set_active(doc); + // The OS window closes in the next pass, the first that no longer shows it; nothing else may ask for one. + ui.ctx().request_repaint(); + } +} + +/// Whether an OS move of the floating window `window` (the container `container`) by its title bar (`bar`, in the +/// window's points) ended this pass with the pointer on the bar over `target`, the main window's tab strip in its +/// points. Where the platform answers the window's hit test (Windows, the app-drawn frame), the OS runs the move and +/// the app sees neither the press nor the release: the window moving from one pass to the next starts it, the +/// physical primary button going up (`Services::primary_down`) ends it, and the OS pointer (`Services::cursor_pos`) +/// says where (#16415). +fn os_move_dropped(app: &mut PhotocraftApp, ctx: &egui::Context, window: u64, container: egui::Id, bar: Option, target: Option) -> bool { + let host = WindowHost::of(ctx); + let Some(facts) = host.viewport_of(container).and_then(|viewport| host.facts(viewport)) else { return false }; + let (last_key, moving_key) = (egui::Id::unique(("floating document place", window)), egui::Id::unique(("floating document moving", window))); + let previous = ctx.data(|d| d.get_temp::(last_key)); + ctx.data_mut(|d| d.insert_temp(last_key, facts.inner)); + // A move keeps the size; a resize or a wrap to the zoom is no move. + let moved = previous.is_some_and(|before| before.min != facts.inner.min && (before.size() - facts.inner.size()).length() < 0.5); + let Some(primary_down) = app.services.primary_down.as_ref() else { return false }; + let down = primary_down(); + // The OS may run the whole move between two of the app's passes (Windows draws no frame of the app while it + // moves a window), so a move first seen with the button up ends at once. + let moving = ctx.data(|d| d.get_temp::(moving_key).unwrap_or(false)) || moved; + if down || !moving { + ctx.data_mut(|d| d.insert_temp(moving_key, moving)); + // Nothing wakes the app when the OS move ends: look again soon while it lasts. + if moving { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + return false; + } + ctx.data_mut(|d| d.remove_temp::(moving_key)); + let (Some(bar), Some(target), Some(main)) = (bar, target, host.facts(egui::ViewportId::ROOT)) else { return false }; + let Some(pointer) = app.services.cursor_pos.as_mut().and_then(|cursor| cursor(ctx)) else { return false }; + // The pointer is in the main window's points; the release on the bar is where the move held the window. + let on_bar = bar.translate(facts.inner.min.to_vec2()).expand(2.0).contains(main.inner.min + pointer.to_vec2()); + on_bar && target.contains(pointer) +} + +/// Whether this pass ends a move of the floating window `window` by its title bar (`bar`, in the window's points) with +/// the pointer over `target`, the main window's tab strip in its points (`PhotocraftApp::dock_drop_rect`): the press on +/// the bar notes where the window was, and the release, which the runtime adds once the OS move ends, docks when the +/// window moved and the pointer is over the strip (#16415). A click on the bar, which moves nothing, docks nothing. +fn dropped_on_main(ui: &egui::Ui, window: u64, bar: Rect, target: Option) -> bool { + let ctx = ui.ctx(); + let host = WindowHost::of(ctx); + let Some(facts) = host.facts(ctx.viewport_id()) else { return false }; + let key = egui::Id::unique(("floating document press", window)); + let (pressed, released, pos) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.interact_pos())); + if pressed && pos.is_some_and(|p| bar.contains(p)) { + ctx.data_mut(|d| d.insert_temp(key, facts.inner.min)); + return false; + } + if !released { + return false; + } + let Some(start) = ctx.data_mut(|d| d.remove_temp::(key)) else { return false }; + let (Some(target), Some(main), Some(pos)) = (target, host.facts(egui::ViewportId::ROOT), pos) else { return false }; + if start == facts.inner.min { + return false; + } + target.translate(main.inner.min.to_vec2()).contains(facts.inner.min + pos.to_vec2()) +} + +/// Keeps the rect the floating window `window` is placed at (`DocumentWindow::first_placed`, the container `container`) +/// where its OS window is. The placed rect is the caller's: the framework puts the window back there on every pass, so +/// without this a move by the title bar or by the OS snapped back at the next pass (#16415). A minimized or maximized +/// window keeps the normal rect. +fn follow_os_window(app: &mut PhotocraftApp, ctx: &egui::Context, window: u64, container: egui::Id) { + let host = WindowHost::of(ctx); + let Some(facts) = host.viewport_of(container).and_then(|viewport| host.facts(viewport)) else { return }; + if facts.state != WindowState::Normal { + return; + } + // The outer origin with the inner size, as the framework places the window: it takes the rect's size as the inner + // size, so the outer size of a decorated window (the system's title bar) would grow it by its frame every pass. + let placed = Rect::from_min_size(facts.outer.unwrap_or(facts.inner).min, facts.inner.size()); + if !placed.is_finite() || placed.width() <= 0.0 || placed.height() <= 0.0 { + return; + } + if let Some((_, rect)) = app.ui.document_windows.floating.iter_mut().find(|(group, _)| group.id == window) + && *rect != placed + { + *rect = placed; + } +} + +/// The title bar of a floating document window with the app-drawn frame (`Frame::Integrated`, the default on Windows +/// and Linux): the document's title, a move band and the caption buttons. `DocumentWindow` leaves that bar to its +/// body there (#16415); without it the window could not be moved, minimized, maximized or closed. With the system's +/// frame the OS draws the bar, and where OS windows are unavailable the fallback layer has its own title row, so +/// nothing is drawn then. Returns the bar's rect and whether its Close was clicked, or `None` with no bar. +fn window_title_bar(ui: &mut egui::Ui, title: Title) -> Option { + let host = WindowHost::of(ui.ctx()); + if !host.viewports_available() || matches!(host.frame(), Frame::Native) { + return None; + } + let out = TitleBar::new().show_titled(ui, title, |_, _| {}, |_, _| {}); + Some(ShownBar { rect: out.response.rect, close: out.close_requested }) +} + +/// A floating document window's title bar as this pass showed it. +struct ShownBar { + /// Its rect, in the window's points. + rect: Rect, + /// Its Close was clicked. + close: bool, } /// The canvas of the document window `window` showing document `doc`, drawn in its own viewport. diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 471d3d7ed7..5ebe93e531 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -38,6 +38,10 @@ pub(super) fn strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, cx: &mut BodyCx< let ctx = ui.ctx().clone(); let out = tabs(app, ui); let response = out.response.clone(); + // A floating document window's title bar dropped on the strip docks it (`document_windows`). + if response.rect.is_positive() { + app.dock_drop_rect = Some(response.rect); + } if let Some(menu) = apply(app, &ctx, out) { cx.keep::().0 = Some(menu); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 33e44212b5..9f91d3279a 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1045,8 +1045,8 @@ fn a_tiled_document_follows_navigator_and_status_bar_zoom() { /// #11276: a document floating in its own window zooms from the zoom typed into the status bar /// and into the Navigator, as a tabbed one does; the window doesn't keep or write back an older -/// copy of the view. Only the typed zoom fields are driven here, not the Navigator's slider or -/// zoom buttons. +/// copy of the view. #16415: so does the zoom typed into the floating window's own status bar. +/// Only the typed zoom fields are driven here, not the Navigator's slider or zoom buttons. #[test] fn a_floating_document_follows_navigator_and_status_bar_zoom() { use egui_kittest::kittest::{NodeT, Queryable}; @@ -1092,9 +1092,20 @@ fn a_floating_document_follows_navigator_and_status_bar_zoom() { f.sort_by(|a, b| a.left().total_cmp(&b.left())); f }; - assert_eq!(fields(&h).len(), 2, "the status bar's and the Navigator's zoom fields"); - for (field, typed, want) in [(0, "200", 2.0), (1, "50", 0.5), (0, "300", 3.0), (1, "100", 1.0)] { - let at = fields(&h)[field].center(); + // The main status bar's field lies lowest, the Navigator's furthest right, the floating window's status bar's is the + // third. + let pick = |f: &[egui::Rect], which: &str| -> egui::Rect { + let lowest = f.iter().copied().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).unwrap_or(egui::Rect::NOTHING); + let right = f.iter().copied().max_by(|a, b| a.left().total_cmp(&b.left())).unwrap_or(egui::Rect::NOTHING); + match which { + "status" => lowest, + "navigator" => right, + _ => f.iter().copied().find(|r| *r != lowest && *r != right).unwrap_or(egui::Rect::NOTHING), + } + }; + assert_eq!(fields(&h).len(), 3, "the status bar's, the Navigator's and the floating window's zoom fields"); + for (field, typed, want) in [("status", "200", 2.0), ("navigator", "50", 0.5), ("window", "300", 3.0), ("navigator", "100", 1.0)] { + let at = pick(&fields(&h), field).center(); h.event(egui::Event::PointerMoved(at)); h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 27af57647d..4094a2c242 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -239,8 +239,9 @@ pub use services::{ AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationLocateFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, - FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn, - Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, + PrimaryDownFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, + WriteFn, }; pub(crate) use services::{opaque_layer, saves_flat_in_place}; pub use text::cjk_fonts; @@ -424,6 +425,9 @@ pub struct PhotocraftApp { /// The document area showing the active document's canvas last frame (not the tabs, the /// start screen or an opening file's card): files dropped here are placed as layers. pub(crate) drop_canvas_rect: Option, + /// Where a floating document window's title bar dropped docks its document, in the main window's points, as of + /// the last frame: the document tab strip, or a band of its height at the top of the document area (#16415). + pub(crate) dock_drop_rect: Option, /// The window's one egui context, for code without one in hand: SAVED-tier reads and writes, /// the Frame tool's transforms from pointer events, and the mapping and panels that read the /// canvas's zoom ease (`document_display::shown_camera`). Read it through [`Self::ctx`]. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index edd1792671..bea440a6d5 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -75,6 +75,7 @@ pub(crate) use info::{SamplerReadouts, sampler_readouts}; pub(crate) use layers::blend_options; pub(crate) use layers_tree::listed_filter; pub use options_bar::options_bar; +pub(crate) use status_bar::document_window_status; pub use status_bar::status_bar; pub use title_bar::{title_bar, window_title}; pub(crate) use toolbar::QUICK_MASK; diff --git a/crates/ui-egui/src/panels/chrome_ui.rs b/crates/ui-egui/src/panels/chrome_ui.rs index 4d5aa96462..c94c8b7161 100644 --- a/crates/ui-egui/src/panels/chrome_ui.rs +++ b/crates/ui-egui/src/panels/chrome_ui.rs @@ -84,7 +84,13 @@ pub(crate) fn set_status_item(chrome: &mut ChromeState, item: StatusItem) { /// What the status bar readout knows about the active document. Items without a value here show a dash. /// The document's values are computed once per document revision and language. pub(crate) fn status_values(app: &PhotocraftApp) -> StatusValues { - let Some(st) = app.session.active() else { return StatusValues::default() }; + app.session.active_index().map_or_else(StatusValues::default, |doc| status_values_of(app, doc)) +} + +/// [`status_values`] for document `doc`, whichever is active: a floating document window's status bar reads its own +/// document (#16415). +pub(crate) fn status_values_of(app: &PhotocraftApp, doc: usize) -> StatusValues { + let Some(st) = app.session.documents().get(doc) else { return StatusValues::default() }; let mut values = app.doc_queries.status(&app.session, st, || { let doc: &Document = &st.doc; let mut values = StatusValues::default(); diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index 342cf9175f..8d912e4e52 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -174,3 +174,27 @@ fn body_members(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { shown.show(ui); } } + +/// The status bar of a floating document window: the readout of its own document `doc` (the zoom field, then the item +/// picked in the main status bar's menu, which picking here changes too), as the reference application's floating +/// document windows have along their bottom (#16415). `view` is the window's canvas as its last pass showed it; a window +/// not shown yet has an empty bar. Returns a view the zoom field set. +pub(crate) fn document_window_status(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: usize, view: Option) -> Option { + let values = chrome_ui::status_values_of(app, doc); + let item = chrome_ui::status_item(&app.ui.chrome); + let size = app.session.documents().get(doc).map(|st| Size::new(st.doc.size.width as f64, st.doc.size.height as f64)); + let (mut picked, mut edited, mut invalid_zoom) = (None, None, None); + Bar::new("", BarKind::Status).show(ui, |ui, _| { + if let (Some(size), Some(view)) = (size, view) { + let out = StatusReadout::new(Bind::given(view), size, item, &values).show(ui); + picked = out.item; + edited = out.view.value().copied(); + invalid_zoom = out.invalid_zoom; + } + }); + if let Some(picked) = picked { + chrome_ui::set_status_item(&mut app.ui.chrome, picked); + } + chrome_ui::zoom_alert(app, invalid_zoom); + edited +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index e84c92bd47..6f53f98f52 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -493,6 +493,11 @@ pub type CapsLockFn = Box bool>; /// Called once per frame; `None` when the window is decorated or the platform needs no fixing. pub type WindowFrameFn = Box; +/// Whether the physical primary mouse button is down now, read from the OS. A move of a floating document window by +/// its title bar runs in the OS (its hit test answers the caption), so the app never sees the press or the release; +/// the button going up ends the move (#16415). +pub type PrimaryDownFn = Box bool + Send + Sync>; + /// Physical right mouse button or stylus barrel button down (Windows; read for brush resize). pub type RightButtonDownFn = Box bool + Send + Sync>; @@ -644,6 +649,8 @@ pub struct Services { pub window_frame: Option, /// Physical right mouse button or pen barrel button currently down. pub right_button_down: Option, + /// Physical primary mouse button currently down (Windows): ends an OS move of a floating document window. + pub primary_down: Option, /// Which end of the pen is in use, where the platform reports it outside the stylus feed /// (Windows: the feed carries no pen samples there). Read for the eraser-end tool switch. pub pen_end: Option,