From 1ef599eb4cdc8fbc7c1d5c3037102e840effcdda Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:27:02 +0700 Subject: [PATCH] canvas-w26: net change of 2 commits - canvas-w26: written from its sheet - canvas-w26: repair 1 --- crates/ui-egui/src/canvas/bar_place.rs | 27 + crates/ui-egui/src/canvas/quick_pen_bar.rs | 314 ++------- crates/ui-egui/src/canvas/task_bar.rs | 765 +++++++-------------- 3 files changed, 329 insertions(+), 777 deletions(-) create mode 100644 crates/ui-egui/src/canvas/bar_place.rs diff --git a/crates/ui-egui/src/canvas/bar_place.rs b/crates/ui-egui/src/canvas/bar_place.rs new file mode 100644 index 0000000000..48d72152c4 --- /dev/null +++ b/crates/ui-egui/src/canvas/bar_place.rs @@ -0,0 +1,27 @@ +//! Where a bar the user moved sits, held with the document and the kind of place the move was made in. + +use craft_ui::canvas_controls::TaskBarPlace; + +/// A [`TaskBarPlace`] with the key of the place it was made in: the document and, for the Quick Pen bar, +/// whether a path is being drawn. A drag's offset holds only there, so one made beside the drawing does not +/// move the resting bar. The framework's place is built through `Default` only (it is `non_exhaustive`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct KeyedPlace { + /// The place the bar was last left at. + pub place: TaskBarPlace, + /// The key `place` was made under; none before the first move. + pub key: Option<(u64, bool)>, +} + +impl KeyedPlace { + /// The place to show under `key`: a pinned place holds in every key, an unpinned one only in the key it was made in. + pub fn for_key(&self, key: (u64, bool)) -> TaskBarPlace { + if self.place.pinned || self.key == Some(key) { self.place } else { TaskBarPlace::default() } + } + + /// Keeps `place`, as made under `key`. + pub fn set(&mut self, key: (u64, bool), place: TaskBarPlace) { + self.place = place; + self.key = Some(key); + } +} diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index fdca1884de..a5893a3fef 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -1,278 +1,92 @@ //! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds //! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last -//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset -//! Toolbar Position. Its handle, at its left end, drags it. +//! sharp-corner arc, and the task bar's More menu (hide, pin, reset the position). //! //! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag //! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets -//! its position, and the toolbar moves by dragging its left side +//! its position, and the toolbar moves by dragging it //! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)). //! The toolbar follows the drawing, beside the point the path goes on from and away from what was //! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)). -//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the -//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept, -//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the -//! artboard), and Window › Quick Pen Toolbar to show it again. +//! VectorCraft's own rules: moving to the drawn side where the other side runs off the canvas, the +//! place with no path being drawn, and Window › Quick Pen Toolbar to show it again. +use craft::behavior::overlay::{Align, Side}; +use craft_ui::canvas::CanvasSpace; +use craft_ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft_ui::buttons::IconButton; +use craft_ui::choice::Segmented; +use craft_ui::primitives::IconSpec; +use craft_ui::runtime::env::{Direction, Env}; +use craft_ui::canvas_controls::TaskBar; +use craft::behavior::IconId; use vectorcraft_tools::quickpen::{self, Stroke as Action}; -use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets}; - -/// The space between the point the path goes on from and the toolbar's nearest corner. -const GAP: f32 = 24.0; -/// The width of the toolbar's handle. -const HANDLE: f32 = 4.0; -/// The side of the toolbar's buttons. -const BUTTON: f32 = 28.0; -/// The space between the toolbar's controls. -const SPACING: f32 = 4.0; - -fn bar_id() -> egui::Id { - egui::Id::unique("quick-pen-bar") -} - -/// Where the Quick Pen toolbar was last drawn (none while it isn't shown). -pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option { - let id = bar_id(); - ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) -} - -/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on -/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it -/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one -/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the -/// other side fits, it goes on the other side; where neither fits, on the side with more room. -/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down. -fn beside(end: Pos2, dir: Option, size: Vec2, room: egui::Rect) -> Pos2 { - // `first` unless it runs out of room and `other` fits or runs out by less. - let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| { - let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0); - if over(other) < over(first) { other } else { first } - }; - let (right, left) = (end.x + GAP, end.x - GAP - size.x); - let (below, above) = (end.y + GAP, end.y - GAP - size.y); - let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) }; - let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) }; - pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y)) -} - -/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`. -fn resting(room: egui::Rect, size: Vec2) -> Pos2 { - pos2(room.center().x - size.x / 2.0, room.bottom() - size.y) -} - -/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`. -fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 { - p.clamp(room.min, (room.max - size).max(room.min)) -} - -/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`, -/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at -/// `home` as if never dragged. -fn unpinned(home: Pos2, offset: Vec2, end: Option, size: Vec2, room: egui::Rect) -> Pos2 { - let moved = keep_in(home + offset, size, room); - if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved } -} - -/// What a click on the toolbar does. -enum Click { - Action(Action), - Run(&'static str, serde_json::Value), -} - -/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the -/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first -/// point all are; a drag of the toolbar's handle is not. -fn canvas_drag(dragging: bool, press: Option, canvas: egui::Rect, bar: Option) -> bool { - dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p))) -} +use super::{Ui, VectorcraftApp, json}; /// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and -/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on +/// no gesture is under way on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on /// ([`VectorcraftApp::try_select_tool`]). -pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { +pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { return; } - let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down())); - // The handle's drag moves the toolbar away from where the press began. - let handle_id = bar_id().with("handle"); - if !down { - ui.ctx().data_mut(|d| d.insert_temp(handle_id, false)); - } - let on_handle = ui.ctx().data(|d| d.get_temp::(handle_id)).unwrap_or(false); - let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size)); - if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) { + // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) + if super::tool_adapter::in_gesture(app, ui.ctx()) { return; } - let Some(doc) = app.session.active().map(|st| st.uid) else { return }; + let Some(uid) = app.session.active().map(|st| st.uid) else { return }; let view = app.view_info(); let end = app.session.tool_drawing_end(view); let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view); let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default(); - let t = Tokens::get(ui.ctx()); - let id = bar_id(); - let bounds = xf.rect.shrink(8.0); - let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0); - let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est); - let end = end.map(|(p, dir)| { - let at = xf.to_screen(p); - (at, dir.map(|d| xf.to_screen(p + d) - at)) - }); - let drawing = end.is_some(); - let home = match end { - Some((at, dir)) => beside(at, dir, size, bounds), - None => resting(bounds, size), - }; - let place = &mut app.ui.quick_pen_bar_place; - // Just unpinned: follow the drawing from the pinned spot. - if !place.pinned - && let Some(at) = place.pin_at.take() - { - place.offset = Some((doc, drawing, xf.rect.min + at - home)); - } - // A drag's offset holds in the document and the kind of place (beside the drawing, or resting) - // it was made in. - let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o); - let pos = match place.pin_at { - Some(at) => keep_in(xf.rect.min + at, size, bounds), - None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds), - }; - place.shown_at = Some(pos - xf.rect.min); - // Pinned before it ever showed: hold it here. - if place.pinned && place.pin_at.is_none() { - place.pin_at = place.shown_at; - } - let pinned = place.pinned; - let mut moved = Vec2::ZERO; - let mut click: Option = None; - egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| { - egui::Frame::NONE - .fill(t.panel) - .stroke(Stroke::new(1.0, t.tool_active)) - .corner_radius(CornerRadius::same(5)) - .inner_margin(egui::Margin::symmetric(8, 6)) - .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) }) - .show(ui, |ui| { - // In a canvas pane narrower than the toolbar, its controls wrap onto more rows. - ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON)); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(SPACING, SPACING); - let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag()); - let active = grip.hovered() || grip.dragged(); - ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border }); - if grip.dragged() { - ui.ctx().data_mut(|d| d.insert_temp(handle_id, true)); - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - moved = grip.drag_delta(); - } else if grip.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); - } - let actions = [ - (Action::Line, "dc-line", tl!("Straight Line")), - (Action::ContinuousArc, "spline", tl!("Continuous Arc")), - (Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")), - ]; - for (action, icon, tip) in actions { - if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() { - click = Some(Click::Action(action)); - } - } - if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() { - click = Some(Click::Run("tool.quickPen.flipArc", json!({}))); - } - let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON); - egui::Popup::menu(&more).show(|ui| { - ui.set_min_width(170.0); - let items = [ - (tl!("Hide Toolbar"), "window.quickPenToolbar", false), - (tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned), - (tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false), - ]; - for (label, cmd, checked) in items { - if widgets::menu_item(ui, label, true, checked) { - click = Some(Click::Run(cmd, json!({}))); - } - } - }); - }); - }); - }); - if moved != Vec2::ZERO { - let to = keep_in(pos + moved, size, bounds); - let place = &mut app.ui.quick_pen_bar_place; - if place.pinned { - place.pin_at = Some(to - xf.rect.min); - } else { - place.offset = Some((doc, drawing, to - home)); + let key = (uid, end.is_some()); + let mut local = app.ui.quick_pen_bar_place.for_key(key); + let before = local; + let rtl = Env::of(ui).view().direction() == Direction::Rtl; + // Beside the end, on the side the path arrives from (a path of one point: right and below); the + // bar's sides are reading-order ones, so a rightward arrival is `End` under LTR and `Start` under RTL. + let (anchor, side, align) = match end { + Some((p, dir)) => { + let heading = dir.map(|d| space.view.to_screen(p + d) - space.view.to_screen(p)); + let right = heading.is_none_or(|d| d.x >= 0.0); + let down = heading.is_none_or(|d| d.y >= 0.0); + ( + vec![p], + if right != rtl { Side::End } else { Side::Start }, + if down { Align::Start } else { Align::End }, + ) } - ui.ctx().request_repaint(); - } - let r = match click { - Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()), - Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()), - None => Ok(()), + None => (vec![space.view.to_doc(space.view.rect.center_bottom())], Side::Above, Align::Center), }; - if let Err(e) = r { + let mut bar = TaskBar::new(tl!("Quick Pen"), &anchor, Bind::bound(&mut local)).side(side, align); + if let Some((p, _)) = end { + bar = bar.keep_clear(p); + } + let entries = [ + Entry::new(Action::Line, tl!("Straight Line")).icon(IconSpec::svg(IconId::new("dc-line"))), + Entry::new(Action::ContinuousArc, tl!("Continuous Arc")).icon(IconSpec::svg(IconId::new("spline"))), + Entry::new(Action::SharpArc, tl!("Sharp Corner Arc")).icon(IconSpec::svg(IconId::new("dc-arc"))), + ]; + let mut run: Option<(&'static str, serde_json::Value)> = None; + let shown = bar.show(ui, space.view.rect, |ui, _| { + if let Some(action) = Segmented::new(tl!("Action"), Bind::given(current), &entries).show(ui).value() { + run = Some(("tool.setOption", json!({"key": "action", "value": action.name()}))); + } + let flip_arc = IconButton::new(IconSpec::svg(IconId::new("flip-horizontal-2"))).label(tl!("Flip Arc")).enabled(flip).show(ui); + if flip_arc.clicked() { + run = Some(("tool.quickPen.flipArc", json!({}))); + } + }); + if shown.output.hide { + run = Some(("window.quickPenToolbar", json!({}))); + } + if local != before { + app.ui.quick_pen_bar_place.set(key, local); + } + if let Some((cmd, params)) = run + && let Err(e) = app.run(cmd, params) + { app.ui.status = e; } } - -#[cfg(test)] -mod tests { - use super::*; - - /// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and - /// above for one drawn left and up, and to the right and below a single point. - #[test] - fn the_toolbar_sits_beside_the_end_away_from_the_drawing() { - let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0)); - let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); - assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0)); - assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0)); - assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0)); - assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0)); - assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0)); - assert_eq!(resting(room, size), pos2(318.0, 568.0)); - // Near the canvas's bottom right corner, the side that runs off it gives way to the other. - let corner = pos2(700.0, 580.0); - assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0)); - // Near the top left corner, a path heading up and left still gets a toolbar off its end. - let corner = pos2(30.0, 30.0); - assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0)); - // On a canvas too narrow for either side across, the toolbar goes on the side with more - // room and stays off the end by going below it. - let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0)); - let end = pos2(60.0, 300.0); - let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow); - assert_eq!(at, pos2(28.0, 324.0)); - assert!(!egui::Rect::from_min_size(at, size).contains(end)); - } - - /// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press - /// (a pan does not); a drag that began on the toolbar, and no drag, do not. - #[test] - fn a_drag_that_began_on_the_canvas_hides_the_toolbar() { - let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0)); - let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0))); - assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas"); - assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet"); - assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag"); - assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag"); - assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel"); - assert!(!canvas_drag(true, None, canvas, bar)); - } - - /// A drag's offset moves the toolbar from its place, unless that would put it over the point - /// the path goes on from. - #[test] - fn a_dragged_toolbar_never_covers_the_end() { - let size = vec2(180.0, 40.0); - let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); - let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0)); - assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0)); - assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end"); - assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0)); - assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas"); - } -} diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 03ced4f7c6..87d8601c20 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -1,30 +1,42 @@ -use super::{ - Color32, CornerRadius, NodeKind, Pos2, Rect, Sense, Stroke, StrokeKind, TextKind, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets, -}; +use craft::behavior::{IconId, Mixed}; +use craft_ui::buttons::{Button, IconButton}; +use craft_ui::canvas::{CanvasSpace, CanvasView}; +use craft_ui::canvas_controls::TaskBar; +use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::menu::PanelRow; +use craft_ui::popover::Popover; +use craft_ui::primitives::IconSpec; +use craft_ui::runtime::commands::{CommandRef, CommandState, CommandStates}; +use craft_ui::runtime::env::Label; +use craft_ui::style::Variant; +use vectorcraft_geom::Point; -/// The Contextual Task Bar's area. -fn task_bar_id() -> egui::Id { - egui::Id::unique("task-bar") -} +use super::{NodeKind, Rect, TextKind, Ui, VectorcraftApp, json}; -/// Where the Contextual Task Bar was last drawn (none while it isn't shown). -pub(crate) fn task_bar_rect(ctx: &egui::Context) -> Option { - let id = task_bar_id(); - ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) -} +/// A memo of a check on the selection, kept for the document's `(uid, revision)`. +type Memo = Option<((u64, u64), bool)>; -/// Whether the Contextual Task Bar, where it was last drawn, held the font controls: on a canvas -/// too narrow for them it leaves them out. -pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { - task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) -} +/// An action of the bar: its label, icon, command and the command's params. +type Action = (&'static str, &'static str, &'static str, serde_json::Value); -/// The actions and chips the Contextual Task Bar offered where it was last drawn, before Bar -/// Actions left any out, as More Options › Bar Actions lists them: each one's name, its id in -/// [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it -/// shows. -pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(&'static str, Option<&'static str>, bool)> { - ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) +/// What the Contextual Task Bar offers for the tool and selection in use. +pub(crate) struct Offer { + /// The actions that show, after Bar Actions left any out. + pub actions: Vec, + /// Every action and chip offered, before Bar Actions left any out, for More › Bar Actions: each one's name, + /// its id in [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it shows. + pub listed: Vec<(&'static str, Option<&'static str>, bool)>, + /// The chips that show, after the action chips Bar Actions left out. + pub chips: Vec, + /// Whether the bar shows the font family, font style and Font Size controls. + pub fonts: bool, + /// The Smooth tool's Fidelity. + pub fidelity: Option, + /// The document points the bar hangs under: the corners of the selection, the picked artboards or the active + /// artboard, or the canvas's center on a blank canvas out of view. + pub anchor: Vec, + /// The live shape the Lock chip's properties popover shows. + pub shape: Option>, } /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, @@ -80,34 +92,32 @@ fn shape_tool_on_shape(app: &VectorcraftApp) -> bool { } /// Whether the Smooth tool is in use with a selected path it can smooth -/// ([`vectorcraft_tools::draw2::can_smooth`]). The answer is kept in `ctx` for the document's +/// ([`vectorcraft_tools::draw2::can_smooth`]). The answer is kept in `memo` for the document's /// revision, which moves with every change of the document or the selection, so an unchanged /// selection is not walked again each frame. -fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { +fn smooth_tool_on_paths(app: &VectorcraftApp, memo: &mut Memo) -> bool { if app.session.tool_id() != "smooth" { return false; } let Some(st) = app.session.active() else { return false }; - let id = task_bar_id().with("smooth"); let key = (st.uid, st.revision); - if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + if let Some((k, found)) = *memo && k == key { return found; } let found = vectorcraft_tools::draw2::can_smooth(&st.doc, &st.selection); - ctx.data_mut(|d| d.insert_temp(id, (key, found))); + *memo = Some((key, found)); found } /// Whether the selection holds images together with other objects, for which the bar offers Make /// Clipping Mask: at least one selected object is an image and at least one is not (a selected id /// with no object counts as not an image). The walk stops once it has seen both. The answer is kept -/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. -pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool { - let id = task_bar_id().with("mixed"); +/// in `memo` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. +pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, memo: &mut Memo) -> bool { let key = (st.uid, st.revision); - if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + if let Some((k, found)) = *memo && k == key { return found; @@ -121,7 +131,7 @@ pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egu } image && other }); - ctx.data_mut(|d| d.insert_temp(id, (key, found))); + *memo = Some((key, found)); found } @@ -135,30 +145,26 @@ fn blank_canvas(app: &VectorcraftApp) -> bool { && app.session.active().is_some_and(|st| st.selection.is_empty() && no_art(&st.doc.layers)) } -/// Where the bar's top edge centers, on screen: under the lowest corner on screen of the selected -/// artboards or the selection, centered on them (the view may be rotated); on a blank canvas, which -/// has no selection, [`blank_canvas_anchor`]. None with nothing to sit under. -fn bar_anchor(app: &mut VectorcraftApp, xf: &Xf, on_artboards: bool, blank: bool) -> Option { - if blank { - return Some(blank_canvas_anchor(app, xf)); - } - let b = if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }?; - let lowest = xf.quad(b).iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); - Some(pos2(xf.to_screen(b.center()).x, lowest)) +/// The four corners of `r`, in document points. +fn corners(r: Rect) -> Vec { + vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] } -/// Where the blank canvas bar's top edge centers, on screen: under the bottom of the active artboard -/// when part of it is in view, else the canvas's center. -fn blank_canvas_anchor(app: &VectorcraftApp, xf: &Xf) -> Pos2 { - let board = app.session.active().and_then(|st| { - let last = st.doc.artboards.len().checked_sub(1)?; - st.doc.artboards.get(app.view().map_or(0, |v| v.artboard).min(last)).map(|a| a.rect) - }); - let shown = board.map(|b| (b, xf.quad(b))).filter(|(_, q)| egui::Rect::from_points(q).intersects(xf.rect)); - match shown { - Some((b, q)) => pos2(xf.to_screen(b.center()).x, q.iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max)), - None => xf.rect.center(), +/// The document points the bar hangs under (the framework hangs it under the lowest of their corners on screen, +/// centred on them, so a rotated view keeps it below): the selected artboards or the selection; on a blank canvas, +/// which has no selection, the active artboard when part of it is in view, else the canvas's center. Empty with +/// nothing to sit under. +fn anchor(app: &mut VectorcraftApp, view: &CanvasView, on_artboards: bool, blank: bool) -> Vec { + if blank { + let board = app.session.active().and_then(|st| { + let last = st.doc.artboards.len().checked_sub(1)?; + st.doc.artboards.get(app.view().map_or(0, |v| v.artboard).min(last)).map(|a| a.rect) + }); + let shown = board.filter(|b| egui::Rect::from_points(&view.quad(*b)).intersects(view.rect)); + return shown.map_or_else(|| vec![view.to_doc(view.rect.center())], corners); } + let bounds = if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }; + bounds.map(corners).unwrap_or_default() } /// Whether a Type tool edits type, or has type selected: its bar then shows only the text @@ -169,33 +175,26 @@ fn type_tool_on_type(app: &VectorcraftApp) -> bool { /// Whether the Contextual Task Bar shows the font family, font style and Font Size controls: a /// Type tool edits or has selected type, or a selection tool has only type selected. -pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { +fn task_bar_shows_type(app: &VectorcraftApp) -> bool { type_tool_on_type(app) || (selection_tool_with_selection(app) && only_type_selected(app)) } -/// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. -/// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard -/// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). +/// What the Contextual Task Bar offers for the tool and selection in use, without the place it hangs at. The +/// per-tool rules: +/// With the Artboard tool it offers Resize (Artboard Options), Duplicate, Rearrange All (with two or more +/// artboards) and Export (Export for Screens). /// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// While a basic shape tool (Rectangle, Rounded Rectangle, Ellipse, Polygon or Star) has one closed /// path selected, as after it draws one, the bar offers Edit Path, Fill and Stroke, and Shape /// Properties for a live rectangle, rounded rectangle, ellipse or polygon; with nothing selected, or /// any other selection, those tools show no bar. While the Smooth tool has a path it can smooth /// selected, the bar shows the tool's Fidelity field and Tool Options…; with no such path it shows -/// no bar. Selected type also shows the font family, font -/// style and Font Size controls before its Fill. -/// While a Type tool edits type, or has type selected, the bar shows only those controls and the -/// Fill. When one row would be wider than the canvas, the font controls take a row of their own, -/// narrowed to fit it, and the actions wrap onto rows under the handle's ([`bar_layout`]). -/// On a blank canvas, a document with no artwork and a selection tool in use, it sits under the -/// active artboard and offers Draw (Pencil) and Place Image. -/// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the -/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions -/// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); -/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. With every -/// one of them off, the bar still shows its handle and More Options, where they turn back on. -pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { - let t = Tokens::get(ui.ctx()); +/// no bar. Selected type also shows the font family, font style and Font Size controls before its Fill. +/// While a Type tool edits type, or has type selected, the bar shows only those controls and the Fill. +/// On a blank canvas, a document with no artwork and a selection tool in use, it offers Draw (Pencil) +/// and Place Image. More › Bar Actions turns each action and chip off; the bar leaves out the ones +/// that are off. `None` where the bar is not shown. +fn offer(app: &VectorcraftApp, images_memo: &mut Memo, smooth_memo: &mut Memo) -> Option { let on_artboards = app.session.tool_id() == "artboard"; // Text added with a Type tool shows its formatting controls, as the help page describes // (). @@ -207,15 +206,14 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let shaping = shape_tool_on_shape(app); // The Smooth tool with a path to smooth offers its option, Fidelity, as the same help page // describes for the Smooth tool, and Tool Options… for its dialog. - let smoothing = smooth_tool_on_paths(app, ui.ctx()); + let smoothing = smooth_tool_on_paths(app, smooth_memo); if !(on_artboards || typing || blank || shaping || smoothing || selection_tool_with_selection(app)) { - return; + return None; } // Selected type has the font controls too, as the help page describes // (). let fonts = task_bar_shows_type(app); - let Some(anchor) = bar_anchor(app, xf, on_artboards, blank) else { return }; - let Some(st) = app.session.active() else { return }; + let st = app.session.active()?; let n = st.selection.len(); let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let is_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { .. })); @@ -228,7 +226,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { _ => None, }); // Images and vector art selected together: a clipping mask is the likely next step. - let mixed = n > 1 && images_with_other_art(st, ui.ctx()); + let mixed = n > 1 && images_with_other_art(st, images_memo); // An Image Trace object: the group the engine names "Image Trace", its source image first. let is_trace = is_group && first.as_ref().is_some_and(|f| { @@ -247,7 +245,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) }) .cloned(); - let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) + let mut items: Vec = vec![]; let none = || json!({}); // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); @@ -359,21 +357,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } items.push((tl!("Duplicate"), "copy", "edit.duplicate", none())); } - let paints = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); - let doc = st.uid; - // Every action and chip the bar offers here, with its name and its id in TASK_BAR_ACTIONS or - // TASK_BAR_CHIPS (none: Bar Actions cannot turn it off), for More Options › Bar Actions; the - // ones that are off there are left out of the bar. - let hidden = &app.ui.task_bar_hidden_actions; - let mut offered: Vec<(&'static str, Option<&'static str>)> = - items.iter().map(|(label, _, cmd, params)| (*label, action_id(cmd, params))).collect(); - items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); - let bounds = xf.rect.shrink(8.0); - // The canvas's width less the frame's margins and stroke. - let room = bounds.width() - BAR_FRAME; - // On a canvas too narrow for the type controls at their narrowest, the bar leaves them out. - let fonts = fonts && room >= crate::panels::character::task_bar_min_room(); // The selected objects' Fill, Stroke, Recolor Artwork (when they have colours to recolour) and // Lock (a basic shape's properties instead), left out with the Artboard tool and on a blank // canvas, which have no selected objects. A Type tool's bar has the Fill alone. A basic shape @@ -389,179 +373,165 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); - offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some()))))); - let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); - // Bar Actions reads this list through task_bar_offered while its menu is open. - let offered: Vec<(&'static str, Option<&'static str>, bool)> = - offered.into_iter().map(|(label, action)| (label, action, action.is_none_or(|a| !hidden.contains(a)))).collect(); - ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered)); - let any_hidden = !hidden.is_empty(); - let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); - let fidelity = app.session.tool_options()["fidelity"].as_f64(); - let font_w = fonts.then(|| { - let w = crate::panels::character::TASK_BAR_WIDTHS; - w.iter().sum::() + BAR_GAP * (w.len() - 1) as f32 - }); - let spacing = ui.spacing().item_spacing.y; - let chip_widths: Vec = chips.iter().map(|c| c.width()).collect(); - let layout = bar_layout(&widths, &chip_widths, font_w, room, bar_max_rows(bounds.height(), spacing)); - // On a canvas too small for its handle and More Options: no bar, rather than one that runs off - // the canvas. - let fonts = layout.as_ref().is_some_and(|l| l.fonts); - ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("fonts"), fonts)); - let Some(layout) = layout else { return }; - let est = layout.size(spacing); - // Its place under the selection, then where the handle moved it, kept on the canvas (with the - // bar's size last frame, the layout's size before it first shows and whenever the layout - // changed since, as after the canvas or the selection changed). - let under = pos2(anchor.x - est.x / 2.0, anchor.y + 28.0); - let id = task_bar_id(); - let unchanged = ui.ctx().data_mut(|d| { - let last = d.get_temp::(id.with("layout")); - d.insert_temp(id.with("layout"), est); - last == Some(est) - }); - let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).filter(|_| unchanged).unwrap_or(est); - let keep_in = |p: Pos2| p.clamp(bounds.min, (bounds.max - size).max(bounds.min)); - let place = &mut app.ui.task_bar_place; - // Just unpinned: follow the selection from the pinned spot. - if !place.pinned - && let Some(at) = place.pin_at.take() - { - place.offset = Some((doc, xf.rect.min + at - under)); - } - let pos = keep_in(match place.pin_at { - Some(at) => xf.rect.min + at, - None => under + place.offset.filter(|(d, _)| *d == doc).map_or(Vec2::ZERO, |(_, o)| o), - }); - place.shown_at = Some(pos - xf.rect.min); - // Pinned before it ever showed: hold it here. - if place.pinned && place.pin_at.is_none() { - place.pin_at = place.shown_at; - } - let pinned = place.pinned; - let mut moved = Vec2::ZERO; - let mut run: Option<(&str, serde_json::Value)> = None; - let mut show_swatches = false; - egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| { - egui::Frame::NONE - .fill(t.panel) - .stroke(Stroke::new(1.0, t.tool_active)) - .corner_radius(CornerRadius::same(5)) - .inner_margin(egui::Margin::symmetric(8, 6)) - .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) }) - .show(ui, |ui| { - // The first row holds the handle and More Options; actions that don't fit beside - // them go on the rows after it, in order. - for row in 0..layout.rows { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = BAR_GAP; - if row == 0 { - let (g, grip) = ui.allocate_exact_size(vec2(BAR_HANDLE, 28.0), Sense::drag()); - let active = grip.hovered() || grip.dragged(); - ui.painter().rect_filled( - g.shrink2(vec2(0.5, 4.0)), - CornerRadius::same(2), - if active { t.text_dim } else { t.button_border }, - ); - if grip.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - moved = grip.drag_delta(); - } else if grip.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); - } - } - for ((label, icon, cmd, params), at) in items.iter().zip(&layout.actions) { - if *at != Some(row) { - continue; - } - run = bar_item(ui, &t, (*label, *icon, *cmd, params), fidelity).or(run.take()); - } - // Type's font family, font style and Font Size, which act as the Character - // panel's do: on the characters a Type tool selects, else on the selected type. - if row == 0 && fonts && !layout.font_row { - crate::panels::character::task_bar(app, ui, f32::INFINITY); - } - for (chip, at) in chips.iter().zip(&layout.chips) { - if *at != row { - continue; - } - match paint_or_object_chip(app, ui, &t, *chip, &paints, shape.as_ref()) { - Some(ChipClick::Fill(fill)) => { - app.session.fill_active = fill; - show_swatches = true; - } - Some(ChipClick::Run(cmd)) => run = Some((cmd, json!({}))), - None => {} - } - } - if row != 0 { - return; - } - let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BAR_MORE); - egui::Popup::menu(&more).show(|ui| { - ui.set_min_width(170.0); - // The actions too wide for any row of the bar. - let listed = items.iter().zip(&layout.actions).filter(|(_, at)| at.is_none()); - let mut any = false; - for ((label, _, cmd, params), _) in listed { - any = true; - if widgets::menu_item_name(ui, label, true, false) { - run = Some((*cmd, params.clone())); - } - } - if any { - ui.separator(); - } - let bar = [ - (tl!("Hide Bar"), "window.taskBar", false), - (tl!("Pin Bar Position"), "window.taskBar.pin", pinned), - (tl!("Reset Bar Position"), "window.taskBar.reset", false), - ]; - for (label, cmd, checked) in bar { - if widgets::menu_item(ui, label, true, checked) { - run = Some((cmd, json!({}))); - } - } - // The actions and chips the bar offers for this selection or tool, each - // checked while it shows, which turns it on or off; then Reset Bar - // Actions, which shows every action again. - ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { - ui.set_min_width(170.0); - for (label, action, shown) in task_bar_offered(ui.ctx()) { - let Some(action) = action else { continue }; - if widgets::menu_item_name(ui, bar_action_name(label), true, shown) { - run = Some(("window.taskBar.actions", json!({ "action": action }))); - } - } - }); - if widgets::menu_item(ui, tl!("Reset Bar Actions"), any_hidden, false) { - run = Some(("window.taskBar.resetActions", json!({}))); - } - ui.separator(); - if widgets::menu_item(ui, tl!("Show Properties Panel"), true, false) { - run = Some(("window.panel", json!({"panel": "properties"}))); - } - }); - }); - } - if layout.font_row { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = BAR_GAP; - crate::panels::character::task_bar(app, ui, room); - }); - } - }); - }); - if moved != Vec2::ZERO { - let to = keep_in(pos + moved); - let place = &mut app.ui.task_bar_place; - if place.pinned { - place.pin_at = Some(to - xf.rect.min); - } else { - place.offset = Some((doc, to - under)); + let hidden = &app.ui.task_bar_hidden_actions; + let is_shown = |id: Option<&str>| id.is_none_or(|a| !hidden.contains(a)); + let mut listed: Vec<(&'static str, Option<&'static str>, bool)> = items + .iter() + .map(|(label, _, cmd, params)| { + let id = action_id(cmd, params); + (*label, id, is_shown(id)) + }) + .collect(); + items.retain(|(_, _, cmd, params)| is_shown(action_id(cmd, params))); + listed.extend(chips.iter().map(|c| { + let id = c.id(shape.is_some()); + (c.label(shape.is_some()), Some(id), is_shown(Some(id))) + })); + let chips = chips.into_iter().filter(|c| is_shown(Some(c.id(shape.is_some())))).collect(); + let fidelity = if smoothing { app.session.tool_options()["fidelity"].as_f64() } else { None }; + Some(Offer { actions: items, listed, chips, fonts, fidelity, anchor: vec![], shape }) +} + +/// What the bar offers and where it hangs, for this canvas view; `None` where it shows no bar. +pub(crate) fn offered(app: &mut VectorcraftApp) -> Option { + let view = app.canvas_view()?; + let (mut images, mut smooth) = (app.canvas.images_with_other_art, app.canvas.smooth_paths); + let offer = offer(app, &mut images, &mut smooth); + app.canvas.images_with_other_art = images; + app.canvas.smooth_paths = smooth; + let mut offer = offer?; + let on_artboards = app.session.tool_id() == "artboard"; + let blank = !on_artboards && blank_canvas(app); + offer.anchor = anchor(app, &view, on_artboards, blank); + (!offer.anchor.is_empty()).then_some(offer) +} + +/// Publishes the states of More › Bar Actions' rows: each action and chip the bar offers is named and checked while +/// it shows, and Reset Bar Actions is enabled while any is off. The commands are the ones `window.taskBar.actions` +/// and `window.taskBar.resetActions` run. +pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { + let (mut images, mut smooth) = (app.canvas.images_with_other_art, app.canvas.smooth_paths); + for (label, id, shown) in offer(app, &mut images, &mut smooth).into_iter().flat_map(|o| o.listed) { + if let Some(id) = id { + let command = CommandRef::with_params("window.taskBar.actions", json!({ "action": id })); + states.set(command, CommandState::new().title(bar_action_name(label)).checked(shown)); } - ui.ctx().request_repaint(); + } + states.set(CommandRef::new("window.taskBar.resetActions"), CommandState::new().enabled(!app.ui.task_bar_hidden_actions.is_empty())); +} + +/// The rows More Options shows after the framework's own: Bar Actions, Reset Bar Actions and Show Properties Panel. +fn more_rows(offer: &Offer) -> Vec { + let actions = offer + .listed + .iter() + .filter_map(|(_, id, _)| *id) + .map(|id| PanelRow::Command(CommandRef::with_params("window.taskBar.actions", json!({ "action": id })))) + .collect(); + vec![ + PanelRow::Submenu(Label::from(tl!("Bar Actions")), actions), + PanelRow::Command(CommandRef::new("window.taskBar.resetActions")), + PanelRow::Separator, + PanelRow::Command(CommandRef::with_params("window.panel", json!({"panel": "properties"}))), + ] +} + +/// The Contextual Task Bar: a floating pill under the selection with the most likely next actions +/// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the +/// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action +/// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the +/// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen. +pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + let offer = offered(app)?; + let key = (app.session.active()?.uid, false); + let mut local = app.ui.task_bar_place.for_key(key); + let before = local; + let paints = chip_paints(app, ui.ctx()); + let has_shape = offer.shape.is_some(); + // PLAN: `CanvasCache::shape_properties_open` is assumed (hub-w1): the Shape Properties popover's open state. + let mut shape_open = app.canvas.shape_properties_open; + let mut run: Option<(&'static str, serde_json::Value)> = None; + let mut show_swatches = false; + let shown = TaskBar::new(tl!("Contextual Task Bar"), &offer.anchor, Bind::bound(&mut local)).more_rows(more_rows(&offer)).show( + ui, + space.view.rect, + |ui, _| { + for (label, icon, cmd, params) in &offer.actions { + if *cmd == TASK_BAR_FIDELITY { + // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. + if let Some(v) = offer.fidelity { + // PLAN: assumed `freehand::fidelity_field` draws no label of its own + ui.label(*label); + if let Some(x) = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth").filter(|x| *x != v) { + run = Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))); + } + } + } else if Button::new(*label).icon(IconSpec::svg(IconId::new(*icon))).variant(Variant::GHOST).show(ui).clicked() { + run = Some((*cmd, params.clone())); + } + } + // Type's font family, font style and Font Size, which act as the Character panel's do: on the + // characters a Type tool selects, else on the selected type. + if offer.fonts { + crate::panels::character::task_bar(app, ui); + } + for chip in &offer.chips { + match chip { + Chip::Fill | Chip::Stroke => { + let stroke = *chip == Chip::Stroke; + let (paint, mixed) = if stroke { (&paints.1, paints.3) } else { (&paints.0, paints.2) }; + let value = if mixed { Mixed::Mixed } else { Mixed::Same(crate::paint_preview::well_paint(paint, &|_| None)) }; + // PLAN: assumed `Srgba: Default` for the chip's fallback colour, which a click never switches to. + let chip = PaintChip::new(chip.label(has_shape), Bind::given(value), Default::default()) + .popover(false) + .ring(stroke) + .selected(app.session.fill_active != stroke) + .show(ui); + if chip.clicked.is_some() { + app.session.fill_active = !stroke; + show_swatches = true; + } + } + Chip::Recolor => { + if IconButton::new(IconSpec::svg(IconId::new("palette"))).label(tl!("Recolor Artwork")).show(ui).clicked() { + run = Some(("ui.recolorDialog", json!({}))); + } + } + Chip::Lock => { + if let Some(shape) = &offer.shape + && let NodeKind::Path { live: Some(live), .. } = &shape.kind + { + // The shape's properties in a popover that stays open while its fields and its + // Corner dropdown are used. + let props = IconButton::new(IconSpec::svg(IconId::new("shapes"))).label(tl!("Shape Properties")).show(ui); + if props.clicked() { + shape_open = !shape_open; + } + let _ = Popover::new(tl!("Shape Properties"), Bind::bound(&mut shape_open)).opened_by(&props.response).show(ui, |ui, _| { + crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); + }); + } else { + // The Lock button is off in isolation mode, as Object › Lock › Selection is. + let lock = IconButton::new(IconSpec::svg(IconId::new("lock"))) + .label(tl!("Lock (⌘2)")) + .enabled(crate::menus::enabled(app, "object.lock")) + .show(ui); + if lock.clicked() { + run = Some(("object.lock", json!({}))); + } + } + } + } + } + }, + ); + let (rect, hide) = (shown.output.rect, shown.output.hide); + app.canvas.shape_properties_open = shape_open; + if local != before { + app.ui.task_bar_place.set(key, local); + } + if hide { + run = Some(("window.taskBar", json!({}))); } // The Swatches panel shows where it is docked, floating or closed. A panel in an icon column // toggles when activated, so an open flyout stays as it is. @@ -583,29 +553,16 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The convert buttons convert the direct-selected anchors, as the Control bar's buttons do. Some((TASK_BAR_TO_CORNER, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "corner"})), Some((TASK_BAR_TO_SMOOTH, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "smooth"})), - // Fidelity listed in More Options, on a canvas too narrow for its field: the Smooth tool's - // Tool Options, which show it. - Some((TASK_BAR_FIDELITY, _)) => crate::menus::invoke(app, "tool.options", json!({"tool": "smooth"})), Some((c, p)) => crate::menus::invoke(app, c, p), None => {} } + Some(rect) } -/// The width of the Contextual Task Bar's frame: its margins and stroke on both sides. -const BAR_FRAME: f32 = 18.0; -/// The gap between the bar's controls. -const BAR_GAP: f32 = 6.0; -/// The width of the bar's handle. -const BAR_HANDLE: f32 = 4.0; -/// The width of the bar's More Options button. -const BAR_MORE: f32 = 30.0; -/// The height of a row of the bar's controls. -const BAR_ROW: f32 = 30.0; - /// The controls the Contextual Task Bar shows after its actions: the Fill and Stroke chips, /// Recolor Artwork, and Lock or a basic shape's Shape Properties. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Chip { +pub(crate) enum Chip { Fill, Stroke, Recolor, @@ -613,13 +570,6 @@ enum Chip { } impl Chip { - fn width(self) -> f32 { - match self { - Chip::Fill | Chip::Stroke => 26.0, - Chip::Recolor | Chip::Lock => 30.0, - } - } - /// The chip's id in [`TASK_BAR_CHIPS`]; Lock is `shapeProperties` while it shows a basic /// `shape`'s properties. fn id(self, shape: bool) -> &'static str { @@ -727,233 +677,6 @@ pub(crate) fn read_hidden_task_bar_actions<'de, D: serde::Deserializer<'de>>(d: Ok(ids.filter(|id| is_task_bar_action(id)).map(str::to_string).collect()) } -/// What a click on one of the bar's [`Chip`]s does: make the Fill (`true`) or the Stroke active and -/// bring up Swatches, or run a command. -enum ChipClick { - Fill(bool), - Run(&'static str), -} - -/// Where each of the Contextual Task Bar's controls goes. -#[derive(Debug, PartialEq)] -struct BarLayout { - /// Each action's row (0 is the row with the handle and More Options), or `None` for an action - /// wider than a row or past the rows the canvas's height allows, which More Options lists - /// instead. - actions: Vec>, - /// Each chip's row. - chips: Vec, - /// Whether the bar shows the font controls it was given. - fonts: bool, - /// Whether the font controls take a row of their own, after the others. - font_row: bool, - /// The number of rows before the font controls' row. - rows: usize, - /// The bar's width, its frame included. - width: f32, -} - -impl BarLayout { - /// The bar's size, with `spacing` points between its rows. - fn size(&self, spacing: f32) -> Vec2 { - let rows = (self.rows + usize::from(self.font_row)) as f32; - vec2(self.width, rows * BAR_ROW + (rows - 1.0) * spacing + 14.0) - } -} - -/// How many rows of the Contextual Task Bar fit in `height` points, with `spacing` points between -/// them. -fn bar_max_rows(height: f32, spacing: f32) -> usize { - ((height - 14.0 + spacing) / (BAR_ROW + spacing)).floor().max(0.0) as usize -} - -/// The Contextual Task Bar's layout in `room` points (the canvas's width less the frame) and at -/// most `max_rows` rows, for actions and chips the given widths wide, and the font controls `fonts` -/// wide when shown. One row holds everything when it fits. Otherwise the font controls take a row -/// of their own, narrowed to the room, and the actions wrap: the first row keeps the handle, the -/// chips and More Options, and each action goes on the last row when it fits there, else on a new -/// row. When the handle, the chips and More Options don't fit in one row, the chips take rows of -/// their own after the actions. An action wider than a row, or one that would need a row past -/// `max_rows`, goes in More Options; without a row to spare the font controls are left out. `None` -/// when not even the handle and More Options, and the chips' rows, fit. -fn bar_layout(actions: &[f32], chips: &[f32], fonts: Option, room: f32, max_rows: usize) -> Option { - // Puts a control `w` wide on the last row when it fits there, else on a new row. - fn place(rows: &mut Vec, w: f32, room: f32) -> usize { - match rows.last_mut() { - Some(last) if *last + BAR_GAP + w <= room => *last += BAR_GAP + w, - _ => rows.push(w), - } - rows.len() - 1 - } - let ends = BAR_HANDLE + BAR_GAP + BAR_MORE; - if room < ends || max_rows == 0 { - return None; - } - let chips_w: f32 = chips.iter().map(|w| w + BAR_GAP).sum(); - let actions_w: f32 = actions.iter().map(|w| w + BAR_GAP).sum(); - let one_row = ends + chips_w + actions_w + fonts.map_or(0.0, |w| w + BAR_GAP); - if one_row <= room { - return Some(BarLayout { - actions: vec![Some(0); actions.len()], - chips: vec![0; chips.len()], - fonts: fonts.is_some(), - font_row: false, - rows: 1, - width: one_row + BAR_FRAME, - }); - } - let chips_first = ends + chips_w <= room; - let mut chip_rows = vec![]; - let chips: Vec = chips.iter().map(|w| if chips_first { 0 } else { place(&mut chip_rows, *w, room) }).collect(); - if 1 + chip_rows.len() > max_rows { - return None; - } - let font_row = fonts.is_some() && 1 + chip_rows.len() < max_rows; - let action_rows = max_rows - chip_rows.len() - usize::from(font_row); - let mut rows = vec![if chips_first { ends + chips_w } else { ends }]; - // Once an action needs a row past the last one, it and the actions after it go in More Options, - // keeping their order. - let mut full = false; - let actions: Vec> = actions - .iter() - .map(|w| { - if *w > room || full { - return None; - } - let mut next = rows.clone(); - let row = place(&mut next, *w, room); - full = row >= action_rows; - (!full).then(|| { - rows = next; - row - }) - }) - .collect(); - let chips = chips.into_iter().map(|row| if chips_first { 0 } else { rows.len() + row }).collect(); - let font_w = if font_row { fonts.map_or(0.0, |w| w.min(room)) } else { 0.0 }; - let width = rows.iter().chain(&chip_rows).fold(font_w, |a, b| a.max(*b)) + BAR_FRAME; - Some(BarLayout { actions, chips, fonts: font_row, font_row, rows: rows.len() + chip_rows.len(), width }) -} - -/// The width of the Contextual Task Bar's action button for `label`. -fn action_width(ui: &Ui, label: &str) -> f32 { - ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), Color32::PLACEHOLDER).size().x + 38.0 -} - -/// The width of the Smooth tool's Fidelity on the Contextual Task Bar: its label, the gap and the -/// field. -fn fidelity_width(ui: &Ui) -> f32 { - widgets::text_width(ui, fidelity_label(tl!("Fidelity:"), &Tokens::get(ui.ctx()))) + BAR_GAP + crate::dialogs::freehand::FIDELITY_FIELD_W -} - -/// The Fidelity field's label, `label`, as the bar draws it. -fn fidelity_label(label: &str, t: &Tokens) -> egui::RichText { - egui::RichText::new(label).size(13.0).color(t.text_strong) -} - -/// The width of the Contextual Task Bar's item `label` that runs `cmd`. -fn item_width(ui: &Ui, label: &str, cmd: &str) -> f32 { - match cmd { - TASK_BAR_FIDELITY => fidelity_width(ui), - _ if icon_only(cmd) => BAR_MORE, - _ => action_width(ui, label), - } -} - -/// One of the Contextual Task Bar's items, `label` with `icon`, which runs `cmd` with `params`, and -/// the Smooth tool's `fidelity`. Returns the command to run when it was used. -fn bar_item( - ui: &mut Ui, - t: &Tokens, - (label, icon, cmd, params): (&str, &str, &'static str, &serde_json::Value), - fidelity: Option, -) -> Option<(&'static str, serde_json::Value)> { - // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. - if cmd == TASK_BAR_FIDELITY { - return fidelity_slot(ui, t, label, fidelity); - } - // The convert buttons show their icon alone, named by their hover text, as the Control bar's do. - let clicked = if icon_only(cmd) { widgets::icon_button(ui, icon, label, false, BAR_MORE).clicked() } else { action_button(ui, t, label, icon) }; - clicked.then(|| (cmd, params.clone())) -} - -/// The Smooth tool's Fidelity on the Contextual Task Bar, `label` and a field showing the tool's -/// `fidelity` (nothing without one). Returns the command that sets a new value typed or stepped to. -fn fidelity_slot(ui: &mut Ui, t: &Tokens, label: &str, fidelity: Option) -> Option<(&'static str, serde_json::Value)> { - let v = fidelity?; - let x = fidelity_field(ui, t, label, v).filter(|x| *x != v)?; - Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))) -} - -/// The Smooth tool's Fidelity on the Contextual Task Bar: `label` and a field showing `v`, centered -/// in a row of the bar. Returns the value typed or stepped to. -fn fidelity_field(ui: &mut Ui, t: &Tokens, label: &str, v: f64) -> Option { - ui.allocate_ui_with_layout(vec2(fidelity_width(ui), BAR_ROW), egui::Layout::left_to_right(egui::Align::Center), |ui| { - widgets::field_label(ui, fidelity_label(label, t)); - crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth") - }) - .inner -} - -/// One of the Contextual Task Bar's action buttons: `icon` and `label`, named for screen readers. -/// Returns whether it was clicked. -fn action_button(ui: &mut Ui, t: &Tokens, label: &str, icon: &str) -> bool { - let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), t.text_strong); - let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x + 38.0, BAR_ROW), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); - if resp.hovered() { - ui.painter().rect_filled(r, CornerRadius::same(3), t.hover); - } - ui.painter().rect_stroke(r, CornerRadius::same(3), Stroke::new(1.0, t.button_border), StrokeKind::Inside); - crate::icons::paint(ui, icon, egui::Rect::from_min_size(r.min + vec2(8.0, 7.0), vec2(16.0, 16.0)), t.icon); - ui.painter().galley(pos2(r.left() + 30.0, r.center().y - galley.size().y / 2.0), galley, t.text_strong); - resp.clicked() -} - -/// One of the Contextual Task Bar's chips, with the Fill and Stroke `paints` ([`chip_paints`]) and -/// the basic `shape` whose properties take Lock's place. Returns what a click on it does. -fn paint_or_object_chip( - app: &mut VectorcraftApp, - ui: &mut Ui, - t: &Tokens, - chip: Chip, - paints: &(vectorcraft_color::Paint, vectorcraft_color::Paint, bool, bool), - shape: Option<&vectorcraft_doc::Node>, -) -> Option { - let (fill, stroke, fill_mixed, stroke_mixed) = paints; - match chip { - Chip::Fill => paint_chip(ui, t, fill, *fill_mixed, None, tl!("Fill")).then_some(ChipClick::Fill(true)), - // The Stroke chip, drawn as a ring as the Control bar's is. - Chip::Stroke => paint_chip(ui, t, stroke, *stroke_mixed, Some(4.0), tl!("Stroke")).then_some(ChipClick::Fill(false)), - Chip::Recolor => { - widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 30.0).clicked().then_some(ChipClick::Run("ui.recolorDialog")) - } - Chip::Lock => { - if let Some(shape) = shape - && let NodeKind::Path { live: Some(live), .. } = &shape.kind - { - // The shape's properties in a popover that stays open while its fields and its - // Corner dropdown are used. - let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); - widgets::popover(&props, props.clicked(), |ui| { - ui.set_min_width(250.0); - crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); - }); - None - } else { - // The Lock button is off in isolation mode, as Object › Lock › Selection is. - let lockable = crate::menus::enabled(app, "object.lock"); - widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked().then_some(ChipClick::Run("object.lock")) - } - } - } -} - -/// Whether the bar's item that runs `cmd` shows its icon alone: the anchor convert buttons. -fn icon_only(cmd: &str) -> bool { - matches!(cmd, TASK_BAR_TO_CORNER | TASK_BAR_TO_SMOOTH) -} - /// The paints the Fill and Stroke chips show, and whether each is mixed ("?"): the proxies', or /// while a Type tool edits type, the edited characters' fill, which a swatch picked then paints. pub(crate) fn chip_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, bool, bool) { @@ -968,21 +691,9 @@ pub(crate) fn chip_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (vectorc (fill, stroke, fill_mixed, stroke_mixed) } -/// One of the Contextual Task Bar's Fill and Stroke chips, showing `paint` ("?" when `mixed`, a -/// ring of `ring` points for the stroke), named `tip` for screen readers. Returns whether it was -/// clicked. -fn paint_chip(ui: &mut Ui, t: &Tokens, paint: &vectorcraft_color::Paint, mixed: bool, ring: Option, tip: &str) -> bool { - let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); - let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); - widgets::proxy_chip(ui, chip, paint, mixed, ring); - ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - resp.on_hover_text(tip).clicked() -} - /// The Contextual Task Bar's items with the Artboard tool in a document of `artboards` artboards: /// Resize, Duplicate, Rearrange All (with two or more) and Export. -fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>, artboards: usize) { +fn artboard_items(items: &mut Vec, artboards: usize) { // As in the reference app, the Artboard tool offers to resize, duplicate and export the // artboards (), // and to rearrange them (). @@ -996,7 +707,7 @@ fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, ser /// The Contextual Task Bar's Center on Top and Center on Bottom, as in the Type menu, for type on a /// closed path. -fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { +fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec) { for (label, icon, id) in [(tl!("Center on Top"), "dc-al-top", "type.pathCenter.top"), (tl!("Center on Bottom"), "dc-al-bottom", "type.pathCenter.bottom")] {