From cb366ee6bb37f3867ada26b9c358583aa5c84d53 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 17 Nov 2026 21:09:22 -0700 Subject: [PATCH] =?UTF-8?q?feat(shell):=20Modify=20=E2=80=BA=20Shape=20dia?= =?UTF-8?q?logs,=20the=20picker's=20eyedropper=20and=20Transform=20about?= =?UTF-8?q?=20(M1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expand Fill and Soften Fill Edges ask for a distance, direction and steps and remember them; the Modify › Shape items are enabled by what the selection has. While a colour picker popup is open the stage is its eyedropper: a chip shows the colour under the pointer, a click gives it to the picker, Esc closes it. Free Transform sends the transformation origin with turns, scales and skews, marks each object's own point, and Properties shows Transform about. --- src/app.rs | 69 ++++++++++++- src/colour.rs | 128 ++++++++++++++++++++++++- src/colour_panel.rs | 3 +- src/erasertool.rs | 46 +++++++++ src/main.rs | 3 +- src/menus.rs | 9 ++ src/panels.rs | 47 +++++++++ src/shape_dialogs.rs | 223 +++++++++++++++++++++++++++++++++++++++++++ src/stage.rs | 35 +++++-- 9 files changed, 550 insertions(+), 13 deletions(-) create mode 100644 src/shape_dialogs.rs diff --git a/src/app.rs b/src/app.rs index dc32b916..b7a65ea7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -387,6 +387,10 @@ pub struct App { /// Open this layer's colour popup on the next frame (screenshots, the audit). pub tl_color_open: Option, pub convert_last: crate::convert_symbol::Last, + /// Expand Fill or Soften Fill Edges while its dialog is open, and what each was last given + /// (ADR 0109). + pub shape_dialog: Option, + pub shape_last: crate::shape_dialogs::Last, pub show_about: bool, pub show_files: bool, pub show_licenses: bool, @@ -731,6 +735,8 @@ impl App { tl_header_spill: 0.0, tl_color_open: None, convert_last: Default::default(), + shape_dialog: None, + shape_last: Default::default(), show_about: false, show_files: false, show_licenses: false, @@ -1855,6 +1861,49 @@ impl App { self.run("layer.select", json!({"index": 0})); self.run("edit.select_all", json!({})); } + Some(which @ ("shapecommands" | "expandfill" | "softenfill")) => { + // Modify › Shape (ADR 0109) on a new layer: a dashed, tapering line converted to + // fills (selected: Properties shows a fill, no line), a star with its fill + // expanded, and a blob with a soft edge of twelve steps. "expandfill" and + // "softenfill" show their dialogs over a selected shape instead. + self.tool = Tool::Select; + self.run("layer.new", json!({"name": "Shapes"})); + self.run("draw.object_drawing", json!({"on": true})); + self.run("draw.star", json!({"cx": 760, "cy": 560, "outer": 70, "points": 5, "fill": "#f3d36b", "stroke": null})); + self.run("modify.expand_fill", json!({"distance": 14})); + self.run("draw.path", json!({"d": "M 880 600 C 880 500 1010 470 1070 540 C 1130 610 1080 680 990 670 C 930 664 880 650 880 600 Z", "fill": "#e8553b", "stroke": null})); + if which == "shapecommands" { + self.run("modify.soften_fill_edges", json!({"distance": 36, "steps": 12})); + self.run("draw.path", json!({"d": "M 80 620 C 200 480 300 720 420 580 C 500 490 600 520 660 640", "fill": null, "stroke": "#1b2a4a", "stroke_width": 18, "profile": "taper_end", "dash": [46, 16], "cap": "round"})); + self.run("modify.lines_to_fills", json!({})); + } else { + crate::shape_dialogs::open(self, if which == "expandfill" { crate::shape_dialogs::Kind::Expand } else { crate::shape_dialogs::Kind::Soften }); + } + } + Some("origins") => { + // Transformation origins (ADR 0109, #296): three hands, each an instance whose + // registration point is at one end, selected with Free Transform and turned a + // sixth of a turn each about its own point; Properties shows Transform about. + self.run("layer.new", json!({"name": "Hands"})); + self.run("draw.object_drawing", json!({"on": true})); + for (i, (x, y)) in [(260.0f32, 600.0f32), (560.0, 560.0), (860.0, 620.0)].into_iter().enumerate() { + self.run("draw.rect", json!({"x": x - 90.0, "y": y - 9.0, "w": 180, "h": 18, "radius": 9, "fill": "#1b2a4a", "stroke": null})); + if let Some(id) = self.run("modify.convert_to_symbol", json!({"name": format!("Hand {}", i + 1)})).and_then(|v| v["instance"].as_u64()) { + // i18n-exempt: a sample symbol name + self.run("symbol.edit", json!({"id": id})); + self.run("edit.select_all", json!({})); + self.run("element.translate", json!({"dx": 80, "dy": 0})); + self.run("symbol.exit", json!({})); + } + } + let layer = self.s.layer; + let ids: Vec = self.s.elements_on(layer).iter().map(|e| e.id.0).collect(); + self.run("element.select", json!({"ids": ids})); + self.tool = Tool::Transform; + self.run("modify.transform_origin", json!({"mode": "registration"})); + let (sin, cos) = (-60f32).to_radians().sin_cos(); + self.run("modify.transform", json!({"a": cos, "b": sin, "c": -sin, "d": cos, "e": 0, "f": 0, "origin": "registration"})); + } Some("points") => { // A pencil stroke and a pen path being edited, with one smooth point selected. let wave: Vec<[f32; 2]> = (0..=240).map(|i| [140.0 + i as f32 * 1.5, 330.0 + (i as f32 * 0.06).sin() * 28.0]).collect(); @@ -2901,7 +2950,7 @@ impl App { /// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause. pub fn modal_open(&self) -> bool { - self.prompt.is_some() || self.convert.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some() || self.templates.save.is_some() + self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some() || self.templates.save.is_some() } /// The single entry point for user-initiated commands: asks first when the engine says the @@ -3249,6 +3298,23 @@ impl App { crate::convert_symbol::open(self); return; } + // Modify › Shape › Expand Fill and Soften Fill Edges ask for a distance (ADR 0109). + if id == "modify.expand_fill" { + crate::shape_dialogs::open(self, crate::shape_dialogs::Kind::Expand); + return; + } + if id == "modify.soften_fill_edges" { + crate::shape_dialogs::open(self, crate::shape_dialogs::Kind::Soften); + return; + } + if id == "modify.transform_origin" { + // The key or the menu moves to the next mode, and says which it is. + if let Some(v) = self.run(id, json!({})) { + let mode = v["mode"].as_str().and_then(anicraft_engine::TransformOrigin::from_key).unwrap_or_default(); + self.status_ok(tr!("Transformation origin: {mode}.", mode = crate::panels::transform_origin_label(mode))); + } + return; + } if id == "edit.paste" { // Paste in the centre of what you are looking at. let c = self.view_center_stage(); @@ -4068,6 +4134,7 @@ impl App { crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); + crate::shape_dialogs::window(self, &ctx); crate::aids_dialog::window(self, &ctx); crate::templates::save_window(self, &ctx); crate::layer_props::window(self, &ctx); diff --git a/src/colour.rs b/src/colour.rs index 287d8f9b..195cd173 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -119,6 +119,69 @@ fn remember(ctx: &egui::Context, popup: Id, c: [u8; 3]) { }); } +/// The picker's eyedropper (ADR 0109, #288): while a picker popup is open, a click on the stage +/// takes the colour drawn there. The picker and the stage are apart in the interface, so they +/// meet here, by frame number: the picker says it is showing, the stage says the pointer is +/// over it and hands back what it sampled, and the picker takes that and closes. +#[derive(Clone, Copy, Default)] +struct Dropper { + /// The picker that showed last, and the frame it showed in. + open: Option<(Id, u64)>, + /// The frame the pointer was last over the stage with a picker open. + over_stage: Option, + /// A colour sampled from the stage for picker `.0`, and the frame it was sampled in. + picked: Option<(Id, [u8; 3], u64)>, +} + +fn dropper_id() -> Id { + Id::new("anicraft.colour.dropper") +} + +fn dropper(ctx: &egui::Context) -> Dropper { + ctx.data(|d| d.get_temp(dropper_id())).unwrap_or_default() +} + +/// Whether something recorded in frame `then` still counts: this frame or the one before (the +/// stage and the panels draw in either order). +fn fresh(ctx: &egui::Context, then: u64) -> bool { + ctx.cumulative_frame_nr().saturating_sub(then) <= 1 +} + +/// The picker that takes a colour clicked on the stage: one showing in a popup now. +pub(crate) fn picking(ctx: &egui::Context) -> Option { + dropper(ctx).open.filter(|(_, frame)| fresh(ctx, *frame)).map(|(id, _)| id) +} + +/// The stage, each frame the pointer is over it while a picker is open: the popup then stays +/// open through a click there. +pub(crate) fn over_stage(ctx: &egui::Context) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|d| d.get_temp_mut_or_default::(dropper_id()).over_stage = Some(frame)); +} + +/// The stage hands picker `to` the colour clicked on it. +pub(crate) fn pick_from_stage(ctx: &egui::Context, to: Id, c: [u8; 3]) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|d| d.get_temp_mut_or_default::(dropper_id()).picked = Some((to, c, frame))); + ctx.request_repaint(); +} + +/// The colour the stage handed picker `popup`, once (one never collected is dropped). +fn take_picked(ctx: &egui::Context, popup: Id) -> Option<[u8; 3]> { + let (to, c, frame) = dropper(ctx).picked?; + let stale = !fresh(ctx, frame); + if stale || to == popup { + ctx.data_mut(|d| d.get_temp_mut_or_default::(dropper_id()).picked = None); + } + (!stale && to == popup).then_some(c) +} + +/// How a picker popup closes: on a click outside it, except a click on the stage, which picks +/// a colour first (the picker closes itself once it has it). +pub(crate) fn close_behavior(ctx: &egui::Context) -> egui::PopupCloseBehavior { + if dropper(ctx).over_stage.is_some_and(|frame| fresh(ctx, frame)) { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClickOutside } +} + /// A new popup opening adds its first change as a new recent colour. pub(crate) fn new_session(ctx: &egui::Context) { ctx.data_mut(|d| d.get_temp_mut_or_default::(recent_id()).from = None); @@ -164,11 +227,18 @@ pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, c: &mut [u8; 4], a new_session(ui.ctx()); } let mut changed = false; - let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + let shown = egui::Popup::menu(anchor).id(popup).close_behavior(close_behavior(ui.ctx())).show(|ui| { changed = picker(ui, popup, c, alpha, none); }); - if let Some(r) = shown { - name_popup(&r.response, tr!("Colour picker")); + match shown { + Some(r) => name_popup(&r.response, tr!("Colour picker")), + // A tap that reached the stage and closed the popup in one frame still picks. + None => { + if let Some(p) = take_picked(ui.ctx(), popup) { + *c = [p[0], p[1], p[2], c[3]]; + changed = true; + } + } } changed } @@ -186,6 +256,16 @@ pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, let view_id = Id::new("anicraft.colour.view"); let mut view: View = ui.data(|d| d.get_temp(view_id)).unwrap_or_default(); let mut changed = false; + // The eyedropper: this picker is the one a click on the stage gives its colour to; the + // alpha stays as set (what is sampled is the colour as drawn, which is opaque). + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|d| d.get_temp_mut_or_default::(dropper_id()).open = Some((popup, frame))); + if let Some(p) = take_picked(ui.ctx(), popup) { + *c = [p[0], p[1], p[2], c[3]]; + remember(ui.ctx(), popup, p); + changed = true; + egui::Popup::close_all(ui.ctx()); + } ui.horizontal(|ui| { let before = view; ui.selectable_value(&mut view, View::Swatches, tr!("Swatches")).on_hover_text(tr!("The web-safe palette and the colours used lately")); @@ -232,6 +312,7 @@ pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, changed = true; } }); + ui.label(text(Type::Caption, tr!("Or click anything on the stage to take its colour."))); // Its own row, with the word on it. A bare percent beside the hex does not read as opacity. if alpha { ui.add_space(4.0); @@ -429,4 +510,45 @@ mod tests { } assert_eq!(list(&ctx).len(), RECENT, "bounded"); } + + #[test] + fn a_click_on_the_stage_gives_the_open_picker_its_colour_once() { + let ctx = egui::Context::default(); + let (a, b) = (Id::new("fill_popup"), Id::new("stroke_popup")); + let mut c = [10, 20, 30, 128]; + let mut frame = |ctx: &egui::Context, id: Id, c: &mut [u8; 4]| { + let mut changed = false; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| changed = picker(ui, id, c, true, None)); + out.textures_delta.clear(); + changed + }; + assert_eq!(picking(&ctx), None, "no picker, no eyedropper"); + assert_eq!(close_behavior(&ctx), egui::PopupCloseBehavior::CloseOnClickOutside); + // The picker shows: the stage is its eyedropper, and nothing has changed. + assert!(!frame(&ctx, a, &mut c)); + assert_eq!(picking(&ctx), Some(a)); + // The pointer over the stage keeps the popup open through the click that picks. + over_stage(&ctx); + assert_eq!(close_behavior(&ctx), egui::PopupCloseBehavior::IgnoreClicks); + // The stage hands over the colour clicked: the picker takes it, alpha kept, once. + pick_from_stage(&ctx, a, [200, 100, 50]); + assert!(frame(&ctx, a, &mut c)); + assert_eq!(c, [200, 100, 50, 128]); + assert!(ctx.data(|d| d.get_temp::(recent_id())).is_some_and(|r| r.colours.first() == Some(&[200, 100, 50])), "and it joins the colours used lately"); + assert!(!frame(&ctx, a, &mut c), "taken once"); + // Another picker doesn't take a colour meant for this one, and one never collected + // (the picker closed first) is dropped rather than turning up later. + pick_from_stage(&ctx, a, [1, 2, 3]); + let mut other = [9, 9, 9, 255]; + assert!(!frame(&ctx, b, &mut other)); + assert_eq!(other, [9, 9, 9, 255]); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + } + assert_eq!(picking(&ctx), None, "the picker closed: the stage is the tools' again"); + assert_eq!(close_behavior(&ctx), egui::PopupCloseBehavior::CloseOnClickOutside); + assert!(!frame(&ctx, a, &mut c)); + assert_eq!(c, [200, 100, 50, 128], "the stale colour is gone"); + } } diff --git a/src/colour_panel.rs b/src/colour_panel.rs index 3fdd60bc..6c622124 100644 --- a/src/colour_panel.rs +++ b/src/colour_panel.rs @@ -149,7 +149,8 @@ pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, paint: Option<&Pai crate::colour::new_session(ui.ctx()); } let mut edit = None; - let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + // A click on the stage while this is open picks a colour there (the picker's eyedropper). + let shown = egui::Popup::menu(anchor).id(popup).close_behavior(crate::colour::close_behavior(ui.ctx())).show(|ui| { edit = fill_picker(ui, popup, paint, bitmaps); }); if let Some(r) = shown { diff --git a/src/erasertool.rs b/src/erasertool.rs index 706afe28..bac9dad1 100644 --- a/src/erasertool.rs +++ b/src/erasertool.rs @@ -154,3 +154,49 @@ pub fn eyedropper(app: &mut App, p: Vec2, shift: bool, zoom: f32) { } app.tool = if into_fill { Tool::PaintBucket } else { Tool::InkBottle }; } + +/// The colour picker's eyedropper on the stage (ADR 0109, #288): while a picker popup is open, +/// the pointer over the stage is an eyedropper. A chip beside it shows the colour drawn under +/// it (`paint.sample`: fills, gradients, bitmaps, lines and effects, as the CPU renderer draws +/// them), and a click hands that colour to the picker, which takes it and closes. Escape closes +/// the picker without picking, like any popup. `at` is the pointer on screen and in the space +/// being edited; `zoom` is screen points per unit there. +pub fn picker_dropper(app: &mut App, ui: &egui::Ui, resp: &egui::Response, picker: egui::Id, at: Option<(Pos2, Vec2)>, zoom: f32) { + let Some((screen, p)) = at.filter(|_| resp.hovered()) else { return }; + let ctx = ui.ctx(); + crate::colour::over_stage(ctx); + ctx.set_cursor_icon(egui::CursorIcon::Crosshair); + // One screen pixel there; sampled again only when the pointer, the view or the document + // changes. + let scale = (zoom * ctx.pixels_per_point()).clamp(0.01, 64.0); + let key = (app.s.state, p.x.to_bits(), p.y.to_bits(), scale.to_bits()); + let cache = egui::Id::new("anicraft.stage.picker_dropper"); + type Sampled = ((anicraft_engine::StateId, u32, u32, u32), [u8; 3]); + let known: Option = ctx.data(|d| d.get_temp(cache)); + let rgb = match known.filter(|(k, _)| *k == key) { + Some((_, rgb)) => Some(rgb), + None => { + let sampled = app.s.execute("paint.sample", &json!({"x": p.x, "y": p.y, "scale": scale})).ok().and_then(|v| { + let byte = |k: &str| v[k].as_u64().and_then(|b| u8::try_from(b).ok()); + Some([byte("r")?, byte("g")?, byte("b")?]) + }); + if let Some(rgb) = sampled { + ctx.data_mut(|d| d.insert_temp::(cache, (key, rgb))); + } + sampled + } + }; + let Some(rgb) = rgb else { return }; + // The chip: the colour that a click takes, below and right of the pointer. + let chip = egui::Rect::from_min_size(screen + egui::vec2(14.0, 14.0), egui::vec2(20.0, 20.0)); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, cache)); + let colour = anicraft_engine::doc::Rgba::new(f32::from(rgb[0]) / 255.0, f32::from(rgb[1]) / 255.0, f32::from(rgb[2]) / 255.0, 1.0); + painter.rect_filled(chip.expand(1.0), crate::theme::T.rc(), crate::theme::T.text); + painter.rect_filled(chip, crate::theme::T.rc(), to_color32(colour)); + painter.rect_stroke(chip, crate::theme::T.rc(), egui::Stroke::new(1.0, crate::theme::T.panel), egui::StrokeKind::Inside); + if ui.input(|i| i.pointer.primary_clicked()) { + crate::colour::pick_from_stage(ctx, picker, rgb); + app.status_ok(tr!("Picked {colour} from the stage.", colour = crate::colour::to_hex([rgb[0], rgb[1], rgb[2], 255], false))); + } +} + diff --git a/src/main.rs b/src/main.rs index 62ad30dc..b09b22f3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -84,6 +84,7 @@ mod rich_edit; mod rulers; mod scale_grid; mod shape_envelope; +mod shape_dialogs; mod sound; mod shape_hints; mod stage; @@ -282,7 +283,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/menus.rs b/src/menus.rs index 5c0f1586..a48dc2eb 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -423,6 +423,10 @@ fn enabled(app: &App, id: &str) -> bool { "edit.undo" => app.s.can_undo(), "edit.redo" => app.s.can_redo(), "edit.delete" | "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" => !app.s.selection.is_empty(), + // Modify › Shape (ADR 0109): what the selection has for them. + "modify.lines_to_fills" => selected_shape(app, |sh| sh.stroke.is_some()), + "modify.expand_fill" => selected_shape(app, |sh| sh.fill.is_some()), + "modify.soften_fill_edges" => selected_shape(app, |sh| sh.fill.as_ref().is_some_and(|f| !matches!(f, anicraft_engine::doc::Paint::Bitmap { .. }))), "layer.delete" => app.s.timeline().layers.len() > 1, "scene.delete" => app.s.doc.scenes.len() > 1, // Ctrl+E opens the selected instance, or goes back to the document (ADR 0045). @@ -447,6 +451,11 @@ fn enabled(app: &App, id: &str) -> bool { } } +/// Whether a selected shape passes `has` (looked at only while a menu is open). +fn selected_shape(app: &App, has: impl Fn(&anicraft_engine::doc::Shape) -> bool) -> bool { + app.s.selected_elements().iter().any(|(_, e)| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if has(sh))) +} + /// Whether a registry command that switches a setting has it on (`None`: not a setting). fn checked(app: &App, id: &str) -> Option { match id { diff --git a/src/panels.rs b/src/panels.rs index f121fbb9..5a463e2f 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -799,6 +799,10 @@ pub(crate) fn properties(app: &mut App, ui: &mut egui::Ui) { if on != app.s.style.snap_objects { app.run("draw.snap_to_objects", json!({"on": on})); } + // What several selected objects turn and scale about (ADR 0109, #296). + if app.tool == Tool::Transform { + transform_origin_row(app, ui); + } }); } // ---- the camera, with the Camera tool or its layer active (ADR 0027) ---- @@ -862,6 +866,49 @@ fn blend_row(app: &mut App, ui: &mut egui::Ui, current: anicraft_engine::doc::Bl }); } +/// A transformation origin's name, as Properties and the status line show it. +pub(crate) fn transform_origin_label(mode: anicraft_engine::TransformOrigin) -> &'static str { + match mode { + anicraft_engine::TransformOrigin::Selection => tr!("The whole selection"), + anicraft_engine::TransformOrigin::Registration => tr!("Each object's own point"), + anicraft_engine::TransformOrigin::Center => tr!("Each object's centre"), + } +} + +/// What each transformation origin does, for its tooltip. +fn transform_origin_tip(mode: anicraft_engine::TransformOrigin) -> &'static str { + match mode { + anicraft_engine::TransformOrigin::Selection => tr!("The selected objects turn, scale and skew together, as one arrangement"), + anicraft_engine::TransformOrigin::Registration => tr!("Each selected object turns, scales and skews where it stands: a symbol or group about its registration point, anything else about its centre"), + anicraft_engine::TransformOrigin::Center => tr!("Each selected object turns, scales and skews about the centre of its own box"), + } +} + +/// The Free Transform tool's Transform about row: the mode stays as set from one selection to +/// the next (`modify.transform_origin`; the same command on a key moves to the next mode). +fn transform_origin_row(app: &mut App, ui: &mut egui::Ui) { + let current = app.s.style.transform_origin; + let key = app.keymap.primary("modify.transform_origin").map(crate::platform::shortcut_label).filter(|k| !k.is_empty()); + row_prose(ui, tr!("Transform about"), |ui| { + let tip = match &key { + Some(k) => tr!("What several selected objects are transformed about. {key} moves to the next choice.", key = k), + None => tr!("What several selected objects are transformed about. Give Modify › Transform › Next Transformation Origin a key in the shortcut editor to change it from the keyboard.").to_string(), + }; + egui::ComboBox::from_id_salt("prop_transform_origin") + .selected_text(transform_origin_label(current)) + .show_ui(ui, |ui| { + for mode in anicraft_engine::TransformOrigin::ALL { + if ui.selectable_label(mode == current, transform_origin_label(mode)).on_hover_text(transform_origin_tip(mode)).clicked() && mode != current { + app.run("modify.transform_origin", json!({"mode": mode.key()})); + } + } + }) + .response + .on_hover_text(tip) + .set_name(tr!("Transform about")); + }); +} + /// A symbol type's name, as the Properties panel shows it. pub(crate) fn symbol_kind_label(kind: SymbolKind) -> &'static str { match kind { diff --git a/src/shape_dialogs.rs b/src/shape_dialogs.rs new file mode 100644 index 00000000..25510e74 --- /dev/null +++ b/src/shape_dialogs.rs @@ -0,0 +1,223 @@ +//! Modify › Shape › Expand Fill… and Soften Fill Edges… (ADR 0109): Animate's two small dialogs. +//! Distance, direction and (for a soft edge) the number of steps; OK runs one +//! `modify.expand_fill` or `modify.soften_fill_edges`, one undo step. What was entered last is +//! offered again (view state), so a run of fills gets the same edge. + +use crate::a11y::Named; +use crate::app::App; +use crate::theme::{FORM_LABEL_DIALOG, Type, form_row, text, with_type}; +use anicraft_engine::cmds_shape::{DEFAULT_STEPS, MAX_DISTANCE}; +use anicraft_engine::geom::outline::MAX_SOFTEN_STEPS; +use egui::Key; +use serde_json::json; + +/// Which dialog. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Expand, + Soften, +} + +impl Kind { + fn command(self) -> &'static str { + match self { + Kind::Expand => "modify.expand_fill", + Kind::Soften => "modify.soften_fill_edges", + } + } +} + +/// What a dialog holds, and what the next one starts from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Values { + /// Stage pixels. + pub distance: f32, + pub steps: u32, + pub inset: bool, +} + +impl Default for Values { + /// Animate's: 4 px, 4 steps, Expand. + fn default() -> Self { + Values { distance: 4.0, steps: DEFAULT_STEPS, inset: false } + } +} + +/// The dialog while it is open. +pub struct ShapeDialog { + pub kind: Kind, + pub values: Values, + /// The distance field takes the keyboard on the first frame. + focus: bool, +} + +/// What each dialog was last given. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Last { + pub expand: Values, + pub soften: Values, +} + +/// Opens the dialog for the selection. With nothing selected the engine says so instead. +pub fn open(app: &mut App, kind: Kind) { + if app.s.selection.is_empty() { + app.request(kind.command(), json!({"distance": 1})); + return; + } + app.playing = false; + let values = match kind { + Kind::Expand => app.shape_last.expand, + Kind::Soften => app.shape_last.soften, + }; + app.shape_dialog = Some(ShapeDialog { kind, values, focus: true }); +} + +/// The command and params a dialog's values run. +pub fn params(kind: Kind, v: &Values) -> serde_json::Value { + let mut p = json!({"distance": v.distance.clamp(0.05, MAX_DISTANCE), "direction": if v.inset { "inset" } else { "expand" }}); + if kind == Kind::Soften { + p["steps"] = json!(v.steps.clamp(1, MAX_SOFTEN_STEPS)); + } + p +} + +pub fn window(app: &mut App, ctx: &egui::Context) { + let Some(d) = &mut app.shape_dialog else { return }; + let (mut submit, mut cancel) = (false, false); + let (title, id) = match d.kind { + Kind::Expand => (tr!("Expand Fill"), "expand_fill"), + Kind::Soften => (tr!("Soften Fill Edges"), "soften_fill_edges"), + }; + crate::windows::new(ctx, title).id(egui::Id::new(id)).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| { + ui.set_min_width(340.0); + form_row(ui, FORM_LABEL_DIALOG, tr!("Distance"), |ui| { + let tip = match d.kind { + Kind::Expand => tr!("How far the fill's edge moves, in stage pixels"), + Kind::Soften => tr!("How wide the soft edge is, in stage pixels"), + }; + let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut d.values.distance).range(0.05..=MAX_DISTANCE).suffix(" px").speed(0.25).max_decimals(2))).named(tr!("Distance")).on_hover_text(tip); + if d.focus { + r.request_focus(); + d.focus = false; + } + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + submit = true; + } + }); + if d.kind == Kind::Soften { + form_row(ui, FORM_LABEL_DIALOG, tr!("Steps"), |ui| { + let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut d.values.steps).range(1..=MAX_SOFTEN_STEPS).speed(0.1))) + .named(tr!("Number of steps")) + .on_hover_text(tr!("How many bands the soft edge is made of: more are smoother, and more shapes to draw")); + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + submit = true; + } + }); + } + form_row(ui, FORM_LABEL_DIALOG, tr!("Direction"), |ui| { + ui.vertical(|ui| { + let (out, inward) = match d.kind { + Kind::Expand => (tr!("The fill grows by the distance; its corners round"), tr!("The fill shrinks by the distance; its corners stay sharp")), + Kind::Soften => (tr!("The soft edge is added round the fill"), tr!("The soft edge is taken from the fill, which keeps its size")), + }; + ui.radio_value(&mut d.values.inset, false, tr!("Expand")).on_hover_text(out); + ui.radio_value(&mut d.values.inset, true, tr!("Inset")).on_hover_text(inward); + }); + }); + if d.kind == Kind::Soften { + ui.label(text(Type::Caption, tr!("Each step is a band of the fill's colour, fainter the farther out. Works best on a fill without an outline."))); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui.button(tr!("OK")).clicked() { + submit = true; + } + if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + cancel = true; + } + }); + }); + if submit { + accept(app); + } else if cancel { + app.shape_dialog = None; + } +} + +/// OK: runs the command with the dialog's values and remembers them for the next time. +fn accept(app: &mut App) { + let Some(d) = app.shape_dialog.take() else { return }; + match d.kind { + Kind::Expand => app.shape_last.expand = d.values, + Kind::Soften => app.shape_last.soften = d.values, + } + app.request(d.kind.command(), params(d.kind, &d.values)); +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::{Document, ElementKind}; + + fn app(ctx: &egui::Context) -> App { + let mut app = App::with_context(ctx, Session::new(Document::default()), Some(std::path::PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": "#3366cc", "stroke": null, "object": true})); + app + } + + fn shapes(app: &App) -> usize { + app.s.visible_elements().iter().filter(|e| matches!(e.kind, ElementKind::Shape(_))).count() + } + + #[test] + fn the_dialogs_run_their_commands_and_remember_what_was_entered() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + open(&mut app, Kind::Expand); + let d = app.shape_dialog.as_mut().expect("the dialog opens on a selection"); + assert_eq!(d.values, Values::default(), "Animate's defaults the first time"); + d.values = Values { distance: 12.0, steps: 9, inset: true }; + accept(&mut app); + assert!(app.shape_dialog.is_none()); + let b = app.s.selection_bounds(); + assert!((b.width() - 176.0).abs() < 0.01 && (b.height() - 76.0).abs() < 0.01, "inset by 12: {b:?}"); + assert_eq!(app.s.undo_label(), Some("Expand Fill…")); + // The next Expand Fill offers the same; Soften Fill Edges keeps its own. + open(&mut app, Kind::Expand); + assert_eq!(app.shape_dialog.as_ref().map(|d| d.values), Some(Values { distance: 12.0, steps: 9, inset: true })); + app.shape_dialog = None; + open(&mut app, Kind::Soften); + let d = app.shape_dialog.as_mut().expect("the dialog opens"); + assert_eq!(d.values, Values::default()); + d.values.steps = 3; + d.values.distance = 9.0; + accept(&mut app); + assert_eq!(shapes(&app), 4, "the fill and three bands"); + assert_eq!(app.shape_last.soften.steps, 3); + app.run("edit.undo", json!({})); + assert_eq!(shapes(&app), 1, "one undo step"); + } + + #[test] + fn the_dialogs_draw_without_changing_anything_and_need_a_selection() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + for kind in [Kind::Expand, Kind::Soften] { + open(&mut app, kind); + let before = app.s.doc.clone(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| window(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.shape_dialog.is_some()); + assert_eq!(app.s.doc, before); + app.shape_dialog = None; + } + // Nothing selected: no dialog; the engine says why. + app.run("edit.deselect", json!({})); + open(&mut app, Kind::Soften); + assert!(app.shape_dialog.is_none()); + // Values out of range are brought into it. + assert_eq!(params(Kind::Soften, &Values { distance: 0.0, steps: 900, inset: false }), json!({"distance": 0.05f32, "direction": "expand", "steps": 50})); + assert_eq!(params(Kind::Expand, &Values { distance: 5000.0, steps: 2, inset: true }), json!({"distance": 1000.0f32, "direction": "inset"})); + } +} diff --git a/src/stage.rs b/src/stage.rs index 7e52874e..c4c8c70e 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -203,6 +203,9 @@ fn tiles_for(z: f32, stage_px: (u32, u32), px: [f32; 4], margin: u32, bg: Option out } +/// Most selected elements whose own transformation points Free Transform marks (ADR 0109). +const MAX_ORIGIN_MARKS: usize = 400; + fn to_v(p: Pos2) -> Vec2 { Vec2::new(p.x, p.y) } @@ -215,7 +218,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::shape_envelope::settle(app); crate::camera_tool::tick(app, ui.ctx(), now); app.stage_cache.canvas = canvas; - let resp = ui.allocate_rect(canvas, Sense::click_and_drag()); + // While a colour picker popup is open the stage is its eyedropper (ADR 0109): a click + // picks the colour there instead of using the tool, so the tools get no presses. + let picker = crate::colour::picking(ui.ctx()); + let resp = ui.allocate_rect(canvas, if picker.is_some() { Sense::hover() } else { Sense::click_and_drag() }); // The drawing surface: Ctrl+F6 lands here, and screen readers hear the tool in hand. crate::a11y::anchor(ui, crate::a11y::Region::Stage, canvas, &resp); let ppp = ui.ctx().pixels_per_point(); @@ -407,6 +413,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { }; ui.ctx().set_cursor_icon(icon); } + if let Some(picker) = picker { + crate::erasertool::picker_dropper(app, ui, &resp, picker, pointer.map(|p| (p, to_v(to_stage(p)))), zoom); + } if resp.clicked() || resp.drag_started() || resp.secondary_clicked() { // Ctrl+X/C/V go back to artwork. @@ -593,7 +602,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let delta = total.mul(&inv); if delta.m.iter().zip(Affine::IDENTITY.m).any(|(a, b)| (a - b).abs() > 1e-6) { let [a, b, cc, d, e, f] = delta.m; - let ok = app.s.execute("modify.transform", &json!({"a": a, "b": b, "c": cc, "d": d, "e": e, "f": f})).is_ok(); + let mut p = json!({"a": a, "b": b, "c": cc, "d": d, "e": e, "f": f}); + // Turning, scaling and skewing follow the transformation origin (ADR + // 0109): each object about its own point. A move is the same for all. + if *kind != XfKind::Move { + p["origin"] = json!(app.s.style.transform_origin.key()); + } + let ok = app.s.execute("modify.transform", &p).is_ok(); if ok { *applied = total; } @@ -1262,11 +1277,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(hr, 0.0, Color32::WHITE); painter.rect_stroke(hr, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); } - // transformation point (centre) - let c = r.center(); - painter.circle(c, 4.0, Color32::WHITE, Stroke::new(1.0, T.selection)); - painter.line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], Stroke::new(1.0, T.selection)); - painter.line_segment([c - vec2(0.0, 6.0), c + vec2(0.0, 6.0)], Stroke::new(1.0, T.selection)); + // The transformation point: the box's centre, or, when each object is transformed + // about its own point (ADR 0109), every object's (past a few hundred objects the box + // alone shows, so a huge selection stays quick). + let mode = app.s.style.transform_origin; + let own = !multi && mode != anicraft_engine::TransformOrigin::Selection && app.s.selection.len() <= MAX_ORIGIN_MARKS; + let points: Vec = if own { anicraft_engine::transform_origins(&app.s, mode).into_iter().map(|(_, at)| to_screen(at)).collect() } else { vec![r.center()] }; + for c in points { + painter.circle(c, 4.0, Color32::WHITE, Stroke::new(1.0, T.selection)); + painter.line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], Stroke::new(1.0, T.selection)); + painter.line_segment([c - vec2(0.0, 6.0), c + vec2(0.0, 6.0)], Stroke::new(1.0, T.selection)); + } } crate::pathtools::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p))); crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));