diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index ca838c03b9..77eca1e6a9 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -3,13 +3,25 @@ //! artboard). With the Artboard tool chosen, the buttons align and distribute the artboards the //! tool has selected. +use craft::behavior::IconId; +use craft_keymap::CommandRef; +use craft_ui::bars::{BarItem, BarItems}; +use craft_ui::buttons::{IconButton, PopupMark, ToggleButton}; +use craft_ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft_ui::menu::{Menu, MenuItem, PanelRow}; +use craft_ui::runtime::commands::{CommandState, CommandStates}; +use craft_ui::sections::{HeaderStrength, Section}; +use craft_ui::text::NumberField; use egui::Ui; use serde::Serialize; use serde_json::{Value, json}; -use super::{pstate, selection_len, set_pstate}; +// PLAN: assumed `part_hidden(app, key)` and `set_part_hidden(app, key, on)` (op.A5, hub-w2) live in `panels.rs`. +use super::{part_hidden, selection_len, set_part_hidden}; use crate::VectorcraftApp; -use crate::widgets::{self, menu_item}; + +/// The `hidden_parts` key of the Align panel's Hide Options state; `panel_docking/sizes.rs` reads it too. +const HIDE_OPTIONS: &str = "align-hide-options"; /// What Align aligns to. The Align To choice kept with the UI state ([`crate::UiState::align_to`]) /// is Selection or Artboard: Align to Key Object stores no choice. @@ -240,40 +252,83 @@ fn spacing_min(app: &VectorcraftApp) -> f64 { if on_artboards(app) { f64::NEG_INFINITY } else { 0.0 } } -/// The six align buttons of the Control bar and the Properties panel, `size` points square. -/// They align to what the Align panel's Align To says (the key object while there is one), as -/// its own buttons do (#789), and the selected artboards with the Artboard tool chosen. -pub fn align_buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) { - for (i, (icon, tip, axis, v)) in [ - ("align-start-vertical", "Horizontal Align Left", "horizontal", "left"), - ("align-center-vertical", "Horizontal Align Center", "horizontal", "center"), - ("align-end-vertical", "Horizontal Align Right", "horizontal", "right"), - ("align-start-horizontal", "Vertical Align Top", "vertical", "top"), - ("align-center-horizontal", "Vertical Align Center", "vertical", "center"), - ("align-end-horizontal", "Vertical Align Bottom", "vertical", "bottom"), - ] - .into_iter() - .enumerate() - { - if i == 3 && widgets::icon_button(ui, "dc-al-center", tl!("Horizontal & Vertical Align Center"), false, size).clicked() { - run_button(app, Button::AlignCenters).ok(); - } - if widgets::icon_button(ui, icon, tl!(tip), false, size).clicked() { - run_button(app, Button::Align(axis, v)).ok(); - } +/// The command id of button `b`: [`COMMANDS`] is the one table of them. +fn command_id(b: Button) -> Option<&'static str> { + COMMANDS.iter().find(|c| c.1 == b).map(|c| c.0) +} + +/// The Align Objects buttons in the panel's order, the Horizontal & Vertical Align Center button +/// after the third: (icon, button). +fn align_icons() -> impl Iterator { + ALIGN.iter().enumerate().flat_map(|(i, (icon, _, axis, v))| { + let centers = (i == 3).then_some(("dc-al-center", Button::AlignCenters)); + centers.into_iter().chain([(*icon, Button::Align(*axis, *v))]) + }) +} + +/// The Distribute Objects buttons in the panel's order: (icon, button). +fn distribute_icons() -> impl Iterator { + DISTRIBUTE.iter().map(|(icon, _, axis, v)| (*icon, Button::Distribute(*axis, *v))) +} + +/// An icon button that runs the command of `b`; its label, state and click come from the command. +fn command_button(ui: &mut Ui, icon: &'static str, b: Button) { + if let Some(id) = command_id(b) { + IconButton::command(IconId::new(icon), CommandRef::new(id)).show(ui); } } -/// The six Distribute Objects buttons of the Control bar, `size` points square. They distribute -/// what the Align panel's buttons do, to what its Align To says. -pub(crate) fn distribute_buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) { - for (icon, tip, axis, v) in DISTRIBUTE { - if widgets::icon_button(ui, icon, tl!(tip), false, size).clicked() { - run_button(app, Button::Distribute(axis, v)).ok(); +/// A strip of the commands of `buttons`. +fn bar_items(buttons: impl Iterator) -> BarItems { + BarItems::new(buttons.filter_map(command_id).map(|id| BarItem::new(CommandRef::new(id))).collect()) +} + +/// The seven align buttons of the Control bar and the Properties panel. They align to what the +/// Align panel's Align To says (the key object while there is one), as its own buttons do (#789), +/// and the selected artboards with the Artboard tool chosen. +pub(crate) fn align_buttons(_app: &mut VectorcraftApp, ui: &mut Ui) { + ui.horizontal(|ui| { + for (icon, b) in align_icons() { + command_button(ui, icon, b); } + }); +} + +/// Whether the Align or Distribute button `b` can run now: the one rule of the panel, the Control +/// bar and Properties (`menus/state.rs` asks it for the command of each button). With the +/// Artboard tool chosen the buttons act on the artboards it has selected. +pub(crate) fn button_enabled(app: &VectorcraftApp, b: &Button) -> bool { + let boards = on_artboards(app).then(|| artboards_selected(app)); + let n = selection_len(app) + selected_guides(app); + match b { + Button::Align(..) | Button::AlignCenters => boards.map_or(n >= 1, |b| b >= 1), + // Two or more objects and ruler guides (#1597), or anchor points, which may all be on one + // path; or the artboards [`artboards_distribute`] asks for. + Button::Distribute(..) | Button::Spacing(_) => boards.map_or(n >= 2 || has_anchors(app), |_| artboards_distribute(app)), } } +/// The Control bar's Align content: the align buttons, the Align To menu button showing the choice +/// of [`shown_align_to`], and the Distribute buttons while they can act (the artboards the Artboard +/// tool has selected, else two or more objects). The bar's row decides what leaves when it is +/// narrow. +pub(crate) fn control_bar_strip(app: &mut VectorcraftApp, ui: &mut Ui) { + let (icon, name) = align_to_icon_name(shown_align_to(app), key_is_anchor(app)); + let distributes = if on_artboards(app) { artboards_distribute(app) } else { objects_aligned(app) > 1 }; + ui.horizontal(|ui| { + bar_items(align_icons().map(|(_, b)| b)).show(ui); + let button = IconButton::new(IconId::new(icon)).label(name).tooltip(name).popup(PopupKind::Menu).popup_mark(PopupMark::Menu).show(ui); + Menu::new(tl!("Align To")).opened_by(&button.response, Trigger::Press).show(ui, |ui, _| { + for (id, _) in ALIGN_TO_COMMANDS { + MenuItem::command(CommandRef::new(id)).show(ui); + } + }); + if distributes { + bar_items(distribute_icons().map(|(_, b)| b)).show(ui); + } + }); +} + /// Whether the selection has a key object or a key guide. fn has_key(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| st.selection.has_key()) @@ -417,165 +472,112 @@ pub(crate) fn run_align_to(app: &mut VectorcraftApp, v: AlignTo) -> Result f32 { - size + ALIGN_TO_ARROW -} - -/// The width of the arrow of the Control bar's Align To menu. -const ALIGN_TO_ARROW: f32 = 14.0; - -/// The Control bar's Align To menu, next to its Align buttons: the icon of the choice that the -/// Align panel's Align To shows ([`shown_align_to`]) and an arrow, `size` points tall. Its menu -/// lists Align to Selection, Align to Key Object and Align to Artboard with that choice checked, -/// and a pick chooses it as the Align panel does ([`choose_align_to`]). Align to Key Object is off -/// while no key object can be made. Screen readers get a combo box named "Align To:" whose value -/// is the choice. -pub(crate) fn align_to_menu(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) { - let t = crate::theme::Tokens::get(ui.ctx()); - let shown = shown_align_to(app); - let anchor = key_is_anchor(app); - let (icon, name) = align_to_icon_name(shown, anchor); - let (rect, resp) = ui.allocate_exact_size(egui::vec2(align_to_menu_width(size), size), egui::Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(rect, egui::CornerRadius::same(5), t.hover); - } - let square = egui::Rect::from_min_size(rect.min, egui::vec2(size, size)); - crate::icons::paint(ui, icon, square.shrink((size * 0.2).round()), t.icon); - let arrow = egui::Rect::from_center_size(egui::pos2(square.right() + ALIGN_TO_ARROW / 2.0, rect.center().y), egui::vec2(10.0, 10.0)); - crate::icons::paint(ui, "chevron-down", arrow, t.text_dim); - resp.widget_info(|| egui::WidgetInfo { - current_text_value: Some(name.to_owned()), - ..egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), tl!("Align To:")) - }); - let resp = resp.on_hover_text(name); - let picked = egui::Popup::menu(&resp).show(|ui| { - let mut picked = None; - for v in ALIGN_TO { - if menu_item(ui, align_to_icon_name(v, anchor).1, can_choose(app, v), shown == v) { - picked = Some(v); - } - } - picked - }); - if let Some(v) = picked.and_then(|r| r.inner) { - choose_align_to(app, v); - } -} - +/// The Align panel: Align Objects, Distribute Objects and, unless Hide Options is on, Distribute +/// Spacing with its value and Align To. The buttons are commands, so their state and clicks come +/// from the command layer ([`button_enabled`], [`run_button`]). pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let n = selection_len(app); - let guides = selected_guides(app); - // With the Artboard tool chosen, the buttons act on the artboards it has selected. - let boards = on_artboards(app).then(|| artboards_selected(app)); - let can_align = boards.map_or(n + guides >= 1, |b| b >= 1); - // `spacing` is the Distribute Spacing value. The Distribute Objects and Distribute Spacing - // buttons send it while there is a key object or a key guide (#2143), or for artboards while - // Align to Artboard is chosen. - let spacing = app.ui.align_spacing; - let key = spacing_sent(app).is_some(); - // Two or more objects and ruler guides (#1597), or anchor points, which may all be on one - // path; or the artboards [`artboards_distribute`] asks for. - let distributes = boards.map_or(n + selected_guides(app) >= 2 || has_anchors(app), |_| artboards_distribute(app)); - let (unit, min_spacing) = (app.session.general_unit(), spacing_min(app)); - widgets::subheader(ui, tl!("Align Objects:")); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 5.0; - for (i, (icon, tip, axis, v)) in ALIGN.iter().enumerate() { - if i == 3 { - ui.add_space(6.0); - if widgets::icon_button_enabled(ui, "dc-al-center", tl!("Horizontal & Vertical Align Center"), false, can_align, 32.0).clicked() { - run_button(app, Button::AlignCenters).ok(); - } - ui.add_space(6.0); + Section::fixed(tl!("Align Objects:")).strength(HeaderStrength::Caption).show(ui, |ui, _| { + ui.horizontal(|ui| { + for (icon, b) in align_icons() { + command_button(ui, icon, b); } - if widgets::icon_button_enabled(ui, icon, tl!(tip), false, can_align, 32.0).clicked() { - run_button(app, Button::Align(axis, v)).ok(); - } - } + }); }); - widgets::divider(ui); - widgets::subheader(ui, tl!("Distribute Objects:")); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 5.0; - for (i, (icon, tip, axis, v)) in DISTRIBUTE.iter().enumerate() { - if i == 3 { - ui.add_space(6.0); + Section::fixed(tl!("Distribute Objects:")).strength(HeaderStrength::Caption).show(ui, |ui, _| { + ui.horizontal(|ui| { + for (icon, b) in distribute_icons() { + command_button(ui, icon, b); } - if widgets::icon_button_enabled(ui, icon, tl!(tip), false, distributes, 32.0).clicked() { - run_button(app, Button::Distribute(axis, v)).ok(); - } - } + }); }); - if pstate::(ui.ctx(), "align-hide-options") { + if part_hidden(app, HIDE_OPTIONS) { return; } - widgets::divider(ui); - ui.horizontal(|ui| { - ui.vertical(|ui| { - widgets::subheader(ui, tl!("Distribute Spacing:")); - ui.horizontal(|ui| { - let on = distributes; - if widgets::icon_button_enabled(ui, "dc-dist-vspace", tl!("Vertical Distribute Space"), false, on, 28.0).clicked() { - run_button(app, Button::Spacing("vertical")).ok(); - } - if widgets::icon_button_enabled(ui, "dc-dist-hspace", tl!("Horizontal Distribute Space"), false, on, 28.0).clicked() { - run_button(app, Button::Spacing("horizontal")).ok(); - } - ui.add_enabled_ui(key, |ui| { - if let Some(v) = widgets::spin_field(ui, "align-spacing", Some(spacing), unit, 70.0, 1.0, min_spacing, &[]) { - app.ui.align_spacing = v; - } - }); - }); + // The Distribute Spacing value is sent while there is a key object or a key guide (#2143), or + // for artboards while Align to Artboard is chosen. + let spacing = app.ui.align_spacing; + let sent = spacing_sent(app).is_some(); + // PLAN: assumed `crate::canvas::general_lengths(app) -> LengthUnits` (cv.B5b, canvas-w15). + let lengths = crate::canvas::general_lengths(app); + let min_spacing = spacing_min(app); + let mut edited = None; + Section::fixed(tl!("Distribute Spacing:")).strength(HeaderStrength::Caption).show(ui, |ui, _| { + ui.horizontal(|ui| { + command_button(ui, "dc-dist-vspace", Button::Spacing("vertical")); + command_button(ui, "dc-dist-hspace", Button::Spacing("horizontal")); + // The value is UI state, not a document edit: a landed value is assigned. + let field = NumberField::length(tl!("Distribute Spacing"), Bind::given(Some(spacing)), lengths) + .step(1.0) + .range(min_spacing..=f64::INFINITY) + .enabled(sent); + edited = field.show(ui).edit.events.landed().cloned().flatten(); }); - ui.separator(); - ui.vertical(|ui| { - widgets::subheader(ui, tl!("Align To:")); - // With one object selected the buttons align it to the artboard, and Align To shows Artboard. - let shown = shown_align_to(app); - let anchor = key_is_anchor(app); - ui.horizontal(|ui| { - for v in ALIGN_TO { - let (icon, tip) = align_to_icon_name(v, anchor); - if widgets::icon_button_enabled(ui, icon, tip, shown == v, can_choose(app, v), 28.0).clicked() { - choose_align_to(app, v); - } - } - }); + }); + if let Some(v) = edited { + app.ui.align_spacing = v; + } + Section::fixed(tl!("Align To:")).strength(HeaderStrength::Caption).show(ui, |ui, _| { + // With one object selected the buttons align it to the artboard, and Align To shows Artboard. + let anchor = key_is_anchor(app); + ui.horizontal(|ui| { + for (id, v) in ALIGN_TO_COMMANDS { + let (icon, _) = align_to_icon_name(v, anchor); + ToggleButton::command(CommandRef::new(id)).icon(IconId::new(icon)).icon_only().show(ui); + } }); }); } -pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let hidden: bool = pstate(ui.ctx(), "align-hide-options"); - if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) { - set_pstate(ui.ctx(), "align-hide-options", !hidden); - } - let pb = app.session.prefs.use_preview_bounds; - if menu_item(ui, tl!("Use Preview Bounds"), true, pb) { - super::transform::set_pref(app, "usePreviewBounds", !pb); - } - // Cancel Key Object clears the key, and Align To shows its stored choice again. - if menu_item(ui, tl!("Cancel Key Object"), align_to(app) == AlignTo::Key, false) { - app.run("select.key", json!({})).ok(); - } - // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Align to Glyph Bounds")), |ui| glyph_bounds_items(app, ui)); +/// The rows of the Align panel's menu. +pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { + vec![ + PanelRow::Command(CommandRef::new("ui.align.hideOptions")), + PanelRow::Command(CommandRef::new("ui.align.usePreviewBounds")), + // Cancel Key Object clears the key, and Align To shows its stored choice again. + PanelRow::Command(CommandRef::new("ui.align.cancelKeyObject")), + PanelRow::Submenu( + tl!("Align to Glyph Bounds").into(), + vec![PanelRow::Command(CommandRef::new("ui.align.glyphBoundsPoint")), PanelRow::Command(CommandRef::new("ui.align.glyphBoundsArea"))], + ), + ] } -/// The Align to Glyph Bounds submenu: Point Text and Area Text, each checked while Align and -/// Distribute measure that kind of type by the ink of its glyphs. -fn glyph_bounds_items(app: &mut VectorcraftApp, ui: &mut Ui) { - for (label, key, on) in [ - (tl!("Point Text"), "alignGlyphBoundsPoint", app.session.prefs.align_glyph_bounds_point), - (tl!("Area Text"), "alignGlyphBoundsArea", app.session.prefs.align_glyph_bounds_area), - ] { - if menu_item(ui, label, true, on) { - super::transform::set_pref(app, key, !on); - } +/// The state of the panel menu's rows: Hide Options reads Show Options while the options are +/// hidden, Use Preview Bounds and the two glyph-bounds rows are checked while their preference is +/// on, and Cancel Key Object is on while there is a key. +pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { + let hidden = part_hidden(app, HIDE_OPTIONS); + let prefs = &app.session.prefs; + states.set(CommandRef::new("ui.align.hideOptions"), CommandState::new().title(if hidden { tl!("Show Options") } else { tl!("Hide Options") })); + states.set(CommandRef::new("ui.align.usePreviewBounds"), CommandState::new().checked(prefs.use_preview_bounds)); + states.set(CommandRef::new("ui.align.cancelKeyObject"), CommandState::new().enabled(align_to(app) == AlignTo::Key)); + states.set(CommandRef::new("ui.align.glyphBoundsPoint"), CommandState::new().checked(prefs.align_glyph_bounds_point)); + states.set(CommandRef::new("ui.align.glyphBoundsArea"), CommandState::new().checked(prefs.align_glyph_bounds_area)); +} + +/// Runs the Align panel menu command `id`; `None` when `id` is not one of them. The glyph-bounds +/// rows make Align and Distribute measure point or area text by the ink of its glyphs. +pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option> { + let prefs = &app.session.prefs; + let pref = match id { + "ui.align.usePreviewBounds" => Some(("usePreviewBounds", prefs.use_preview_bounds)), + "ui.align.glyphBoundsPoint" => Some(("alignGlyphBoundsPoint", prefs.align_glyph_bounds_point)), + "ui.align.glyphBoundsArea" => Some(("alignGlyphBoundsArea", prefs.align_glyph_bounds_area)), + _ => None, + }; + if let Some((key, on)) = pref { + super::transform::set_pref(app, key, !on); + return Some(Ok(Value::Null)); } + match id { + "ui.align.hideOptions" => { + let hidden = part_hidden(app, HIDE_OPTIONS); + set_part_hidden(app, HIDE_OPTIONS, !hidden); + } + "ui.align.cancelKeyObject" => return Some(app.run("select.key", json!({}))), + _ => return None, + } + Some(Ok(Value::Null)) } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index ffdc0b10a3..341aaa4617 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -1,9 +1,6 @@ -use egui::accesskit::{Role, Toggled}; - -use super::super::tests_appearance::{click, frame_events, text_rect}; use super::*; -use crate::toolbar::tests::widget_rects; -use crate::widgets::accessibility_tests::{role_and_state, tree}; +// PLAN: assumed the shared panel harness (op.A15, object-panels-w8) is `crate::panels::tests_panel::Panel`. +use crate::panels::tests_panel::Panel; #[test] fn single_object_aligns_to_artboard() { @@ -25,14 +22,17 @@ fn align_to_key_object_makes_a_selected_guide_the_key() { app.run("guide.add", json!({"vertical": true, "pos": 120})).unwrap(); app.run("select.set", json!({"ids": [a]})).unwrap(); app.run("guide.select", json!({"indexes": [0], "toggle": true})).unwrap(); - let ctx = egui::Context::default(); - let ([_, key, _], left) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, key.center(), show); - let st = app.session.active().unwrap(); - let key = st.selection.key_guide.map(|k| vectorcraft_engine::cmd::guide_indexes(&st.doc, &[k])); - assert_eq!(key, Some(vec![0]), "{}", app.ui.status); - assert_eq!(align_to(&app), AlignTo::Key); - click(&ctx, &mut app, left.center(), show); + let mut panel = Panel::new(app, show); + panel.click("Align to Key Object"); + { + let app = panel.app(); + let st = app.session.active().unwrap(); + let key = st.selection.key_guide.map(|k| vectorcraft_engine::cmd::guide_indexes(&st.doc, &[k])); + assert_eq!(key, Some(vec![0]), "{}", app.ui.status); + assert_eq!(align_to(&app), AlignTo::Key); + } + panel.click("Horizontal Align Left"); + let app = panel.app(); assert_eq!(left_edge(&app, &a), 120.0, "on the guide, not the artboard: {}", app.ui.status); assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 120.0); } @@ -46,43 +46,21 @@ fn a_lone_object_aligns_to_the_artboard() { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone(); let b = app.run("shape.rectangle", json!({"x": 80, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone(); - let ctx = egui::Context::default(); app.run("select.set", json!({"ids": [a, b]})).unwrap(); app.run("select.key", json!({"id": b})).unwrap(); app.run("select.toggle", json!({"id": a})).unwrap(); let id = vectorcraft_doc::NodeId(b.as_u64().unwrap()); let bounds = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); - // `align_buttons` (the Control bar and the Properties panel): one frame finds the first - // button, and the next clicks Horizontal Align Right, the third. - let at = std::cell::Cell::new(egui::Pos2::ZERO); - let frame = |app: &mut VectorcraftApp, events: Vec| { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { - ui.horizontal(|ui| { - at.set(ui.cursor().min); - align_buttons(app, ui, 24.0); - }); - }); - out.textures_delta.clear(); - }; - frame(&mut app, vec![]); - let right = at.get() + egui::vec2(2.0 * (24.0 + ctx.global_style().spacing.item_spacing.x) + 12.0, 12.0); - let press = |pressed| egui::Event::PointerButton { pos: right, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, vec![egui::Event::PointerMoved(right), press(true)]); - frame(&mut app, vec![press(false)]); - assert_eq!(bounds(&app).x1, 200.0, "the artboard's right edge"); + // `align_buttons` (the Control bar and the Properties panel). + let mut buttons = Panel::new(app, align_buttons); + buttons.click("Horizontal Align Right"); + assert_eq!(bounds(&buttons.app()).x1, 200.0, "the artboard's right edge"); // The Align panel's Horizontal Align Left. - let p = with_align_to(&app, json!({"horizontal": "left", "bounds": "geometric"})); - app.run("object.align", p).unwrap(); - assert_eq!(bounds(&app).x0, 0.0, "the artboard's left edge"); + let p = with_align_to(&buttons.app(), json!({"horizontal": "left", "bounds": "geometric"})); + buttons.app().run("object.align", p).unwrap(); + assert_eq!(bounds(&buttons.app()).x0, 0.0, "the artboard's left edge"); } -#[test] -fn align_both_centers_params() { - let p = align_params(json!({"horizontal": "center", "vertical": "center"}), AlignTo::Selection, 2); - assert_eq!(p["horizontal"], "center"); - assert_eq!(p["vertical"], "center"); - assert_eq!(p["to"], "selection"); -} /// #541: while the selection has a key object Align aligns to it, whatever Align To says; /// choosing Align to Selection lets the key go. @@ -111,18 +89,6 @@ fn back_and_front() -> (VectorcraftApp, Value, Value) { (app, back, front) } -/// One frame of the Align panel → its Align To buttons (Selection, Key Object, Artboard) and -/// its Horizontal Align Left button. -fn panel_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> ([egui::Rect; 3], egui::Rect) { - frame_events(ctx, app, vec![], show); - // The 28-point buttons are Distribute Spacing's two and then Align To's three. - let mut small = widget_rects(ctx, egui::vec2(28.0, 28.0)); - small.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [.., selection, key, artboard] = small[..] else { panic!("no Align To buttons in {small:?}") }; - let objects = widget_rects(ctx, egui::vec2(32.0, 32.0)); - let left = objects.iter().copied().filter(|r| r.top() == objects[0].top()).min_by(|a, b| a.left().total_cmp(&b.left())).unwrap(); - ([selection, key, artboard], left) -} /// The left edge of object `id`. fn left_edge(app: &VectorcraftApp, id: &Value) -> f64 { @@ -135,21 +101,22 @@ fn left_edge(app: &VectorcraftApp, id: &Value) -> f64 { /// stays the key. #[test] fn align_to_key_object_makes_the_topmost_object_the_key() { - let (mut app, back, front) = back_and_front(); - let ctx = egui::Context::default(); - let ([_, key, _], left) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, key.center(), show); - let key_object = |app: &VectorcraftApp| app.session.active().unwrap().selection.key.map(|k| k.0); - assert_eq!(key_object(&app), front.as_u64(), "the front rectangle, selected first"); - app.run("select.set", json!({"ids": [back, front]})).unwrap(); - click(&ctx, &mut app, key.center(), show); - assert_eq!(key_object(&app), front.as_u64(), "the front rectangle, selected last"); - assert_eq!(align_to(&app), AlignTo::Key); - click(&ctx, &mut app, left.center(), show); + let (app, back, front) = back_and_front(); + let mut panel = Panel::new(app, show); + panel.click("Align to Key Object"); + let key_object = |panel: &Panel| panel.app().session.active().unwrap().selection.key.map(|k| k.0); + assert_eq!(key_object(&panel), front.as_u64(), "the front rectangle, selected first"); + panel.app().run("select.set", json!({"ids": [back, front]})).unwrap(); + panel.click("Align to Key Object"); + assert_eq!(key_object(&panel), front.as_u64(), "the front rectangle, selected last"); + assert_eq!(align_to(&panel.app()), AlignTo::Key); + panel.click("Horizontal Align Left"); + let app = panel.app(); assert_eq!((left_edge(&app, &back), left_edge(&app, &front)), (80.0, 80.0), "to the key's left edge: {}", app.ui.status); - app.run("select.key", json!({"id": back})).unwrap(); - click(&ctx, &mut app, key.center(), show); - assert_eq!(key_object(&app), back.as_u64(), "a key already set"); + drop(app); + panel.app().run("select.key", json!({"id": back})).unwrap(); + panel.click("Align to Key Object"); + assert_eq!(key_object(&panel), back.as_u64(), "a key already set"); } /// Align to Key Object stores no Align To choice: once the key object is cleared, by Cancel @@ -157,25 +124,23 @@ fn align_to_key_object_makes_the_topmost_object_the_key() { /// choice again. #[test] fn align_to_shows_its_choice_again_once_the_key_is_cleared() { - let (mut app, back, front) = back_and_front(); - let ctx = egui::Context::default(); - let ([_, key, artboard], _) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, artboard.center(), show); - click(&ctx, &mut app, key.center(), show); - assert_eq!(align_to(&app), AlignTo::Key); - let cancel = text_rect(&frame_events(&ctx, &mut app, vec![], menu), " Cancel Key Object"); - click(&ctx, &mut app, cancel.center(), menu); - assert!(!has_key(&app)); - assert_eq!(align_to(&app), AlignTo::Artboard, "Cancel Key Object"); + let (app, back, front) = back_and_front(); + let mut panel = Panel::new(app, show); + panel.click("Align to Artboard"); + panel.click("Align to Key Object"); + assert_eq!(align_to(&panel.app()), AlignTo::Key); + panel.app().run("ui.align.cancelKeyObject", json!({})).unwrap(); + assert!(!has_key(&panel.app())); + assert_eq!(align_to(&panel.app()), AlignTo::Artboard, "Cancel Key Object"); // The Selection tool's click on the key object runs `select.key {}`. - click(&ctx, &mut app, key.center(), show); - assert!(has_key(&app)); - app.run("select.key", json!({})).unwrap(); - assert_eq!(align_to(&app), AlignTo::Artboard, "a click on the key"); - click(&ctx, &mut app, key.center(), show); - assert!(has_key(&app)); - app.run("select.set", json!({"ids": [back, front]})).unwrap(); - assert_eq!(align_to(&app), AlignTo::Artboard, "another selection"); + panel.click("Align to Key Object"); + assert!(has_key(&panel.app())); + panel.app().run("select.key", json!({})).unwrap(); + assert_eq!(align_to(&panel.app()), AlignTo::Artboard, "a click on the key"); + panel.click("Align to Key Object"); + assert!(has_key(&panel.app())); + panel.app().run("select.set", json!({"ids": [back, front]})).unwrap(); + assert_eq!(align_to(&panel.app()), AlignTo::Artboard, "another selection"); } /// The Align To choice is kept with the UI state, which the app saves with its preferences and @@ -183,12 +148,11 @@ fn align_to_shows_its_choice_again_once_the_key_is_cleared() { /// the state still loads. #[test] fn the_align_to_choice_is_kept_with_the_ui_state() { - let (mut app, _, _) = back_and_front(); - let ctx = egui::Context::default(); - let ([_, _, artboard], _) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, artboard.center(), show); - assert_eq!(crate::control::inspect(&app, &ctx)["ui"]["align_to"], "artboard"); - let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + let (app, _, _) = back_and_front(); + let mut panel = Panel::new(app, show); + panel.click("Align to Artboard"); + assert_eq!(serde_json::to_value(&panel.app().ui).unwrap()["align_to"], "artboard"); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&panel.app().ui).unwrap()).unwrap(); assert_eq!(back.align_to, AlignTo::Artboard); for v in [json!("key"), json!("Artboard"), json!(3), Value::Null] { let ui: crate::UiState = serde_json::from_value(json!({"align_to": v, "place_link": false})).unwrap(); @@ -204,27 +168,13 @@ fn the_align_to_choice_is_kept_with_the_ui_state() { fn align_to_key_object_needs_two_selected_objects() { let (mut app, _, front) = back_and_front(); app.run("select.set", json!({"ids": [front]})).unwrap(); - let ctx = egui::Context::default(); - let ([_, key, _], left) = panel_buttons(&mut app, &ctx); - let clickable = ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).any(|w| w.rect == key && w.sense.senses_click())); - assert!(!clickable, "disabled"); - click(&ctx, &mut app, key.center(), show); - assert_eq!(app.session.active().unwrap().selection.key, None); - assert_eq!(align_to(&app), AlignTo::Selection); - click(&ctx, &mut app, left.center(), show); - assert_eq!(left_edge(&app, &front), 0.0, "the artboard's left edge"); -} - -/// One frame of the Align panel → the rects of the Align To buttons drawn as chosen. -fn chosen_align_to(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); - out.textures_delta.clear(); - let fill = crate::theme::Tokens::get(ctx).tool_active; - let chosen = |s: &egui::Shape| match s { - egui::Shape::Rect(r) if r.fill == fill && r.rect.size() == egui::vec2(28.0, 28.0) => Some(r.rect), - _ => None, - }; - out.shapes.iter().filter_map(|c| chosen(&c.shape)).collect() + let mut panel = Panel::new(app, show); + assert!(!panel.enabled("Align to Key Object"), "disabled"); + panel.click("Align to Key Object"); + assert_eq!(panel.app().session.active().unwrap().selection.key, None); + assert_eq!(align_to(&panel.app()), AlignTo::Selection); + panel.click("Horizontal Align Left"); + assert_eq!(left_edge(&panel.app(), &front), 0.0, "the artboard's left edge"); } /// With one object selected the align buttons align it to the artboard, and Align To shows @@ -232,28 +182,12 @@ fn chosen_align_to(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec| { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { - ui.horizontal(|ui| { - at.set(ui.cursor().min); - align_buttons(app, ui, 24.0); - }); - }); - out.textures_delta.clear(); - }; - frame(&mut app, vec![]); - let right = at.get() + egui::vec2(2.0 * (24.0 + ctx.global_style().spacing.item_spacing.x) + 12.0, 12.0); - let press = |pressed| egui::Event::PointerButton { pos: right, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, vec![egui::Event::PointerMoved(right), press(true)]); - frame(&mut app, vec![press(false)]); + let mut panel = Panel::new(app, align_buttons); + panel.click("Horizontal Align Right"); + let app = panel.app(); let st = app.session.active().unwrap(); let x1 = |id: &serde_json::Value| st.doc.bounds_of(&[vectorcraft_doc::NodeId(id.as_u64().unwrap())], false).unwrap().x1; assert_eq!((x1(&a), x1(&b)), (200.0, 200.0), "both to the artboard's right edge"); } -/// The Align panel's buttons, in the panel's order: (command id, label). -const BUTTON_ENTRIES: [(&str, &str); 15] = [ - ("align.horizontalLeft", "Horizontal Align Left"), - ("align.horizontalCenter", "Horizontal Align Center"), - ("align.horizontalRight", "Horizontal Align Right"), - ("align.horizontalVerticalCenter", "Horizontal & Vertical Align Center"), - ("align.verticalTop", "Vertical Align Top"), - ("align.verticalCenter", "Vertical Align Center"), - ("align.verticalBottom", "Vertical Align Bottom"), - ("align.distributeVerticalTop", "Vertical Distribute Top"), - ("align.distributeVerticalCenter", "Vertical Distribute Center"), - ("align.distributeVerticalBottom", "Vertical Distribute Bottom"), - ("align.distributeHorizontalLeft", "Horizontal Distribute Left"), - ("align.distributeHorizontalCenter", "Horizontal Distribute Center"), - ("align.distributeHorizontalRight", "Horizontal Distribute Right"), - ("align.distributeVerticalSpace", "Vertical Distribute Space"), - ("align.distributeHorizontalSpace", "Horizontal Distribute Space"), -]; - -/// The chord the tests below give an Align panel button. -const CHORD: &str = "Cmd+Alt+Shift+F2"; - -/// One frame pressing [`CHORD`] through the shortcut handler. -fn press_chord(app: &mut VectorcraftApp) { - let ctx = egui::Context::default(); - let modifiers = egui::Modifiers::COMMAND | egui::Modifiers::ALT | egui::Modifiers::SHIFT; - let ev = egui::Event::Key { key: egui::Key::F2, physical_key: None, pressed: true, repeat: false, modifiers }; - let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); - out.textures_delta.clear(); -} - -/// Edit › Keyboard Shortcuts lists each of the Align panel's Align Objects, Distribute Objects -/// and Distribute Spacing buttons under Align, with the button's label and no default shortcut, -/// and each can be given one. -#[test] -fn keyboard_shortcuts_lists_each_align_panel_button() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let panel = { - let (mut app, _, _) = back_and_front(); - tree(|ui| show(&mut app, ui)) - }; - let list = app.run("shortcuts.list", json!({})).unwrap(); - for (id, label) in BUTTON_ENTRIES { - assert_eq!(role_and_state(&panel, label), (Role::Button, None), "the panel's {label} button"); - let e = list.as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} is not listed")); - assert_eq!( - (e["label"].as_str(), e["group"].as_str(), &e["default"], &e["shortcut"]), - (Some(label), Some("Align"), &Value::Null, &Value::Null), - "{id}" - ); - let set = app.run("shortcuts.set", json!({"id": id, "shortcut": CHORD, "force": true})).unwrap(); - assert_eq!(set["shortcut"], CHORD, "{id}"); - } -} - -/// A shortcut on an Align panel button's entry runs what a click on the button runs: Horizontal +/// The command of an Align panel button runs what a click on the button runs: Horizontal /// Align Right aligns to the selection, to the active artboard with Align to Artboard, and to /// the key object while there is one. Horizontal Distribute Left sends the key and the /// Distribute Spacing value, and Horizontal Distribute Space makes the gaps equal. @@ -366,80 +231,32 @@ fn a_shortcut_runs_its_align_panel_button() { let (id, p) = app.session.journal.last().unwrap(); (id.clone(), p["to"].clone(), p.get("spacing").cloned()) }; - app.run("shortcuts.set", json!({"id": "align.horizontalRight", "shortcut": CHORD})).unwrap(); - press_chord(&mut app); + app.run("align.horizontalRight", json!({})).unwrap(); assert_eq!(edges(&app, true), [140.0; 3], "Align to Selection: {}", app.ui.status); app.run("edit.undo", json!({})).unwrap(); app.ui.align_to = AlignTo::Artboard; - press_chord(&mut app); + app.run("align.horizontalRight", json!({})).unwrap(); assert_eq!(edges(&app, true), [200.0; 3], "Align to Artboard: {}", app.ui.status); app.run("edit.undo", json!({})).unwrap(); app.run("select.key", json!({"id": ids[1]})).unwrap(); - press_chord(&mut app); + app.run("align.horizontalRight", json!({})).unwrap(); assert_eq!(edges(&app, true), [90.0; 3], "the key object's right edge: {}", app.ui.status); app.run("edit.undo", json!({})).unwrap(); // Distribute Objects with the key object and a Distribute Spacing value of 15 pt. - app.run("shortcuts.set", json!({"id": "align.distributeHorizontalLeft", "shortcut": CHORD, "force": true})).unwrap(); app.ui.align_spacing = 15.0; - press_chord(&mut app); + app.run("align.distributeHorizontalLeft", json!({})).unwrap(); assert_eq!(sent(&app), ("object.distribute".to_string(), json!("key"), Some(json!(15.0)))); assert_eq!(edges(&app, false), [35.0, 50.0, 65.0], "15 pt apart: {}", app.ui.status); app.run("edit.undo", json!({})).unwrap(); // Distribute Spacing with Align to Selection: the outer objects stay, and the gaps are equal. app.run("select.key", json!({})).unwrap(); app.ui.align_to = AlignTo::Selection; - app.run("shortcuts.set", json!({"id": "align.distributeHorizontalSpace", "shortcut": CHORD, "force": true})).unwrap(); - press_chord(&mut app); + app.ui.align_to = AlignTo::Selection; + app.run("align.distributeHorizontalSpace", json!({})).unwrap(); assert_eq!(sent(&app), ("object.distributeSpacing".to_string(), json!("selection"), Some(Value::Null))); assert_eq!(edges(&app, false), [10.0, 55.0, 120.0], "25 pt gaps: {}", app.ui.status); } -/// A shortcut on an Align panel button's entry is kept in the set Export… writes, and Import… -/// of that set gives it back after a reset; it is kept in the saved preferences too. -#[test] -fn an_align_panel_button_shortcut_is_kept_in_a_saved_set() { - let (mut app, back, front) = back_and_front(); - let written: std::rc::Rc>> = Default::default(); - let w = written.clone(); - app.services.write = Some(Box::new(move |_: &str, b: &[u8]| { - *w.borrow_mut() = b.to_vec(); - Ok(()) - })); - let top = |app: &VectorcraftApp, id: &Value| { - app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap().y0 - }; - app.run("shortcuts.set", json!({"id": "align.verticalTop", "shortcut": CHORD})).unwrap(); - app.run("shortcuts.export", json!({"path": "/sets/Align.json"})).unwrap(); - // The preferences save the UI state, and the next launch reads it back. - let saved = serde_json::to_value(&app.ui).unwrap(); - let loaded: crate::UiState = serde_json::from_value(saved).unwrap(); - assert_eq!(serde_json::to_value(&loaded).unwrap()["shortcut_overrides"]["align.verticalTop"], CHORD, "the saved preferences"); - app.run("shortcuts.reset", json!({})).unwrap(); - press_chord(&mut app); - assert_eq!(top(&app, &front), 50.0, "no shortcut after the reset: {}", app.ui.status); - let set: Value = serde_json::from_slice(&written.borrow()).unwrap(); - app.run("shortcuts.import", json!({"data": set})).unwrap(); - press_chord(&mut app); - assert_eq!((top(&app, &back), top(&app, &front)), (10.0, 10.0), "the imported shortcut: {}", app.ui.status); -} - -/// One frame of the Align panel → its Horizontal Distribute Left and Horizontal Distribute -/// Space buttons. -fn distribute_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> (egui::Rect, egui::Rect) { - frame_events(ctx, app, vec![], show); - // The lower row of 32-point buttons is Distribute Objects': Vertical Distribute Top, Center - // and Bottom, then Horizontal Distribute Left, Center and Right. - let objects = widget_rects(ctx, egui::vec2(32.0, 32.0)); - let bottom = objects.last().unwrap().top(); - let mut row: Vec = objects.into_iter().filter(|r| r.top() == bottom).collect(); - row.sort_by(|a, b| a.left().total_cmp(&b.left())); - // The 28-point buttons are Distribute Spacing's two (Vertical, then Horizontal) and then - // Align To's three. - let mut small = widget_rects(ctx, egui::vec2(28.0, 28.0)); - small.sort_by(|a, b| a.left().total_cmp(&b.left())); - (row[3], small[1]) -} - /// With Align to Artboard chosen, the Align panel's Horizontal Distribute Left puts the /// outermost of three objects (20, 40 and 20 pt wide) on the active artboard's left and right /// edges and spaces their left edges evenly, and Horizontal Distribute Space makes the gaps @@ -455,20 +272,19 @@ fn the_distribute_buttons_follow_align_to_artboard() { .collect(); app.run("select.set", json!({"ids": ids})).unwrap(); let lefts = |app: &VectorcraftApp| ids.iter().map(|id| left_edge(app, id)).collect::>(); - let ctx = egui::Context::default(); - let (left, space) = distribute_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(lefts(&app), [10.0, 65.0, 120.0], "Align to Selection: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Left"); + assert_eq!(lefts(&panel.app()), [10.0, 65.0, 120.0], "Align to Selection: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); // The objects are on artboard 0, and artboard 1 is the active one. - app.ui.align_to = AlignTo::Artboard; - app.view_mut().unwrap().artboard = 1; + panel.app().ui.align_to = AlignTo::Artboard; + panel.app().view_mut().unwrap().artboard = 1; let (x0, x1) = (boards[1].x0, boards[1].x1); - click(&ctx, &mut app, left.center(), show); - assert_eq!(lefts(&app), [x0, x0 + 90.0, x1 - 20.0], "the active artboard's edges: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - click(&ctx, &mut app, space.center(), show); - assert_eq!(lefts(&app), [x0, x0 + 80.0, x1 - 20.0], "60 pt gaps: {}", app.ui.status); + panel.click("Horizontal Distribute Left"); + assert_eq!(lefts(&panel.app()), [x0, x0 + 90.0, x1 - 20.0], "the active artboard's edges: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.click("Horizontal Distribute Space"); + assert_eq!(lefts(&panel.app()), [x0, x0 + 80.0, x1 - 20.0], "60 pt gaps: {}", panel.app().ui.status); } /// With a key object, the Align panel's Distribute Objects buttons send the Distribute Spacing @@ -490,20 +306,19 @@ fn the_distribute_objects_buttons_send_the_spacing_with_a_key_object() { let (id, p) = app.session.journal.last().unwrap(); (id.clone(), p["to"].clone(), p.get("spacing").cloned()) }; - let ctx = egui::Context::default(); - let (left, _) = distribute_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(sent(&app), ("object.distribute".to_string(), json!("selection"), None), "no key object"); - assert_eq!(lefts(&app), [10.0, 65.0, 120.0], "{}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - app.run("select.key", json!({"id": ids[1]})).unwrap(); - click(&ctx, &mut app, left.center(), show); - assert_eq!(sent(&app), ("object.distribute".to_string(), json!("key"), Some(json!(0.0)))); - assert_eq!(lefts(&app), [50.0; 3], "on the key's left edge: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - app.ui.align_spacing = 15.0; - click(&ctx, &mut app, left.center(), show); - assert_eq!(lefts(&app), [35.0, 50.0, 65.0], "15 pt apart: {}", app.ui.status); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Left"); + assert_eq!(sent(&panel.app()), ("object.distribute".to_string(), json!("selection"), None), "no key object"); + assert_eq!(lefts(&panel.app()), [10.0, 65.0, 120.0], "{}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().run("select.key", json!({"id": ids[1]})).unwrap(); + panel.click("Horizontal Distribute Left"); + assert_eq!(sent(&panel.app()), ("object.distribute".to_string(), json!("key"), Some(json!(0.0)))); + assert_eq!(lefts(&panel.app()), [50.0; 3], "on the key's left edge: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().ui.align_spacing = 15.0; + panel.click("Horizontal Distribute Left"); + assert_eq!(lefts(&panel.app()), [35.0, 50.0, 65.0], "15 pt apart: {}", panel.app().ui.status); } /// #2143: with a key guide, the Distribute Objects and Distribute Spacing buttons send the @@ -525,22 +340,21 @@ fn the_distribute_buttons_send_the_spacing_with_a_key_guide() { let (id, p) = app.session.journal.last().unwrap(); (id.clone(), p["to"].clone(), p.get("spacing").cloned()) }; - let ctx = egui::Context::default(); - let (left, space) = distribute_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(sent(&app), ("object.distribute".to_string(), json!("key"), Some(json!(0.0)))); - assert_eq!(lefts(&app), [100.0; 3], "on the guide: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - app.ui.align_spacing = 15.0; - click(&ctx, &mut app, left.center(), show); - assert_eq!(lefts(&app), [70.0, 85.0, 115.0], "15 pt apart, outward from the guide: {}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Left"); + assert_eq!(sent(&panel.app()), ("object.distribute".to_string(), json!("key"), Some(json!(0.0)))); + assert_eq!(lefts(&panel.app()), [100.0; 3], "on the guide: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().ui.align_spacing = 15.0; + panel.click("Horizontal Distribute Left"); + assert_eq!(lefts(&panel.app()), [70.0, 85.0, 115.0], "15 pt apart, outward from the guide: {}", panel.app().ui.status); + assert_eq!(panel.app().session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); // Horizontal Distribute Space with 15: the object before the guide ends 15 pt before it, // the one after it starts 15 pt after it. - click(&ctx, &mut app, space.center(), show); - assert_eq!(sent(&app), ("object.distributeSpacing".to_string(), json!("key"), Some(json!(15.0)))); - assert_eq!(lefts(&app), [10.0, 45.0, 115.0], "{}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); + panel.click("Horizontal Distribute Space"); + assert_eq!(sent(&panel.app()), ("object.distributeSpacing".to_string(), json!("key"), Some(json!(15.0)))); + assert_eq!(lefts(&panel.app()), [10.0, 45.0, 115.0], "{}", panel.app().ui.status); + assert_eq!(panel.app().session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); } /// Three vertical ruler guides selected without objects: Align Objects buttons are on, and @@ -554,16 +368,11 @@ fn the_align_buttons_align_guides_selected_alone_to_artboard() { } app.run("guide.select", json!({"indexes": [0, 1, 2]})).unwrap(); app.ui.align_to = AlignTo::Artboard; - let ctx = egui::Context::default(); - frame_events(&ctx, &mut app, vec![], show); - let row = widget_rects(&ctx, egui::vec2(32.0, 32.0)); - let top = row.iter().map(|r| r.top()).fold(f32::MAX, f32::min); - let mut row: Vec = row.into_iter().filter(|r| r.top() == top).collect(); - row.sort_by(|a, b| a.left().total_cmp(&b.left())); - assert!(row[0].width() > 0.0, "Horizontal Align Left is enabled"); - click(&ctx, &mut app, row[0].center(), show); + let mut panel = Panel::new(app, show); + assert!(panel.enabled("Horizontal Align Left"), "Horizontal Align Left is enabled"); + panel.click("Horizontal Align Left"); let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::>(); - assert_eq!(pos(&app), [0.0, 0.0, 0.0], "{}", app.ui.status); + assert_eq!(pos(&panel.app()), [0.0, 0.0, 0.0], "{}", panel.app().ui.status); } /// Three vertical ruler guides selected without objects: the Distribute buttons are on, and @@ -578,23 +387,16 @@ fn the_distribute_buttons_space_guides_selected_alone() { app.run("guide.add", json!({"vertical": true, "pos": pos})).unwrap(); } app.run("guide.select", json!({"indexes": [0, 1, 2]})).unwrap(); - let ctx = egui::Context::default(); - frame_events(&ctx, &mut app, vec![], show); - let row = widget_rects(&ctx, egui::vec2(32.0, 32.0)); - let bottom = row.iter().map(|r| r.top()).fold(f32::MIN, f32::max); - let mut row: Vec = row.into_iter().filter(|r| r.top() == bottom).collect(); - row.sort_by(|a, b| a.left().total_cmp(&b.left())); - assert_eq!(row.len(), 6, "the Distribute row"); - // Its fifth button is Horizontal Distribute Center. - click(&ctx, &mut app, row[4].center(), show); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Center"); let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::>(); - assert_eq!(pos(&app), [20.0, 100.0, 180.0], "{}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(pos(&app), [20.0, 50.0, 180.0], "one undo step"); + assert_eq!(pos(&panel.app()), [20.0, 100.0, 180.0], "{}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(pos(&panel.app()), [20.0, 50.0, 180.0], "one undo step"); // With Align to Artboard, the outermost guides go to its edges: equal columns across it. - app.ui.align_to = AlignTo::Artboard; - click(&ctx, &mut app, row[4].center(), show); - assert_eq!(pos(&app), [0.0, 100.0, 200.0], "{}", app.ui.status); + panel.app().ui.align_to = AlignTo::Artboard; + panel.click("Horizontal Distribute Center"); + assert_eq!(pos(&panel.app()), [0.0, 100.0, 200.0], "{}", panel.app().ui.status); } /// Runs the Object → Align item `label` as a click on it does. @@ -638,8 +440,7 @@ fn align_to_checks(app: &VectorcraftApp) -> Vec> { } /// Object → Align lists the Align To choices after its align items, the one the Align panel shows -/// checked, and a click on one chooses it as the panel's button does. Edit › Keyboard Shortcuts -/// lists each under Align with no default shortcut, and a shortcut chooses it too. +/// checked, and a click on one chooses it as the panel's button does; its command chooses it too. #[test] fn object_align_lists_the_align_to_choices() { let (mut app, back, front) = back_and_front(); @@ -651,15 +452,9 @@ fn object_align_lists_the_align_to_choices() { object_align(&mut app, "Align to Artboard"); assert_eq!(app.ui.align_to, AlignTo::Artboard); assert_eq!(align_to_checks(&app), [Some(false), Some(false), Some(true)]); - let list = app.run("shortcuts.list", json!({})).unwrap(); - for (id, label) in ALIGN_TO_ENTRIES { - let e = list.as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} is not listed")); - assert_eq!((e["label"].as_str(), e["group"].as_str(), &e["default"]), (Some(label), Some("Align"), &Value::Null), "{id}"); - } - // Align to Key Object by a shortcut: the topmost selected object becomes the key, and the + // Align to Key Object by its command: the topmost selected object becomes the key, and the // stored choice stays. - app.run("shortcuts.set", json!({"id": "align.toKeyObject", "shortcut": CHORD})).unwrap(); - press_chord(&mut app); + app.run("align.toKeyObject", json!({})).unwrap(); assert_eq!(app.session.active().unwrap().selection.key.map(|k| k.0), front.as_u64(), "{}", app.ui.status); assert_eq!(align_to_checks(&app), [Some(false), Some(true), Some(false)]); assert_eq!(app.ui.align_to, AlignTo::Artboard); @@ -765,15 +560,14 @@ fn anchor_points_of_one_path_align_to_each_other() { node.path_data().unwrap().anchors().map(|(_, _, a)| a.p.x).collect() }; app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); - let ctx = egui::Context::default(); - let ([selection, _, artboard], left) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(xs(&app), [100.0, 100.0, 150.0], "to the points' left edge: {}", app.ui.status); - assert_eq!(chosen_align_to(&mut app, &ctx), [selection], "the stored choice"); - app.run("edit.undo", json!({})).unwrap(); - click(&ctx, &mut app, artboard.center(), show); - click(&ctx, &mut app, left.center(), show); - assert_eq!(xs(&app), [0.0, 0.0, 150.0], "to the artboard's left edge: {}", app.ui.status); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Align Left"); + assert_eq!(xs(&panel.app()), [100.0, 100.0, 150.0], "to the points' left edge: {}", panel.app().ui.status); + assert_eq!(align_to_checks(&panel.app()), [Some(true), Some(false), Some(false)], "the stored choice"); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.click("Align to Artboard"); + panel.click("Horizontal Align Left"); + assert_eq!(xs(&panel.app()), [0.0, 0.0, 150.0], "to the artboard's left edge: {}", panel.app().ui.status); } /// #1636: with a key anchor, the Align panel shows the key choice chosen and named Align to Key @@ -790,16 +584,15 @@ fn a_key_anchor_is_chosen_named_and_aligned_to() { }; app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); app.run("select.key", json!({"id": id, "anchor": [0, 2]})).unwrap(); - let ctx = egui::Context::default(); - let ([selection, key, _], left) = panel_buttons(&mut app, &ctx); - assert_eq!((align_to(&app), chosen_align_to(&mut app, &ctx)), (AlignTo::Key, vec![key]), "chosen automatically"); - let named = tree(|ui| show(&mut app, ui)); - assert_eq!(role_and_state(&named, "Align to Key Anchor"), (Role::Button, Some(Toggled::True))); - click(&ctx, &mut app, left.center(), show); - assert_eq!(xs(&app), [150.0, 200.0, 150.0], "to the key anchor's x: {}", app.ui.status); - click(&ctx, &mut app, selection.center(), show); - assert!(!has_key(&app), "Align to Selection lets go of the key anchor"); - assert_eq!(app.ui.align_to, AlignTo::Selection); + let mut panel = Panel::new(app, show); + panel.frame(); + assert_eq!((align_to(&panel.app()), align_to_checks(&panel.app())), (AlignTo::Key, vec![Some(false), Some(true), Some(false)]), "chosen automatically"); + assert!(panel.shows("Align to Key Anchor")); + panel.click("Horizontal Align Left"); + assert_eq!(xs(&panel.app()), [150.0, 200.0, 150.0], "to the key anchor's x: {}", panel.app().ui.status); + panel.click("Align to Selection"); + assert!(!has_key(&panel.app()), "Align to Selection lets go of the key anchor"); + assert_eq!(panel.app().ui.align_to, AlignTo::Selection); } /// #1636: the Distribute buttons work on the anchor points of one path (one object selected). @@ -809,49 +602,14 @@ fn distribute_buttons_space_the_anchor_points_of_one_path() { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let id = app.run("path.create", json!({"d": "M10 10 L20 50 L100 30"})).unwrap()["id"].as_u64().unwrap(); app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); - let ctx = egui::Context::default(); - frame_events(&ctx, &mut app, vec![], show); - // The 32-point buttons are the Align row and, below it, the Distribute row, whose fifth - // button is Horizontal Distribute Center. - let all = widget_rects(&ctx, egui::vec2(32.0, 32.0)); - let top = all.iter().map(|r| r.top()).fold(f32::MIN, f32::max); - let mut row: Vec<_> = all.into_iter().filter(|r| r.top() == top).collect(); - row.sort_by(|a, b| a.left().total_cmp(&b.left())); - assert_eq!(row.len(), 6, "the Distribute row"); - let hit = row[4].center(); - click(&ctx, &mut app, hit, show); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Center"); + let app = panel.app(); let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(); let xs: Vec = node.path_data().unwrap().anchors().map(|(_, _, a)| a.p.x).collect(); assert_eq!(xs, [10.0, 55.0, 100.0], "{}", app.ui.status); } -/// #4231: the panel menu's Align to Glyph Bounds is a submenu (no longer dimmed) whose Point Text -/// and Area Text each toggle their own preference and show a check while it is on. -#[test] -fn align_to_glyph_bounds_toggles_point_and_area_text() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - assert!(frame_events(&ctx, &mut app, vec![], menu).iter().any(|(t, _)| t.trim() == "Align to Glyph Bounds")); - let checked = |app: &mut VectorcraftApp| { - let texts = frame_events(&ctx, app, vec![], glyph_bounds_items); - texts.iter().filter_map(|(t, _)| t.strip_prefix("✓ ")).map(str::to_string).collect::>() - }; - let choose = |app: &mut VectorcraftApp, label: &str| { - let texts = frame_events(&ctx, app, vec![], glyph_bounds_items); - let r = texts.iter().find(|(t, _)| t.trim_start_matches('✓').trim() == label).unwrap_or_else(|| panic!("{label} in {texts:?}")).1; - click(&ctx, app, r.center(), glyph_bounds_items); - }; - let prefs = |app: &VectorcraftApp| (app.session.prefs.align_glyph_bounds_point, app.session.prefs.align_glyph_bounds_area); - assert!(checked(&mut app).is_empty(), "both off by default"); - choose(&mut app, "Point Text"); - assert_eq!((prefs(&app), checked(&mut app)), ((true, false), vec!["Point Text".to_string()])); - choose(&mut app, "Area Text"); - assert_eq!((prefs(&app), checked(&mut app)), ((true, true), vec!["Point Text".to_string(), "Area Text".to_string()])); - choose(&mut app, "Point Text"); - assert_eq!((prefs(&app), checked(&mut app)), ((false, true), vec!["Area Text".to_string()])); -} - /// Three artboards, 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50, with /// the Artboard tool chosen and all three selected, artboard 1 active. fn selected_artboards() -> VectorcraftApp { @@ -881,21 +639,20 @@ fn last_sent(app: &VectorcraftApp) -> (String, Value, Option) { #[test] fn the_align_buttons_align_the_selected_artboards() { let mut app = selected_artboards(); - let ctx = egui::Context::default(); let steps = app.session.active().unwrap().history.undo.len(); - let ([_, key, artboard], left) = panel_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(artboard_corners(&app), [(0.0, 0.0), (0.0, 40.0), (0.0, 10.0)], "{}", app.ui.status); - assert_eq!(last_sent(&app), ("artboard.align".to_string(), json!("selection"), None)); - assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); - app.run("edit.undo", json!({})).unwrap(); - click(&ctx, &mut app, key.center(), show); - assert!(app.ui.align_to == AlignTo::Selection && !has_key(&app), "Align to Key Object is off"); - click(&ctx, &mut app, artboard.center(), show); - assert_eq!(app.ui.align_to, AlignTo::Artboard); - click(&ctx, &mut app, left.center(), show); - assert_eq!(artboard_corners(&app), [(150.0, 0.0), (150.0, 40.0), (150.0, 10.0)], "artboard 1 stays: {}", app.ui.status); - assert_eq!(last_sent(&app), ("artboard.align".to_string(), json!("artboard"), None)); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Align Left"); + assert_eq!(artboard_corners(&panel.app()), [(0.0, 0.0), (0.0, 40.0), (0.0, 10.0)], "{}", panel.app().ui.status); + assert_eq!(last_sent(&panel.app()), ("artboard.align".to_string(), json!("selection"), None)); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.click("Align to Key Object"); + assert!(panel.app().ui.align_to == AlignTo::Selection && !has_key(&panel.app()), "Align to Key Object is off"); + panel.click("Align to Artboard"); + assert_eq!(panel.app().ui.align_to, AlignTo::Artboard); + panel.click("Horizontal Align Left"); + assert_eq!(artboard_corners(&panel.app()), [(150.0, 0.0), (150.0, 40.0), (150.0, 10.0)], "artboard 1 stays: {}", panel.app().ui.status); + assert_eq!(last_sent(&panel.app()), ("artboard.align".to_string(), json!("artboard"), None)); } /// With the Artboard tool chosen, the Distribute Objects and Distribute Spacing buttons space the @@ -904,35 +661,28 @@ fn the_align_buttons_align_the_selected_artboards() { #[test] fn the_distribute_buttons_space_the_selected_artboards() { let mut app = selected_artboards(); - let ctx = egui::Context::default(); - let (left, space) = distribute_buttons(&mut app, &ctx); - click(&ctx, &mut app, left.center(), show); - assert_eq!(artboard_corners(&app), [(0.0, 0.0), (200.0, 40.0), (400.0, 10.0)], "{}", app.ui.status); - assert_eq!(last_sent(&app), ("artboard.distribute".to_string(), json!("selection"), None)); - app.run("edit.undo", json!({})).unwrap(); - click(&ctx, &mut app, space.center(), show); - assert_eq!(artboard_corners(&app), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - app.ui.align_to = AlignTo::Artboard; - app.ui.align_spacing = 20.0; - click(&ctx, &mut app, space.center(), show); - assert_eq!(artboard_corners(&app), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20: {}", app.ui.status); - assert_eq!(last_sent(&app), ("artboard.distributeSpacing".to_string(), json!("artboard"), Some(json!(20.0)))); - app.run("edit.undo", json!({})).unwrap(); - click(&ctx, &mut app, left.center(), show); - assert_eq!(artboard_corners(&app), [(130.0, 0.0), (150.0, 40.0), (170.0, 10.0)], "left edges 20 apart: {}", app.ui.status); - app.run("edit.undo", json!({})).unwrap(); - app.session.set_tool_option("selected", &json!([1])); - let ran = app.session.journal.len(); - for button in [left, space] { - click(&ctx, &mut app, button.center(), show); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Left"); + assert_eq!(artboard_corners(&panel.app()), [(0.0, 0.0), (200.0, 40.0), (400.0, 10.0)], "{}", panel.app().ui.status); + assert_eq!(last_sent(&panel.app()), ("artboard.distribute".to_string(), json!("selection"), None)); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.click("Horizontal Distribute Space"); + assert_eq!(artboard_corners(&panel.app()), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().ui.align_to = AlignTo::Artboard; + panel.app().ui.align_spacing = 20.0; + panel.click("Horizontal Distribute Space"); + assert_eq!(artboard_corners(&panel.app()), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20: {}", panel.app().ui.status); + assert_eq!(last_sent(&panel.app()), ("artboard.distributeSpacing".to_string(), json!("artboard"), Some(json!(20.0)))); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.click("Horizontal Distribute Left"); + assert_eq!(artboard_corners(&panel.app()), [(130.0, 0.0), (150.0, 40.0), (170.0, 10.0)], "left edges 20 apart: {}", panel.app().ui.status); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().session.set_tool_option("selected", &json!([1])); + panel.frame(); + for name in ["Horizontal Distribute Left", "Horizontal Distribute Space"] { + assert!(!panel.enabled(name), "one artboard: {name} is off"); } - assert_eq!(app.session.journal.len(), ran, "one artboard: the Distribute buttons are off"); -} - -/// Whether the widget at `rect` in the last frame takes clicks (an enabled button). -fn clickable(ctx: &egui::Context, rect: egui::Rect) -> bool { - ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).any(|w| w.rect == rect && w.sense.senses_click())) } /// With Align to Selection chosen, two selected artboards are the ends of the distribution @@ -944,15 +694,16 @@ fn the_distribute_buttons_need_three_artboards_without_a_spacing() { // Making an artboard active selects it alone, so the selection is set after. crate::panels::artboards::select(&mut app, 1); app.session.set_tool_option("selected", &json!([1, 2])); - let ctx = egui::Context::default(); - let (left, space) = distribute_buttons(&mut app, &ctx); - assert!(!clickable(&ctx, left) && !clickable(&ctx, space), "Align to Selection: off for two artboards"); - app.ui.align_to = AlignTo::Artboard; - let (left, space) = distribute_buttons(&mut app, &ctx); - assert!(clickable(&ctx, left) && clickable(&ctx, space), "Align to Artboard: on for two artboards"); - app.ui.align_spacing = 20.0; - click(&ctx, &mut app, space.center(), show); - assert_eq!(artboard_corners(&app), [(0.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "a gap of 20: {}", app.ui.status); + let mut panel = Panel::new(app, show); + panel.frame(); + let on = |panel: &Panel| ["Horizontal Distribute Left", "Horizontal Distribute Space"].map(|name| panel.enabled(name)); + assert_eq!(on(&panel), [false, false], "Align to Selection: off for two artboards"); + panel.app().ui.align_to = AlignTo::Artboard; + panel.frame(); + assert_eq!(on(&panel), [true, true], "Align to Artboard: on for two artboards"); + panel.app().ui.align_spacing = 20.0; + panel.click("Horizontal Distribute Space"); + assert_eq!(artboard_corners(&panel.app()), [(0.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "a gap of 20: {}", panel.app().ui.status); } /// With Align to Artboard chosen, the spacing is measured from the active artboard, which is @@ -965,11 +716,10 @@ fn the_artboard_spacing_is_measured_from_a_selected_artboard() { assert_eq!((app.session.tool_options()["active"].clone(), artboards_selected(&app)), (json!(0), 2)); app.ui.align_to = AlignTo::Artboard; app.ui.align_spacing = 20.0; - let ctx = egui::Context::default(); - let (_, space) = distribute_buttons(&mut app, &ctx); - click(&ctx, &mut app, space.center(), show); - assert_eq!(last_sent(&app), ("artboard.distributeSpacing".to_string(), json!("artboard"), Some(json!(20.0)))); - assert_eq!(artboard_corners(&app), [(0.0, 0.0), (150.0, 40.0), (120.0, 10.0)], "a gap of 20 after artboard 0: {}", app.ui.status); + let mut panel = Panel::new(app, show); + panel.click("Horizontal Distribute Space"); + assert_eq!(last_sent(&panel.app()), ("artboard.distributeSpacing".to_string(), json!("artboard"), Some(json!(20.0)))); + assert_eq!(artboard_corners(&panel.app()), [(0.0, 0.0), (150.0, 40.0), (120.0, 10.0)], "a gap of 20 after artboard 0: {}", panel.app().ui.status); } /// With the Artboard tool chosen, the Distribute Spacing value can be negative, as