diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 682c8ca66c..16ddc169c7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -52,7 +52,7 @@ pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; pub(crate) use rulers::{general_lengths, stroke_lengths}; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions}; pub use tool_adapter::{apply_requests, dispatch, mods}; -pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page}; +pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page, tool_enter}; /// Which body a document's canvas runs: the current window's interactive one, or a display-only /// pane of a tiled or floating window. diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 4dedfa2f09..0d4f6a1076 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -378,12 +378,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { super::drops::show(app, &mut catcher, w, BodyKind::Pane); } drop_released(app); - // Note the fits this frame made, for `refit_resized`. - for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { - if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { - app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); - } - } + note_fits(app, &areas, &unfitted); }); let activated = split.output.activated; app.canvas.panes.at = lines; @@ -434,6 +429,16 @@ pub(crate) fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect) .collect() } +/// Note the fits this frame made, for [`refit_resized`]: each of `areas`' views that was unfitted +/// (`unfitted`, as `refit_resized` returned) and is fitted now, with its area's size. +pub(crate) fn note_fits(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)], unfitted: &[bool]) { + for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { + if let (true, Some(v), Some(s)) = (*was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { + app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); + } + } +} + /// Fit `v` to show its artboard (the first if it has gone) in `area`, with the interface zoomed by /// `ui_zoom` on a screen of `pixels_per_point`, as Fit Artboard in Window does. fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, area: egui::Rect, (ui_zoom, pixels_per_point): (f32, f32), scheme: &ZoomScheme) { diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 9bb95ae577..bf97fb56c2 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -109,6 +109,30 @@ fn sync_artboard(app: &mut VectorcraftApp) { } } +/// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate, Scale, +/// Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a double-click on the +/// tool's button does. Taken only when a dialog opened, so that Enter is not also its OK. +pub(crate) fn tool_enter(app: &mut VectorcraftApp, mods: Mods, view: ViewInfo) -> bool { + if app.session.tool_busy() { + return false; + } + let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); + let before = open(app); + let r = app.session.tool_key(EngineKey::Enter, mods, view); + apply_requests(app, r); + let tool = app.session.tool_id().to_owned(); + if open(app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) { + // Nothing selected: it fails and nothing opens (the menu item is disabled then too). + let _ = crate::toolbar::open_options(app, &tool); + } + let opened = open(app) > before; + // The dialog uses the tool a held key chose. + if opened { + crate::shortcuts::note_tool_use(app); + } + opened +} + /// The session as a tool for one pass. The host's trait takes `&self` for the cursor and the claims, which the /// session answers through `&mut`, so the app sits in a cell. struct SessionTool<'a> { @@ -126,9 +150,10 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } - /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas. + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating + /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { - self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer) + self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer) || crate::panel_docking::os_window_at(&self.app(), &self.ctx, pointer.pos) } fn app(&self) -> RefMut<'_, &'a mut VectorcraftApp> { @@ -153,29 +178,9 @@ impl<'a> SessionTool<'a> { true } - /// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate, - /// Scale, Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a - /// double-click on the tool's button does. Taken only when a dialog opened, so that Enter is not also its OK. + /// [`tool_enter`] in this canvas's view. fn enter(&self, mods: Mods) -> bool { - let mut app = self.app(); - if app.session.tool_busy() { - return false; - } - let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); - let before = open(&app); - let r = app.session.tool_key(EngineKey::Enter, mods, self.view); - apply_requests(&mut app, r); - let tool = app.session.tool_id().to_owned(); - if open(&app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) { - // Nothing selected: it fails and nothing opens (the menu item is disabled then too). - let _ = crate::toolbar::open_options(&mut app, &tool); - } - let opened = open(&app) > before; - // The dialog uses the tool a held key chose. - if opened { - crate::shortcuts::note_tool_use(&mut app); - } - opened + tool_enter(&mut self.app(), mods, self.view) } /// A key the tool does not claim while its gesture runs: arrows and digits still reach it, with no modifier (a @@ -286,7 +291,8 @@ impl CanvasTool for SessionTool<'_> { return; } // Art carried off the canvas waits where it last moved; back on the canvas the move goes on. - let carried = super::drops::carry_out(&mut self.app(), cx, pointer, self.covered(pointer)); + let covered = self.covered(pointer); + let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { let ev = pointer_event(PointerKind::Drag, pointer, cx); dispatch(&mut self.app(), &ev, self.view); @@ -306,7 +312,8 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); - let carried = super::drops::carried(&self.app(), cx, pointer, self.covered(pointer)); + let covered = self.covered(pointer); + let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); if cx.over_drop_target() || carried.is_some() { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index b0bf95f59f..affc548233 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -26,10 +26,13 @@ pub(crate) mod rank { /// The parts of a group that its other members work without: the width profile, Recolor Artwork, Global Edit /// Options, Document Setup, an image's Edit Original. pub const DETAIL: u8 = 3; + /// The Opacity link and field: they leave before the groups, so the narrower Style link and picker after them + /// can show without them. + pub const OPACITY: u8 = 4; /// Every other member of the bar. - pub const GROUP: u8 = 4; + pub const GROUP: u8 = 5; /// A section's link that stays after its fields leave. - pub const LINK: u8 = 6; + pub const LINK: u8 = 7; } /// An anchor button: icon, tooltip, command and the convert command's `to`. @@ -300,7 +303,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) { fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: bool) { let label = tl!("Opacity:"); let (mut link, mut typed) = (false, None); - group(ui, rank::GROUP, |ui| { + group(ui, rank::OPACITY, |ui| { Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| { let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))).range(0.0..=100.0).unit("%").scrub_by_label().show(ui); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 81d82b702c..e9feeaaac1 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -3,9 +3,10 @@ use craft::behavior::IconId; use craft::behavior::kurbo::Size; use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{Bind, Entry, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger}; +use craft::ui::contract::{Bind, Entry, Gap, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger}; use craft::ui::display::{Divider, Elide, Shade, Text}; use craft::ui::form::Field; +use craft::ui::layout_components::Row; use craft::ui::menu::Menu; use craft::ui::pickers::Select; use craft::ui::style::TypeRole; @@ -83,18 +84,23 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(shown.to_owned()).shade(Shade::Muted).elide(Elide::End).show(ui); let more = IconButton::new(IconId::new("chevron_down")).label(tl!("Show")).show(ui); show_pick = Menu::new(tl!("Show")).values().opened_by(more.response(), Trigger::Press).pick(ui, &shows).picked; + // A narrow bar leaves out the timings first, then the pointer's position, before the message. let readout = |text: String, sample: String| Text::new(text).shade(Shade::Faint).sample(sample); - readout(format!("{render} {:.1} ms", app.perf.render_ms), format!("{render} 8888.8 ms")).show(ui); - readout(format!("{ui_name} {:.1} ms", app.perf.frame_ms), format!("{ui_name} 8888.8 ms")).show(ui); - // No rate until the window has drawn continuously for a moment (`frame_rate`). - let fps = if app.perf.fps > 0.0 { format!("{:.0} fps", app.perf.fps) } else { "\u{2013} fps".into() }; - readout(fps, "8888 fps".into()).show(ui); + Row::new().gap(Gap::Item).fit_rank(1).show(ui, |ui, _| { + readout(format!("{render} {:.1} ms", app.perf.render_ms), format!("{render} 8888.8 ms")).show(ui); + readout(format!("{ui_name} {:.1} ms", app.perf.frame_ms), format!("{ui_name} 8888.8 ms")).show(ui); + // No rate until the window has drawn continuously for a moment (`frame_rate`). + let fps = if app.perf.fps > 0.0 { format!("{:.0} fps", app.perf.fps) } else { "\u{2013} fps".into() }; + readout(fps, "8888 fps".into()).show(ui); + }); // With no hover point the axes stay empty and keep their width. let origin = app.ruler_origin(); - for (axis, value) in [("X", app.hover_doc.map(|p| p.x - origin.x)), ("Y", app.hover_doc.map(|p| p.y - origin.y))] { - let text = value.map(|v| format!("{axis}: {}", unit.readout(v))).unwrap_or_default(); - Text::new(text).role(TypeRole::Mono).shade(Shade::Muted).sample(format!("{axis}: -8888.88 {}", unit.suffix())).show(ui); - } + Row::new().gap(Gap::Item).fit_rank(2).show(ui, |ui, _| { + for (axis, value) in [("X", app.hover_doc.map(|p| p.x - origin.x)), ("Y", app.hover_doc.map(|p| p.y - origin.y))] { + let text = value.map(|v| format!("{axis}: {}", unit.readout(v))).unwrap_or_default(); + Text::new(text).role(TypeRole::Mono).shade(Shade::Muted).sample(format!("{axis}: -8888.88 {}", unit.suffix())).show(ui); + } + }); if app.session.script_running() { stop = Button::new(tl!("Stop")).show(ui).response().clicked(); } diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index a2235c79d4..e19c5a6ddd 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -101,7 +101,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } let held = !carrying && ui.input(|i| i.pointer.primary_down()); for event in strip.show(ui).events { - if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. }) { + if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. } | DocumentTabsEvent::DroppedInto { .. }) { ui.data_mut(|d| d.remove::(pressed)); } match event { @@ -134,7 +134,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } } DocumentTabsEvent::DroppedInto { documents, .. } => { - for (index, view) in documents { + // A tab of this strip dropped back on it past the tabs is already docked. + let floating: Vec = documents.into_iter().filter(|w| doc_windows::floats(app, *w)).collect(); + for (index, view) in floating { run_reporting(app, "window.arrange.consolidateAllWindows", json!({"index": index, "view": view})); } } @@ -142,6 +144,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { _ => {} } } + // A press that moved past a click's reach is a drag, whether or not it reordered the tabs. + if held && ui.input(|i| i.pointer.is_decidedly_dragging()) { + ui.data_mut(|d| d.remove::(pressed)); + } if !held && let Some(w) = ui.data_mut(|d| d.remove_temp::(pressed)) { doc_windows::show_window(app, w); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 1514732bc2..217900f513 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1141,10 +1141,12 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown { }) } -/// A point on the isolation bar's own surface, right of every control on it. +/// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up +/// to the pattern editing buttons at its right. fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 { let back = bar.named("Back"); - egui::pos2(1200.0 - 40.0, back.center().y) + let path = bar.named("Isolation path"); + egui::pos2(path.rect.right() - 8.0, back.center().y) } /// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, @@ -2235,7 +2237,7 @@ fn the_control_bar_keeps_its_label_and_menu_with_every_group_off() { let mut bar = control_shown(app); bar.room(egui::vec2(1400.0, 900.0)).settle(); assert!(bar.shows(&label), "the label stays: {:?}", bar.names()); - for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform", "X:"] { + for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform", BAR_FIELDS[0]] { assert!(!bar.shows(s), "{s} is off"); } open_control_bar_menu(&mut bar); @@ -2326,20 +2328,20 @@ fn the_artboard_tool_s_control_bar_follows_its_two_groups() { let freed = (40..=240).map(|w| w as f32 * 10.0).any(|w| { bar.room(egui::vec2(w, 300.0)); options(&mut bar, true); - let on = bar.settle().shows("X:"); + let on = bar.settle().shows(BAR_FIELDS[0]); options(&mut bar, false); - let off = bar.settle().shows("X:"); + let off = bar.settle().shows(BAR_FIELDS[0]); !on && off }); assert!(freed, "with Artboard Options off the fields find room in a window too narrow for them otherwise"); options(&mut bar, false); bar.room(egui::vec2(2400.0, 300.0)).settle(); assert!(!bar.shows("Name:") && !bar.shows("Move Artwork with Artboard"), "{:?}", bar.names()); - assert!(bar.shows("Artboard") && bar.shows("Transform") && bar.shows("X:"), "{:?}", bar.names()); + assert!(bar.shows("Artboard") && bar.shows("Transform") && bar.shows(BAR_FIELDS[0]), "{:?}", bar.names()); options(&mut bar, true); bar.app().run("window.control.options", json!({"group": "transform", "visible": false})).unwrap(); bar.settle(); - assert!(!bar.shows("Transform") && !bar.shows("X:"), "{:?}", bar.names()); + assert!(!bar.shows("Transform") && !bar.shows(BAR_FIELDS[0]), "{:?}", bar.names()); assert!(bar.shows("Name:") && bar.shows("Move Artwork with Artboard"), "{:?}", bar.names()); } @@ -2423,16 +2425,20 @@ fn the_control_bar_leaves_members_out_in_its_priority_order() { groups(&mut bar, &ahead, true); select(&mut bar, json!([rect])); - let seen = control_bar_widths(&mut bar, &["Horizontal Align Left", "X:", "Y:", "W:", "H:"]); + let [x, y, w, h] = BAR_FIELDS; + let seen = control_bar_widths(&mut bar, &["Horizontal Align Left", x, y, w, h]); assert!(seen.iter().all(|s| s[2..].iter().all(|f| *f == s[1])), "the four fields show or go together"); assert!(seen.iter().any(|s| s[0] && s[1]), "a wide bar shows the fields and the Align buttons"); assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Align buttons without the fields"); } -/// The caption `name` of a field on the bar: the label, not the field it names. -fn caption(bar: &Shown, name: &str) -> Option { +/// The names of the bar's X, Y, W and H fields, in their order. +const BAR_FIELDS: [&str; 4] = ["X position", "Y position", "Width", "Height"]; + +/// The caption of the bar's field named `field`: the link that names it, not the field. +fn caption(bar: &Shown, field: &str) -> Option { let tree = bar.tree(); - bar.fixture.by_role(Role::LABEL).into_iter().find(|t| tree.name_of(t.node) == Some(name) || tree.value_of(t.node) == Some(name)) + bar.fixture.by_role(Role::LINK).into_iter().find(|t| tree.name_of(t.node) == Some(field)) } /// The Control bar's labels that open a panel: a click on the Linked File or Embedded label shows the Links panel @@ -2490,7 +2496,7 @@ fn label_links_open_their_panels() { // The Transform panel's Rotate field is not on the bar itself. let open = |bar: &Shown| bar.find("Rotate").is_some(); let before = state(&bar); - for name in ["X:", "Y:", "W:", "H:"] { + for name in BAR_FIELDS { bar.settle(); assert!(!open(&bar), "{name}: the Transform panel is closed at first"); let at = caption(&bar, name).unwrap_or_else(|| panic!("no {name} caption: {:?}", bar.names())); @@ -2704,8 +2710,8 @@ fn the_control_bar_shows_the_global_edit_options() { assert_eq!(ge, Some(2), "Start Global Edit takes the two rectangles of the same size"); let button = bar.named("Global Edit Options"); assert!(bar.tree().is_disabled_key(button.node), "the options are off while Global Edit is on"); - assert!(!results(&bar), "Global Edit starting closes the open options"); - assert!(!results(bar.settle())); + // The closed popover's body still runs through its exit fade, so the options are looked for once it ends. + assert!(!results(bar.advance(1.0).settle()), "Global Edit starting closes the open options"); bar.app().run("select.globalEdit", json!({})).unwrap(); assert!(!results(bar.settle()), "the options stay closed once Global Edit stops"); } diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 619d1ee8c8..ca2fa7fe3b 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -348,6 +348,8 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { for w in wins { if let Some(v) = view_mut(app, w) { v.fitted = false; + // The area it last showed its art in is the main window's: it fits its window's. + v.rect = egui::Rect::NOTHING; } } } @@ -381,21 +383,24 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin)); let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window }; let out = window.show(ui, |ui, _| { + // A press anywhere on the window, its title bar and tab included, makes its document current. + pressed = pressed_on_layer(ui); crate::chrome::window_tab(app, ui, win); - let rect = ui.available_rect_before_wrap(); - crate::canvas::panes::refit_resized(app, &[(win, rect)]); + let areas = [(win, ui.available_rect_before_wrap())]; + let unfitted = crate::canvas::panes::refit_resized(app, &areas); if live { show_document(app, ui, win, BodyKind::Live); } else { - pressed = crate::canvas::pane(app, ui, win, rect); + pressed |= crate::canvas::pane(app, ui, win, areas[0].1); } + crate::canvas::panes::note_fits(app, &areas, &unfitted); }); if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) { x.focused = out.focused; } if out.close_requested.is_some() { close = Some(win); - } else if (out.focus_gained || pressed) && !is_current { + } else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() { activate = Some(win); } } @@ -413,5 +418,11 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } +/// Whether the primary button went down over `ui`'s layer in this pass. +fn pressed_on_layer(ui: &egui::Ui) -> bool { + let at = ui.ctx().input(|i| i.pointer.primary_pressed().then_some(i.pointer.interact_pos()).flatten()); + at.is_some_and(|at| ui.ctx().layer_id_at(at) == Some(ui.layer_id())) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 887cb15def..28bab1d05a 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -23,19 +23,54 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec s => out.push(s), } } + let out = run_frame(app, ctx, events); + let mut shapes = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); + shapes +} + +/// One headless frame of the canvas panel's body and the floating document windows on a 1200 × +/// 800 window. The windows' access nodes, by name, are kept for [`window_of`]. +fn run_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), max_texture_side: Some(8192), events, ..Default::default() }; + ctx.enable_accesskit(); let out = crate::testing::part_frame(app, ctx, raw, |app, ui| { app.canvas_area(ui); show(app, ui); }); - let mut shapes = vec![]; - out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); - shapes + let nodes = out.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]); + let named: Vec = nodes + .iter() + .filter(|(_, n)| matches!(n.role(), egui::accesskit::Role::Group | egui::accesskit::Role::TabList)) + .filter_map(|(_, n)| { + let b = n.bounds()?; + Some((n.role(), n.label()?.to_owned(), egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))) + }) + .collect(); + ctx.data_mut(|d| d.insert_temp(egui::Id::new(NAMED), std::sync::Arc::new(named))); + out +} + +/// A group or tab list of the last frame's accessibility tree: its role, name and bounds. +type Named = (egui::accesskit::Role, String, egui::Rect); + +/// Where [`run_frame`] keeps the last frame's [`Named`] nodes. +const NAMED: &str = "doc-window-tests-named"; + +/// The last frame's [`Named`] nodes of `role` whose name `matches`. +fn named(ctx: &egui::Context, role: egui::accesskit::Role, matches: impl Fn(&str) -> bool) -> Option { + let nodes: std::sync::Arc> = ctx.data(|d| d.get_temp(egui::Id::new(NAMED))).unwrap_or_default(); + nodes.iter().find(|(r, name, _)| *r == role && matches(name)).map(|(_, _, rect)| *rect) +} + +/// The main window's document tab strip, as the last frame drew it. +fn strip(ctx: &egui::Context) -> egui::Rect { + named(ctx, egui::accesskit::Role::TabList, |name| name == "Documents").expect("the tab strip was drawn") } fn button(pos: Pos2, pressed: bool) -> egui::Event { @@ -61,11 +96,15 @@ fn canvas_rect(app: &VectorcraftApp) -> egui::Rect { app.view().unwrap().rect } -/// The whole of document `i`'s window, title bar included. -fn window_of(app: &VectorcraftApp, _ctx: &egui::Context, i: usize) -> egui::Rect { - let uid = app.session.documents()[i].uid; - // PLAN: the window's bounds come from its access node (canvas-w27's kit driver); the placed rect stands in until then. - app.ui.floating.iter().find(|w| w.uid == uid).unwrap().place +/// The whole of document `i`'s window, title bar included, as the last frame drew it: the bounds +/// of its access node, named by its title. +fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect { + let title = app.session.documents()[i].title(); + // The name is the title, a `*` while it has unsaved changes, then the zoom and color mode. + let window = |name: &str| { + name.strip_prefix(title.as_str()).map(|rest| rest.trim_start_matches('*')).is_some_and(|rest| rest.is_empty() || rest.starts_with(' ')) + }; + named(ctx, egui::accesskit::Role::Group, window).unwrap_or_else(|| panic!("document {i}'s window, {title}, was drawn")) } /// Where the last frame drew the tab of the window `window` at the top of its body (the title text @@ -488,8 +527,8 @@ fn dragging_a_tab_off_the_strip_floats_its_document_at_the_pointer() { let tab = tab_at(&shapes, &title); // A short drag, and a drag along the strip short of the next tab's middle, leave the tabs as // they are. - // The strip is 35 points tall: a drag that stays within its height is no tear-off. - drag(&mut app, &ctx, tab, tab + vec2(0.0, 35.0 - tab.y)); + // A drag that stays within the strip's height is no tear-off. + drag(&mut app, &ctx, tab, pos2(tab.x, strip(&ctx).bottom())); drag(&mut app, &ctx, tab, tab + vec2(40.0, 0.0)); assert!(app.ui.floating.is_empty(), "the document stays under its tab"); assert_eq!(app.session.active_index(), Some(2), "a drag is not a click"); @@ -530,7 +569,7 @@ fn a_window_dragged_by_its_tab_onto_the_strip_goes_back_under_the_tabs() { assert!(tab_drawn(&shapes, &app.session.documents()[2].title()), "it has its tab again"); assert!(app.views[2].fitted, "it fits the canvas under the tabs"); let canvas = canvas_rect(&app); - assert!(canvas.top() >= 35.0 && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); + assert!(canvas.top() >= strip(&ctx).bottom() && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); // Torn off again, it opens where its tab is dropped, not where its last window was. let to = pos2(200.0, 300.0); let tab = tab_at(&shapes, &app.session.documents()[2].title()); @@ -694,8 +733,9 @@ fn an_os_windows_tab_docks_on_the_strip() { }; // The tab at the top of the window. let tab = pos2(20.0, 15.0); - // Released over the main window's tab strip (y 0 to 35 on the screen), it docks. - os_drag(&mut app, tab, pos2(20.0, -280.0)); + // Released over the main window's tab strip, it docks. + let over_strip = strip(&ctx).center().y - 300.0; + os_drag(&mut app, tab, pos2(20.0, over_strip)); assert!(app.ui.floating.is_empty(), "the document is back under the tabs"); assert_eq!(docked(&app), [0, 1]); assert_eq!(app.session.active_index(), Some(1)); @@ -861,17 +901,7 @@ fn switching_views_targets_the_artboard_the_view_shows() { /// ([`crate::canvas::release_over_panel`]), then the tabs and the canvas or panes, then the floating /// document windows. → the cursor. fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::CursorIcon { - let raw = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), - max_texture_side: Some(8192), - events, - ..Default::default() - }; - let out = crate::testing::part_frame(app, ctx, raw, |app, ui| { - app.canvas_area(ui); - show(app, ui); - }); - out.platform_output.cursor_icon + run_frame(app, ctx, events).platform_output.cursor_icon } /// Two 400 × 300 pt documents on `ctx`: the first, current under its tab, holds a 50 pt square at diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 5e9a153fcf..acf0092547 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -71,6 +71,11 @@ fn inside(nodes: &Nodes, name: &str, within: Rect) -> Rect { named(nodes, name).into_iter().find(|r| within.contains(r.center())).unwrap_or_else(|| panic!("no `{name}` inside {within:?}")) } +/// The open drawer: the Edit Toolbar node that holds its cells, larger than the ••• buttons of that name. +fn drawer(nodes: &Nodes) -> Rect { + named(nodes, EDIT).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the drawer is open") +} + /// The toolbar button of `tool`: the rail names a tool by its label (its shortcut is in its tip). fn button_name(tool: &str) -> String { tl!(tool_info(tool).unwrap().label).to_string() @@ -283,18 +288,18 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() { // Dragged onto the blank toolbar, a tool is added to it. let nodes = settle(&mut app, &ctx, 2.0); let bar = one(&nodes, "Mine"); - drag(&mut app, &ctx, 3.0, one(&nodes, "Ellipse Tool").center(), bar.center()); + drag(&mut app, &ctx, 3.0, inside(&nodes, "Ellipse Tool", drawer(&nodes)).center(), bar.center()); assert_eq!(held(&app, "Mine"), [["ellipse"]]); assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched"); // Onto the lower third of its tool: a slot of its own after it. let nodes = settle(&mut app, &ctx, 4.0); let tool = inside(&nodes, &button_name("ellipse"), one(&nodes, "Mine")); - drag(&mut app, &ctx, 5.0, one(&nodes, "Artboard Tool").center(), pos2(tool.center().x, tool.top() + 0.85 * tool.height())); + drag(&mut app, &ctx, 5.0, inside(&nodes, "Artboard Tool", drawer(&nodes)).center(), pos2(tool.center().x, tool.top() + 0.85 * tool.height())); assert_eq!(held(&app, "Mine"), [["ellipse"], ["artboard"]]); // Onto the middle of the first tool: into its group. let nodes = settle(&mut app, &ctx, 6.0); let tool = inside(&nodes, &button_name("ellipse"), one(&nodes, "Mine")); - drag(&mut app, &ctx, 7.0, one(&nodes, "Slice Tool").center(), tool.center()); + drag(&mut app, &ctx, 7.0, inside(&nodes, "Slice Tool", drawer(&nodes)).center(), tool.center()); assert_eq!(held(&app, "Mine"), [vec!["ellipse", "slice"], vec!["artboard"]]); // A click on a tool picks it; the drawer stays open. let nodes = settle(&mut app, &ctx, 8.0); @@ -304,7 +309,7 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() { assert!(app.ui.tools_drawer); // Dragged from the toolbar into the drawer, a tool leaves it. let artboard = inside(&nodes, &button_name("artboard"), one(&nodes, "Mine")); - drag(&mut app, &ctx, 10.0, artboard.center(), one(&nodes, "Ellipse Tool").center()); + drag(&mut app, &ctx, 10.0, artboard.center(), inside(&nodes, "Ellipse Tool", drawer(&nodes)).center()); assert_eq!(held(&app, "Mine"), [["ellipse", "slice"]]); assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched"); // The Tools panel's ••• button takes the drawer back beside its toolbar. @@ -324,10 +329,10 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { let ctx = ctx(); let shipped = slots(&app); app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); - // The menu's items called `name`, top first (the toolbar's own buttons aside). + // The menu's items called `name`, top first: inside the menu, the Add Tool… node larger than the + button. let items = |nodes: &Nodes, name: &str| -> Vec { - let bar = one(nodes, "Mine"); - named(nodes, name).into_iter().filter(|r| !bar.contains(r.center())).collect() + let menu = named(nodes, ADD).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the menu is open"); + named(nodes, name).into_iter().filter(|r| menu.contains(r.center())).collect() }; // The menu at `time`, opened with a click on the + button unless it is open. let open = |app: &mut VectorcraftApp, time: f64| -> Nodes { @@ -373,6 +378,9 @@ fn the_drawer_moves_between_new_toolbars() { for name in ["A", "B"] { app.run("window.toolbar.new", json!({"name": name})).unwrap(); } + // B away from A, which the cascade puts it over. + let b = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&app.ui, "B").unwrap().id); + crate::panel_docking::place_floating(&mut app, &b, pos2(600.0, 900.0), 0.0).unwrap(); for (k, name) in ["B", "A", "B"].into_iter().enumerate() { let nodes = settle(&mut app, &ctx, 1.0 + 2.0 * k as f64); let edit = inside(&nodes, EDIT, one(&nodes, name)); diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 8388969c29..3dd38efe78 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -1025,6 +1025,19 @@ mod tests { // PLAN: files-w11 owns Missing Fonts' hosted type; its test asserts the search there } + /// `f`'s answer, read while the font menu held still: tests running alongside add fonts to + /// the shared database and lend it composite fonts. + fn while_fonts_hold(mut f: impl FnMut() -> T) -> T { + let db = vectorcraft_text::FontDb::global(); + loop { + let before = db.menu_family_list(); + let out = f(); + if before == db.menu_family_list() { + return out; + } + } + } + /// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font. fn two_font_document() -> VectorcraftApp { let mut app = new_app(); @@ -1160,12 +1173,11 @@ mod tests { assert!(recent.iter().all(|r| r.family == "Inter"), "{recent:?}"); assert_eq!(recent.len(), db.styles("Inter").len(), "each style once, the closest not repeated"); assert!(recent.iter().all(|r| !r.style.is_empty()), "every row names its style: {recent:?}"); - let system = replacement_rows(&app, "system", &used); + let (system, menu) = while_fonts_hold(|| (replacement_rows(&app, "system", &used), db.menu_family_list())); assert!(system.iter().any(|r| r.family == "Source Sans 3" && r.style == "Regular"), "{system:?}"); assert!(!system.iter().any(|r| r.family.starts_with('.')), "the font menu's hidden families stay out"); // A composite font is a family without styles of its own, listed by its name alone. assert!(system.iter().all(|r| !r.style.is_empty() || db.styles(&r.family).is_empty()), "no nameless rows: {system:?}"); - let menu = db.menu_family_list(); let listed: std::collections::BTreeSet<&str> = system.iter().map(|r| r.family.as_str()).collect(); assert_eq!(listed.len(), menu.len(), "every family the font menu shows is listed"); let mut unique = system.clone(); @@ -1173,8 +1185,11 @@ mod tests { assert_eq!(unique.len(), system.len(), "no family and style is listed twice"); // The dialog stores the rows when it opens and when the source changes, and a picked row // sets both fields Change then uses. - open(&mut app); - assert_eq!(opened(&app).rows.len(), system.len()); + let (rows, system) = while_fonts_hold(|| { + open(&mut app); + (opened(&app).rows, replacement_rows(&app, "system", &used)) + }); + assert_eq!(rows.len(), system.len()); let mut d = opened(&app); set_source(&app, &mut d, "document", &used); assert_eq!(d.rows.len(), document.len()); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 3e06c81731..d200bc85d4 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -152,9 +152,13 @@ fn help_f1_opens_discover_without_a_document() { /// shows, marks nothing and the status bar says why. #[test] fn discover_says_why_a_tool_cannot_be_marked() { - fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + fn pass(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::discover::show(app, ui)); out.textures_delta.clear(); + out + } + fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let out = pass(ctx, app, events); fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { match s { egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), @@ -172,11 +176,23 @@ fn discover_says_why_a_tool_cannot_be_marked() { texts(ctx, app, vec![]); let drawn = texts(ctx, app, vec![]); let pos = drawn.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("`{label}` not drawn: {drawn:?}")).1.center(); + press_at(ctx, app, pos); + } + fn press_at(ctx: &egui::Context, app: &mut VectorcraftApp, pos: egui::Pos2) { let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; for e in [egui::Event::PointerMoved(pos), button(true), button(false)] { - texts(ctx, app, vec![e]); + pass(ctx, app, vec![e]); } } + // A step's tool name is a link inside its sentence: the Link node named by its words. + fn click_link(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str) { + ctx.enable_accesskit(); + pass(ctx, app, vec![]); + let nodes = pass(ctx, app, vec![]).platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let link = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Link && n.label().is_some_and(|l| l == name)); + let b = link.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no link `{name}`")); + press_at(ctx, app, egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)); + } crate::i18n::set_current(crate::i18n::Lang::EN); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); let ctx = crate::testing::ui_context(); @@ -195,16 +211,16 @@ fn discover_says_why_a_tool_cannot_be_marked() { assert!(app.ui.learn_locate.is_none()); assert_eq!(app.ui.status, reason); - let (tutorial, tool) = crate::panels::learn::catalog::SKILLS + let (tutorial, link) = crate::panels::learn::catalog::SKILLS .iter() .flat_map(|skill| skill.tutorials.iter()) - .find_map(|t| t.steps.iter().find_map(|s| s.tool).map(|tool| (t, tool))) + .find_map(|t| t.steps.iter().find_map(|s| s.tool_name()).map(|(_, name, _)| (t, name))) .unwrap(); let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); app.run("help.discover.choose", json!({"index": index})).unwrap(); app.status(""); - click(&ctx, &mut app, vectorcraft_tools::tool_info(tool).unwrap().label); + click_link(&ctx, &mut app, link); assert!(app.ui.learn_locate.is_none()); assert_eq!(app.ui.status, reason); } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 397f084fe1..5c54be48bf 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1382,8 +1382,10 @@ mod tests { assert_eq!(window.app.ui.recent_commands, recorded); // Cancel closes the dialog without running the command. close_dialogs(&mut window.app, false); - assert!(!window.app.any_dialog_open()); + assert!(crate::tests::picks::open_dialogs(&window.app).is_empty()); + // The window's next pass draws it gone: until then its layer, last drawn, is still up. window.frame(vec![]); + assert!(!window.app.any_dialog_open()); assert_eq!(window.app.ui.recent_commands, recorded); assert_eq!(window.app.ui.command_uses.count_of(&clean_up.key_text()), 1, "counted once, at the pick"); } @@ -1587,8 +1589,10 @@ mod tests { // selected tool), the status line aside. let look = |app: &VectorcraftApp| { let mut ui = serde_json::to_value(&app.ui).unwrap_or_default(); + // The pick's count is the palette's record of the pick ([`record_pick`]), not the command's doing. if let Some(o) = ui.as_object_mut() { o.remove("status"); + o.remove("command_uses"); } let doc = app.session.active().map(|st| { (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) @@ -2024,9 +2028,20 @@ mod tests { window.app.ui.recent_commands = vec![CommandRef::new("object.ungroup"), CommandRef::new("select.all")]; window.app.ui.palette_open = true; window.frame(vec![]); - assert!(!window.resolved("object.ungroup").enabled); - let all = window.resolved("select.all"); - assert!(all.enabled && hint_of(&all).is_none()); + // The rows are judged from the window under the palette, where a pick runs; a command read from + // inside the open palette is under its modal layer. + let nodes = window.frame(vec![]); + let names = names(Lang::EN); + let row = |id: &str| { + // A row shows the result's label; its name's menu path is the row's path. + let name = + names.iter().find(|(at, _)| at == id).and_then(|(_, name)| name.rsplit(" › ").next()).unwrap_or_else(|| panic!("{id} has a name")); + let option = + |n: &&egui::accesskit::Node| n.role() == egui::accesskit::Role::ListBoxOption && n.label().is_some_and(|l| l.starts_with(name)); + nodes.iter().find(option).unwrap_or_else(|| panic!("a row for {name}")) + }; + assert!(row("object.ungroup").is_disabled()); + assert!(!row("select.all").is_disabled()); } /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system @@ -2034,6 +2049,8 @@ mod tests { #[test] fn paste_is_dimmed_only_while_nothing_can_be_pasted() { let mut window = Window::on(Fixture::Multi.session()); + // A still clock: the tick's next look at the (empty) system clipboard would undo the flag. + window.app.now_override = Some(window.app.system_paste_at.max(0.0)); window.app.system_paste = false; window.frame(vec![]); let hint = hint_of(&window.resolved("edit.paste")).expect("Paste is dimmed"); diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index bdf8309acb..66094006a7 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -459,6 +459,26 @@ pub(crate) fn hide_group(app: &mut VectorcraftApp, panel: &str) -> Result