diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs index 4b560eeba6..8c14fc8333 100644 --- a/crates/ui-egui/src/canvas/contour_bar.rs +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -3,24 +3,29 @@ //! turns the live Contour into plain paths. It acts through `addon.contour.set` and //! `effect.expandAppearance`, so everything it does is a command with its own undo step. +use craft::behavior::overlay::{Align, Side}; +use craft_ui::bars::{Bar, BarKind}; +use craft_ui::buttons::Button; +use craft_ui::canvas::CanvasSpace; +use craft_ui::choice::Segmented; +use craft_ui::contract::overlay::{Anchor, Dismiss, Outside, Overlay, Place}; +use craft_ui::contract::{Bind, Entry}; +use craft_ui::display::Text; +use craft_ui::popover::Popover; +use craft_ui::runtime::env::Env; +use craft_ui::style::SurfaceKind; +use craft_ui::text::NumberField; use serde_json::Value; use vectorcraft_doc::{Node, NodeKind}; -use super::{CornerRadius, Stroke, Tokens, Ui, VectorcraftApp, Xf, json, pos2, vec2}; +use super::{Ui, VectorcraftApp, json, vec2}; /// The live effect a Contour is made of. const EFFECT: &str = "path.offsetPath"; - -fn bar_id() -> egui::Id { - egui::Id::unique("contour-bar") -} - -/// Where the Contour bar was last drawn (none while it isn't shown). -#[cfg(test)] -pub(super) fn 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 corner styles, as the Offset Path effect and the tool's `corners` option name them. +const SHARP: &str = "sharp"; +const ROUND: &str = "round"; +const SQUARE: &str = "square"; /// A selected Contour's distance and corner style, read from its Offset Path effect. struct Standing { @@ -32,15 +37,15 @@ fn standing(n: &Node) -> Option { let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; let offset = e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0); let corners = match e.params.get("joins").and_then(Value::as_str) { - Some("round") => "round", - Some("bevel") => "square", - _ => "sharp", + Some("round") => ROUND, + Some("bevel") => SQUARE, + _ => SHARP, }; Some(Standing { offset, corners }) } /// The Contour bar, over the selection's top edge (under it when the top is off the canvas). -pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { +pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { if app.session.tool_id() != "contour" { return; } @@ -58,61 +63,49 @@ pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } let stand = shapes.first().and_then(|n| standing(n)); drop(shapes); - let tool_corners = app.session.tool_options().get("corners").and_then(Value::as_str).unwrap_or("sharp").to_string(); - let corners = stand.as_ref().map_or(tool_corners.as_str(), |s| s.corners); + let tool_corners = app.session.tool_options().get("corners").and_then(Value::as_str).unwrap_or(SHARP).to_string(); + let corners = stand.as_ref().map_or_else(|| [SHARP, ROUND, SQUARE].into_iter().find(|c| *c == tool_corners).unwrap_or(SHARP), |s| s.corners); let shown = stand.as_ref().map_or(0.0, |s| s.offset); // A grown Contour reaches past the outline it was made from: keep the bar clear of it. let b = b.inflate(shown.max(0.0), shown.max(0.0)); - let t = Tokens::get(ui.ctx()); - let quad = xf.quad(b); - let top = quad.iter().map(|c| c.y).fold(f32::INFINITY, f32::min); - let bottom = quad.iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); - let size = egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size).unwrap_or(vec2(330.0, 40.0)); - let area = xf.rect.shrink(8.0); - let above = top - size.y - 12.0; - let y = if above >= area.top() { above } else { bottom + 12.0 }; - let at = pos2(xf.to_screen(b.center()).x - size.x / 2.0, y); - let at = at.clamp(area.min, (area.max - size).max(area.min)); + let gap = Env::of(ui).tokens.space.gap.section; + let selection = egui::Rect::from_points(&space.view.quad(b)); + // The gap is part of the anchor, so the bar keeps it above the selection and below it after a flip. + let hung = selection.expand2(vec2(0.0, gap)); + let area = space.view.rect.shrink(gap); + let corner_entries = [Entry::new(SHARP, tl!("Sharp")), Entry::new(ROUND, tl!("Round")), Entry::new(SQUARE, tl!("Square"))]; let mut run: Option<(&str, Value)> = None; - let mut corner_pick: Option<&str> = None; - egui::Area::new(bar_id()).order(egui::Order::Middle).fixed_pos(at).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: egui::Color32::from_black_alpha(70) }) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - ui.label(egui::RichText::new(tl!("Contour")).color(t.text_strong)); - // The distance: a drag or typed value is applied when it ends, as one step. - let key = egui::Id::unique("contour-bar-offset"); - let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or(shown); - let resp = ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt")); - if resp.dragged() || resp.has_focus() { - ui.data_mut(|d| d.insert_temp(key, v)); - } - if resp.drag_stopped() || resp.lost_focus() { - ui.data_mut(|d| d.remove_temp::(key)); - if (v - shown).abs() > 1e-9 { - run = Some(("addon.contour.set", json!({"offset": v, "corners": corners}))); - } - } - for (label, id) in [(tl!("Sharp"), "sharp"), (tl!("Round"), "round"), (tl!("Square"), "square")] { - if ui.selectable_label(corners == id, label).clicked() { - corner_pick = Some(id); - } - } - let bake = ui.add_enabled(stand.is_some(), egui::Button::new(tl!("Bake"))); - if bake.on_hover_text(tl!("Turn the Contour into plain paths")).clicked() { - run = Some(("effect.expandAppearance", json!({}))); - } - }); + let mut corner_pick: Option<&'static str> = None; + let _ = Popover::new("Contour", Bind::given(true)) + .content_surface() + .overlay(|_| { + Overlay::floating() + .modeless() + .bounds(area) + .place(Place::anchored(Anchor::Rect(hung), Side::Above, Align::Center).flipping_across()) + }) + .dismiss(Dismiss::new().outside(Outside::Keep)) + .escape(false) + .show(ui, |ui, _| { + let _ = Bar::new("Contour", BarKind::Tool).surface(SurfaceKind::Floating).show(ui, |ui, _| { + let _ = Text::new(tl!("Contour")).show(ui); + // The distance applies when its edit ends, as one step. + let distance = NumberField::new(tl!("Distance"), Bind::given(Some(shown))).unit("pt").range(-1e5..=1e5).step(0.5).show(ui); + if let Some(Some(v)) = distance.edit.events.committed() + && (v - shown).abs() > 1e-9 + { + run = Some(("addon.contour.set", json!({"offset": v, "corners": corners}))); + } + let pick = Segmented::new(tl!("Corners"), Bind::given(corners), &corner_entries).show(ui); + corner_pick = pick.events.committed().copied(); + let bake = Button::new(tl!("Bake")).enabled(stand.is_some()).tooltip(tl!("Turn the Contour into plain paths")).show(ui); + if bake.clicked() { + run = Some(("effect.expandAppearance", json!({}))); + } }); - }); + }); if let Some(id) = corner_pick { // The tool keeps the style for the next Contour; a selected Contour changes now. let mut result = app.run("tool.setOption", json!({"key": "corners", "value": id})); diff --git a/crates/ui-egui/src/free_transform.rs b/crates/ui-egui/src/free_transform.rs index 9240c1e529..80e77bb55f 100644 --- a/crates/ui-egui/src/free_transform.rs +++ b/crates/ui-egui/src/free_transform.rs @@ -4,224 +4,76 @@ //! Free Transform, Perspective Distort and Free Distort. It sets the tool's options through `tool.setOption` (`constrain`, `mode`), as agents //! do; the modifier keys keep working while dragging. -use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use craft::behavior::IconId; +use craft_ui::bars::{Bar, BarKind}; +use craft_ui::buttons::ToggleButton; +use craft_ui::canvas::CanvasSpace; +use craft_ui::contract::Bind; +use craft_ui::contract::overlay::Overlay; +use craft_ui::display::Divider; +use craft_ui::popover::Popover; +use craft_ui::runtime::env::Env; +use craft_ui::style::SurfaceKind; +use egui::{Ui, Vec2}; use serde_json::{Value, json}; +use std::num::NonZeroU8; use crate::VectorcraftApp; -use crate::theme::Tokens; /// The tool the widget belongs to. const TOOL: &str = "freeTransform"; -/// A button's side. -const BUTTON: f32 = 28.0; -/// What a button shows. -#[derive(Clone, Copy)] -enum Glyph { - /// An icon of the set. - Icon(&'static str), - /// A box narrower at the top than at the bottom, its corners marked. - Perspective, - /// A box with corners pulled every which way, its corners marked. - Distort, -} - -/// The tool's modes as its `mode` option names them, with their buttons. -fn modes() -> [(&'static str, Glyph, &'static str); 3] { +/// The tool's modes as its `mode` option names them, with their icons and tooltips. +fn modes() -> [(&'static str, &'static str, &'static str); 3] { [ - ("free", Glyph::Icon("dc-free-transform"), tl!("Free Transform")), - ("perspective", Glyph::Perspective, tl!("Perspective Distort")), - ("distort", Glyph::Distort, tl!("Free Distort")), + ("free", "dc-free-transform", tl!("Free Transform")), + ("perspective", "dc-perspective", tl!("Perspective Distort")), + ("distort", "dc-free-distort", tl!("Free Distort")), ] } -/// Where the widget was last drawn (none while it isn't shown). -pub(crate) fn rect(ctx: &egui::Context) -> Option { - let id = egui::Id::unique(TOOL); - ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) -} - -/// Show the widget in `canvas` (the canvas's area inside the rulers) while the Free Transform -/// tool is active. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &Ui, canvas: Rect) { +/// Show the widget at the top left of the canvas while the Free Transform tool is active. +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { if app.session.tool_id() != TOOL { return; } - let t = Tokens::get(ui.ctx()); let opts = app.session.tool_options(); let mode = opts["mode"].as_str().unwrap_or("free").to_string(); let constrain = opts["constrain"].as_bool().unwrap_or(false); + let canvas = space.view.rect; + let at = canvas.min + Vec2::splat(Env::of(ui).tokens.space.gap.section); let mut set: Option<(&str, Value)> = None; - egui::Area::new(egui::Id::unique(TOOL)).order(egui::Order::Middle).fixed_pos(canvas.min + vec2(10.0, 10.0)).show(ui.ctx(), |ui| { - egui::Frame::NONE - .fill(t.panel) - .stroke(Stroke::new(1.0, t.button_border)) - .corner_radius(CornerRadius::same(4)) - .inner_margin(egui::Margin::same(3)) - .shadow(egui::epaint::Shadow { offset: [0, 2], blur: 8, spread: 0, color: Color32::from_black_alpha(60) }) - .show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 2.0; - // Constrain shapes what the Free Transform and Free Distort modes do. - if button(ui, Glyph::Icon("link"), tl!("Constrain"), constrain, mode != "perspective") { - set = Some(("constrain", json!(!constrain))); - } - let (line, _) = ui.allocate_exact_size(vec2(BUTTON, 3.0), Sense::hover()); - ui.painter().hline(line.x_range().shrink(4.0), line.center().y, Stroke::new(1.0, t.button_border)); - for (name, glyph, tip) in modes() { - if button(ui, glyph, tip, mode == name, true) && mode != name { - set = Some(("mode", json!(name))); + let _ = Popover::new("Free Transform", Bind::given(true)) + .content_surface() + .overlay(|_| Overlay::floating().modeless().bounds(canvas).placed_at(at)) + .show(ui, |ui, _| { + let _ = Bar::new("Free Transform", BarKind::Tool) + .surface(SurfaceKind::Floating) + .rows(NonZeroU8::MIN.saturating_add(3)) + .show(ui, |ui, _| { + // Constrain shapes what the Free Transform and Free Distort modes do. + let toggle = ToggleButton::new(tl!("Constrain"), Bind::given(constrain)) + .icon(IconId::new("link")) + .icon_only() + .tooltip(tl!("Constrain")) + .enabled(mode != "perspective") + .show(ui); + if let Some(on) = toggle.events.committed() { + set = Some(("constrain", json!(on))); } - } - }); - }); + let _ = Divider::horizontal().show(ui); + for (name, icon, tip) in modes() { + let button = ToggleButton::new(tip, Bind::given(mode == name)).icon(IconId::new(icon)).icon_only().tooltip(tip).show(ui); + // A click on the mode that is on turns it off in the button; the option stays. + if button.events.committed() == Some(&true) && mode != name { + set = Some(("mode", json!(name))); + } + } + }); + }); if let Some((key, value)) = set && let Err(e) = app.run("tool.setOption", json!({ "key": key, "value": value })) { app.status(e); } } - -/// A square button showing `glyph`, highlighted when `on`, greyed and inert unless `enabled`. -/// Returns whether it was clicked. -fn button(ui: &mut Ui, glyph: Glyph, tip: &str, on: bool, enabled: bool) -> bool { - let t = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(BUTTON, BUTTON), if enabled { Sense::click() } else { Sense::hover() }); - let bg = if on && enabled { - t.tool_active - } else if enabled && resp.hovered() { - t.hover - } else { - Color32::TRANSPARENT - }; - ui.painter().rect_filled(rect, CornerRadius::same(3), bg); - let color = match (enabled, on) { - (false, _) => t.text_dim, - (true, true) => t.text, - (true, false) => t.icon, - }; - paint(ui, glyph, rect.shrink(6.0), color); - resp.on_hover_text(tip).clicked() && enabled -} - -/// Draw `glyph` in `r`. -fn paint(ui: &Ui, glyph: Glyph, r: Rect, color: Color32) { - let at = |x: f32, y: f32| pos2(r.left() + x * r.width(), r.top() + y * r.height()); - let quad: [Pos2; 4] = match glyph { - Glyph::Icon(name) => return crate::icons::paint(ui, name, r, color), - Glyph::Perspective => [at(0.3, 0.12), at(0.7, 0.12), at(0.95, 0.88), at(0.05, 0.88)], - Glyph::Distort => [at(0.08, 0.2), at(0.78, 0.06), at(0.94, 0.9), at(0.2, 0.76)], - }; - let (p, fill) = (ui.painter(), Tokens::get(ui.ctx()).panel); - p.add(egui::Shape::closed_line(quad.to_vec(), Stroke::new(1.3, color))); - for c in quad { - let mark = Rect::from_center_size(c, vec2(3.5, 3.5)); - p.rect_filled(mark, 0.0, fill); - p.rect_stroke(mark, 0.0, Stroke::new(1.0, color), StrokeKind::Middle); - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - use vectorcraft_engine::Session; - use vectorcraft_geom::Point; - - use super::*; - use crate::canvas::Xf; - - fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; - ctx.run_ui(raw, |ui| crate::canvas::show(app, ui)).textures_delta.clear(); - } - - /// A press and release at `at`, then a frame to settle. - fn click(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) { - let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(app, ctx, vec![egui::Event::PointerMoved(at), button(true)]); - frame(app, ctx, vec![button(false)]); - frame(app, ctx, vec![]); - } - - fn options(app: &VectorcraftApp) -> (String, bool) { - let o = app.session.tool_options(); - (o["mode"].as_str().unwrap_or_default().to_string(), o["constrain"].as_bool().unwrap_or_default()) - } - - /// The widget shows with the Free Transform tool only; its buttons set the mode and Constrain - /// (inert in Perspective Distort); a corner dragged in Free Distort moves that corner alone, and - /// with Constrain on it keeps to the diagonal through the opposite corner. - #[test] - fn the_widget_sets_the_mode_and_a_corner_drag_then_distorts() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap()["id"].clone(); - app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); - let ctx = egui::Context::default(); - app.select_tool("selection"); - frame(&mut app, &ctx, vec![]); - assert!(rect(&ctx).is_none(), "not with the Selection tool"); - app.select_tool(TOOL); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - let w = rect(&ctx).expect("the widget shows"); - let canvas = app.canvas_rect.unwrap(); - assert!(canvas.contains(w.min) && w.left() - canvas.left() < 20.0 && w.top() - canvas.top() < 20.0, "{w:?} in {canvas:?}"); - // Constrain, a rule, then Free Transform, Perspective Distort and Free Distort. - let at = |i: usize| { - let rule = if i > 0 { 3.0 + 2.0 } else { 0.0 }; - pos2(w.center().x, w.top() + 4.0 + BUTTON / 2.0 + i as f32 * (BUTTON + 2.0) + rule) - }; - assert_eq!(options(&app), ("free".into(), false)); - click(&mut app, &ctx, at(0)); - assert_eq!(options(&app), ("free".into(), true), "Constrain on"); - click(&mut app, &ctx, at(3)); - assert_eq!(options(&app), ("distort".into(), true)); - click(&mut app, &ctx, at(2)); - assert_eq!(options(&app).0, "perspective"); - click(&mut app, &ctx, at(0)); - assert_eq!(options(&app), ("perspective".into(), true), "Constrain is inert in Perspective Distort"); - click(&mut app, &ctx, at(3)); - // Free Distort with Constrain on: the top-left corner dragged by (-20, -10) keeps to the - // diagonal (-100, -60), so it moves by 2,600 / 13,600 of it, about (-19.1, -11.5). - let xf = Xf::new(canvas, app.view().unwrap()); - let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let drag = |app: &mut VectorcraftApp, from: Point, to: Point| { - let (from, to) = (xf.to_screen(from), xf.to_screen(to)); - frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); - frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) / 2.0)]); - frame(app, &ctx, vec![egui::Event::PointerMoved(to)]); - frame(app, &ctx, vec![button(to, false)]); - frame(app, &ctx, vec![]); - }; - let corners = |app: &VectorcraftApp| -> Vec { - let st = app.session.active().unwrap(); - let node = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); - node.path_data().unwrap().anchors().map(|(.., a)| a.p).collect() - }; - let has = |pts: &[Point], q: Point| pts.iter().any(|p| p.distance(q) < 0.5); - drag(&mut app, Point::new(100.0, 100.0), Point::new(80.0, 90.0)); - let k = (20.0 * 100.0 + 10.0 * 60.0) / (100.0f64 * 100.0 + 60.0 * 60.0); - let pts = corners(&app); - assert!( - has(&pts, Point::new(100.0 - 100.0 * k, 100.0 - 60.0 * k)) - && has(&pts, Point::new(200.0, 100.0)) - && has(&pts, Point::new(200.0, 160.0)) - && has(&pts, Point::new(100.0, 160.0)), - "{pts:?}" - ); - app.run("edit.undo", json!({})).unwrap(); - // Constrain off in Free Distort: the corner moves with the pointer. - click(&mut app, &ctx, at(0)); - assert_eq!(options(&app), ("distort".into(), false), "Constrain works in Free Distort"); - drag(&mut app, Point::new(100.0, 100.0), Point::new(80.0, 90.0)); - let pts = corners(&app); - assert!( - has(&pts, Point::new(80.0, 90.0)) - && has(&pts, Point::new(200.0, 100.0)) - && has(&pts, Point::new(200.0, 160.0)) - && has(&pts, Point::new(100.0, 160.0)), - "{pts:?}" - ); - assert_eq!(app.session.tool_id(), TOOL); - } -}