diff --git a/Cargo.lock b/Cargo.lock index 8365b32a69..78306baae3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3282,6 +3282,7 @@ dependencies = [ "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", ] [[package]] @@ -6052,8 +6053,10 @@ dependencies = [ "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-core-text", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", "pollster 1.0.1", "raw-window-handle", "rfd", diff --git a/README.md b/README.md index bf358b2d78..fd45eb9cdd 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ doesn't write Affinity files. Current `.af` validation includes 33 pinned files, and every-board SVG/PDF/PSD export, with fixes for Affinity 3 artboards, source-backed JPEGs and text runs. [Scope and limits](crates/affinity/README.md); [source audit and remaining gaps](docs/affinity-validation.md). The interface -speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified Chinese, Spanish, French, Hungarian, Italian, Polish, Brazilian Portuguese, Russian, Swedish, Ukrainian, Finnish, Bulgarian, Greek, Czech and Georgian; +speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified Chinese, Spanish, French, Hungarian, Italian, Polish, Brazilian Portuguese, Russian, Swedish, Ukrainian, Finnish, Bulgarian, Greek, Czech, Georgian and Catalan; [localization-parity.md](docs/localization-parity.md) has the details. The scores are self-assessed from our code against public documentation; [target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them. diff --git a/ROADMAP.md b/ROADMAP.md index 28c15f3268..8a4d00db95 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -112,7 +112,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Korean | `ko` | full | 100% | | Vietnamese | `vi` | full | 100% | -Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Czech (catalog complete; render-site gaps reduced; native review pending). +Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md). ## Upcoming @@ -144,6 +144,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | Date | What landed | |---|---| +| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. | | 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. | | 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. | | 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. | @@ -198,6 +199,7 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. | diff --git a/apps/vectorcraft-web/index.html b/apps/vectorcraft-web/index.html index 42eaaf74e0..2ccfc271b0 100644 --- a/apps/vectorcraft-web/index.html +++ b/apps/vectorcraft-web/index.html @@ -9,6 +9,13 @@ VectorCraft + + + + + + + x"#); + let t = only_text(&d); + assert_eq!(t.first_style().fill.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000")); +} + #[test] fn css_selectors_reach_text() { let d = open( diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs index d79615cd89..656bf4a8bb 100644 --- a/crates/testkit/src/fixtures.rs +++ b/crates/testkit/src/fixtures.rs @@ -52,6 +52,38 @@ pub fn select(s: &mut Session, ids: &[NodeId]) { exec(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::>()})); } +/// Place `png` as `cut.png` with `params` (`file.place`'s, besides `name` and `dataBase64`), then +/// cut the placed image's pixel data short right after its first `IDAT` chunk's type, as a +/// document saved with a damaged image holds it: the header still reads, but the renderer can't +/// decode the image and draws nothing. Place refuses such a file, so tests cut a placed one. The +/// image is stored under the key of its new bytes. → `file.place`'s reply. +pub fn place_cut_png(s: &mut Session, png: &[u8], params: Value) -> Value { + let mut p = json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(png)}); + if let (Some(o), Value::Object(extra)) = (p.as_object_mut(), params) { + o.extend(extra); + } + let r = exec(s, "file.place", p); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Image(im)) = doc.node(id).map(|n| &n.kind) else { panic!("{id:?} is not an image") }; + let old = im.key.clone(); + let mut bytes = doc.images[&old].bytes.to_vec(); + let idat = bytes.windows(4).position(|w| w == b"IDAT").unwrap(); + bytes.truncate(idat + 8); + let cut = vectorcraft_doc::ImageBlob::new("image/png", bytes); + let key = cut.content_key(); + doc.images.insert(key.clone(), cut); + if let Some(Node { kind: NodeKind::Image(im), .. }) = doc.node_mut(id) { + im.key = key; + } + let mut shown = false; + doc.visit_images(|_, im| shown |= im.key == old); + if !shown { + doc.images.remove(&old); + } + r +} + /// The three standard fixture states for sweeping commands. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Fixture { diff --git a/crates/testkit/src/strategies.rs b/crates/testkit/src/strategies.rs index fe857506c6..4dbac8f6ec 100644 --- a/crates/testkit/src/strategies.rs +++ b/crates/testkit/src/strategies.rs @@ -141,6 +141,8 @@ pub enum Op { ClipRelease, Compound, CompoundRelease, + /// Make Compound Shape in one of the four shape modes, a member's mode, Release or Expand. + CompoundShape(u8), Lock, UnlockAll, Hide, @@ -238,6 +240,7 @@ fn arb_leaf_op() -> impl Strategy { 1 => Just(Op::ClipRelease), 1 => Just(Op::Compound), 1 => Just(Op::CompoundRelease), + 1 => (0u8..7).prop_map(Op::CompoundShape), 1 => Just(Op::Lock), 1 => Just(Op::UnlockAll), 1 => Just(Op::Hide), @@ -369,6 +372,15 @@ impl Op { Op::ClipRelease => c("object.clippingMask.release", json!({})), Op::Compound => c("object.compoundPath.make", json!({})), Op::CompoundRelease => c("object.compoundPath.release", json!({})), + Op::CompoundShape(i) => { + const MODES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; + match i % 7 { + i @ 0..4 => c("object.compoundShape.make", json!({"mode": MODES[i as usize]})), + 4 => c("object.compoundShape.setMode", json!({"mode": "exclude"})), + 5 => c("object.compoundShape.release", json!({})), + _ => c("object.compoundShape.expand", json!({})), + } + } Op::Lock => c("object.lock", json!({})), Op::UnlockAll => c("object.unlockAll", json!({})), Op::Hide => c("object.hide", json!({})), diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 6276f86cdc..758acc2c2e 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -214,6 +214,11 @@ impl FontFace { pub fn vertical_metrics(&self) -> (f64, f64) { (self.ascent, self.descent) } + /// The height of the lowercase letters in font units, positive (estimated from the ascent + /// when the font has no OS/2 value). + pub fn x_height(&self) -> f64 { + self.x_height + } /// The line gap the font asks for between lines, in font units (from the same table as /// [`vertical_metrics`](Self::vertical_metrics); 0 when it has none). pub fn line_gap(&self) -> f64 { diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index 9d1cc358c6..16aa674ca6 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -90,6 +90,26 @@ fn parse_exception(entry: &str) -> (String, Exception) { (word, Exception::Only(points)) } +/// Exception points count chars of the lowercased word; lowercasing can add chars ('İ' becomes +/// 'i' + U+0307), so map each point back to the char index in `word` it falls before. Points +/// inside one char's lowercase expansion are dropped; a point at the end of the word is kept. +fn lowercase_points_to_word(word: &str, pts: &[usize]) -> Vec { + let mut out = Vec::with_capacity(pts.len()); + let mut lower = 0; + let mut len = 0; + for (i, ch) in word.chars().enumerate() { + if pts.contains(&lower) { + out.push(i); + } + lower += ch.to_lowercase().count(); + len = i + 1; + } + if pts.contains(&lower) { + out.push(len); + } + out +} + fn normalize_word(word: &str) -> String { word.chars().flat_map(|c| c.to_lowercase()).collect() } @@ -140,7 +160,7 @@ pub fn hyphen_points_with(word: &str, opts: &HyphenationOptions) -> Vec { if let Some(ex) = exception_for(word) { return match ex { Exception::Never => vec![], - Exception::Only(pts) => pts, + Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; } let c: Vec = word.chars().collect(); @@ -243,6 +263,17 @@ mod tests { assert_eq!(hyphen_points("typography"), pattern, "override cleared"); } + /// Exception break points are char indices into the word itself, even when lowercasing + /// changes the char count ('İ' lowercases to 'i' + U+0307). + #[test] + fn exception_points_index_the_original_word() { + with_exceptions("İs-tan-bul", || { + assert_eq!(hyphen_points("İstanbul"), vec![2, 5]); + assert_eq!(hyphenate_word("İstanbul"), "İs-tan-bul"); + assert_eq!(hyphenate_word("İSTANBUL"), "İS-TAN-BUL"); + }); + } + /// The default Hyphenation options are the limits of [`hyphen_points`]: words of 6 letters or /// more, 3 letters on each side of the hyphen. #[test] diff --git a/crates/text/src/justify.rs b/crates/text/src/justify.rs index 33fbe91b36..ef7f13be80 100644 --- a/crates/text/src/justify.rs +++ b/crates/text/src/justify.rs @@ -55,7 +55,7 @@ pub(crate) fn is_word_space(g: &SGlyph) -> bool { /// A glyph letter spacing follows: a visible glyph followed by another one in the same word. fn letter_gap(g: &SGlyph, next: Option<&SGlyph>) -> bool { - !g.is_space() && g.inline.is_none() && next.is_some_and(|n| !n.is_space()) + !g.is_space() && g.ch != '\u{2028}' && g.inline.is_none() && next.is_some_and(|n| !n.is_space() && n.ch != '\u{2028}') } /// The width of a word space in `g`'s font and size: what letter spacing is a share of. @@ -83,7 +83,7 @@ pub(crate) fn apply_desired(sg: &mut [SGlyph], j: &JustificationOptions, scale_g f.word = (base * (w_max - w_des).max(0.0), base * (w_des - w_min).max(0.0)); continue; } - if g.is_space() || g.inline.is_some() { + if g.is_space() || g.inline.is_some() || g.ch == '\u{2028}' { continue; } let base = g.adv; diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 838940ddb2..66cdaf304d 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -182,7 +182,7 @@ impl Ctx<'_> { fn emit(&mut self, g: &SGlyph, pre: Affine, origin: Point, angle: f64, advance: f64, line: usize) { // Control characters (tabs) and soft hyphens draw nothing (fonts map them to .notdef). - let blank = g.is_soft_hyphen() || g.ch.is_control(); + let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}'; // A colour glyph draws its art (COLR layers, an SVG document) or its image (a bitmap, or // COLR paints documents have no form for), not its outline; COLR, then SVG, then bitmaps. // Art in the text's colours takes the run's fill (black when it isn't a colour) and @@ -216,6 +216,12 @@ impl Ctx<'_> { Affine::rotate(-g.rotation.to_radians()) * Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy) } }; + let unturned = if g.inline.is_none() && g.rotation != 0.0 && g.sx != 0.0 && g.sy != 0.0 { + let placed = Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy); + placed.inverse() * Affine::rotate(g.rotation.to_radians()) * placed + } else { + Affine::IDENTITY + }; let mut m = pre * local; if self.vertical && self.on_path { // Vertical path type keeps the baseline path and turns each glyph across it. @@ -271,6 +277,7 @@ impl Ctx<'_> { image, colour, bend: None, + unturned, }); } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 0b9251e831..b83640d029 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -169,7 +169,7 @@ impl Pen<'_> { pub(super) fn tab_advance<'t>(tabs: &'t [vectorcraft_doc::TabStop], origin: f64, x: f64, rest: &[SGlyph]) -> (f64, &'t str) { use vectorcraft_doc::TabAlign; let rel = x - origin; - let seg: Vec<&SGlyph> = rest.iter().take_while(|g| g.ch != '\t').collect(); + let seg: Vec<&SGlyph> = rest.iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect(); let width: f64 = seg.iter().map(|g| g.adv).sum(); let target = |pos: f64, align: TabAlign, on: char| match align { TabAlign::Left => pos, @@ -282,6 +282,9 @@ pub(super) fn break_line( kinsoku: Kinsoku, ) -> (usize, bool) { if !width.is_finite() { + if let Some(pos) = g[i..].iter().position(|gl| gl.ch == '\u{2028}') { + return (i + pos + 1, false); + } return (g.len(), false); } let mut x = 0.0; @@ -297,9 +300,9 @@ pub(super) fn break_line( cluster_end += 1; } // No Break: the marked characters stay on one line, including across a space inside the run. - if gl.no_break { + if gl.no_break && gl.ch != '\u{2028}' { while let Some(n) = g.get(cluster_end) { - if !n.no_break { + if !n.no_break || n.ch == '\u{2028}' { break; } let b = n.byte; @@ -314,6 +317,9 @@ pub(super) fn break_line( } else { g[j..cluster_end].iter().map(|glyph| glyph.adv).sum() }; + if gl.ch == '\u{2028}' { + return (cluster_end, false); + } if j > first && !gl.is_space() && x + cluster_width > width + EPS { // It ends the line with the spaces after it. if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1, kinsoku) { diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 957aa913cc..03c2eb3c40 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -36,7 +36,15 @@ fn compose_para( // can't follow: such a paragraph is broken line by line ([`break_line`] measures its tabs). // The tab after a list marker always starts the first line and has a fixed width. let has_tab = sg.iter().any(|g| g.ch == '\t' && g.len > 0); - if composer != Composer::EveryLine || pen.regions.is_none() || sg.len() < 2 || sg.len() > MAX_COMPOSE_GLYPHS || may_hang || has_tab { + let has_soft_break = sg.iter().any(|g| g.ch == '\u{2028}'); + if composer != Composer::EveryLine + || pen.regions.is_none() + || sg.len() < 2 + || sg.len() > MAX_COMPOSE_GLYPHS + || may_hang + || has_tab + || has_soft_break + { return None; } let m = Metrics::of(&sg[0]); @@ -382,7 +390,15 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut let mut hyphen_run = 0; let mut line_in_paragraph = 0; let mut index = 0; + let mut emitted_empty_continuation = false; loop { + let pm = if index >= n + && let Some(last) = paragraph.sg.last() + { + Metrics::of(last) + } else { + paragraph.pm + }; let mut placement = PlacementContext { para: paragraph.para, pr: ¶graph.pr, @@ -390,7 +406,7 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut continued: paragraph.continued, rtl: paragraph.rtl, mirror: paragraph.mirror, - pm: paragraph.pm, + pm, composed: ¶graph.composed, hyphen_run, hyphen_limit: paragraph.hyphen_limit, @@ -407,7 +423,13 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut line_in_paragraph += 1; index = geometry.position.end; if index >= n { - break; + if emitted_empty_continuation { + break; + } + emitted_empty_continuation = paragraph.sg.last().is_some_and(|g| g.ch == '\u{2028}'); + if !emitted_empty_continuation { + break; + } } } pen.pending += paragraph.para.space_after; @@ -422,7 +444,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData if paragraph.regions.is_some() { (position.x0 + position.ind_l, position.x1 - position.ind_r) } else { (position.x0, position.x1) }; let width = ax1 - ax0; let mut trimmed = position.end; - while trimmed > index && sg[trimmed - 1].is_space() { + while trimmed > index && (sg[trimmed - 1].is_space() || sg[trimmed - 1].ch == '\u{2028}') { trimmed -= 1; } let hyphen = (position.hyph && position.end > index).then(|| hyphen_glyph(&sg[position.end - 1])); @@ -521,7 +543,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData // Justification adds nothing to the list marker's glyphs. let mut held = held; held.extend(index..paragraph.marker.min(body)); - let last_of_para = position.end >= n; + let last_of_para = position.end >= n || position.end.checked_sub(1).and_then(|i| sg.get(i)).is_some_and(|g| g.ch == '\u{2028}'); LineGeometry { position, index, @@ -786,16 +808,21 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData } else { position.m.first_baseline(pen.fb, pen.fb_min) }, - start: if index < sg.len() { sg[index].byte } else { paragraph.pr.start }, - end: if line.last_of_para { paragraph.pr.end } else { sg[position.end].byte }, + start: if index < sg.len() { sg[index].byte } else { paragraph.pr.end }, + end: if position.end >= sg.len() { paragraph.pr.end } else { sg[position.end].byte }, glyph_start, glyph_end: cx.out.glyphs.len(), avail: if paragraph.regions.is_some() { (ax0, ax1) } else { (start_x, x_end) }, region: if paragraph.regions.is_some() { pen.ri } else { 0 }, }); pen.settled(position.baseline, position.m); - // Further spans of this line band share the settled baseline. - for queued in &mut pen.queued { - queued.0 = position.baseline; + let forced_break = position.end > index && sg.get(position.end - 1).is_some_and(|g| g.ch == '\u{2028}'); + if forced_break { + pen.queued.clear(); + } else { + // Further spans of this line band share the settled baseline. + for queued in &mut pen.queued { + queued.0 = position.baseline; + } } } diff --git a/crates/text/src/layout/ruby.rs b/crates/text/src/layout/ruby.rs index 4f2c76fe22..54681da89d 100644 --- a/crates/text/src/layout/ruby.rs +++ b/crates/text/src/layout/ruby.rs @@ -367,5 +367,6 @@ fn ruby_glyph(g: &PositionedGlyph, m: Affine, run: usize, byte: usize, line: usi image: None, colour: None, bend: None, + unturned: Affine::IDENTITY, } } diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 4ce9f03d8d..0953ae6567 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -1,6 +1,6 @@ use super::flow::flow; use super::region::Region; -use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Shape, Tcy, TextLayout, TextObject, VerticalAlign, is_cjk, punct}; +use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject, VerticalAlign, is_cjk, punct}; /// System Layout on or Fractional Widths off: each character that takes space advances by a whole /// number of points, at least one, so small type does not collapse onto itself. A zero advance (a @@ -23,7 +23,7 @@ pub(super) fn whole_character_widths(glyphs: &mut [SGlyph]) { /// before the automatic digit rule. /// pub(super) fn tate_chu_yoko(g: &mut [SGlyph], style: impl Fn(&SGlyph) -> (f64, bool)) { - let manual: Vec = g.iter().map(|gl| style(gl).1).collect(); + let manual: Vec = g.iter().map(|gl| gl.ch != '\u{2028}' && style(gl).1).collect(); let digits: Vec = g.iter().map(|gl| gl.inline.is_none() && gl.ch.is_ascii_digit()).collect(); let mut i = 0; while i < g.len() { @@ -242,28 +242,8 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool { pub(super) fn finish_bounds(out: &mut TextLayout) { let xf = out.line_xf; - let mut b: Option = None; + let mut b: Option = out.ink_bounds(); let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r))); - for g in &out.glyphs { - if !g.outline.elements().is_empty() { - add(g.outline.bounding_box()); - } - if let Some((image, xf)) = g.placed_image() { - add(xf.transform_rect_bbox(image.rect())); - } - if let Some(b) = g.colour.as_ref().and_then(|c| c.geometric_bounds()) { - add(g.xf.transform_rect_bbox(b)); - } - } - // Ruby: covered by its line's ascent, but its ink can overhang sideways past the line. - for g in &out.ruby { - if !g.outline.elements().is_empty() { - add(g.outline.bounding_box()); - } - } - for i in &out.inlines { - add(i.bounds); - } if !out.on_path { for l in &out.lines { add(xf.transform_rect_bbox(Rect::new(l.x0.min(l.x1), l.baseline - l.ascent, l.x0.max(l.x1), l.baseline + l.descent))); diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 4299e61d22..8524a5962f 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -43,7 +43,7 @@ pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; use std::sync::Arc; pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; -use kurbo::{Affine, BezPath, Point, Rect, Vec2}; +use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, fit_first_line, layout, layout_with, scaled}; pub use vectorcraft_doc::TextObject; @@ -136,6 +136,9 @@ pub struct PositionedGlyph { /// the path ([`GlyphBend`]) so it meets its neighbours, and `xf` is only the straight glyph /// nearest it (for the caret, hit testing and tools). `None`: the glyph is drawn through `xf`. pub bend: Option, + /// Font units → font units: `xf * unturned` places the glyph as it would be placed without + /// its Character Rotation. The identity for a glyph without one. + pub unturned: Affine, } /// How a glyph on a path is bent along it: a point of its pen space (x along its advance from its @@ -338,6 +341,21 @@ impl TextLayout { }; self.lines.iter().filter(|l| l.x1 > l.x0).map(line).collect() } + /// The ink of the type in text space: its glyphs (and ruby) as drawn, colour glyphs, images and + /// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers. + /// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text). + pub fn ink_bounds(&self) -> Option { + let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box()); + let glyphs = self.glyphs.iter().flat_map(|g| { + let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect())); + let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b)); + [outlined(g), image, colour] + }); + // Ruby is covered by its line's ascent, but its ink can overhang sideways past the line. + let ruby = self.ruby.iter().map(outlined); + let inlines = self.inlines.iter().map(|i| Some(i.bounds)); + glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b)) + } /// All glyph outlines combined (e.g. for Create Outlines). pub fn to_bezpath(&self) -> BezPath { let mut p = BezPath::new(); diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index e833d95dbf..2c79099b4b 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -5,12 +5,14 @@ use std::sync::Arc; use unicode_bidi::Level; use unicode_script::{Script, UnicodeScript}; +use unicode_segmentation::UnicodeSegmentation; use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; use skrifa::MetadataProvider; +use skrifa::charmap::Charmap; use skrifa::instance::Size; use vectorcraft_doc::text::INLINE_CHAR; -use vectorcraft_doc::{CharStyle, InlineArt}; +use vectorcraft_doc::{CharStyle, Digits, InlineArt}; use crate::features::{OtFeatures, ligatures_suppressed_by}; use crate::fontdb::{FontDb, FontFace}; @@ -132,7 +134,10 @@ impl SGlyph { } /// A line may break after this glyph. pub fn break_after(&self) -> bool { - self.is_space() || self.word_end || matches!(self.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/' | SOFT_HYPHEN) || is_cjk(self.ch) + self.is_space() + || self.word_end + || matches!(self.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/' | SOFT_HYPHEN | '\u{2028}') + || is_cjk(self.ch) } /// A soft (discretionary) hyphen: invisible unless a line breaks after it. pub fn is_soft_hyphen(&self) -> bool { @@ -393,24 +398,23 @@ pub(crate) fn shape_range( let small_caps = st.small_caps.is_some() && !st.all_caps; // Split into segments by font coverage (and case, for Small Caps). let mut seg = Segment { range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) }; - let mut cache: std::collections::HashMap> = std::collections::HashMap::new(); + let mut cache: std::collections::HashMap<&str, Arc> = std::collections::HashMap::new(); let mut script = Script::Common; - for (i, c) in text[a..b].char_indices() { + // A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face. + for (i, cluster) in text[a..b].grapheme_indices(true) { let i = a + i; // Digits are drawn in the style's numeral system: the font must cover that digit. - let c = st.digits.map(c); + let Some(c) = cluster.chars().next().map(|c| st.digits.map(c)) else { continue }; let level = level_at(i); // Whitespace the primary font doesn't map goes to the fallback face like any other // character (#1844): an ideographic space set at zero width would remove an indent. - // What the layout handles itself (tab, line and paragraph breaks) stays. - let covered = c.is_control() || pmap.as_ref().is_none_or(|m| m.map(c).is_some()); - let face = if covered { + let face = if drawn_chars(cluster, st.digits).all(|c| in_face(pmap.as_ref(), c)) { primary.clone() - } else if let Some(f) = cache.get(&c) { + } else if let Some(f) = cache.get(cluster) { f.clone() } else { - let f = db.fallback_for_style(c, primary.id(), primary.weight, primary.italic).unwrap_or_else(|| primary.clone()); - cache.insert(c, f.clone()); + let f = fallback_face(db, &primary, pmap.as_ref(), cluster, st.digits); + cache.insert(cluster, f.clone()); f }; let small = small_caps && c.is_lowercase(); @@ -516,6 +520,32 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { && ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking) } +/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system +/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or +/// variation selectors. +fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator + '_ { + cluster + .chars() + .map(move |c| digits.map(c)) + .filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))) +} + +/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)? +fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool { + map.is_none_or(|m| m.map(c).is_some()) +} + +/// The face of a grapheme cluster the primary face (charmap `pmap`) lacks a character of: the +/// first fallback face with all of them, so that a letter's marks are shaped with it and attach to +/// it (#4491); when there is none, the face its first character takes on its own. +fn fallback_face(db: &FontDb, primary: &Arc, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc { + let fallback = |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic); + drawn_chars(cluster, digits) + .find_map(|c| fallback(c).filter(|f| drawn_chars(cluster, digits).all(|c| f.covers(c)))) + .or_else(|| drawn_chars(cluster, digits).next().filter(|&c| !in_face(pmap, c)).and_then(fallback)) + .unwrap_or_else(|| primary.clone()) +} + /// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and /// Bopomofo, shaped together (splitting them would cost a shaper call per change of script). fn shaping_script(c: char) -> Script { @@ -811,7 +841,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; let ch = first_char(cl); let mut adv = xa as f64 * k * hs; - if ch == SOFT_HYPHEN { + if ch == SOFT_HYPHEN || ch == '\u{2028}' { adv = 0.0; } else if last_in_cluster { let tracking = gst.tracking / 1000.0 * size; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 79ce4f5667..7ed2eb48ce 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -25,6 +25,7 @@ mod typo; mod variable; mod versions; mod vertical; +mod vietnamese; /// The bundled fonts only: what these tests measure doesn't change with the fonts installed. fn db() -> &'static FontDb { diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index af67365b0e..1ec51d15ac 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -163,6 +163,7 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout image: None, colour: None, bend: None, + unturned: Affine::IDENTITY, }); x += advance; } diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index c06396a1e4..345340b52e 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1339,3 +1339,58 @@ fn thai_words_are_words_to_the_caret() { assert_eq!(edit::word_at(s, s.len() - 1), end + 1..s.len()); assert_eq!(edit::next_word("hello world", 0), 5); } + +#[test] +fn soft_return_breaks_line_without_new_paragraph() { + let mut t = TextObject::point(Point::ZERO, "Line 1\u{2028}Line 2", style(12.0)); + t.para.space_before = 20.0; + t.para.space_after = 20.0; + let lay = layout(db(), &t); + assert_eq!(lay.lines.len(), 2, "broken into two lines"); + let l0 = &lay.lines[0]; + let l1 = &lay.lines[1]; + let line_gap = l1.baseline - l0.baseline; + assert!((line_gap - 12.0 * 1.2).abs() < 1.0, "normal line leading: {line_gap}"); + assert_eq!(&t.plain_text()[l0.start..l0.end], "Line 1\u{2028}"); + assert_eq!(&t.plain_text()[l1.start..l1.end], "Line 2"); +} + +#[test] +fn soft_return_in_justified_text_does_not_spread() { + let text = "Short\u{2028}A much longer second line of text inside the frame."; + let t = area(text, style(12.0), Rect::new(0.0, 0.0, 300.0, 200.0), Justify::JustifyLeft); + let lay = layout(db(), &t); + assert!(lay.lines.len() >= 2); + let l0 = &lay.lines[0]; + assert!(l0.x1 - l0.x0 < 100.0, "short line ending with soft return is not justified: {}", l0.x1 - l0.x0); +} + +#[test] +fn soft_return_in_list_does_not_repeat_marker() { + use vectorcraft_doc::text::{Bullet, ParaList}; + let mut t = area("First line\u{2028}Continuation line", style(12.0), Rect::new(0.0, 0.0, 300.0, 200.0), Justify::Left); + t.para.list = Some(ParaList::bulleted(Bullet::Dot)); + let lay = layout(db(), &t); + assert_eq!(lay.lines.len(), 2); + let l0_glyphs = &lay.glyphs[lay.lines[0].glyph_start..lay.lines[0].glyph_end]; + let l1_glyphs = &lay.glyphs[lay.lines[1].glyph_start..lay.lines[1].glyph_end]; + assert!(l0_glyphs.iter().any(|g| g.len == 0), "line 0 has bullet marker"); + assert!(!l1_glyphs.iter().any(|g| g.len == 0), "continuation line does not have bullet marker"); +} + +#[test] +fn trailing_soft_return_creates_empty_continuation_line() { + let t = TextObject::point(Point::ZERO, "Line 1\u{2028}", style(12.0)); + let lay = layout(db(), &t); + assert_eq!(lay.lines.len(), 2, "trailing soft return produces a second empty line"); + assert_eq!(lay.line_of(t.plain_text().len()), 1, "caret at end sits on the new line"); +} + +#[test] +fn soft_return_breaks_line_even_inside_no_break() { + let mut st = style(12.0); + st.no_break = true; + let t = area("First\u{2028}Second", st, Rect::new(0.0, 0.0, 300.0, 200.0), Justify::Left); + let lay = layout(db(), &t); + assert_eq!(lay.lines.len(), 2, "soft return honors line break despite no_break"); +} diff --git a/crates/text/src/tests/vietnamese.rs b/crates/text/src/tests/vietnamese.rs new file mode 100644 index 0000000000..29f98d0727 --- /dev/null +++ b/crates/text/src/tests/vietnamese.rs @@ -0,0 +1,123 @@ +//! Vietnamese letters with two diacritics (Ể, Ứ, Ự, Ẩ…) draw both marks on their base letter +//! (#4491), whichever form the text comes in: precomposed (NFC), decomposed (NFD), or as +//! Vietnamese keyboards type it (a precomposed vowel and a combining tone mark), in a font with +//! the precomposed letters, one that builds them from its marks (GPOS mark-to-base and +//! mark-to-mark), and one that has to borrow the marks from a fallback font. + +use kurbo::{Point, Rect, Shape}; +use skrifa::MetadataProvider; +use unicode_segmentation::UnicodeSegmentation; +use vectorcraft_doc::{CharStyle, TextObject}; +use write_fonts::FontBuilder; +use write_fonts::types::Tag; + +use crate::test_fonts::name_table; +use crate::{FontDb, TextLayout, layout}; + +/// Letters as (precomposed, decomposed, keyboard) text: the words "HỌC ĐỂ ỨNG DỤNG" and more +/// letters with two marks, capital and small. +const LETTERS: [[&str; 3]; 20] = [ + ["H", "H", "H"], + ["\u{1ECC}", "O\u{323}", "O\u{323}"], + ["C", "C", "C"], + ["\u{110}", "\u{110}", "\u{110}"], + ["\u{1EC2}", "E\u{302}\u{309}", "\u{CA}\u{309}"], + ["\u{1EE8}", "U\u{31B}\u{301}", "\u{1AF}\u{301}"], + ["N", "N", "N"], + ["G", "G", "G"], + ["D", "D", "D"], + ["\u{1EE4}", "U\u{323}", "U\u{323}"], + ["\u{1EF0}", "U\u{31B}\u{323}", "\u{1AF}\u{323}"], + ["\u{1EA8}", "A\u{302}\u{309}", "\u{C2}\u{309}"], + ["\u{1EBE}", "E\u{302}\u{301}", "\u{CA}\u{301}"], + ["\u{1ED8}", "O\u{302}\u{323}", "\u{D4}\u{323}"], + ["\u{1EDC}", "O\u{31B}\u{300}", "\u{1A0}\u{300}"], + ["\u{1EC3}", "e\u{302}\u{309}", "\u{EA}\u{309}"], + ["\u{1EE9}", "u\u{31B}\u{301}", "\u{1B0}\u{301}"], + ["\u{1EF1}", "u\u{31B}\u{323}", "\u{1B0}\u{323}"], + ["\u{1EA9}", "a\u{302}\u{309}", "\u{E2}\u{309}"], + ["\u{1EAB}", "a\u{306}\u{303}", "\u{103}\u{303}"], +]; + +const SIZE: f64 = 100.0; +const SOURCE_SANS: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + +fn text(form: usize) -> String { + LETTERS.iter().filter_map(|l| l.get(form).copied()).collect::>().join(" ") +} + +/// Each letter's ink, relative to the pen position of its first glyph. +fn letter_inks(db: &FontDb, family: &str, text: &str) -> Vec { + let st = CharStyle { font_family: family.into(), font_style: "Regular".into(), size: SIZE, ..CharStyle::default() }; + let l: TextLayout = layout(db, &TextObject::point(Point::ZERO, text, st)); + text.grapheme_indices(true) + .filter(|(_, g)| *g != " ") + .map(|(start, g)| { + let glyphs: Vec<_> = l.glyphs.iter().filter(|gl| (start..start + g.len()).contains(&gl.byte)).collect(); + assert!(!glyphs.is_empty(), "{g:?} has glyphs"); + let pen = glyphs[0].origin.x; + let ink = glyphs.iter().map(|gl| gl.outline.bounding_box()).reduce(|a, b| a.union(b)).unwrap(); + assert!(ink.area() > 0.0, "{g:?} draws"); + assert!(glyphs.iter().all(|gl| gl.gid != 0), "{g:?} has no missing glyph"); + ink - kurbo::Vec2::new(pen, 0.0) + }) + .collect() +} + +/// Every letter of `form` (drawn in `family` of `db`) has the ink of the precomposed letter in +/// Source Sans 3: its marks are on the letter, not beside it. +fn assert_attached(db: &FontDb, family: &str, form: usize) { + let want = letter_inks(FontDb::global(), "Source Sans 3", &text(0)); + let got = letter_inks(db, family, &text(form)); + assert_eq!(want.len(), got.len()); + for ((w, g), letter) in want.iter().zip(&got).zip(LETTERS) { + let off = [w.x0 - g.x0, w.x1 - g.x1, w.y0 - g.y0, w.y1 - g.y1].into_iter().fold(0.0_f64, |m, d| m.max(d.abs())); + assert!(off < 0.08 * SIZE, "{family}, form {form}: {:?} drawn {g:?}, precomposed {w:?}", letter[form]); + } +} + +#[test] +fn stacked_marks_sit_on_their_letter_in_every_form() { + for form in 0..3 { + assert_attached(FontDb::global(), "Source Sans 3", form); + } +} + +/// Source Sans 3 renamed `family`, with only the characters `keep` takes in its cmap. +fn source_sans_with(family: &str, keep: impl Fn(u32) -> bool) -> Vec { + let font = skrifa::FontRef::new(SOURCE_SANS).unwrap(); + let map: Vec<(u32, u16)> = font.charmap().mappings().filter(|(c, _)| keep(*c)).map(|(c, g)| (c, u16::try_from(g.to_u32()).unwrap())).collect(); + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"cmap"), crate::embed::cmap(&map).unwrap()); + builder.add_raw(Tag::new(b"name"), name_table(&[(1, family), (2, "Regular"), (4, family), (6, "Viettest-Regular")]).unwrap()); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag()).unwrap().as_bytes()); + } + } + builder.build() +} + +/// A font without the precomposed letters builds them from its base letters and marks. +#[test] +fn stacked_marks_are_positioned_mark_to_mark() { + const FAMILY: &str = "Viettest Marks"; + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(source_sans_with(FAMILY, |c| c < 0x1E00 && !(0xC0..0x250).contains(&c))), 1); + for form in 0..3 { + assert_attached(&db, FAMILY, form); + } +} + +/// A font with the base letters but none of the marks takes the whole letter, marks included, +/// from a font that has them. +#[test] +fn letters_whose_marks_a_font_lacks_fall_back_whole() { + const FAMILY: &str = "Viettest Bare"; + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(source_sans_with(FAMILY, |c| c < 0x80)), 1); + for form in 0..3 { + assert_attached(&db, FAMILY, form); + } +} diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 2ed8ff6d63..5903ac5b3d 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -38,9 +38,9 @@ use live_paint::LpHover; use live_paint::lp_color; pub use live_paint::{LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, LivePaintBucketTool, LivePaintSelectionTool}; pub use lookup::{ - EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, drawn_outlines, edge_near, edges, face_at, faces, is_live_paint, - leaf_shapes, live_paint_at, live_paint_takes, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, - visible_edge_near, visible_face_at, + EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, builder_members, drawn_outlines, edge_near, edges, face_at, faces, + is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, + sources, visible_edge_near, visible_face_at, }; pub use map::{BuilderMap, HATCH, HIGHLIGHT_RED, Hit, Touched, hatch, maps_built, sample_polyline, sorted_roots}; /// Small, Medium and Large gap lengths in points. @@ -142,8 +142,8 @@ fn step_swatch(list: &[&Swatch], fill: &Paint, last: Option, forward: boo /// red, and the gesture deletes the regions it touches, the pieces of open paths and the edges /// (outline pieces between the points where paths meet) it passes over. With Shift held at the /// press, the drag draws a rectangular marquee and touches the regions it reaches (see -/// [`BuilderMap::regions_in_marquee`]): they merge, or with Alt they are deleted. Its options are -/// [`ShapeBuilderOptions`]. +/// [`BuilderMap::regions_in_marquee`]): they merge, or with Alt they are deleted. Escape during a +/// drag cancels it. Its options are [`ShapeBuilderOptions`]. #[derive(Default)] pub struct ShapeBuilderTool { cache: RegionCache, @@ -461,15 +461,23 @@ impl Tool for ShapeBuilderTool { } /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch - /// before or after the current fill. + /// before or after the current fill. Escape during a drag cancels it: the release after it + /// merges and deletes nothing. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) } fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if !self.claims_key(cx, key) { return vec![]; } + if key == ToolKey::Escape { + self.dragging = false; + self.points.clear(); + self.touched = Touched::default(); + (self.marquee, self.hover, self.far) = (None, None, false); + return vec![]; + } let list = color_swatches(cx.doc); let Some((i, s)) = step_swatch(&list, &cx.paint.fill, self.picked, key == ToolKey::Right).and_then(|i| Some((i, list.get(i)?))) else { return vec![]; diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index aef5bd087c..607584bb93 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -1,8 +1,9 @@ use super::cache::RegionCache; -use super::lookup::{is_live_paint, live_paint_at, visible_edge_near, visible_face_at}; +use super::lookup::{is_live_paint, live_paint_at, live_paint_at_where, visible_edge_near, visible_face_at}; use super::map::{HIGHLIGHT_RED, sorted_roots}; use super::{ - Action, Arc, BezPath, Cursor, Document, Mods, Node, NodeId, Overlay, Point, PointerEvent, PointerKind, Tool, ToolContext, Value, json, json_ids, + Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent, + PointerKind, Rect, Tool, ToolContext, ToolKey, Value, json, json_ids, path_contains, }; // ---------- Live Paint Bucket ---------- @@ -22,9 +23,11 @@ pub(super) enum LpHover { /// of a visible Live Paint group ([`live_paint_at`]) it is that group with its visible face under /// `p`, or with `edge` its visible edge nearest `p` within `tol` (None when there is none). Outside /// every visible face, with `edge`, it is the visible edge nearest `p` within `tol` among the -/// visible Live Paint groups (the front-most group's on a tie). None when no group is found. -fn lp_part_at(doc: &Document, p: Point, tol: f64, edge: bool) -> Option<(NodeId, Option<&Arc>)> { - if let Some(g) = live_paint_at(doc, p).and_then(|id| doc.node(id)) { +/// visible Live Paint groups (the front-most group's on a tie). None when no group is found. Only +/// the groups for which `takes` is true are looked at: [`lp_visible`] for the Live Paint Bucket and +/// [`lp_selectable`] for Live Paint Selection. +fn lp_part_at<'a>(doc: &'a Document, p: Point, tol: f64, edge: bool, takes: &dyn Fn(NodeId) -> bool) -> Option<(NodeId, Option<&'a Arc>)> { + if let Some(g) = live_paint_at_where(doc, p, takes).and_then(|id| doc.node(id)) { return Some((g.id, if edge { visible_edge_near(g, p, tol) } else { visible_face_at(g, p) })); } if !edge { @@ -36,7 +39,7 @@ fn lp_part_at(doc: &Document, p: Point, tol: f64, edge: bool) -> Option<(NodeId, && let Some(e) = visible_edge_near(n, p, tol) && let Some((.., d)) = e.path_data().and_then(|pd| pd.nearest(p)) && best.is_none_or(|b| d <= b.0) - && doc.is_visible(n.id) + && takes(n.id) { best = Some((d, n.id, e)); } @@ -44,11 +47,25 @@ fn lp_part_at(doc: &Document, p: Point, tol: f64, edge: bool) -> Option<(NodeId, best.map(|(_, g, e)| (g, Some(e))) } -/// What the Live Paint tools highlight at `p`: the part of a Live Paint group ([`lp_part_at`]), else -/// with `cache` the region of the selection under `p`. A large selection's regions are found on -/// another thread ([`RegionCache::ready`]), and until they are, no region is highlighted. -fn lp_hover(cx: &ToolContext, cache: Option<&mut RegionCache>, p: Point, edge: bool) -> LpHover { - if let Some((_, part)) = lp_part_at(cx.doc, p, cx.tol(4.0), edge) { +/// Whether the Live Paint Bucket takes Live Paint group `id`: it is visible, with every layer and +/// group around it. +fn lp_visible(cx: &ToolContext, id: NodeId) -> bool { + cx.doc.is_visible(id) +} + +/// Whether the Live Paint Selection tool takes Live Paint group `id`: it is editable +/// ([`Document::is_editable`]: visible, and not locked, on a locked layer or on a locked artboard), +/// and in isolation mode it is the isolated object or inside it ([`crate::direct::in_scope`]). +fn lp_selectable(cx: &ToolContext, id: NodeId) -> bool { + cx.doc.is_editable(id) && crate::direct::in_scope(cx.doc, cx.isolation, id) +} + +/// What the Live Paint tools highlight at `p`: the part of a Live Paint group ([`lp_part_at`], among +/// the groups `takes` takes), else with `cache` the region of the selection under `p`. A large +/// selection's regions are found on another thread ([`RegionCache::ready`]), and until they are, no +/// region is highlighted. +fn lp_hover(cx: &ToolContext, cache: Option<&mut RegionCache>, p: Point, edge: bool, takes: &dyn Fn(NodeId) -> bool) -> LpHover { + if let Some((_, part)) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, takes) { return part.and_then(|n| n.path_data()).map(|pd| LpHover::Part(pd.to_bezpath())).unwrap_or_default(); } let sel_is_live = cx.selection.objects.iter().any(|id| cx.doc.node(*id).is_some_and(is_live_paint)); @@ -95,14 +112,14 @@ impl Tool for LivePaintBucketTool { match ev.kind { PointerKind::Move => { self.at = Some((p, ev.mods.shift)); - self.hover = lp_hover(cx, Some(&mut self.cache), p, ev.mods.shift); + self.hover = lp_hover(cx, Some(&mut self.cache), p, ev.mods.shift, &|id| lp_visible(cx, id)); vec![] } PointerKind::Down => { self.hover = LpHover::None; let point = json!([p.x, p.y]); if ev.mods.shift { - return match lp_part_at(cx.doc, p, cx.tol(4.0), true) { + return match lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { Some((g, Some(_))) => { vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))] } @@ -143,7 +160,7 @@ impl Tool for LivePaintBucketTool { loop { self.cache.settle(wait); if let Some((p, shift)) = self.at { - self.hover = lp_hover(cx, Some(&mut self.cache), p, shift); + self.hover = lp_hover(cx, Some(&mut self.cache), p, shift, &|id| lp_visible(cx, id)); } if !wait || !self.cache.waiting() { break; @@ -160,12 +177,18 @@ pub const LP_SELECT_WIDTH: f64 = 4.0; /// The least and greatest highlight width (screen pixels) the Live Paint Selection tool takes. pub const LP_SELECT_WIDTH_RANGE: (f64, f64) = (1.0, 20.0); -/// Live Paint Selection: click selects a face (Shift adds); Alt-click selects an edge. Its Tool -/// Options (double-click the tool) are `selectFills` and `selectStrokes` (both on), the highlight -/// `color` (`#rrggbb`, red by default) and its `width` ([`LP_SELECT_WIDTH`] pixels). With Select -/// Strokes off, Alt-click selects the face under the pointer as a click does; with Select Fills -/// off, a click selects the edge nearest the pointer as Alt-click does; with both off, a click -/// selects no face or edge. +/// Live Paint Selection: click selects a face (Shift adds); Alt-click selects an edge. A drag draws +/// a marquee, and on release the faces and edges it touches ([`lp_parts_in`]) become the selection; +/// with Shift held at the press, each of them leaves the selection if it is selected and joins it +/// otherwise. A click and a marquee change the selection on release, so Escape between the press +/// and the release (which removes the marquee) leaves the selection as it was. The tool does not +/// highlight or select the faces and edges of a Live Paint group that is locked, on a locked layer +/// or on a locked artboard, or in isolation mode outside the isolated art. Its Tool Options +/// (double-click the tool) are `selectFills` and `selectStrokes` (both on), the highlight `color` +/// (`#rrggbb`, red by default) and its `width` ([`LP_SELECT_WIDTH`] pixels). With +/// Select Strokes off, Alt-click selects the face under the pointer as a click does and a marquee +/// takes no edges; with Select Fills off, a click selects the edge nearest the pointer as Alt-click +/// does and a marquee takes no faces; with both off, a click or a marquee selects no face or edge. pub struct LivePaintSelectionTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, @@ -173,11 +196,44 @@ pub struct LivePaintSelectionTool { strokes: bool, color: [u8; 3], width: f64, + /// The drag in progress, from the press to the release. + drag: Option, +} + +/// A press and drag of the Live Paint Selection tool. +#[derive(Clone, Copy, Debug)] +struct LpDrag { + /// Where the press was. + start: Point, + /// Where the pointer is. + cur: Point, + /// Shift was held at the press. + shift: bool, + /// The face or edge under the press, which a click selects (or with Shift toggles). + hit: Option, +} + +impl LpDrag { + /// The marquee from the press to the pointer, None while the drag is shorter than + /// [`CLICK_TOL_PX`] screen pixels both across and down (a click). + fn marquee(&self, cx: &ToolContext) -> Option { + let r = Rect::from_points(self.start, self.cur); + let tol = cx.tol(CLICK_TOL_PX); + (r.width() >= tol || r.height() >= tol).then_some(r) + } } impl Default for LivePaintSelectionTool { fn default() -> Self { - Self { cache: RegionCache::live_paint(), hover: LpHover::None, fills: true, strokes: true, color: HIGHLIGHT_RED, width: LP_SELECT_WIDTH } + Self { + cache: RegionCache::live_paint(), + hover: LpHover::None, + fills: true, + strokes: true, + color: HIGHLIGHT_RED, + width: LP_SELECT_WIDTH, + drag: None, + } } } @@ -193,6 +249,30 @@ impl LivePaintSelectionTool { } } +/// The faces (with `faces`) and edges (with `edges`) that marquee `r` touches, among the faces and +/// edges that are not hidden of the Live Paint groups the tool takes ([`lp_selectable`]), in paint +/// order. A face is touched when its outline has an anchor inside `r` or crosses `r`'s sides, or +/// when it holds `r`'s center. An edge is touched when it has an anchor inside `r` or crosses +/// `r`'s sides. A face or edge partly inside `r` is touched. +fn lp_parts_in(cx: &ToolContext, r: Rect, faces: bool, edges: bool) -> Vec { + let mut out = vec![]; + cx.doc.walk(|n| { + if !is_live_paint(n) || !lp_selectable(cx, n.id) { + return; + } + for c in n.children().into_iter().flatten().filter(|c| c.visible) { + let Some(pd) = c.path_data() else { continue }; + let face = faces && c.name.as_deref() == Some(FACE_NAME); + let edge = edges && c.name.as_deref() == Some(EDGE_NAME); + let touched = vectorcraft_geom::hit::intersects_rect(pd, r) || (face && path_contains(pd, FillRule::NonZero, r.center())); + if (face || edge) && touched { + out.push(c.id); + } + } + }); + out +} + /// A highlight color option: `#rrggbb` or a layer color's name (any case). pub(super) fn lp_color(v: &Value) -> Option<[u8; 3]> { let s = v.as_str()?.trim(); @@ -214,26 +294,70 @@ impl Tool for LivePaintSelectionTool { match ev.kind { PointerKind::Move => { // Only the parts of Live Paint groups highlight, so no map of the selection is built. - self.hover = match edge.map(|e| lp_hover(cx, None, p, e)) { + self.hover = match edge.map(|e| lp_hover(cx, None, p, e, &|id| lp_selectable(cx, id))) { Some(h @ LpHover::Part(_)) => h, _ => LpHover::None, }; vec![] } PointerKind::Down => { - let hit = edge.and_then(|e| lp_part_at(cx.doc, p, cx.tol(4.0), e)).and_then(|(_, part)| part).map(|n| n.id); - match (hit, ev.mods.shift) { - (Some(id), true) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))], - (Some(id), false) => vec![Action::Exec("select.set".into(), json!({ "ids": [id.0] }))], - (None, true) => vec![], - (None, false) => vec![Action::Exec("select.none".into(), json!({}))], + let part = edge.and_then(|e| lp_part_at(cx.doc, p, cx.tol(4.0), e, &|id| lp_selectable(cx, id))); + let hit = part.and_then(|(_, part)| part).map(|n| n.id); + self.drag = Some(LpDrag { start: p, cur: p, shift: ev.mods.shift, hit }); + vec![] + } + PointerKind::Drag => { + if let Some(d) = &mut self.drag { + d.cur = p; + self.hover = LpHover::None; + } + vec![] + } + PointerKind::Up => { + let Some(d) = self.drag.take() else { return vec![] }; + let d = LpDrag { cur: p, ..d }; + let Some(r) = d.marquee(cx) else { + // A click selects what the press picked. + return match (d.hit, d.shift) { + (Some(id), true) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))], + (Some(id), false) => vec![Action::Exec("select.set".into(), json!({ "ids": [id.0] }))], + (None, true) => vec![], + (None, false) => vec![Action::Exec("select.none".into(), json!({}))], + }; + }; + let ids = lp_parts_in(cx, r, self.fills, self.strokes); + match (ids.is_empty(), d.shift) { + (true, true) => vec![], + (true, false) => vec![Action::Exec("select.none".into(), json!({}))], + (false, true) => vec![Action::Exec("select.toggle".into(), json!({ "ids": json_ids(&ids) }))], + (false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))], } } _ => vec![], } } - fn overlays(&self, _cx: &ToolContext) -> Vec { + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + // Escape during a press or drag drops it; the release then selects nothing. + if key == ToolKey::Escape { + self.drag = None; + } + vec![] + } + + fn busy(&self) -> bool { + self.drag.is_some() + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.drag = None; + vec![] + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + if let Some(r) = self.drag.and_then(|d| d.marquee(cx)) { + return vec![Overlay::Marquee(r)]; + } lp_overlays(&self.hover, &self.cache, self.color, self.width as f32) } diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index 30475be342..99aeeb7aad 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -106,9 +106,14 @@ fn nearest_edge<'a>(edges: impl IntoIterator>, p: Point, to /// The visible Live Paint group with a face under `p` that is not hidden (front-most in paint order). pub fn live_paint_at(doc: &Document, p: Point) -> Option { + live_paint_at_where(doc, p, |id| doc.is_visible(id)) +} + +/// [`live_paint_at`] among the Live Paint groups for which `takes` is true. +pub(super) fn live_paint_at_where(doc: &Document, p: Point, takes: impl Fn(NodeId) -> bool) -> Option { let mut hit = None; doc.walk(|n| { - if is_live_paint(n) && doc.is_visible(n.id) && visible_face_at(n, p).is_some() { + if is_live_paint(n) && visible_face_at(n, p).is_some() && takes(n.id) { hit = Some(n.id); } }); @@ -121,28 +126,48 @@ pub fn leaf_shapes<'a>(n: &'a Node, out: &mut Vec<&'a Node>) { collect_leaves(n, false, out); } -/// [`leaf_shapes`]; with `filled_faces`, a Live Paint group contributes only its filled faces and -/// its stroked edges. -fn collect_leaves<'a>(n: &'a Node, filled_faces: bool, out: &mut Vec<&'a Node>) { - if !n.visible { +/// [`leaf_shapes`]; with `builder` (the Shape Builder's inputs), a Live Paint group contributes +/// only its filled faces and its stroked edges, and locked objects contribute nothing. +fn collect_leaves<'a>(n: &'a Node, builder: bool, out: &mut Vec<&'a Node>) { + collect_members(n, builder, out); + if builder { + out.retain(|m| m.visible && !m.locked); + } +} + +/// The leaves the Shape Builder takes from `n` ([`collect_leaves`]), in paint order, with each +/// hidden or locked object it skips in its place. +pub fn builder_members(n: &Node) -> Vec<&Node> { + let mut out = vec![]; + collect_members(n, true, &mut out); + out +} + +/// [`collect_leaves`] with, for `builder`, each hidden or locked object in place of what it holds. +fn collect_members<'a>(n: &'a Node, builder: bool, out: &mut Vec<&'a Node>) { + if !n.visible && !builder { + return; + } + if builder && (!n.visible || n.locked) { + out.push(n); return; } if n.extras().shaper.is_some() { for c in n.children().into_iter().flatten().skip(1) { - collect_leaves(c, filled_faces, out); + collect_members(c, builder, out); } return; } match &n.kind { NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => {} NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push(n), - NodeKind::Group { .. } if filled_faces && is_live_paint(n) => { - out.extend(faces(n).into_iter().filter(|f| f.visible && !f.appearance.fill_paint().is_none()).map(|f| &**f)); - out.extend(edges(n).into_iter().filter(|e| e.visible && !e.appearance.stroke_paint().is_none()).map(|e| &**e)); + NodeKind::Group { .. } if builder && is_live_paint(n) => { + out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || !f.appearance.fill_paint().is_none()).map(|f| &**f)); + out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || !e.appearance.stroke_paint().is_none()).map(|e| &**e)); } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { for c in children { - collect_leaves(c, filled_faces, out); + collect_members(c, builder, out); } } _ => {} @@ -191,13 +216,15 @@ pub fn shapes_for<'a>(doc: &'a Document, roots: &[NodeId]) -> (Vec, V shapes_of(doc, roots, false) } -/// [`shapes_for`]; with `filled_faces`, a Live Paint group contributes only its filled faces and -/// its stroked edges. -fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], filled_faces: bool) -> (Vec, Vec<&'a Node>) { +/// [`shapes_for`]; with `builder`, the leaves [`collect_leaves`] takes for the Shape Builder, and +/// nothing from a root in a locked or hidden group or layer. +fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], builder: bool) -> (Vec, Vec<&'a Node>) { let mut lv = vec![]; for id in roots { - if let Some(n) = doc.node(*id) { - collect_leaves(n, filled_faces, &mut lv); + if let Some(n) = doc.node(*id) + && (!builder || doc.is_editable(*id)) + { + collect_leaves(n, builder, &mut lv); } } let mut shapes = vec![]; @@ -219,7 +246,8 @@ fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], filled_faces: bool) -> (Ve /// `open_filled_as_closed`. Unfilled open paths and straight lines stay open and cut the regions /// they cross, and so do filled open paths without `open_filled_as_closed`. A Live Paint group /// contributes its filled faces as shapes and its stroked edges as open lines; its unfilled faces -/// and its edges without a stroke are left out. +/// and its edges without a stroke are left out. Locked objects, and objects in a locked group or +/// layer, give nothing. pub fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId], open_filled_as_closed: bool) -> (Vec, Vec<&'a Node>) { let (mut shapes, leaves) = shapes_of(doc, roots, true); for (s, l) in shapes.iter_mut().zip(&leaves) { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a0a6bfb650..aeb753b4c7 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -60,6 +60,40 @@ fn shape_builder_drag_emits_merge() { assert!(v["points"].as_array().unwrap().len() >= 2); } +/// Escape during a merge drag, an Alt erase drag or a Shift marquee cancels it: the tool takes +/// the key, nothing stays highlighted, and the release merges and deletes nothing. Enter leaves +/// the drag alone, and with no drag Escape is not the tool's. +#[test] +fn escape_cancels_a_shape_builder_drag() { + let (d, a, b) = two_rects(); + let mut s = Selection::default(); + s.set([a, b]); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let shift = Mods { shift: true, ..Mods::default() }; + for (what, mods) in [("merge", Mods::default()), ("erase", alt), ("marquee", shift)] { + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0).with_mods(mods)); + t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 60.0).with_mods(mods)); + assert!(!t.touched.is_empty(), "{what}"); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty(), "{what}: Enter leaves the drag alone"); + assert!(t.busy(), "{what}"); + assert!(t.claims_key(&cx, ToolKey::Escape), "{what}: Escape is the tool's during the drag"); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty(), "{what}: no interaction began, so none is canceled"); + assert!(!t.busy(), "{what}"); + assert!(t.overlays(&cx).is_empty(), "{what}: nothing stays highlighted"); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 70.0).with_mods(mods)).is_empty(), "{what}"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 70.0).with_mods(mods)).is_empty(), "{what}: the release merges nothing"); + assert!(!t.claims_key(&cx, ToolKey::Escape), "{what}: with no drag, Escape is not the tool's"); + // The next drag merges as before. + t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{what}: {acts:?}"); + } +} + #[test] fn shape_builder_rebuilds_its_map_for_a_new_revision_at_the_same_address() { let (mut d, a, b) = two_rects(); @@ -824,6 +858,13 @@ fn live_paint_selection_hover_builds_no_map_of_the_selection() { assert!(!t.waiting()); } +/// A Live Paint Selection click pressed with `down`: the press does nothing, and the release does +/// what is returned. +fn lp_click(t: &mut LivePaintSelectionTool, cx: &ToolContext, down: PointerEvent) -> Vec { + assert!(t.pointer(cx, &down).is_empty(), "the press changes nothing"); + t.pointer(cx, &PointerEvent { kind: PointerKind::Up, ..down }) +} + #[test] fn live_paint_selection_selects_faces() { let (d, _gid, f2, e) = live_group_doc(); @@ -831,12 +872,12 @@ fn live_paint_selection_selects_faces() { let p = paint(); let cx = cx(&d, &s, &p); let mut t = LivePaintSelectionTool::default(); - let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)); + let acts = lp_click(&mut t, &cx, ev(PointerKind::Down, 75.0, 25.0)); assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({ "ids": [f2.0] }))]); let alt = Mods { alt: true, ..Default::default() }; - let acts = t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)); + let acts = lp_click(&mut t, &cx, ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)); assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({ "ids": [e.0] }))]); - let acts = t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + let acts = lp_click(&mut t, &cx, ev(PointerKind::Down, 300.0, 300.0)); assert_eq!(acts, vec![Action::Exec("select.none".into(), json!({}))]); } @@ -853,15 +894,15 @@ fn live_paint_selection_options_choose_what_a_click_selects() { assert_eq!(t.options(), json!({"selectFills": true, "selectStrokes": true, "color": "#ff2a2a", "width": 4.0})); // Select Fills off: a click inside a face selects nothing, and a click by an edge selects it. t.set_option("selectFills", &json!(false)); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)), none); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 75.0, 25.0)), none); t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); assert!(t.overlays(&cx).is_empty()); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0)), set(&[e])); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[e])); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 51.0, 25.0)), set(&[e])); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[e])); // Select Strokes off: Alt-click by an edge selects the face under the pointer. t.set_option("selectFills", &json!(true)); t.set_option("selectStrokes", &json!(false)); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[f2])); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[f2])); t.pointer(&cx, &ev(PointerKind::Move, 51.0, 25.0).with_mods(alt)); let ov = t.overlays(&cx); let [Overlay::Path { path, .. }] = ov.as_slice() else { panic!("{ov:?}") }; @@ -869,12 +910,12 @@ fn live_paint_selection_options_choose_what_a_click_selects() { // Both off: nothing is selected or highlighted. t.set_option("selectFills", &json!(false)); for m in [Mods::default(), alt] { - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(m)), none); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 51.0, 25.0).with_mods(m)), none); t.pointer(&cx, &ev(PointerKind::Move, 51.0, 25.0).with_mods(m)); assert!(t.overlays(&cx).is_empty()); } let shift = Mods { shift: true, ..Default::default() }; - assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0).with_mods(shift)).is_empty()); + assert!(lp_click(&mut t, &cx, ev(PointerKind::Down, 75.0, 25.0).with_mods(shift)).is_empty()); } #[test] @@ -894,15 +935,156 @@ fn live_paint_selection_click_outside_the_faces_selects_the_edge_it_highlights() let ov = t.overlays(&cx); let [Overlay::Path { path, .. }] = ov.as_slice() else { panic!("{ov:?}") }; assert_eq!(path.bounding_box(), Rect::new(100.0, 0.0, 100.0, 100.0)); - let acts = t.pointer(&cx, &ev(PointerKind::Down, 102.0, 50.0).with_mods(m)); + let acts = lp_click(&mut t, &cx, ev(PointerKind::Down, 102.0, 50.0).with_mods(m)); assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({ "ids": [right.0] }))]); - let acts = t.pointer(&cx, &ev(PointerKind::Down, 102.0, 50.0).with_mods(Mods { shift: true, ..m })); + let acts = lp_click(&mut t, &cx, ev(PointerKind::Down, 102.0, 50.0).with_mods(Mods { shift: true, ..m })); assert_eq!(acts, vec![Action::Exec("select.toggle".into(), json!({ "id": right.0 }))]); } // Farther than 4 pixels from every edge: no highlight, and a click selects nothing. t.pointer(&cx, &ev(PointerKind::Move, 106.0, 50.0)); assert!(t.overlays(&cx).is_empty()); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 106.0, 50.0)), vec![Action::Exec("select.none".into(), json!({}))]); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 106.0, 50.0)), vec![Action::Exec("select.none".into(), json!({}))]); +} + +/// Presses at `from` with `m`, drags to `to` and releases there; returns what the release does +/// (the press and the drag do nothing). +fn lp_drag(t: &mut LivePaintSelectionTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods) -> Vec { + assert!(t.pointer(cx, &ev(PointerKind::Down, from.0, from.1).with_mods(m)).is_empty()); + assert!(t.pointer(cx, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)).is_empty()); + t.pointer(cx, &ev(PointerKind::Up, to.0, to.1).with_mods(m)) +} + +#[test] +fn live_paint_selection_marquee_selects_the_faces_and_edges_it_touches() { + let mut d = Document::new(500.0, 500.0); + let (_, [left, top, right, bottom]) = live_square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + let face = faces(d.node(d.layers[0].children().unwrap()[0].id).unwrap())[0].id; + live_square(&mut d, Rect::new(200.0, 0.0, 300.0, 100.0)); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let mut t = LivePaintSelectionTool::default(); + // While the drag is on, the tool is busy and draws the marquee. + t.pointer(&cx, &ev(PointerKind::Down, -10.0, -10.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 50.0, 50.0)); + assert!(t.busy()); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(-10.0, -10.0, 50.0, 50.0))]); + // Partly inside the marquee: the face and its left and top sides, not the other group. + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 50.0, 50.0)), set(&[face, left, top])); + assert!(!t.busy()); + // A marquee inside the face takes the face. + assert_eq!(lp_drag(&mut t, &cx, (20.0, 20.0), (40.0, 40.0), Mods::default()), set(&[face])); + // Across the right side, which ends outside the marquee, and the bottom-right corner. + assert_eq!(lp_drag(&mut t, &cx, (90.0, 40.0), (110.0, 150.0), Mods::default()), set(&[face, right, bottom])); + // A marquee that touches nothing selects nothing. + assert_eq!(lp_drag(&mut t, &cx, (120.0, 120.0), (180.0, 180.0), Mods::default()), vec![Action::Exec("select.none".into(), json!({}))]); + // A drag shorter than 3 pixels is a click: the release selects the face under the press. + assert_eq!(lp_drag(&mut t, &cx, (50.0, 50.0), (52.0, 51.0), Mods::default()), set(&[face])); + // Select Fills off takes no faces, and Select Strokes off no edges. + t.set_option("selectFills", &json!(false)); + assert_eq!(lp_drag(&mut t, &cx, (-10.0, -10.0), (50.0, 50.0), Mods::default()), set(&[left, top])); + t.set_option("selectFills", &json!(true)); + t.set_option("selectStrokes", &json!(false)); + assert_eq!(lp_drag(&mut t, &cx, (-10.0, -10.0), (50.0, 50.0), Mods::default()), set(&[face])); +} + +#[test] +fn live_paint_selection_shift_marquee_adds_and_removes() { + let mut d = Document::new(500.0, 500.0); + let (_, [left, top, right, _]) = live_square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + let face = faces(d.node(d.layers[0].children().unwrap()[0].id).unwrap())[0].id; + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let toggle = |ids: &[NodeId]| vec![Action::Exec("select.toggle".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = LivePaintSelectionTool::default(); + // Each face and edge the marquee touches leaves the selection or joins it. + assert_eq!(lp_drag(&mut t, &cx, (-10.0, -10.0), (50.0, 50.0), shift), toggle(&[face, left, top])); + // From a press on the face, the face is toggled once, with the rest of what the marquee touches. + assert_eq!(lp_drag(&mut t, &cx, (50.0, 50.0), (60.0, -10.0), shift), toggle(&[face, top])); + // From a press by the right side (which a Shift-click there toggles), a marquee that touches + // nothing changes nothing. + let alt_shift = Mods { alt: true, shift: true, ..Default::default() }; + assert_eq!(lp_drag(&mut t, &cx, (102.0, 50.0), (102.0, 50.0), alt_shift), vec![Action::Exec("select.toggle".into(), json!({ "id": right.0 }))]); + assert!(lp_drag(&mut t, &cx, (102.0, 50.0), (150.0, 60.0), alt_shift).is_empty()); +} + +#[test] +fn live_paint_selection_escape_cancels_the_marquee() { + let mut d = Document::new(500.0, 500.0); + live_square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + // Pressed outside the group and on its face, with and without Shift, and then dragged or not. + for (m, from, to) in [ + (Mods::default(), (-10.0, -10.0), (50.0, 50.0)), + (Mods { shift: true, ..Default::default() }, (-10.0, -10.0), (50.0, 50.0)), + (Mods::default(), (50.0, 50.0), (80.0, 80.0)), + (Mods { shift: true, ..Default::default() }, (50.0, 50.0), (80.0, 80.0)), + (Mods::default(), (50.0, 50.0), (50.0, 50.0)), + ] { + let mut t = LivePaintSelectionTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, from.0, from.1).with_mods(m)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)).is_empty()); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!t.busy()); + assert!(t.overlays(&cx).is_empty(), "no marquee after Escape"); + // The rest of the drag and the release select nothing. + t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 60.0).with_mods(m)); + assert!(t.overlays(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 60.0, 60.0).with_mods(m)).is_empty(), "{m:?} {from:?}"); + } +} + +#[test] +fn live_paint_selection_skips_locked_groups_and_art_outside_isolation() { + let mut d = Document::new(500.0, 500.0); + let (back, [_, _, back_right, back_bottom]) = live_square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + let (front, _) = live_square(&mut d, Rect::new(50.0, 0.0, 150.0, 100.0)); + let face = |d: &Document, g: NodeId| faces(d.node(g).unwrap())[0].id; + let back_face = face(&d, back); + d.node_mut(front).unwrap().locked = true; + let s = Selection::default(); + let p = paint(); + let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let none = vec![Action::Exec("select.none".into(), json!({}))]; + let part = |ov: &[Overlay]| match ov { + [] => None, + [Overlay::Path { path, .. }] => Some(path.bounding_box()), + _ => panic!("{ov:?}"), + }; + let mut t = LivePaintSelectionTool::default(); + { + let cx = cx(&d, &s, &p); + // Where the faces overlap, the back group's face under the locked one is highlighted and picked. + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); + assert_eq!(part(&t.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 75.0, 50.0)), set(&[back_face])); + // Over the locked group alone, nothing is highlighted or picked. + t.pointer(&cx, &ev(PointerKind::Move, 125.0, 50.0)); + assert_eq!(part(&t.overlays(&cx)), None); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 125.0, 50.0)), none); + // A marquee across both groups takes only the back group's face and edges. + assert_eq!(lp_drag(&mut t, &cx, (90.0, 90.0), (140.0, 110.0), Mods::default()), set(&[back_face, back_right, back_bottom])); + } + // With the back group isolated, the front group is not picked either. + d.node_mut(front).unwrap().locked = false; + { + let cx = ToolContext { isolation: Some(back), ..cx(&d, &s, &p) }; + t.pointer(&cx, &ev(PointerKind::Move, 125.0, 50.0)); + assert_eq!(part(&t.overlays(&cx)), None); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 125.0, 50.0)), none); + assert_eq!(lp_drag(&mut t, &cx, (90.0, 90.0), (140.0, 110.0), Mods::default()), set(&[back_face, back_right, back_bottom])); + } + // On a locked layer, no group is picked. + let layer = d.layers[0].id; + d.node_mut(layer).unwrap().locked = true; + let cx = cx(&d, &s, &p); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 75.0, 50.0)), none); + assert_eq!(lp_drag(&mut t, &cx, (-10.0, -10.0), (200.0, 200.0), Mods::default()), none); } #[test] @@ -931,7 +1113,7 @@ fn live_paint_edges_outside_the_faces_come_from_the_nearest_visible_group() { Some((_, e, _)) => Action::Exec("select.set".into(), json!({ "ids": [e.0] })), None => Action::Exec("select.none".into(), json!({})), }; - assert_eq!(sel.pointer(&cx, &ev(PointerKind::Down, x, y).with_mods(alt)), vec![picked]); + assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, x, y).with_mods(alt)), vec![picked]); let mut bucket = LivePaintBucketTool::default(); bucket.pointer(&cx, &ev(PointerKind::Move, x, y).with_mods(shift)); assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2)); @@ -974,7 +1156,7 @@ fn live_paint_tools_skip_hidden_edges() { Some((_, e, _)) => Action::Exec("select.set".into(), json!({ "ids": [e.0] })), None => Action::Exec("select.none".into(), json!({})), }; - assert_eq!(sel.pointer(&cx, &ev(PointerKind::Down, x, 50.0).with_mods(alt)), vec![picked], "x {x}"); + assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, x, 50.0).with_mods(alt)), vec![picked], "x {x}"); let mut bucket = LivePaintBucketTool::default(); bucket.pointer(&cx, &ev(PointerKind::Move, x, 50.0).with_mods(shift)); assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2), "x {x}"); @@ -1010,19 +1192,19 @@ fn live_paint_tools_skip_hidden_faces() { let mut sel = LivePaintSelectionTool::default(); sel.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); assert_eq!(part(&sel.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0))); - assert_eq!(sel.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [back_face.0] }))]); + assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, 75.0, 50.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [back_face.0] }))]); // Over the hidden face alone, neither tool highlights or picks a face. bucket.pointer(&cx, &ev(PointerKind::Move, 125.0, 50.0)); assert_eq!(part(&bucket.overlays(&cx)), None); assert!(bucket.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)).is_empty()); sel.pointer(&cx, &ev(PointerKind::Move, 125.0, 50.0)); assert_eq!(part(&sel.overlays(&cx)), None); - assert_eq!(sel.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)), vec![Action::Exec("select.none".into(), json!({}))]); + assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, 125.0, 50.0)), vec![Action::Exec("select.none".into(), json!({}))]); // Inside the hidden face, 1.5 pt from the back group's right side, Alt-click takes that side // as it does outside every face. sel.pointer(&cx, &ev(PointerKind::Move, 101.5, 50.0).with_mods(alt)); assert_eq!(part(&sel.overlays(&cx)), Some(Rect::new(100.0, 0.0, 100.0, 100.0))); - let picked = sel.pointer(&cx, &ev(PointerKind::Down, 101.5, 50.0).with_mods(alt)); + let picked = lp_click(&mut sel, &cx, ev(PointerKind::Down, 101.5, 50.0).with_mods(alt)); assert_eq!(picked, vec![Action::Exec("select.set".into(), json!({ "ids": [back_right.0] }))]); } diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index f3a0e3c190..97b9f85973 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -96,7 +96,8 @@ pub struct ToolContext<'a> { pub snap_tangent: bool, /// View → Snapping → Snap to Perpendicular: likewise where it meets a nearby segment square. pub snap_perpendicular: bool, - /// View → Snap to Glyph: drawn points snap to live-text baselines and glyph bounds (with Smart Guides). + /// View → Snap to Glyph: drawn points snap to live-text glyph bounds, and on a single line of type + /// to its baseline, x-height, character widths and glyph anchor points (with Smart Guides). pub snap_to_glyph: bool, /// View → Show Corner Widget: paths show draggable Live Corners widgets in their corners. pub corner_widgets: bool, diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index d3cb7d3e88..cb0a958f65 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -3,8 +3,9 @@ //! Direct Selection: click an anchor to select it (Shift toggles), click a segment to select the //! segment independently of its endpoint anchors, drag to move selected anchors (the one pressed on snaps to //! anchors, segments and Smart Guides, or with them off Snap to Point; Shift keeps the move at 45° -//! steps; Alt on an anchor or a segment picks the whole path and Alt-drag copies it), drag a -//! direction handle to +//! steps; Alt on an anchor or a segment picks the whole path and Alt-drag copies it; an Alt-click +//! on a path selected whole adds its group, and each further Alt-click adds the next group up, as +//! Group Selection's clicks do), drag a direction handle to //! reshape (Shift keeps it at 45° steps round its anchor, Alt moves it alone; smart guides snap //! it), marquee to select anchors (Shift-drag toggles them: the selected ones inside are //! deselected, the others selected), drag a corner widget of any path (a star, a pen path) to round its corners @@ -15,7 +16,10 @@ //! objects entirely inside it (members of groups too), whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. -//! Both move objects selected as a whole as the Selection tool does, snapping alike. +//! Both move objects selected as a whole as the Selection tool does, snapping alike. When the +//! selection also holds direct-selected anchors or segments, a drag from an object moves those +//! anchors and the objects selected whole, as an anchor drag does, and while Alt is held it +//! copies the selected objects. //! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]). //! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the //! pointer ([`release_guide_at`]). @@ -23,8 +27,11 @@ //! with it) and, once a point is clicked, its handles; and the points of selected gradient meshes //! and mesh envelopes and their handles ([`MeshEdit`]; a solid fill colour recolours a gradient //! mesh's point last clicked). Dragging a corner or an edge of area -//! type's frame reshapes the type area (`text.reshapeArea`): the text reflows at its size; dragging -//! an anchor of type on a path's path reshapes the path (`text.reshapePath`): the text reflows along it. +//! type's frame reshapes the type area (`text.reshapeArea`): the text reflows at its size. A click +//! on a frame anchor or a marquee selects frame anchors (Shift toggles them). While the selection +//! holds only area type with selected frame anchors, those show filled, a drag of one of them moves +//! them all, and the arrow keys nudge them; otherwise the type is selected whole. Dragging an anchor of type on +//! a path's path reshapes the path (`text.reshapePath`): the text reflows along it. //! Dragging the brackets of selected type on a path moves or flips it ([`crate::pathtype`]). //! //! A press on the stroke of a path that isn't selected as a whole selects that segment's two anchors @@ -32,9 +39,10 @@ //! moves its anchors. use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{HitKind, compound_part_at, hit_test}; +use vectorcraft_doc::hit::{HitKind, compound_part_at, hit_test, selected_hidden_at}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Anchor, PathData, Point, Rect, Vec2}; @@ -121,16 +129,34 @@ enum State { }, /// Dragging a mesh point or handle ([`MeshEdit`]). Mesh, - /// Dragging anchors of area type's frame (a corner, or the two ends of an edge), or an anchor - /// of type on a path's path. + /// Dragging anchors of area type's frames (a corner, the two ends of an edge, or the selected + /// frame anchors), or an anchor of type on a path's path: each object with its anchors. TypeArea { - id: NodeId, - anchors: Vec, + items: FrameAnchors, start: Point, began: bool, }, } +/// Anchors of the frames of area type (or of the path of type on a path), each object with its +/// anchors. +type FrameAnchors = Vec<(NodeId, Vec)>; + +/// What [`DirectSelectionTool::notify`] hears after a press or a marquee selected frame anchors: +/// the selected objects to keep them with. +const FRAME_PICKED: &str = "frameAnchors"; + +/// The params of `text.reshapeArea` or `text.reshapePath` moving `items` by `d`. +fn reshape_params(items: &[(NodeId, Vec)], d: Vec2) -> Value { + match items { + [(id, anchors)] => json!({"id": id.0, "anchors": anchors_json(anchors), "dx": d.x, "dy": d.y}), + _ => { + let items: Vec = items.iter().map(|(id, v)| json!({"id": id.0, "anchors": anchors_json(v)})).collect(); + json!({"items": items, "dx": d.x, "dy": d.y}) + } + } +} + /// How far (pt) a snap must move a dragged point for the arrow to say it snapped. const SNAPPED: f64 = 1e-9; @@ -158,6 +184,13 @@ pub struct DirectSelectionTool { handle_snap: HandleSnap, /// What the objects being moved snap to, gathered when the move begins. move_snap: Option, + /// What the point holding a move of objects snaps to while the move takes direct-selected + /// anchors along (`path.moveAnchors`): each move of objects sets it when it begins, to the + /// targets of an anchor drag when anchors are selected, else to `None`. + partial_snap: Option, + /// With Snap to Grid or Snap to Pixel on, what such a move from a fill snaps instead of the + /// point it holds: the box around the selected anchors and the objects selected whole. + partial_grid: Option, /// The drag snapped to a point or a guide at its last step: the arrow turns hollow. snapped: bool, /// The anchor under the pointer (Highlight anchors on mouse over): its path, where it is. @@ -168,6 +201,18 @@ pub struct DirectSelectionTool { click: Option<(NodeId, usize, usize)>, /// A click on a whole path picks the segment on release; a drag still moves the whole path. click_segment: Option<(NodeId, usize, usize)>, + /// An Alt-click on a path selected whole adds this enclosing group on release, as a Group + /// Selection click does; an Alt-drag still copies the selection. + click_group: Option, + /// The selected anchors of area type's frames, picked by a click or a marquee: they show + /// filled, a drag of one moves them all, and the arrow keys nudge them. They stay selected + /// while the document and its selection are at `frame_revision`, the revision after they were + /// picked or the tool last moved them. + frame: BTreeMap>, + frame_revision: (u64, u64), + /// The already selected frame anchor the press landed on without Shift: a click (no drag) + /// selects it alone, as a drag moves every selected frame anchor with it. + frame_click: Option<(NodeId, AnchorRef)>, } impl DirectSelectionTool { @@ -182,14 +227,75 @@ impl DirectSelectionTool { copy_snap: None, handle_snap: HandleSnap::default(), move_snap: None, + partial_snap: None, + partial_grid: None, snapped: false, hover: None, guide: GuideEdit::default(), click: None, click_segment: None, + click_group: None, + frame: BTreeMap::new(), + frame_revision: (0, 0), + frame_click: None, } } + /// The selected frame anchors that still apply, each object with its anchors. They apply while + /// nothing else changed the document or the selection since they were picked (a drag of them + /// changes it as it goes), and only while the selection holds nothing else: every selected + /// object is editable area type with selected frame anchors, and no path anchors or ruler + /// guides are selected. Otherwise the type is selected whole. + fn frame_anchors(&self, cx: &ToolContext) -> FrameAnchors { + let dragging = matches!(self.state, State::TypeArea { began: true, .. }); + if self.group + || self.frame.is_empty() + || (!dragging && cx.revision != self.frame_revision) + || !cx.selection.anchors.is_empty() + || !cx.selection.guides.is_empty() + { + return vec![]; + } + let editable = cx.doc.editable(); + let v: FrameAnchors = self + .frame + .iter() + .filter_map(|(id, set)| { + let n = cx + .doc + .node(*id) + .filter(|n| cx.selection.contains(*id) && is_area_type(n) && editable(*id) && in_scope(cx.doc, cx.isolation, *id))?; + let frame = editable_path(n)?; + let v: Vec = + set.iter().copied().filter(|(si, ai)| frame.subpaths.get(*si).is_some_and(|sp| *ai < sp.anchors.len())).collect(); + (!v.is_empty()).then_some((*id, v)) + }) + .collect(); + if v.len() == cx.selection.objects.len() { v } else { vec![] } + } + + /// The move an arrow key nudges the selected frame anchors by (General › Keyboard Increment, + /// ten times with Shift, along General › Constrain Angle's axes), with those anchors. + fn frame_nudge(&self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Option<(FrameAnchors, Vec2)> { + if !matches!(self.state, State::Idle) { + return None; + } + let step = cx.keyboard_increment * if mods.shift { 10.0 } else { 1.0 }; + let d = match key { + ToolKey::Left => Point::new(-step, 0.0), + ToolKey::Right => Point::new(step, 0.0), + ToolKey::Up => Point::new(0.0, -step), + ToolKey::Down => Point::new(0.0, step), + _ => return None, + }; + let items = self.frame_anchors(cx); + if items.is_empty() { + return None; + } + let d = vectorcraft_geom::constrain_axes(cx.constrain_angle).map_or(d, |axes| axes * d); + Some((items, d.to_vec2())) + } + /// Is `key` the E that Group Selection takes while a marquee is being dragged? Direct /// Selection takes no letter. fn claims_letter(&self, key: ToolKey) -> bool { @@ -199,7 +305,7 @@ impl DirectSelectionTool { /// Whether `id` may be picked while `scope` is isolated: it is that object, or it sits inside it. /// With no isolation, everything may be picked. -fn in_scope(doc: &vectorcraft_doc::Document, scope: Option, id: NodeId) -> bool { +pub(crate) fn in_scope(doc: &vectorcraft_doc::Document, scope: Option, id: NodeId) -> bool { scope.is_none_or(|scope| doc.ancestry(id).is_some_and(|anc| anc.contains(&scope))) } @@ -432,6 +538,23 @@ struct SegmentHit { curved: bool, } +/// The group a Group Selection click on a selected object adds, given the object's `ancestry` +/// (its layer and sublayers first, the object last). It walks up from the object and returns the +/// first ancestor below the layer and its sublayers that is not yet selected. The walk stops at the +/// isolated object, since the next group up is outside isolation mode, and at any layer or +/// sublayer, including one inside a group. +fn next_group(cx: &ToolContext, ancestry: &[NodeId]) -> Option { + // Skip the layer and its sublayers: they are not objects. + let layers = ancestry.iter().take_while(|id| cx.doc.node(**id).is_some_and(Node::is_layer)).count().max(1); + ancestry + .iter() + .skip(layers) + .rev() + .copied() + .take_while(|id| in_scope(cx.doc, cx.isolation, *id) && !cx.doc.node(*id).is_some_and(Node::is_layer)) + .find(|id| !cx.selection.contains(*id)) +} + /// The segment of path `id` nearest to `p`, where the hit test found its stroke. fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option { let pd = cx.doc.node(id)?.path_data()?; @@ -453,11 +576,16 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } - /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, a - /// marquee) cancels it: what it moved goes back and the tool waits for the next press (#1743). + /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh + /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved + /// goes back and the tool waits for the next press (#1743). /// With Group Selection, E during a marquee drag makes the marquee select only the objects /// entirely inside it, whole, and E pressed again makes it select what it selects by default. - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + /// The arrow keys nudge the selected frame anchors of area type. + fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { + if let Some((items, d)) = self.frame_nudge(cx, key, mods) { + return vec![Action::Exec("text.reshapeArea".into(), reshape_params(&items, d)), Action::Notify(FRAME_PICKED.into())]; + } if self.claims_letter(key) && let State::Marquee { enclosed, .. } = &mut self.state { @@ -467,17 +595,26 @@ impl Tool for DirectSelectionTool { if key == ToolKey::Escape && self.guide.busy() { return self.guide.cancel(); } - if key != ToolKey::Escape || matches!(self.state, State::Idle | State::Mesh | State::Corner(_) | State::Bracket(_)) { + if key != ToolKey::Escape || matches!(self.state, State::Idle) { return vec![]; } + // A mesh point drag ends here too; the `Action::Cancel` below undoes it. + self.mesh.cancel(); + // The frame anchors a cancelled drag held stay selected. + let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty(); self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); - (self.click, self.click_segment) = (None, None); - vec![Action::Cancel] + (self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None); + if frame { vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())] } else { vec![Action::Cancel] } } - fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - self.claims_letter(key) + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { + self.claims_letter(key) || self.frame_nudge(cx, key, Mods::default()).is_some() + } + fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == FRAME_PICKED { + self.frame_revision = cx.revision; + } } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { if let Some(out) = self.guide.pointer(cx, ev) { @@ -497,6 +634,8 @@ impl Tool for DirectSelectionTool { (PointerKind::Down, _) => { self.click = None; self.click_segment = None; + self.click_group = None; + self.frame_click = None; if let Some(c) = CornerDrag::hit(cx, ev, true) { self.state = State::Corner(c); return vec![]; @@ -534,7 +673,8 @@ impl Tool for DirectSelectionTool { return self.press_anchor(cx, ev, p, (id, si, ai, grab)); } if let Some((id, anchors)) = hit_frame_edge(cx, p, tol) { - return self.press_type_area(cx, id, anchors, p, ev.mods.shift); + self.frame.clear(); + return self.press_type_area(cx, id, vec![(id, anchors)], p, ev.mods.shift); } // A curved segment of a selected blend's spine reshapes, as a path's does. if let Some((id, seg, t, false)) = hit_spine_segment(cx, p, tol) { @@ -548,6 +688,9 @@ impl Tool for DirectSelectionTool { if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) { return self.press_object(cx, ev, p, tol, h); } + if let Some(out) = self.press_hidden(cx, ev, p) { + return out; + } self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false }; vec![] } @@ -569,9 +712,9 @@ impl Tool for DirectSelectionTool { out } (PointerKind::Drag, State::MoveObject { start, grab, hold, began, .. }) => self.drag_move_object(cx, ev, p, (start, grab, hold, began)), - (PointerKind::Drag, State::TypeArea { id, anchors, start, began }) => { + (PointerKind::Drag, State::TypeArea { items, start, began }) => { let mut out = vec![]; - let on_path = cx.doc.node(id).is_some_and(is_path_type); + let on_path = items.first().and_then(|(id, _)| cx.doc.node(*id)).is_some_and(is_path_type); if !began { if p.distance(start) < cx.tol(3.0) { return out; @@ -580,8 +723,8 @@ impl Tool for DirectSelectionTool { } let d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); let cmd = if on_path { "text.reshapePath" } else { "text.reshapeArea" }; - out.push(Action::Preview(cmd.into(), json!({"id": id.0, "anchors": anchors_json(&anchors), "dx": d.x, "dy": d.y}))); - self.state = State::TypeArea { id, anchors, start, began: true }; + out.push(Action::Preview(cmd.into(), reshape_params(&items, d))); + self.state = State::TypeArea { items, start, began: true }; out } (PointerKind::Drag, State::Handle { id, si, ai, out }) => { @@ -661,7 +804,7 @@ impl Tool for DirectSelectionTool { | State::SpinePoint { began, .. } | State::SpineSegment { began, .. } | State::TypeArea { began, .. }, - ) => self.release_move(began), + ) => self.release_move(cx, began), (PointerKind::Up, State::Handle { .. } | State::SpineHandle { .. }) => { self.state = State::Idle; self.guides.clear(); @@ -679,7 +822,7 @@ impl Tool for DirectSelectionTool { let mut out = self.spine_overlays(cx); out.extend(self.mesh.overlays(cx)); if !self.group { - out.extend(frame_overlays(cx)); + out.extend(frame_overlays(cx, &self.frame_anchors(cx))); out.extend(pathtype::overlays(cx)); } if matches!(self.state, State::Handle { .. } | State::MoveAnchors { .. } | State::MoveObject { .. }) { @@ -792,22 +935,60 @@ fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> { } /// The frame anchors of the selected area type and the path anchors of the selected type on a -/// path, which Direct Selection drags. -fn frame_overlays(cx: &ToolContext) -> Vec { +/// path, which Direct Selection drags; the `selected` frame anchors are filled. +fn frame_overlays(cx: &ToolContext, selected: &[(NodeId, Vec)]) -> Vec { let mut out = vec![]; for id in &cx.selection.objects { let Some(frame) = cx.doc.node(*id).filter(|n| is_area_type(n) || is_path_type(n)).and_then(editable_path) else { continue }; let color = cx.doc.layer_color(*id); - out.extend(frame.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 })); + let picked = selected.iter().find(|(s, _)| s == id).map(|(_, v)| v.as_slice()).unwrap_or_default(); + out.extend(frame.anchors().map(|(si, ai, a)| Overlay::Anchor { p: a.p, color, filled: picked.contains(&(si, ai)), size: 5.0 })); } out } impl DirectSelectionTool { + /// Press on a frame anchor of area type: Shift toggles it among the selected frame anchors; + /// without Shift, one not among them becomes the only one, and one among them becomes the only + /// one when the press is released without a drag. A drag moves them all. + fn press_frame_anchor(&mut self, cx: &ToolContext, id: NodeId, anchor: AnchorRef, p: Point, shift: bool) -> Vec { + let mut picked: BTreeMap> = + self.frame_anchors(cx).into_iter().map(|(id, v)| (id, v.into_iter().collect())).collect(); + let on = picked.get(&id).is_some_and(|set| set.contains(&anchor)); + if shift { + let set = picked.entry(id).or_default(); + if on { + set.remove(&anchor); + } else { + set.insert(anchor); + } + if set.is_empty() { + picked.remove(&id); + } + } else if !on { + picked = BTreeMap::from([(id, BTreeSet::from([anchor]))]); + } + // The selected objects follow: the type is selected while it has selected frame anchors, + // and a click that picks a new anchor without Shift selects that type alone. + let mut out = vec![]; + let any = picked.contains_key(&id); + if !shift && !on && cx.selection.objects != [id] { + out.push(Action::Exec("select.set".into(), json!({"ids": [id.0]}))); + } else if shift && cx.selection.contains(id) != any { + out.push(Action::Exec("select.toggle".into(), json!({"id": id.0}))); + } + let items: FrameAnchors = picked.iter().map(|(id, set)| (*id, set.iter().copied().collect())).collect(); + self.state = if items.is_empty() { State::Idle } else { State::TypeArea { items, start: p, began: false } }; + self.frame = picked; + self.frame_click = (on && !shift).then_some((id, anchor)); + out.push(Action::Notify(FRAME_PICKED.into())); + out + } + /// Press on area type's frame anchors (a corner, or an edge's two ends) or an anchor of type - /// on a path's path: select the text and get ready to drag them. - fn press_type_area(&mut self, cx: &ToolContext, id: NodeId, anchors: Vec, p: Point, shift: bool) -> Vec { - self.state = State::TypeArea { id, anchors, start: p, began: false }; + /// on a path's path, of `id`: select the text and get ready to drag `items`. + fn press_type_area(&mut self, cx: &ToolContext, id: NodeId, items: FrameAnchors, p: Point, shift: bool) -> Vec { + self.state = State::TypeArea { items, start: p, began: false }; if cx.selection.contains(id) { vec![] } else if shift { @@ -836,12 +1017,26 @@ impl DirectSelectionTool { mod tests; impl DirectSelectionTool { + /// A press where a clipping mask hides the art of a selected object (picked in the Layers + /// panel, say) grabs the selection by it, as a press on its visible part does; `None` + /// elsewhere, and with Shift (a marquee then adds to the selection). + fn press_hidden(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option> { + if ev.mods.shift { + return None; + } + selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects)?; + self.state = State::MoveObject { start: p, grab: None, hold: p, began: false, deselect: None }; + Some(vec![]) + } fn press_group(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64) -> Vec { if let Some(out) = self.guide.press(cx, ev) { self.state = State::Idle; return out; } let Some(mut h) = hit_test(cx.doc, p, cx.selection_hit_options()) else { + if let Some(out) = self.press_hidden(cx, ev, p) { + return out; + } self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false }; return vec![]; }; @@ -850,11 +1045,7 @@ impl DirectSelectionTool { h.ancestry.push(part); h.leaf = part; } - // Walk up from the leaf: select the first ancestor not yet selected (below the layer). - // Stop at the isolated object: the next group up is outside isolation mode. - let chain: Vec = h.ancestry.iter().skip(1).rev().copied().take_while(|id| in_scope(cx.doc, cx.isolation, *id)).collect(); - let target = - if cx.selection.contains(h.leaf) { chain.iter().find(|id| !cx.selection.contains(**id)).copied().unwrap_or(h.leaf) } else { h.leaf }; + let target = if cx.selection.contains(h.leaf) { next_group(cx, &h.ancestry).unwrap_or(h.leaf) } else { h.leaf }; let mut deselect = None; let mut out = vec![]; if ev.mods.shift { @@ -887,19 +1078,31 @@ impl DirectSelectionTool { return vec![]; } // A double-click edits what is drawn: not a clipping path's outline. - if hit_test(cx.doc, p, cx.hit_options()).and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { + let hit = hit_test(cx.doc, p, cx.hit_options()); + if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } + // Outside the isolated art it leaves isolation mode, as with the Selection tool (#4466). + if hit.is_none() && cx.isolation.is_some() { + return vec![Action::Exec("object.exitIsolation".into(), json!({}))]; + } vec![] } fn press_anchor(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, (id, si, ai, grab): (NodeId, usize, usize, Point)) -> Vec { - if cx.doc.node(id).is_some_and(|n| is_area_type(n) || is_path_type(n)) { - return self.press_type_area(cx, id, vec![(si, ai)], p, ev.mods.shift); + if cx.doc.node(id).is_some_and(is_area_type) { + return self.press_frame_anchor(cx, id, (si, ai), p, ev.mods.shift); } - // Alt picks the whole path (and Alt-drag copies it), as on a segment. + if cx.doc.node(id).is_some_and(is_path_type) { + return self.press_type_area(cx, id, vec![(id, vec![(si, ai)])], p, ev.mods.shift); + } + // Alt picks the whole path (and Alt-drag copies it), as on a segment. On a path + // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None }; let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); + if whole && !ev.mods.shift { + self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); + } return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } // A path with all its anchors selected is stored whole (no partial entry). @@ -956,11 +1159,17 @@ impl DirectSelectionTool { return vec![Action::Exec("select.segments".into(), json!({"id": h.leaf.0, "segments": [[s.si, s.seg]]}))]; } } - // Clicking the fill selects the whole leaf path (all anchors). + // Clicking the fill selects the whole leaf path (all anchors). With Alt, a click + // on a path already selected whole adds the next enclosing group on release, + // as Group Selection's click does; each further Alt-click climbs one level. self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect: None }; + if ev.mods.alt && whole && !ev.mods.shift { + self.click_group = next_group(cx, &h.ancestry); + } if ev.mods.shift { return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))]; } + self.frame.clear(); if !cx.selection.contains(h.leaf) || cx.selection.partial(h.leaf).is_some() { return vec![Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))]; } @@ -1002,7 +1211,16 @@ impl DirectSelectionTool { if p.distance(start) < cx.tol(3.0) { return out; } - out.push(Action::Begin(if ev.mods.alt { "Copy".into() } else { "Move".into() })); + // With direct-selected anchors or segments in the selection, the drag moves + // them and the objects selected whole (`path.moveAnchors`), as an anchor drag + // does, while Alt is up; the other anchors of a partly selected path stay in + // place. The history names the move or the copy at the end. + self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); + let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snap_to_pixel); + self.partial_grid = + grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds(cx.selection, cx.doc, cx.preview_bounds))); + let copy = ev.mods.alt && self.partial_snap.is_none(); + out.push(Action::Begin(if copy { "Copy".into() } else { "Move".into() })); self.state = State::MoveObject { start, grab, hold, began: true, deselect: None }; if grab.is_some() { // Alt can go down or up at any time: gather both while nothing has moved. @@ -1015,6 +1233,21 @@ impl DirectSelectionTool { let mut d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); let unsnapped = d; self.guides.clear(); + if !ev.mods.alt + && let Some(snap) = &self.partial_snap + { + let held = grab.unwrap_or(hold); + if let Some(grid) = &self.partial_grid { + (d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) }; + } else { + let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true)); + let (q, guides) = snap.snap_from(cx, held + (p - start), shift.as_ref()); + (d, self.guides) = (q - held, guides); + } + self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y}))); + return out; + } let snap = if ev.mods.alt { &self.copy_snap } else { &self.anchor_snap }; if let (Some(grab), Some(snap)) = (grab, snap) { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); @@ -1030,15 +1263,29 @@ impl DirectSelectionTool { )); out } - fn release_move(&mut self, began: bool) -> Vec { + fn release_move(&mut self, cx: &ToolContext, began: bool) -> Vec { let deselect = match self.state { State::MoveObject { deselect, .. } => deselect, _ => None, }; + // The frame anchors a drag moved stay selected. + let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty(); self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); + let group = self.click_group.take(); + // A click on one of several selected frame anchors selects it alone. + if let (false, Some((id, anchor))) = (began, self.frame_click.take()) { + self.frame = BTreeMap::from([(id, BTreeSet::from([anchor]))]); + let mut out = vec![]; + if cx.selection.objects != [id] { + out.push(Action::Exec("select.set".into(), json!({"ids": [id.0]}))); + } + out.push(Action::Notify(FRAME_PICKED.into())); + return out; + } match (began, deselect, self.click.take(), self.click_segment.take()) { + (true, ..) if frame => vec![Action::Commit, Action::Notify(FRAME_PICKED.into())], (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { @@ -1047,14 +1294,18 @@ impl DirectSelectionTool { (false, None, None, Some((id, si, seg))) => { vec![Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]]}))] } - (false, None, None, None) => vec![], + (false, None, None, None) => group.map(|g| Action::Exec("select.add".into(), json!({"ids": [g.0]}))).into_iter().collect(), } } fn release_marquee(&mut self, cx: &ToolContext, p: Point, (start, toggle, enclosed): (Point, bool, bool)) -> Vec { self.state = State::Idle; let r = Rect::from_points(start, p); if r.width() < cx.tol(3.0) && r.height() < cx.tol(3.0) { - return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; + if toggle { + return vec![]; + } + self.frame.clear(); + return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it // (members of groups too), each whole, as a click selects one. @@ -1076,18 +1327,54 @@ impl DirectSelectionTool { } } }); + let editable = cx.doc.editable(); + // Direct Selection: the frame anchors of area type inside the rect are selected + // (with Shift, toggled), and the type with them, whole. + let mut framed: Vec<(NodeId, BTreeSet)> = vec![]; + if !self.group { + walk_pickable(cx.doc, cx.isolation, |n| { + if is_area_type(n) + && let Some(frame) = editable_path(n) + { + let inside: BTreeSet = frame.anchors().filter(|(_, _, a)| r.contains(a.p)).map(|(s, i, _)| (s, i)).collect(); + if !inside.is_empty() { + framed.push((n.id, inside)); + } + } + }); + framed.retain(|(id, _)| editable(*id)); + } + let mut marked: BTreeMap> = + if toggle { self.frame_anchors(cx).into_iter().map(|(id, v)| (id, v.into_iter().collect())).collect() } else { BTreeMap::new() }; + for (id, inside) in &framed { + let set = marked.entry(*id).or_default(); + *set = if toggle { set.symmetric_difference(inside).copied().collect() } else { inside.clone() }; + let any = !set.is_empty(); + if !any { + marked.remove(id); + } + // With Shift the type is toggled only when it gains its first selected frame + // anchor or loses its last one. + if !toggle || cx.selection.contains(*id) != any { + sel.push((*id, vec![])); + } + } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); - if whole && !sel.iter().any(|(s, _)| *s == id) { + if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) { sel.push((id, vec![])); } } - let editable = cx.doc.editable(); sel.retain(|(id, _)| editable(*id)); + self.frame = marked; let items: Vec = sel.iter().map(|(id, v)| json!({"id": id.0, "anchors": anchors_json(v)})).collect(); let art = Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": if toggle { "toggle" } else { "set" }})); - std::iter::once(art).chain(crate::rulerguide::marquee_select(cx, r, false)).collect() + let mut out: Vec = std::iter::once(art).chain(crate::rulerguide::marquee_select(cx, r, false)).collect(); + if !self.frame.is_empty() { + out.push(Action::Notify(FRAME_PICKED.into())); + } + out } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 311efe2231..d191085091 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2,6 +2,40 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; +/// Direct Selection and Group Selection grab a selected clipped object (picked in the Layers +/// panel) where its mask hides it, as on its visible part: a drag moves it. With nothing of it +/// selected there, a press starts a marquee. +#[test] +fn a_press_where_a_mask_hides_a_selected_object_drags_it() { + let (d, _, _, art) = doc_with_masked_square(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(art); + let none = Selection::default(); + // (370, 450): on the art, outside the mask (400..500). + for group in [false, true] { + let c = cx(&d, &picked, &p); + let mut t = DirectSelectionTool::new(group); + let down = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 370.0, 450.0)); + assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c.starts_with("select."))), "{down:?} (group: {group})"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 470.0)); + assert!(a.iter().any(|a| matches!(a, Action::Begin(n) if n == "Move")), "{a:?} (group: {group})"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 390.0, 470.0)); + // With Shift, a marquee. + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = DirectSelectionTool::new(group); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 370.0, 450.0).with_mods(shift)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 470.0).with_mods(shift)); + assert!(!a.iter().any(|a| matches!(a, Action::Begin(_))), "{a:?} (group: {group})"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_))), "a marquee (group: {group})"); + let c = cx(&d, &none, &p); + let mut t = DirectSelectionTool::new(group); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 370.0, 450.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 470.0)); + assert!(!a.iter().any(|a| matches!(a, Action::Begin(_))), "{a:?} (group: {group})"); + } +} + /// #414: a ruler guide is picked over the art, but an anchor on it is picked first. #[test] fn direct_and_group_selection_pick_ruler_guides() { @@ -250,13 +284,13 @@ fn dragging_a_frame_corner_or_edge_reshapes_area_type() { // The bottom-right corner of the 120 × 40 frame at (300, 300) selects the text... assert_eq!( t.pointer(&cx1, &PointerEvent::new(PointerKind::Down, 421.0, 339.0)), - vec![Action::Exec("select.set".into(), json!({"ids": [text.0]}))] + vec![Action::Exec("select.set".into(), json!({"ids": [text.0]})), Action::Notify(FRAME_PICKED.into())] ); // ...and drags that corner. let a = t.pointer(&cx1, &PointerEvent::new(PointerKind::Drag, 461.0, 399.0)); assert_eq!(a[0], Action::Begin("Reshape Type Area".into())); assert_eq!(a[1], Action::Preview("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 2]], "dx": 40.0, "dy": 60.0}))); - assert_eq!(t.pointer(&cx1, &PointerEvent::new(PointerKind::Up, 461.0, 399.0)), vec![Action::Commit]); + assert_eq!(t.pointer(&cx1, &PointerEvent::new(PointerKind::Up, 461.0, 399.0)), vec![Action::Commit, Action::Notify(FRAME_PICKED.into())]); // The top edge drags both its ends; a click alone changes nothing. let mut s = Selection::default(); s.add(text); @@ -265,10 +299,146 @@ fn dragging_a_frame_corner_or_edge_reshapes_area_type() { let a = t.pointer(&cx2, &PointerEvent::new(PointerKind::Drag, 350.0, 281.0)); assert_eq!(a[1], Action::Preview("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 0], [0, 1]], "dx": 0.0, "dy": -20.0}))); t.pointer(&cx2, &PointerEvent::new(PointerKind::Up, 350.0, 281.0)); - assert!(t.pointer(&cx2, &PointerEvent::new(PointerKind::Down, 300.0, 340.0)).is_empty()); + assert_eq!(t.pointer(&cx2, &PointerEvent::new(PointerKind::Down, 300.0, 340.0)), vec![Action::Notify(FRAME_PICKED.into())]); assert!(t.pointer(&cx2, &PointerEvent::new(PointerKind::Up, 300.0, 340.0)).is_empty()); - // The selected frame's corners show. - assert_eq!(t.overlays(&cx2).iter().filter(|o| matches!(o, Overlay::Anchor { filled: false, .. })).count(), 4); + // The selected frame's corners show, the one clicked filled. + assert_eq!(t.overlays(&cx2).iter().filter(|o| matches!(o, Overlay::Anchor { filled: false, .. })).count(), 3); + assert_eq!(t.overlays(&cx2).iter().filter(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if *p == Point::new(300.0, 340.0))).count(), 1); +} + +/// The frame anchor squares of the selected area type that `t` draws: (filled, hollow). +fn frame_squares(t: &DirectSelectionTool, c: &ToolContext) -> (Vec, Vec) { + let mut out = (vec![], vec![]); + for o in t.overlays(c) { + if let Overlay::Anchor { p, filled, size: 5.0, .. } = o { + if filled { out.0.push(p) } else { out.1.push(p) } + } + } + out +} + +/// A Direct Selection marquee selects the frame anchors of area type inside it, which show +/// filled: a drag of one moves them all, the arrow keys nudge them, and Shift toggles them. +#[test] +fn a_marquee_selects_frame_anchors_of_area_type() { + let (d, text) = doc_with_area_type(); + let p = paint(); + let none = Selection::default(); + let cx1 = cx(&d, &none, &p); + let mut t = DirectSelectionTool::new(false); + let ev = |k, x, y| PointerEvent::new(k, x, y); + let shift = |k, x, y| PointerEvent::new(k, x, y).with_mods(Mods { shift: true, ..Mods::default() }); + // A marquee round the 120 × 40 frame's right-hand corners, (420, 300) and (420, 340). + assert!(t.pointer(&cx1, &ev(PointerKind::Down, 400.0, 280.0)).is_empty()); + t.pointer(&cx1, &ev(PointerKind::Drag, 440.0, 360.0)); + assert_eq!( + t.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), + vec![ + Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": text.0, "anchors": []}], "mode": "set"})), + Action::Notify(FRAME_PICKED.into()), + ] + ); + let mut s = Selection::default(); + s.add(text); + let cx2 = cx(&d, &s, &p); + t.notify(&cx2, FRAME_PICKED); + let (filled, hollow) = frame_squares(&t, &cx2); + assert_eq!(filled, vec![Point::new(420.0, 300.0), Point::new(420.0, 340.0)]); + assert_eq!(hollow, vec![Point::new(300.0, 300.0), Point::new(300.0, 340.0)]); + // A drag of one of them moves both. + assert_eq!(t.pointer(&cx2, &ev(PointerKind::Down, 420.0, 340.0)), vec![Action::Notify(FRAME_PICKED.into())]); + let a = t.pointer(&cx2, &ev(PointerKind::Drag, 440.0, 360.0)); + assert_eq!(a[0], Action::Begin("Reshape Type Area".into())); + assert_eq!(a[1], Action::Preview("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 1], [0, 2]], "dx": 20.0, "dy": 20.0}))); + assert_eq!(t.pointer(&cx2, &ev(PointerKind::Up, 440.0, 360.0)), vec![Action::Commit, Action::Notify(FRAME_PICKED.into())]); + // The arrow keys nudge them by the keyboard increment, ten times that with Shift. + let nudged = |anchors: Value, dx: f64, dy: f64| { + vec![ + Action::Exec("text.reshapeArea".into(), json!({"id": text.0, "anchors": anchors, "dx": dx, "dy": dy})), + Action::Notify(FRAME_PICKED.into()), + ] + }; + assert!(t.claims_key(&cx2, ToolKey::Right) && !t.claims_key(&cx2, ToolKey::Enter)); + assert_eq!(t.key(&cx2, ToolKey::Right, Mods::default()), nudged(json!([[0, 1], [0, 2]]), 1.0, 0.0)); + assert_eq!(t.key(&cx2, ToolKey::Up, Mods { shift: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), 0.0, -10.0)); + // Any other change of the document or the selection (Deselect, then the same type selected + // again) leaves the type selected whole: the arrow keys are no longer the tool's. + let mut later = cx(&d, &s, &p); + later.revision = (0, 1); + assert!(frame_squares(&t, &later).0.is_empty()); + assert!(!t.claims_key(&later, ToolKey::Right)); + // Shift-click takes one out; the other still nudges. + assert_eq!(t.pointer(&cx2, &shift(PointerKind::Down, 420.0, 300.0)), vec![Action::Notify(FRAME_PICKED.into())]); + assert!(t.pointer(&cx2, &shift(PointerKind::Up, 420.0, 300.0)).is_empty()); + assert_eq!(frame_squares(&t, &cx2).0, vec![Point::new(420.0, 340.0)]); + assert_eq!(t.key(&cx2, ToolKey::Down, Mods::default()), nudged(json!([[0, 2]]), 0.0, 1.0)); + // A Shift-marquee round the bottom corners toggles them: (300, 340) joins, (420, 340) leaves. + t.pointer(&cx2, &shift(PointerKind::Down, 280.0, 330.0)); + t.pointer(&cx2, &shift(PointerKind::Drag, 440.0, 360.0)); + let a = t.pointer(&cx2, &shift(PointerKind::Up, 440.0, 360.0)); + assert_eq!(a[0], Action::Exec("select.anchorsMany".into(), json!({"items": [], "mode": "toggle"})), "the type stays selected"); + assert_eq!(frame_squares(&t, &cx2).0, vec![Point::new(300.0, 340.0)]); + // When the selection changes, the frame anchors are no longer selected. + assert!(frame_squares(&t, &cx1).0.is_empty()); + assert!(!t.claims_key(&cx1, ToolKey::Right) && t.key(&cx1, ToolKey::Right, Mods::default()).is_empty()); + // A marquee that also reaches a path's anchor (the rectangle's corner at (200, 200)) selects + // the type whole, as before: the arrow keys move the path's anchor and the type alike. + let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap(); + t.pointer(&cx1, &ev(PointerKind::Down, 440.0, 360.0)); + t.pointer(&cx1, &ev(PointerKind::Drag, 190.0, 190.0)); + let a = t.pointer(&cx1, &ev(PointerKind::Up, 190.0, 190.0)); + let items = json!([{"id": rect.0, "anchors": [[0, 2]]}, {"id": text.0, "anchors": []}]); + assert_eq!(a[0], Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))); + let mut mixed = Selection::default(); + mixed.add(rect); + mixed.anchors.insert(rect, [(0, 2)].into()); + mixed.add(text); + let cx3 = cx(&d, &mixed, &p); + t.notify(&cx3, FRAME_PICKED); + assert!(frame_squares(&t, &cx3).0.is_empty()); + assert!(!t.claims_key(&cx3, ToolKey::Right)); + // Group Selection's marquee selects the type whole, without its frame anchors. + let mut g = DirectSelectionTool::new(true); + g.pointer(&cx1, &ev(PointerKind::Down, 400.0, 280.0)); + g.pointer(&cx1, &ev(PointerKind::Drag, 440.0, 360.0)); + assert_eq!( + g.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)), + vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": text.0, "anchors": []}], "mode": "set"}))] + ); +} + +/// A click without a drag on one of several selected frame anchors selects it alone, as a click on +/// a selected path anchor does; a drag of it still moves them all. +#[test] +fn a_click_on_a_selected_frame_anchor_selects_it_alone() { + let (d, text) = doc_with_area_type(); + let p = paint(); + let none = Selection::default(); + let cx1 = cx(&d, &none, &p); + let mut t = DirectSelectionTool::new(false); + let ev = |k, x, y| PointerEvent::new(k, x, y); + // A marquee round the right-hand corners, (420, 300) and (420, 340). + t.pointer(&cx1, &ev(PointerKind::Down, 400.0, 280.0)); + t.pointer(&cx1, &ev(PointerKind::Drag, 440.0, 360.0)); + t.pointer(&cx1, &ev(PointerKind::Up, 440.0, 360.0)); + let mut s = Selection::default(); + s.add(text); + let cx2 = cx(&d, &s, &p); + t.notify(&cx2, FRAME_PICKED); + assert_eq!(frame_squares(&t, &cx2).0, vec![Point::new(420.0, 300.0), Point::new(420.0, 340.0)]); + // A click on (420, 340) keeps both until the release, then selects it alone. + assert_eq!(t.pointer(&cx2, &ev(PointerKind::Down, 420.0, 340.0)), vec![Action::Notify(FRAME_PICKED.into())]); + assert_eq!(frame_squares(&t, &cx2).0.len(), 2, "both, for a drag"); + assert_eq!(t.pointer(&cx2, &ev(PointerKind::Up, 420.0, 340.0)), vec![Action::Notify(FRAME_PICKED.into())]); + t.notify(&cx2, FRAME_PICKED); + assert_eq!(frame_squares(&t, &cx2).0, vec![Point::new(420.0, 340.0)]); + assert_eq!( + t.key(&cx2, ToolKey::Right, Mods::default()), + vec![ + Action::Exec("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 2]], "dx": 1.0, "dy": 0.0})), + Action::Notify(FRAME_PICKED.into()), + ] + ); } /// #3980: type on a path shows its path's anchors and a drag of one reshapes the path, the last @@ -526,6 +696,141 @@ fn isolation_mode_leaves_art_outside_the_isolated_group() { assert!(a.is_empty(), "does not add the group outside isolation ({outer:?}): {a:?}"); } +/// #4466: in isolation mode a Direct Selection double-click outside the isolated art (on the +/// object beside it, or on nothing) leaves isolation mode, as the Selection tool's does; on the +/// isolated art it doesn't. +#[test] +fn a_double_click_outside_isolation_leaves_it() { + let (d, _, _, inner, _) = nested_group_doc(); + let p = paint(); + let none = Selection::default(); + let isolated = ToolContext { isolation: Some(inner), ..cx(&d, &none, &p) }; + let double = |x: f64, y: f64| DirectSelectionTool::new(false).pointer(&isolated, &PointerEvent::new(PointerKind::DoubleClick, x, y)); + let exit = vec![Action::Exec("object.exitIsolation".into(), json!({}))]; + assert_eq!(double(350.0, 350.0), exit, "on the object beside the isolated group"); + assert_eq!(double(700.0, 700.0), exit, "on nothing"); + assert!(double(150.0, 150.0).is_empty(), "on the isolated art"); + assert!(DirectSelectionTool::new(false).pointer(&cx(&d, &none, &p), &PointerEvent::new(PointerKind::DoubleClick, 700.0, 700.0)).is_empty()); +} + +/// With Direct Selection, an Alt-click on a path selected whole adds its group on release, and +/// each further Alt-click adds the next group up, as Group Selection's clicks do, on an anchor, +/// a segment and the fill alike. The climb stops below the layer and at the isolated group. +#[test] +fn alt_clicks_on_a_path_selected_whole_add_its_groups() { + let (d, inside, _, inner, outer) = nested_group_doc(); + let p = paint(); + let alt = Mods { alt: true, ..Default::default() }; + let add = |id: NodeId| vec![Action::Exec("select.add".into(), json!({"ids": [id.0]}))]; + let click = |cx: &ToolContext, x: f64, y: f64| { + let mut t = DirectSelectionTool::new(false); + let down = t.pointer(cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(alt)); + assert!(down.is_empty(), "({x}, {y}): {down:?}"); + t.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(alt)) + }; + for (x, y) in [(100.0, 100.0), (150.0, 100.0), (150.0, 150.0)] { + let mut s = Selection::default(); + s.set([inside]); + assert_eq!(click(&cx(&d, &s, &p), x, y), add(inner), "({x}, {y}): the path's group"); + s.set([inside, inner]); + assert_eq!(click(&cx(&d, &s, &p), x, y), add(outer), "({x}, {y}): the group around it"); + s.set([inside, inner, outer]); + assert!(click(&cx(&d, &s, &p), x, y).is_empty(), "({x}, {y}): the layer is not added"); + s.set([inside, inner]); + let isolated = ToolContext { isolation: Some(inner), ..cx(&d, &s, &p) }; + assert!(click(&isolated, x, y).is_empty(), "({x}, {y}): not the group outside isolation"); + } +} + +/// In a sublayer, a Group Selection click and a Direct Selection Alt-click climb to the group +/// and stop there: the sublayer is not added. +#[test] +fn group_clicks_in_a_sublayer_stop_below_the_sublayer() { + use vectorcraft_doc::{Appearance, Document, LayerColor, Node}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (sub, g, a) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + d.insert(Some(sub), 0, Node::group(g, vec![])).unwrap(); + d.insert(Some(g), 0, Node::path(a, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Appearance::default_art())) + .unwrap(); + let p = paint(); + let alt = Mods { alt: true, ..Default::default() }; + let click = |s: &Selection, group: bool, mods: Mods| { + let c = cx(&d, s, &p); + let mut t = DirectSelectionTool::new(group); + let down = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(mods)); + let up = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(mods)); + [down, up].concat() + }; + let add = |id: NodeId| vec![Action::Exec("select.add".into(), json!({"ids": [id.0]}))]; + let mut s = Selection::default(); + s.set([a]); + assert_eq!(click(&s, true, Mods::default()), add(g), "Group Selection adds the group"); + assert_eq!(click(&s, false, alt), add(g), "an Alt-click adds the group"); + s.set([a, g]); + assert!(click(&s, true, Mods::default()).is_empty(), "Group Selection does not add the sublayer"); + assert!(click(&s, false, alt).is_empty(), "an Alt-click does not add the sublayer"); +} + +/// When a group holds a sublayer, the climb stops at the sublayer: it adds neither the sublayer +/// nor the group above it. +#[test] +fn group_clicks_stop_at_a_sublayer_inside_a_group() { + use vectorcraft_doc::{Appearance, Document, LayerColor, Node}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (outer, sub, g, a) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::group(outer, vec![])).unwrap(); + d.insert(Some(outer), 0, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + d.insert(Some(sub), 0, Node::group(g, vec![])).unwrap(); + d.insert(Some(g), 0, Node::path(a, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Appearance::default_art())) + .unwrap(); + let p = paint(); + let alt = Mods { alt: true, ..Default::default() }; + let click = |s: &Selection, group: bool, mods: Mods| { + let c = cx(&d, s, &p); + let mut t = DirectSelectionTool::new(group); + let down = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(mods)); + let up = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(mods)); + [down, up].concat() + }; + let add = |id: NodeId| vec![Action::Exec("select.add".into(), json!({"ids": [id.0]}))]; + let mut s = Selection::default(); + s.set([a]); + assert_eq!(click(&s, true, Mods::default()), add(g), "Group Selection adds the group"); + assert_eq!(click(&s, false, alt), add(g), "an Alt-click adds the group"); + s.set([a, g]); + assert!(click(&s, true, Mods::default()).is_empty(), "Group Selection does not add the sublayer"); + assert!(click(&s, false, alt).is_empty(), "an Alt-click does not add the sublayer"); +} + +/// An Alt-drag from a path selected whole inside a group copies the path and adds no group, and +/// Alt+Shift-click on a segment or the fill still toggles the path, adding no group either. +#[test] +fn alt_drags_and_alt_shift_clicks_on_a_path_in_a_group_add_no_group() { + let (d, inside, ..) = nested_group_doc(); + let p = paint(); + let mut s = Selection::default(); + s.set([inside]); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Default::default() }; + for (x, y) in [(100.0, 100.0), (150.0, 100.0), (150.0, 150.0)] { + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(alt)).is_empty()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 20.0, y).with_mods(alt)); + assert!(matches!(a.as_slice(), [Action::Begin(_), Action::Preview(c, v)] if c == "object.transform" && v["copy"] == true), "{a:?}"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x + 20.0, y).with_mods(alt)), vec![Action::Commit]); + } + let alt_shift = Mods { alt: true, shift: true, ..Default::default() }; + for (x, y) in [(150.0, 100.0), (150.0, 150.0)] { + let mut t = DirectSelectionTool::new(false); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(alt_shift)); + assert_eq!(a, vec![Action::Exec("select.toggle".into(), json!({"id": inside.0}))], "({x}, {y})"); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(alt_shift)).is_empty(), "({x}, {y})"); + } +} + /// #927: a marquee across type selects the type object whole, beside the anchors it holds. #[test] fn marquee_selects_type_it_touches() { @@ -541,7 +846,8 @@ fn marquee_selects_type_it_touches() { t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0)); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)); let items = json!([{"id": rect.0, "anchors": [[0, 2]]}, {"id": text.0, "anchors": []}]); - assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))]); + // The frame's corners are inside too: they are selected with the type. + assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"})), Action::Notify(FRAME_PICKED.into())]); // Away from the type, only anchors. t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0)); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0)); @@ -661,6 +967,41 @@ fn escape_cancels_a_drag() { assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![], "nothing to cancel"); } +/// Escape also cancels a corner widget drag and a drag of the brackets of type on a path, and +/// the release after it does nothing. After a press on a widget that has not moved, Escape drops +/// the press, so its release selects no corner. +#[test] +fn escape_cancels_a_corner_widget_or_bracket_drag() { + let p = paint(); + let (d, rect) = doc_with_rect(); + let mut s = Selection::default(); + s.set([rect]); + let corners = cx(&d, &s, &p); + let (d2, text) = doc_with_path_type(); + let mut s2 = Selection::default(); + s2.add(text); + let brackets = cx(&d2, &s2, &p); + // (what, its context, the press, the drag's first step) + for (what, c, from, to) in [ + ("corner widget", &corners, Point::new(110.0, 110.0), Point::new(120.0, 120.0)), + ("bracket", &brackets, Point::new(400.0, 290.0), Point::new(340.0, 290.0)), + ] { + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(c, &PointerEvent::new(PointerKind::Down, from.x, from.y)).is_empty(), "{what}"); + let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{what}: {a:?}"); + assert!(t.busy(), "{what}"); + assert_eq!(t.key(c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{what}: Escape cancels the drag"); + assert!(!t.busy(), "{what}"); + assert!(t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x - 5.0, to.y)).is_empty(), "{what}: the drag is over"); + assert!(t.pointer(c, &PointerEvent::new(PointerKind::Up, to.x - 5.0, to.y)).is_empty(), "{what}: the release does nothing"); + } + let mut t = DirectSelectionTool::new(false); + t.pointer(&corners, &PointerEvent::new(PointerKind::Down, 110.0, 110.0)); + assert_eq!(t.key(&corners, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&corners, &PointerEvent::new(PointerKind::Up, 110.0, 110.0)).is_empty(), "the click selects no corner"); +} + #[test] fn dragging_a_curved_segment_reshapes_it_and_a_straight_one_moves_its_anchors() { let (d, arch) = arch_doc(); @@ -963,6 +1304,92 @@ fn alt_during_a_drag_by_an_anchor_toggles_the_copy() { assert!(matches!(a.last(), Some(Action::Preview(c, _)) if c == "path.moveAnchors"), "{a:?}"); } +/// A drag from the fill of a path selected whole, while another path has some anchors selected, +/// moves the selected anchors and the paths selected whole (`path.moveAnchors`), as a drag of +/// an anchor does, with Direct Selection and Group Selection alike. Alt, pressed or released at +/// any time during the drag, turns the copy of the selected objects on and off, and a selection +/// of whole paths only still moves as objects. +#[test] +fn a_drag_from_a_fill_with_anchors_selected_moves_the_anchors() { + let (d, a, b) = two_squares(); + let p = paint(); + let mut mixed = anchors_of(b, &[(0, 0)]); + mixed.objects.insert(0, a); + let mut whole = Selection::default(); + whole.set([a, b]); + let alt = Mods { alt: true, ..Default::default() }; + for group in [false, true] { + let c = cx(&d, &mixed, &p); + let mut t = DirectSelectionTool::new(group); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty(), "group: {group}"); + let out = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 171.0, 153.0)); + assert_eq!( + out, + vec![Action::Begin("Move".into()), Action::Preview("path.moveAnchors".into(), json!({"dx": 21.0, "dy": 3.0}))], + "group: {group}" + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 171.0, 153.0)), vec![Action::Commit]); + // Alt held at the start, released and pressed again: a copy, a move, a copy. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(alt)); + let out = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 171.0, 153.0).with_mods(alt)); + assert!(matches!(out.last(), Some(Action::Preview(c, v)) if c == "object.transform" && v["copy"] == true), "group: {group} {out:?}"); + assert_eq!(out.first(), Some(&Action::Begin("Move".into())), "the history names it by the last preview"); + let out = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 172.0, 153.0)); + assert_eq!(out, vec![Action::Preview("path.moveAnchors".into(), json!({"dx": 22.0, "dy": 3.0}))], "group: {group}"); + let out = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 173.0, 153.0).with_mods(alt)); + assert!(matches!(out.as_slice(), [Action::Preview(c, v)] if c == "object.transform" && v["copy"] == true), "group: {group} {out:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 173.0, 153.0).with_mods(alt)); + let c = cx(&d, &whole, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + let out = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 171.0, 153.0)); + assert!(matches!(out.last(), Some(Action::Preview(c, _)) if c == "object.transform"), "group: {group} {out:?}"); + } +} + +/// A drag from the fill of A, selected whole, while B's top-left anchor is selected snaps the +/// point it holds as a dragged anchor does: near an anchor of B that stays put, it lands on it. +/// With Snap to Grid on, the box around A and B's selected anchor, (100, 100)–(300, 300), lands an +/// edge on the 9 pt grid instead: moved by (21, 3), its right side and bottom (321, 303) are +/// nearest the gridlines 324 and 306, and with Shift the level move by 13 lands the right side on +/// 315. +#[test] +fn a_drag_from_a_fill_with_anchors_selected_snaps() { + let (d, a, b) = two_squares(); + let p = paint(); + let mut mixed = anchors_of(b, &[(0, 0)]); + mixed.objects.insert(0, a); + let none = Mods::default(); + for group in [false, true] { + let mut t = DirectSelectionTool::new(group); + let c = cx(&d, &mixed, &p); + let (v, labels) = drag(&mut t, &c, (150.0, 150.0), (298.0, 401.0), none); + assert_eq!((v, labels), (json!({"dx": 150.0, "dy": 250.0}), vec!["anchor".to_string()]), "group: {group}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 298.0, 401.0)); + let c = ToolContext { snap_to_grid: true, ..cx(&d, &mixed, &p) }; + assert_eq!(drag(&mut t, &c, (150.0, 150.0), (171.0, 153.0), none).0, json!({"dx": 24.0, "dy": 6.0}), "group: {group}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 171.0, 153.0)); + let (v, _) = drag(&mut t, &c, (150.0, 150.0), (163.0, 151.0), Mods { shift: true, ..none }); + let (x, y) = (v["dx"].as_f64().unwrap(), v["dy"].as_f64().unwrap()); + assert!((x - 15.0).abs() < 1e-9 && y.abs() < 1e-9, "group: {group}: {v}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 163.0, 151.0)); + } +} + +/// A path inside a selected group moves whole with the group, even with some of its anchors +/// direct-selected, so a drag from a fill does not snap to its other anchors: here to the +/// bottom-right corner (400, 400) of the path at (300, 300)–(400, 400). +#[test] +fn a_drag_from_a_fill_skips_the_anchors_of_a_path_in_a_selected_group() { + let (d, _, outside, _, outer) = nested_group_doc(); + let p = paint(); + let mut sel = anchors_of(outside, &[(0, 0)]); + sel.objects.insert(0, outer); + let c = cx(&d, &sel, &p); + let mut t = DirectSelectionTool::new(true); + let (v, labels) = drag(&mut t, &c, (150.0, 150.0), (398.0, 401.0), Mods::default()); + assert_eq!((v, labels), (json!({"dx": 248.0, "dy": 251.0}), Vec::::new())); +} + /// A dragged anchor lands on another path's anchor or segment, lines up with the other anchors /// of its own path, and with several selected the one pressed on snaps, the others following. #[test] diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index c8537bd75c..be2019a383 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -38,6 +38,16 @@ pub fn min_fidelity(id: &str) -> f64 { if id == "smooth" { SMOOTH_MIN_FIDELITY } else { MIN_FIDELITY } } +/// The Blob Brush's or the Eraser's width at pen `pressure` (0..1) with Size set to Pressure: `size` − +/// `variation` at the lightest pressure to `size` + `variation` at the heaviest, at least +/// [`MIN_BRUSH_SIZE`]. +pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 { + (size + variation * (2.0 * pressure.clamp(0.0, 1.0) - 1.0)).max(MIN_BRUSH_SIZE) +} + +/// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum). +pub const MIN_BRUSH_SIZE: f64 = 0.1; + /// Create a drawing tool by id (None = not one of ours). pub fn create(id: &str) -> Option> { Some(match id { diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 3cebc0079f..58664704ad 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -19,7 +19,7 @@ use vectorcraft_geom::Point; use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; use crate::guides::HandleSnap; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use vectorcraft_geom::constrain_angle_from; #[derive(Clone, Copy, Debug)] @@ -296,6 +296,30 @@ impl Tool for AnchorTool { fn busy(&self) -> bool { !matches!(self.state, State::Idle) } + /// Escape during an Anchor Point drag (an anchor pulled into a smooth point or moved, a + /// handle, a segment, a blend spine's point, handle or segment) cancels it: what it moved goes + /// back and the release does nothing. Escape after a press that has not moved yet drops the + /// press, so its release converts nothing. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key != ToolKey::Escape || matches!(self.state, State::Idle) { + return vec![]; + } + let began = matches!( + self.state, + State::Convert { began: true, .. } + | State::Move { began: true, .. } + | State::SpineMove { began: true, .. } + | State::Handle { began: true, .. } + | State::SpineConvert { began: true, .. } + | State::SpineHandle { began: true, .. } + | State::Reshape { began: true, .. } + ); + self.state = State::Idle; + self.guides.clear(); + self.measure = None; + self.space_resume = None; + if began { vec![Action::Cancel] } else { vec![] } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; // Anchors and handle ends are picked from a little further than segments. diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 11c843e05e..f6986cf7e9 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -537,6 +537,58 @@ fn anchor_point_space_mid_drag_moves_the_anchor() { assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 260.0, 370.0)), vec![Action::Commit]); } +/// Escape during a drag cancels it, whatever the drag does, and the release after it does +/// nothing; Enter leaves the drag alone. After a press that has not moved, Escape drops the press, +/// so its release does not make the smooth anchor a corner. +#[test] +fn escape_cancels_an_anchor_point_drag() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(300.0, 300.0)], false); + sp.anchors[1] = vectorcraft_geom::Anchor::smooth(Point::new(200.0, 300.0), Point::new(240.0, 320.0)); + let path = vectorcraft_geom::PathData::single(sp); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let space = Mods { space: true, ..Mods::default() }; + // (what, the press, its modifiers, Space held during the second drag step) + for (what, x, y, mods, spaced) in [ + ("convert", 100.0, 300.0, Mods::default(), false), + ("handle", 240.0, 320.0, Mods::default(), false), + ("segment", 150.0, 200.0, Mods::default(), false), + ("shift move", 200.0, 300.0, shift, false), + ("space move", 100.0, 300.0, Mods::default(), true), + ] { + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(mods)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 20.0, y + 30.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(..)]), "{what}: {a:?}"); + let step = if spaced { space } else { Mods::default() }; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 30.0, y + 40.0).with_mods(step)); + let moved = matches!(&a[..], [Action::Preview(c, _)] if c == "path.moveAnchor"); + assert_eq!(moved, spaced || what == "shift move", "{what}: {a:?}"); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty(), "{what}: Enter leaves the drag alone"); + assert!(t.busy(), "{what}"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{what}: Escape cancels the drag"); + assert!(!t.busy(), "{what}"); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 40.0, y + 50.0)).is_empty(), "{what}: the drag is over"); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x + 40.0, y + 50.0)).is_empty(), "{what}: the release does nothing"); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Measure { .. })), "{what}: no readout stays"); + } + // A click on the smooth anchor makes it a corner; Escape between press and release drops it. + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty(), "nothing began, so nothing is canceled"); + assert!(!t.busy()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 300.0)).is_empty()); + // With nothing pressed, Escape is not the tool's. + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); +} + #[test] fn anchor_point_shift_drag_honors_measurement_labels() { let (mut d, _) = doc_with_rect(); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 21c090f213..2a6380aa94 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -9,9 +9,9 @@ //! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil's new path starts and ends on //! Smart Guides ([`DrawSnap`]: an anchor, a path, in line with the art), hovering too; the points //! between follow the hand. The Paintbrush records the pen pressure of each point (a stroke a pen -//! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes. The -//! other tools collect the drag polyline (shown as an overlay) and run -//! one command on release. With Shift held, the Blob Brush's points stay on the horizontal or +//! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and +//! so do the Blob Brush and the Eraser while their Size varies with Pressure. The other tools +//! collect the drag polyline (shown as an overlay) and run one command on release. With Shift held, the Blob Brush's points stay on the horizontal or //! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag //! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths. @@ -27,12 +27,19 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// radius while Alt switches it to the Smooth tool. const SMOOTH_RADIUS: f64 = 12.0; +/// The finest Fidelity (screen pixels) a Pencil or Paintbrush stroke is fitted at while it is drawn: +/// a fit's cost grows as its Fidelity shrinks (at 0.01 pt a long pen stroke lagged, #4565), and +/// a preview within half a pixel of the stroke looks the same. The release fits it at its Fidelity. +const PREVIEW_FIDELITY_PX: f64 = 0.5; + pub struct GestureTool { - /// How many points the last preview of the stroke had ([`crate::previews_at`]). + /// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was + /// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]). previewed: usize, id: &'static str, points: Vec, - /// The pen pressure of each of `points` (the Paintbrush only). + /// The pen pressure of each of `points` (the Paintbrush, and the Blob Brush and the Eraser + /// with `size_pressure`). pressures: Vec, active: bool, began: bool, @@ -51,6 +58,12 @@ pub struct GestureTool { pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, + /// Blob Brush and Eraser Tool Options' Size set to Pressure (else Fixed): the tip is `size` − + /// `size_variation` wide at the lightest pen pressure and `size` + `size_variation` at the + /// heaviest. + pub size_pressure: bool, + /// Blob Brush and Eraser Tool Options' Size Variation, in points. + pub size_variation: f64, /// The angle of the Eraser tip's long axis, in degrees counter-clockwise from horizontal. pub angle: f64, /// The Eraser tip's short axis in percent of its long one (100: round). @@ -82,13 +95,7 @@ pub struct GestureTool { /// The straight line is Alt's: the pointer is not constrained to 45° steps, and the line's end /// snaps to Smart Guides as a stroke's end does. unconstrained: bool, - /// Where the pointer was for each Blob Brush point dragged since Shift went down: the last - /// `shift_raw.len()` of `points`. - shift_raw: Vec, - /// Where the pointer was for the Shift-constrained point the next [`Self::push`] adds. - shift_next: Option, - /// The angle of the line the dragged points were last moved onto: while it holds they are on - /// it, and the next drag event need not move them again. + /// Axis selected during the current uninterrupted Shift interval, in degrees. shift_line: Option, /// "Merge only with selection": a Blob Brush stroke merges only with selected paths. pub merge_only_selection: bool, @@ -137,6 +144,8 @@ impl GestureTool { redraw: None, fidelity, size: 10.0, + size_pressure: false, + size_variation: 0.0, angle: 0.0, roundness: 100.0, fill: false, @@ -149,8 +158,6 @@ impl GestureTool { moved: false, straight: false, unconstrained: false, - shift_raw: vec![], - shift_next: None, shift_line: None, merge_only_selection: false, edit_within: 12.0, @@ -176,14 +183,8 @@ impl GestureTool { /// Add a stroke sample. fn push(&mut self, p: Point, pressure: f32) { - let raw = self.shift_next.take(); - if self.points.is_empty() { - self.shift_raw.clear(); - } else if let Some(raw) = raw { - self.shift_raw.push(raw); - } self.points.push(p); - if self.id == "paintbrush" { + if self.id == "paintbrush" || (self.varies_size() && self.size_pressure) { self.pressures.push(pressure); } } @@ -200,14 +201,10 @@ impl GestureTool { self.id == "blobBrush" && m.alt && !self.moved } - /// Where the stroke takes a pointer at `p`. For the Blob Brush with Shift held, that is the - /// horizontal or vertical line through the press point that is nearer in angle to `p` (90° - /// steps from the Constrain Angle), at `p`'s distance from the press point. The points dragged - /// since Shift went down move to that line too, each at its pointer position's distance and on - /// that position's side of the press point; a pointer at the press point leaves them on their - /// line. Without Shift, or while the Blob Brush smooths, the stroke takes `p`. + /// Constrain the Pencil line or the current Blob Brush sample. Blob Brush chooses an + /// axis once per uninterrupted Shift interval; samples already drawn never move. + /// A smoothing drag follows the pointer without a Shift constraint. fn constrained(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Point { - self.shift_next = None; if self.straight && self.unconstrained { return p; } @@ -217,26 +214,26 @@ impl GestureTool { return start + vectorcraft_geom::constrain_angle_from(p - start, 45.0, cx.constrain_angle); } let Some(&start) = self.points.first().filter(|_| self.id == "blobBrush" && m.shift && !self.smoothing) else { - self.shift_raw.clear(); self.shift_line = None; return p; }; - self.shift_next = Some(p); - // The press point is on both lines: the points dragged before stay on theirs. - if (p - start).hypot() < vectorcraft_geom::EPS { - return start; + if self.shift_line.is_none() { + // Raw press-to-pointer displacement in logical screen pixels along the constraint + // axes. Zoom changes the document distance, not the activation tolerance. + let v = p - start; + let v = vectorcraft_geom::constrain_axes(cx.constrain_angle).map_or(Point::new(v.x, v.y), |axes| axes.inverse() * Point::new(v.x, v.y)); + let x = v.x.abs() * cx.zoom; + let y = v.y.abs() * cx.zoom; + self.shift_line = if x >= 1.0 && y < 0.5 { + Some(cx.constrain_angle) + } else if y >= 1.0 && x < 0.5 { + Some(cx.constrain_angle + 90.0) + } else { + // No unconstrained trail while pending, including an initially diagonal drag. + return self.points.last().copied().unwrap_or(start); + }; } - let d = vectorcraft_geom::constrain_angle_from(p - start, 90.0, cx.constrain_angle); - // `line` is the line's angle, measured counterclockwise on screen as the Constrain Angle is measured. - let line = (-d.y).atan2(d.x).to_degrees(); - let on_line = |q: Point| start + vectorcraft_geom::constrain_angle_from(q - start, 180.0, line); - if self.shift_line != Some(line) { - for (q, raw) in self.points.iter_mut().skip(1).rev().zip(self.shift_raw.iter().rev()) { - *q = on_line(*raw); - } - self.shift_line = Some(line); - } - on_line(p) + start + vectorcraft_geom::constrain_angle_from(p - start, 180.0, self.shift_line.unwrap_or(cx.constrain_angle)) } /// Forget the stroke. @@ -248,6 +245,19 @@ impl GestureTool { self.shift_line = None; } + /// Does the tool's Size take Fixed or Pressure (the Blob Brush and the Eraser)? + fn varies_size(&self) -> bool { + matches!(self.id, "blobBrush" | "eraser") + } + + /// The pen pressure of each point of a Blob Brush or Eraser stroke whose Size varies with + /// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure + /// keeps its Size). + fn size_pressures(&self) -> Option<&[f32]> { + let pressed = self.pressures.len() == self.points.len() && self.pressures.iter().any(|p| *p < 1.0); + (self.varies_size() && self.size_pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice()) + } + /// The stroke's points, each `[x, y, pressure]` when a pen pressed less than fully anywhere /// along it (a mouse always presses fully). fn stroke_json(&self) -> Value { @@ -386,8 +396,10 @@ impl GestureTool { "blobBrush" => vec![Action::Exec( "path.blob".into(), json!({ - "points": points_json(pts), + "points": self.stroke_json(), "size": self.size, + "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, + "sizeVariation": self.size_variation, "fidelity": self.fidelity, "keepSelected": self.keep_selected, "mergeOnlySelection": self.merge_only_selection @@ -395,7 +407,14 @@ impl GestureTool { )], "eraser" => vec![Action::Exec( "path.eraseRegion".into(), - json!({"points": points_json(pts), "size": self.size, "angle": self.angle, "roundness": self.roundness}), + json!({ + "points": self.stroke_json(), + "size": self.size, + "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, + "sizeVariation": self.size_variation, + "angle": self.angle, + "roundness": self.roundness + }), )], "knife" if pts.len() >= 2 => vec![Action::Exec("path.knife".into(), json!({"points": points_json(pts)}))], "smooth" if has_sel && pts.len() >= 2 => { @@ -506,8 +525,11 @@ impl Tool for GestureTool { } // With the Pencil's Live preview off a thin line shows instead (`overlays`). if self.previews() && crate::previews_at(self.points.len()) { - self.previewed = self.points.len(); let mut v = self.freehand_params(false); + let fidelity = self.fidelity.max(cx.tol(PREVIEW_FIDELITY_PX)); + v["fidelity"] = json!(fidelity); + // A preview fitted coarser than the stroke kept is stale (`deactivate`). + self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() }; if !self.live_fit { // Live curve fitting off: the release fits the stroke (`finish`). v["fit"] = json!(false); @@ -626,12 +648,22 @@ impl Tool for GestureTool { }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; // A tip that is not round shows the outline of the area it covers. + // shortcut: at its Size even with Pressure; the release erases at the pen's widths. if self.id == "eraser" && self.roundness < 100.0 { let area = eraser_area(&self.points, self.size, self.angle, self.roundness); o.push(Overlay::Path { path: area.to_bezpath(), color, width: 1.0, dashed: false }); return o; } - o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" }); + // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. + if let Some(pressures) = self.size_pressures() { + for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { + let pressure = f64::from(p[0] + p[1]) / 2.0; + let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom; + o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false }); + } + } else { + o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" }); + } if cx.measurement_labels && self.id == "blobBrush" && !self.smoothing { let last = self.points[self.points.len() - 1]; let length = self.points.windows(2).map(|w| w[0].distance(w[1])).sum(); @@ -700,9 +732,22 @@ impl Tool for GestureTool { } "smooth" => json!({"fidelity": self.fidelity}), "blobBrush" => { - json!({"fidelity": self.fidelity, "size": self.size, "keepSelected": self.keep_selected, "mergeOnlySelection": self.merge_only_selection}) + json!({ + "fidelity": self.fidelity, + "size": self.size, + "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, + "sizeVariation": self.size_variation, + "keepSelected": self.keep_selected, + "mergeOnlySelection": self.merge_only_selection + }) } - "eraser" => json!({"size": self.size, "angle": self.angle, "roundness": self.roundness}), + "eraser" => json!({ + "size": self.size, + "sizeMode": if self.size_pressure { "pressure" } else { "fixed" }, + "sizeVariation": self.size_variation, + "angle": self.angle, + "roundness": self.roundness + }), _ => Value::Null, } } @@ -710,6 +755,12 @@ impl Tool for GestureTool { match key { "fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0), "size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0), + "sizeMode" if self.varies_size() => match v.as_str() { + Some("pressure") => self.size_pressure = true, + Some("fixed") => self.size_pressure = false, + _ => {} + }, + "sizeVariation" if self.varies_size() => self.size_variation = v.as_f64().unwrap_or(self.size_variation).clamp(0.0, 1000.0), "angle" => self.angle = v.as_f64().unwrap_or(self.angle).clamp(-180.0, 180.0), "roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(1.0, 100.0), "fill" => self.fill = v.as_bool().unwrap_or(self.fill), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 25e59c67cf..c3335d1cf4 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -122,6 +122,40 @@ fn pencil_with_live_curve_fitting_off_previews_the_stroke_unfitted() { assert!(!drawn.is_empty() && drawn.iter().all(Option::is_none), "{drawn:?}"); } +/// A stroke whose Fidelity is finer than half a screen pixel previews fitted at half a pixel, which +/// looks the same at a fraction of the fit's cost (#4565); the release, and another tool chosen +/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. +#[test] +fn fine_fidelity_previews_at_half_a_pixel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let stroke = [(0.0, 0.0), (10.0, 5.0), (20.0, 0.0), (30.0, 5.0)]; + let fidelities = |acts: &[Action]| -> Vec { + acts.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect() + }; + for id in ["pencil", "paintbrush"] { + for (zoom, fidelity, drawn) in [(1.0, 0.01, 0.5), (4.0, 0.01, 0.125), (1.0, 1.5, 1.5)] { + cx.zoom = zoom; + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(fidelity)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let (release, during) = acts.split_last().unwrap(); + assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} pt"); + assert_eq!(fidelities(release), [fidelity], "{id} at {zoom}x, {fidelity} pt: the release"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + for &(x, y) in &stroke[1..] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + let acts = t.deactivate(&cx); + let kept = if drawn > fidelity { [fidelity].to_vec() } else { vec![] }; + assert_eq!(fidelities(&acts), kept, "{id} at {zoom}x, {fidelity} pt: another tool chosen"); + assert_eq!(acts.last(), Some(&Action::Commit)); + } + } +} + /// Keep selected is on by default, and every Pencil and Paintbrush preview sends it. #[test] fn pencil_and_paintbrush_send_keep_selected() { @@ -279,8 +313,11 @@ fn blob_brush_sends_keep_selected_and_merge_only_with_selection() { "{acts:?}" ); } - // The Eraser keeps Size, Angle and Roundness: a round tip by default. - assert_eq!(GestureTool::new("eraser").options(), json!({"size": 10.0, "angle": 0.0, "roundness": 100.0})); + // The Eraser keeps Size (Fixed by default), Angle and Roundness: a round tip by default. + assert_eq!( + GestureTool::new("eraser").options(), + json!({"size": 10.0, "sizeMode": "fixed", "sizeVariation": 0.0, "angle": 0.0, "roundness": 100.0}) + ); } /// The Blob Brush has a Fidelity, 1.5 pt by default and 0.01 to 100 pt, and its stroke sends it. @@ -301,9 +338,7 @@ fn blob_brush_sends_its_fidelity() { } /// Shift keeps a Blob Brush stroke on the horizontal or vertical line through the press point, -/// whichever is nearer to the pointer, at 90° steps from the Constrain Angle; the points -/// dragged with Shift held move to the other line together, and each point follows the Shift -/// state of its own event. +/// with its axis chosen by the first clear axial movement. Crossing it never moves earlier samples. #[test] fn blob_brush_shift_keeps_the_stroke_horizontal_or_vertical() { let (d, _) = doc_with_rect(); @@ -311,46 +346,51 @@ fn blob_brush_shift_keeps_the_stroke_horizontal_or_vertical() { let p = paint(); let mut cx = cx(&d, &s, &p); let shift = Mods { shift: true, ..Default::default() }; - let blob = |acts: &[Vec]| -> Vec<(f64, f64)> { - let Some(Action::Exec(c, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; - assert_eq!(c, "path.blob"); - v["points"].as_array().unwrap().iter().map(|q| (q[0].as_f64().unwrap(), q[1].as_f64().unwrap())).collect() - }; let mut t = GestureTool::new("blobBrush"); - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (30.0, 5.0), (50.0, 8.0)], shift)); - assert_eq!(pts.len(), 3); - assert!(pts.iter().all(|q| q.1 == 0.0 && q.0 >= 0.0), "{pts:?}"); - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (5.0, 30.0), (8.0, 50.0)], shift)); - assert!(pts.iter().all(|q| q.0.abs() < 1e-9 && q.1 >= 0.0), "{pts:?}"); - // A pointer that crosses to the vertical line takes the points before it along, each on - // its own side of the press point and at its own distance. - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (-40.0, -2.0), (100.0, 99.0), (90.0, 120.0)], shift)); - assert_eq!(pts.len(), 4, "{pts:?}"); - assert!(pts.iter().all(|q| q.0.abs() < 1e-9), "{pts:?}"); - assert!((pts[1].1 + 1604f64.sqrt()).abs() < 1e-9 && (pts[2].1 - 19801f64.sqrt()).abs() < 1e-9 && (pts[3].1 - 150.0).abs() < 1e-9, "{pts:?}"); - // Without Shift the stroke follows the pointer. - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (30.0, 5.0), (50.0, 8.0)], Mods::default())); - assert_eq!(pts, vec![(0.0, 0.0), (30.0, 5.0), (50.0, 8.0)]); - // Shift pressed and let go mid-stroke constrains only the points dragged while it is down, - // and a later press of Shift leaves the points of the earlier one where they are. let ev = |k, x, y, m| PointerEvent::new(k, x, y).with_mods(m); - t.pointer(&cx, &ev(PointerKind::Down, 0.0, 0.0, Mods::default())); - t.pointer(&cx, &ev(PointerKind::Drag, 20.0, 10.0, Mods::default())); - t.pointer(&cx, &ev(PointerKind::Drag, 40.0, 10.0, shift)); - t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 10.0, Mods::default())); - let pts = blob(&[t.pointer(&cx, &ev(PointerKind::Up, 10.0, 80.0, shift))]); - assert_eq!((pts.len(), pts[1], pts[3]), (5, (20.0, 10.0), (60.0, 10.0)), "{pts:?}"); - assert!(pts[2].1 == 0.0 && (pts[2].0 - 1700f64.sqrt()).abs() < 1e-9, "{pts:?}"); - assert!(pts[4].0.abs() < 1e-9 && (pts[4].1 - 6500f64.sqrt()).abs() < 1e-9, "{pts:?}"); - // The axes turn with the Constrain Angle. - cx.constrain_angle = 30.0; - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (40.0, -20.0)], shift)); - let a = (-pts[1].1).atan2(pts[1].0).to_degrees(); - assert!((a - 30.0).abs() < 1e-9, "{pts:?}"); - // A pointer back at the press point leaves the stroke on its line. - let pts = blob(&drag_held(&mut t, &cx, &[(0.0, 0.0), (40.0, -20.0), (0.0, 0.0)], shift)); - let a = (-pts[1].1).atan2(pts[1].0).to_degrees(); - assert!(pts.len() == 3 && pts[2] == (0.0, 0.0) && (a - 30.0).abs() < 1e-9, "{pts:?}"); + for zoom in [0.5, 1.0, 4.0] { + cx.zoom = zoom; + t.pointer(&cx, &ev(PointerKind::Down, 0.0, 0.0, shift)); + t.pointer(&cx, &ev(PointerKind::Drag, 4.0 / zoom, 4.0 / zoom, shift)); + assert_eq!(t.points, vec![Point::ZERO]); + assert!(t.overlays(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Drag, 1.0 / zoom, 0.5 / zoom, shift)); + assert_eq!(t.points.len(), 1, "small component has a strict bound"); + t.pointer(&cx, &ev(PointerKind::Drag, 1.0 / zoom, 0.0, shift)); + let first = t.points[1]; + t.pointer(&cx, &ev(PointerKind::Drag, 3.0 / zoom, 10.0 / zoom, shift)); + assert_eq!(t.points[1], first); + assert!(t.points.iter().all(|p| p.y.abs() < 1e-9)); + // Release Shift: freehand resumes without relocating the constrained points. + t.pointer(&cx, &ev(PointerKind::Drag, 8.0 / zoom, 12.0 / zoom, Mods::default())); + assert_eq!(t.points.last(), Some(&Point::new(8.0 / zoom, 12.0 / zoom))); + t.pointer(&cx, &ev(PointerKind::Drag, 0.0, 15.0 / zoom, shift)); + assert_eq!(t.points[1], first); + assert!(t.points.last().unwrap().x.abs() < 1e-9); + t.pointer(&cx, &ev(PointerKind::Up, 0.0, 15.0 / zoom, shift)); + } + // Exact quarter turns preserve the strict half-pixel boundary in either direction. + for angle in [-450.0, -180.0, -90.0, 90.0, 180.0, 450.0] { + cx.constrain_angle = angle; + cx.zoom = 1.0; + let axes = vectorcraft_geom::constrain_axes(angle).unwrap(); + for (x, y) in [(1.0, 0.5), (0.5, 1.0), (-1.0, -0.5), (-0.5, -1.0)] { + t.pointer(&cx, &ev(PointerKind::Down, 0.0, 0.0, shift)); + let at = axes * Point::new(x, y); + t.pointer(&cx, &ev(PointerKind::Drag, at.x, at.y, shift)); + assert_eq!(t.points, vec![Point::ZERO], "angle {angle}, ({x}, {y}) stays pending"); + assert!(t.shift_line.is_none()); + let at = axes * Point::new(x, 0.0); + t.pointer(&cx, &ev(PointerKind::Drag, at.x, at.y, shift)); + assert_eq!(t.shift_line.is_some(), x.abs() >= 1.0); + t.clear(); + } + } + cx.constrain_angle = 0.0; + // A pending diagonal released without locking makes the ordinary dot at the press. + t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0, shift)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 30.0, 30.0, shift)); + assert!(matches!(&acts[0], Action::Exec(c, v) if c == "path.blob" && v["points"] == json!([[20.0, 20.0]])), "{acts:?}"); } /// Alt switches the Blob Brush to the Smooth tool: held before the press, or pressed before the diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 013578edc5..123c4b1efc 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -1,9 +1,11 @@ //! Flare, Reshape, Shaper and Graph tools. //! -//! Flare: drag sets the centre and its size (click without dragging opens the Flare Tool Options), -//! then a click sets the end point of the rings; the rest comes from the tool's options (the Flare -//! Tool Options, which last). Reshape: drag a point of a selected path; the engine's -//! `path.reshape` adds an anchor there if needed and moves the neighbourhood smoothly. +//! Flare: drag sets the center and its size and turns the rays as the pointer moves up or down +//! (Shift holds their turn; click without dragging opens the Flare Tool Options), then a click +//! sets the end point of the rings; Space held during either drag moves the flare. The rest comes +//! from the tool's options (the Flare Tool Options, which last). Reshape: drag a point of a +//! selected path; the engine's `path.reshape` adds an anchor there if needed and moves the +//! neighbourhood smoothly. use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; @@ -51,9 +53,13 @@ pub struct FlareTool { /// Centre placed, waiting for the end-point click: (centre, diameter). placed: Option<(Point, f64)>, hover: Point, + /// The pointer at the last press or drag, from which Space held moves the flare. + last: Point, began: bool, /// Ray count changed with ↑/↓ during the gesture (None = the options' count). rays: Option, + /// The rays' turn (`shape.flare`'s `rotation`, degrees) the center drag set. + turn: f64, /// The options' values, in [`FLARE_OPTIONS`] order. values: [f64; 12], /// Whether the flare has rays and rings (the options' Rays and Rings checkboxes). @@ -67,8 +73,10 @@ impl Default for FlareTool { drag: None, placed: None, hover: Point::ZERO, + last: Point::ZERO, began: false, rays: None, + turn: 0.0, values: FLARE_OPTIONS.map(|(_, default, _, _)| default), rays_on: true, rings_on: true, @@ -101,12 +109,26 @@ pub fn flare_params(o: &Value, c: Point) -> Value { v } +/// The chosen rotation rate: one degree per document point of vertical pointer travel. +/// This is independent of pointer event frequency and elapsed time. +const RAY_DEGREES_PER_POINT: f64 = 1.0; + +/// Accumulate travel rather than an event-count step. Frozen/moving samples still update +/// the pointer baseline, so releasing a modifier never catches up skipped rotation. +fn ray_turn(turn: f64, dy: f64, shift: bool) -> f64 { + if shift || !dy.is_finite() { + return turn; + } + (turn + dy * RAY_DEGREES_PER_POINT).rem_euclid(360.0) +} + impl FlareTool { - /// `shape.flare`'s params: the options, with the dragged centre and diameter, the ray count - /// ↑/↓ chose and the rings' end point once clicked. + /// `shape.flare`'s params: the options, with the dragged center and diameter, the rays' turn, + /// the ray count ↑/↓ chose and the rings' end point once clicked. fn params(&self, c: Point, diameter: f64, end: Option) -> Value { let mut v = flare_params(&self.options(), c); v["diameter"] = json!(diameter.max(1.0)); + v["rotation"] = json!(self.turn); if let Some(r) = self.rays.filter(|_| self.rays_on) { v["rays"] = json!(r); } @@ -132,12 +154,20 @@ impl Tool for FlareTool { if self.placed.is_none() { self.drag = Some((ev.pos, ev.pos)); self.rays = None; + self.turn = 0.0; } + self.last = ev.pos; vec![] } PointerKind::Drag => { - if let Some((c, _)) = self.drag { + if let Some((mut c, _)) = self.drag { + // Space held moves the center with the pointer, so the size and the turn stay. + let dy = ev.pos.y - self.last.y; + crate::shape::space_moves(&mut c, &mut self.last, ev, self.began); self.drag = Some((c, ev.pos)); + if !ev.mods.space { + self.turn = ray_turn(self.turn, dy, ev.mods.shift); + } if !self.began && ev.pos.distance(c) >= cx.tol(3.0) { self.began = true; return vec![ @@ -148,13 +178,17 @@ impl Tool for FlareTool { if self.began { return vec![Action::Preview("shape.flare".into(), self.params(c, 2.0 * ev.pos.distance(c), None))]; } - } else if let Some((c, d)) = self.placed { + } else if let Some((mut c, d)) = self.placed { + // Space held moves the whole flare, rings' end point included. + crate::shape::space_moves(&mut c, &mut self.last, ev, true); + self.placed = Some((c, d)); return vec![Action::Preview("shape.flare".into(), self.params(c, d, Some(ev.pos)))]; } vec![] } PointerKind::Up => { - if let Some((c, d)) = self.placed.take() { + if let Some((mut c, d)) = self.placed.take() { + crate::shape::space_moves(&mut c, &mut self.last, ev, true); self.began = false; return vec![Action::Preview("shape.flare".into(), self.params(c, d, Some(ev.pos))), Action::Commit]; } @@ -538,6 +572,109 @@ mod tests { assert_eq!(t.params(Point::ZERO, 1.0, None)["rays"].as_u64(), Some(0)); } + /// The last `shape.flare` preview of `a`. + fn flare_preview(a: &[Action]) -> Value { + match a.iter().rev().find(|a| matches!(a, Action::Preview(..))) { + Some(Action::Preview(c, v)) if c == "shape.flare" => v.clone(), + other => panic!("no flare preview: {other:?}"), + } + } + + /// Equal vertical travel gives equal rotation, regardless of event partitioning. + #[test] + fn flare_drag_turns_the_rays_and_shift_holds_their_turn() { + use crate::testutil::*; + use vectorcraft_doc::Selection; + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let space = Mods { space: true, ..Default::default() }; + let mut results = vec![]; + for steps in [1, 8, 64] { + let mut t = FlareTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + for i in 1..=steps { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0 + 80.0 * i as f64 / steps as f64)); + } + assert_eq!(t.turn, 80.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 180.0, 180.0)); + assert_eq!(t.turn, 80.0, "horizontal movement doesn't turn"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 180.0, 150.0)); + assert_eq!(t.turn, 50.0, "reverse travel subtracts its distance"); + let v = flare_preview(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 200.0).with_mods(shift))); + assert_eq!(v["rotation"].as_f64(), Some(50.0)); + assert_eq!(v["diameter"].as_f64(), Some(200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 220.0)); + assert_eq!(t.turn, 70.0, "release does not catch up frozen movement"); + t.key(&cx, ToolKey::Up, Mods::default()); + assert_eq!(t.turn, 70.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 120.0, 220.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 200.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 260.0)); + assert_eq!(a.last(), Some(&Action::Commit)); + assert_eq!(flare_preview(&a)["rotation"].as_f64(), Some(70.0)); + results.push(t.turn); + } + assert!(results.windows(2).all(|p| p[0] == p[1])); + // Space held before the first drag update freezes rotation too. + let mut t = FlareTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 140.0).with_mods(space)); + assert_eq!(t.turn, 0.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 150.0)); + assert_eq!(t.turn, 10.0); + } + + /// Space held while dragging out a flare moves it at its current size and turn, in the center + /// drag and in the drag that places the rings' end point; let go, the drag goes on from there. + #[test] + fn space_moves_the_flare_being_drawn() { + use crate::testutil::*; + use vectorcraft_doc::Selection; + + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let space = Mods { space: true, ..Default::default() }; + let step = 30.0; + let mut t = FlareTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 130.0)); + // Space held: the pointer's y grows, but the flare moves without turning. + let v = flare_preview(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 180.0).with_mods(space))); + let at = |v: &Value| (v["cx"].as_f64(), v["cy"].as_f64(), v["diameter"].as_f64()); + let turned = |v: &Value, by: f64| v["rotation"].as_f64().is_some_and(|r| (r - by).abs() < 1e-9); + assert_eq!(at(&v), (Some(150.0), Some(150.0), Some(60.0))); + assert!(turned(&v, step)); + // Space let go: the size follows the pointer again, from the moved center, and so does the turn. + let v = flare_preview(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 190.0))); + assert_eq!(at(&v), (Some(150.0), Some(150.0), Some(80.0))); + assert!(turned(&v, step + 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 190.0)); + // The second drag: Space held moves the flare, its rings' end point with it. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 300.0, 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + let v = flare_preview(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 310.0).with_mods(space))); + assert_eq!((at(&v), v["x2"].as_f64(), v["y2"].as_f64()), ((Some(170.0), Some(160.0), Some(80.0)), Some(320.0), Some(310.0))); + assert!(turned(&v, step + 10.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 340.0, 310.0)); + assert_eq!(a.last(), Some(&Action::Commit)); + let v = flare_preview(&a); + assert_eq!((v["cx"].as_f64(), v["cy"].as_f64(), v["x2"].as_f64()), (Some(170.0), Some(160.0), Some(340.0))); + // A release with Space held away from the last drag moves the flare there too. + let mut t = FlareTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 300.0)); + let v = flare_preview(&t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 340.0, 310.0).with_mods(space))); + assert_eq!((v["cx"].as_f64(), v["cy"].as_f64(), v["x2"].as_f64()), (Some(120.0), Some(110.0), Some(340.0))); + } + #[test] fn reshape_drag_honors_measurement_labels() { use crate::testutil::*; diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index c3401b010f..894e7ca5a7 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -307,7 +307,7 @@ impl SnapKey { exclude: exclude.to_vec(), screen: cx.screen, view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides, cx.snap_tangent, cx.snap_perpendicular], - snap_to_glyph: cx.snap_to_glyph && cx.alignment_guides, + snap_to_glyph: cx.snap_to_glyph && cx.smart_guides && cx.alignment_guides, style: GuideStyle::of(cx), tolerances: [cx.snapping_tolerance, cx.snap_tolerance], } diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 5c5c061e9e..a1e1291fe7 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -47,6 +47,10 @@ pub struct Targets { /// it ends, as the end that stays put and the unit direction towards the dragged one /// ([`Self::for_anchor_drag`]). pub(super) extensions: Vec<(Point, Vec2)>, + /// Snap to Glyph's guides that run at an angle (in rotated type, or along a glyph's slanted + /// segments), as a point on each and its unit direction: a drawn point lands on the nearest + /// ([`Self::for_drawing`]). + pub(super) angled: Vec<(Point, Vec2)>, /// Snap to Tangent and Snap to Perpendicular: a drawn line from an anchor lands where it /// grazes a curve, or meets a segment square ([`Self::touching`]). pub(super) tangent: bool, @@ -209,12 +213,34 @@ impl Targets { self.ys.push((a.y, a, Kind::Anchor)); } - /// Live-text baselines and glyph bounds (View › Snap to Glyph). + /// A glyph guide through `at` along `dir` (on the page): a line the art lines up with when it + /// runs across or down the page, else an angled line a point lands on. + fn push_glyph_line(&mut self, at: Point, dir: Vec2) { + let len = dir.hypot(); + if !(len.is_finite() && len > 1e-12 && at.is_finite()) { + return; + } + let d = dir / len; + if d.y.abs() <= 1e-9 { + self.ys.push((at.y, at, Kind::Glyph)); + } else if d.x.abs() <= 1e-9 { + self.xs.push((at.x, at, Kind::Glyph)); + } else { + self.angled.push((at, d)); + } + } + + /// Live text as View › Snap to Glyph shows it: the glyph bounds of every text object, and for + /// a single line of type also its baseline and x-height, the proximity guides at the edges of + /// each character's advance width, and its glyphs' anchor points. In rotated type these + /// guides run at its angle (angular guides), and type of one glyph also has angular guides + /// along the glyph's slanted straight segments. fn push_glyphs(&mut self, doc: &Document, exclude: &[NodeId], visible: Option) { let skip: HashSet = exclude.iter().copied().collect(); let db = FontDb::global(); let kind = Kind::Glyph; let mut budget = BUDGET / 4; + let (mut anchors, mut angular) = (BUDGET, BUDGET / 4); walk_but(&doc.layers, &skip, &mut |n| { if budget == 0 || !n.visible { return; @@ -231,25 +257,84 @@ impl Targets { { return; } + // A paragraph shows glyph bounds only. + let single = lay.lines.len() == 1; + // Angular guides along a glyph's slanted segments: type of one glyph only. + let one_glyph = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).count() == 1; + // Text space → the page, and a direction in text space → one on the page. let to_doc = |p: Point| t.xf * p; - for line in &lay.lines { - let at = to_doc(Point::new(line.x0, line.baseline)); - self.ys.push((at.y, at, kind)); + let along = |m: Affine, v: Vec2| (m * v.to_point()) - (m * Point::ZERO); + if single { + let line_doc = t.xf * lay.line_xf; + for line in &lay.lines { + self.push_glyph_line(line_doc * Point::new(line.x0, line.baseline), along(line_doc, Vec2::new(1.0, 0.0))); + } } + // The last x-height pushed, to push each run of glyphs alike once. + let mut last_x_height: Option<(Point, Vec2)> = None; for g in &lay.glyphs { if budget == 0 { break; } + // Glyphs that draw nothing (spaces) give no guides. let bb = g.outline.bounding_box(); if !(bb.width() > 0.0 && bb.height() > 0.0) { continue; } + budget -= 1; + // Horizontal type and type on a path: the baseline runs from where the pen stood + // along the glyph's angle (not the glyph's own drawing, which Character Rotation + // turns), up being to its left. + if single + && !lay.vertical + && let Some(face) = db.face_by_id(g.font_id) + { + let ahead = Vec2::new(g.angle.cos(), g.angle.sin()); + let up = Vec2::new(ahead.y, -ahead.x); + let dir = along(t.xf, ahead); + // The x-height of the glyph as placed without its Character Rotation (raised or + // lowered by its baseline shift), measured across the baseline. + let top = g.xf * g.unturned * Point::new(0.0, -face.x_height()); + let at = to_doc(g.origin + up * (top - g.origin).dot(up)); + let same = last_x_height.is_some_and(|(a, d)| { + let (l, k) = (d.hypot(), dir.hypot()); + l > 1e-12 && k > 1e-12 && (d / l - dir / k).hypot() <= 1e-9 && ((at - a).cross(d / l)).abs() <= 1e-6 + }); + if face.x_height() > 0.0 && !same { + self.push_glyph_line(at, dir); + last_x_height = Some((at, dir)); + } + // Proximity guides: across the baseline at both edges of the width the layout + // gives the character (its advance with tracking and kerning). + for e in [g.origin, g.origin + ahead * g.advance] { + self.push_glyph_line(to_doc(e), along(t.xf, up)); + } + } + if single { + for seg in g.outline.segments() { + if anchors > 0 { + self.points.push((to_doc(seg.start()), Kind::Anchor)); + anchors -= 1; + } + if one_glyph + && angular > 0 + && let PathSeg::Line(l) = seg + { + let (p, q) = (to_doc(l.p0), to_doc(l.p1)); + let d = q - p; + let len = d.hypot(); + if len > 1e-6 && d.x.abs() > 1e-9 * len && d.y.abs() > 1e-9 * len { + self.push_glyph_line(p, d); + angular -= 1; + } + } + } + } let r = t.xf.transform_rect_bbox(bb); for p in [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] { self.xs.push((p.x, p, kind)); self.ys.push((p.y, p, kind)); } - budget -= 1; } }); } @@ -287,7 +372,11 @@ impl Targets { // With several anchors moving, the one under the pointer is not known here, and the // others' extensions don't run through it. let single = sel.objects.len() <= 1 && sel.anchors.values().map(|s| s.len()).sum::() == 1; - for (id, set) in &sel.anchors { + // A path inside another selected object, such as a path in a selected group, moves whole + // with that object, so none of its anchors or segments stay put. + let selected: HashSet = sel.objects.iter().copied().collect(); + let inside_selected = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().rev().skip(1).any(|p| selected.contains(p))); + for (id, set) in sel.anchors.iter().filter(|(id, _)| !inside_selected(**id)) { let Some(path) = doc.node(*id).and_then(|n| n.path_data()) else { continue }; for (si, sp) in path.subpaths.iter().enumerate() { let moving = |ai: usize| set.contains(&(si, ai)); @@ -399,6 +488,7 @@ impl Targets { self.ys.clear(); self.segments.clear(); self.extensions.clear(); + self.angled.clear(); self } @@ -508,7 +598,11 @@ impl Targets { } // A construction guide through the point it leaves, else a dragged segment's extension: // it lands on the guide, sliding into line with a target crossing it nearby. - if let Some((at, dir, q)) = from.and_then(|f| f.construction(p, tol).map(|(dir, q)| (f.at, dir, q))).or_else(|| self.extension(p, tol)) { + if let Some((at, dir, q)) = from + .and_then(|f| f.construction(p, tol).map(|(dir, q)| (f.at, dir, q))) + .or_else(|| self.extension(p, tol)) + .or_else(|| self.on_angled(p, tol)) + { let construction = |q: Point| Overlay::Line { a: at, b: q, color: self.style.color, dashed: false }; return match self.slide(at, dir, q, tol, false) { Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect()), @@ -606,6 +700,18 @@ impl Targets { .map(|(at, d, q, _)| (at, d, q)) } + /// The angled glyph guide ([`Self::angled`]) nearest `p`, within `tol` of it: a point on it, its + /// direction and where `p` lands on it. + fn on_angled(&self, p: Point, tol: f64) -> Option<(Point, Vec2, Point)> { + self.angled + .iter() + .map(|&(at, d)| (at, d, at + d * (p - at).dot(d))) + .map(|(at, d, q)| (at, d, q, q.distance(p))) + .filter(|(.., dist)| *dist <= tol) + .min_by(|a, b| a.3.total_cmp(&b.3)) + .map(|(at, d, q, _)| (at, d, q)) + } + /// The anchor or centre nearest `p`, within `tol`. /// Is a target point (an anchor, a centre) within `tol` of `p`? pub(crate) fn has_point_near(&self, p: Point, tol: f64) -> bool { @@ -621,7 +727,7 @@ impl Targets { } /// Slide `q`, on the line through `at` along `dir` (beyond `at` only, for a `ray`), to where - /// the nearest target line crosses it, at most twice `tol` away: where it lands and the + /// the nearest target line or angled glyph guide crosses it, at most twice `tol` away: where it lands and the /// target's own point (where its line starts). fn slide(&self, at: Point, dir: Vec2, q: Point, tol: f64, ray: bool) -> Option<(Point, Point)> { if !dir.hypot2().is_finite() || dir.hypot2() <= 1e-18 { @@ -646,6 +752,19 @@ impl Targets { } } } + // The angled glyph guides it crosses. + for &(on, e) in &self.angled { + let across = dir.cross(e); + if across.abs() <= 1e-9 * dir.hypot() { + continue; + } + let s = (on - at).cross(e) / across; + let hit = at + dir * s; + let moved = hit.distance(q); + if moved <= reach && (!ray || s > 0.0) && best.is_none_or(|b| moved < b.0) { + best = Some((moved, hit, on)); + } + } best.map(|(_, hit, from)| (hit, from)) } diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 517937c74c..200ab5008f 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -608,3 +608,208 @@ fn draw_snap_gathers_once_per_document_state() { let q = snap.press(&c, Point::new(31.0, 2.0), &[], Some(&from)); assert!((q.y - 0.0).abs() < 1e-9, "{q:?}"); } + +/// A document holding point type `text` at (100, 300), 60 pt, turned `angle` radians about +/// where it starts, and the type. +fn glyph_doc(text: &str, angle: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::TextObject) { + glyph_doc_with(text, angle, vectorcraft_doc::CharStyle { size: 60.0, ..Default::default() }) +} + +/// [`glyph_doc`] with the type in `style`. +fn glyph_doc_with(text: &str, angle: f64, style: vectorcraft_doc::CharStyle) -> (vectorcraft_doc::Document, vectorcraft_doc::TextObject) { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let at = Point::new(100.0, 300.0); + let mut t = vectorcraft_doc::TextObject::point(at, text, style); + t.xf = Affine::rotate_about(angle, at) * t.xf; + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t.clone())))).unwrap(); + (d, t) +} + +/// Snap to Glyph: a Pen click near an anchor point of a glyph's outline lands on it, and not with +/// Snap to Glyph off. +#[test] +fn pen_click_near_a_glyph_anchor_lands_on_it() { + use crate::{Action, PointerEvent, PointerKind, Tool}; + let (d, t) = glyph_doc("H", 0.0); + let lay = layout_text(FontDb::global(), &t); + let g = lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()).expect("a glyph with an outline"); + // An anchor inside the glyph's bounds (a corner where the crossbar meets a stem), which no + // glyph bounds line passes through. + let bb = g.outline.bounding_box(); + let inside = |p: Point| p.x > bb.x0 + 1.0 && p.x < bb.x1 - 1.0 && p.y > bb.y0 + 1.0 && p.y < bb.y1 - 1.0; + let anchor = t.xf * g.outline.segments().map(|s| s.start()).find(|p| inside(*p)).expect("an anchor inside the glyph"); + let (s, p) = (Selection::default(), paint()); + let click = anchor + Vec2::new(1.5, -1.0); + let first_anchor = |glyphs: bool| { + let c = ToolContext { snap_to_glyph: glyphs, ..cx(&d, &s, &p) }; + let mut pen = crate::pen::PenTool::default(); + let acts = pen.pointer(&c, &PointerEvent::new(PointerKind::Down, click.x, click.y)); + let Some(Action::Preview(_, v)) = acts.get(1) else { panic!("{acts:?}") }; + Point::new(v["anchors"][0]["x"].as_f64().unwrap(), v["anchors"][0]["y"].as_f64().unwrap()) + }; + assert!(first_anchor(true).distance(anchor) < 1e-9, "{:?} vs {anchor:?}", first_anchor(true)); + assert!(first_anchor(false).distance(anchor) > 1e-3); + // Snap to Glyph works with Smart Guides on: Snap to Point alone does not land on glyph anchors. + let c = ToolContext { snap_to_glyph: true, smart_guides: false, snap_to_point: true, ..cx(&d, &s, &p) }; + let mut pen = crate::pen::PenTool::default(); + let acts = pen.pointer(&c, &PointerEvent::new(PointerKind::Down, click.x, click.y)); + let Some(Action::Preview(_, v)) = acts.get(1) else { panic!("{acts:?}") }; + let q = Point::new(v["anchors"][0]["x"].as_f64().unwrap(), v["anchors"][0]["y"].as_f64().unwrap()); + assert!(q.distance(anchor) > 1e-3, "{q:?} landed on the glyph anchor with Smart Guides off"); +} + +/// Snap to Glyph: a single line of type has an x-height guide; a paragraph shows glyph bounds only. +#[test] +fn drawn_points_line_up_with_the_x_height_of_a_single_line() { + let (d, t) = glyph_doc("H", 0.0); + let lay = layout_text(FontDb::global(), &t); + let g = &lay.glyphs[0]; + let face = FontDb::global().face_by_id(g.font_id).unwrap(); + let x_height = (t.xf * g.xf * Point::new(0.0, -face.x_height())).y; + let p = Point::new(400.0, x_height + 2.0); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!((q.y - x_height).abs() < 1e-9, "{q:?}, x-height {x_height}"); + let (q, _) = Targets::for_drawing(&d, &[], None, false).snap_point(p, 4.0); + assert_eq!(q.y, p.y); + let (d, _) = glyph_doc("H\nH", 0.0); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert_eq!(q.y, p.y, "a paragraph has no x-height guide"); + // Baseline Shift raises the x-height with the glyphs. + let (d, _) = glyph_doc_with("H", 0.0, vectorcraft_doc::CharStyle { size: 60.0, baseline_shift: 10.0, ..Default::default() }); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(Point::new(400.0, x_height - 10.0 + 2.0), 4.0); + assert!((q.y - (x_height - 10.0)).abs() < 1e-9, "{q:?}, shifted x-height {}", x_height - 10.0); + // Character Rotation turns the glyph, not its baseline shift. + let style = vectorcraft_doc::CharStyle { size: 60.0, baseline_shift: 10.0, rotation: 30.0, ..Default::default() }; + let (d, _) = glyph_doc_with("H", 0.0, style); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(Point::new(400.0, x_height - 10.0 + 2.0), 4.0); + assert!((q.y - (x_height - 10.0)).abs() < 1e-9, "{q:?}, shifted x-height {}", x_height - 10.0); + // Glyph Scaling widens a rotated glyph without raising its x-height. + let mut t = + vectorcraft_doc::TextObject::point(Point::ZERO, "HH HH", vectorcraft_doc::CharStyle { size: 60.0, rotation: 90.0, ..Default::default() }); + let frame = kurbo::Shape::to_path(&kurbo::Rect::new(50.0, 100.0, 450.0, 400.0), 0.1); + t.kind = vectorcraft_doc::TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&frame) }; + t.xf = Affine::IDENTITY; + t.para.justify = vectorcraft_doc::Justify::JustifyAll; + t.para.justification.glyph_scaling = [100.0, 100.0, 200.0]; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t.clone())))).unwrap(); + let lay = layout_text(FontDb::global(), &t); + assert_eq!(lay.lines.len(), 1); + let g = lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()).expect("a glyph with an outline"); + assert!(g.scale > 1.2, "Glyph Scaling widens the glyph: {}", g.scale); + let expected = (t.xf * g.origin).y - (300.0 - x_height); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(Point::new(30.0, expected + 2.0), 4.0); + assert!((q.y - expected).abs() < 1e-9, "{q:?}, x-height {expected}"); +} + +/// Snap to Glyph: the x-height guide of type skewed along a slanted path runs through the glyph's +/// x-height. +#[test] +fn the_x_height_guide_of_skewed_path_type_runs_through_the_glyphs_x_height() { + let mut path = kurbo::BezPath::new(); + path.move_to((100.0, 400.0)); + path.line_to((300.0, 54.0)); + let mut t = vectorcraft_doc::TextObject::point(Point::ZERO, "H", vectorcraft_doc::CharStyle { size: 60.0, ..Default::default() }); + t.kind = vectorcraft_doc::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t.clone())))).unwrap(); + let lay = layout_text(FontDb::global(), &t); + let g = lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()).expect("a glyph with an outline"); + let face = FontDb::global().face_by_id(g.font_id).unwrap(); + let top = t.xf * g.xf * Point::new(0.0, -face.x_height()); + let ahead = Vec2::new(g.angle.cos(), g.angle.sin()); + let normal = Vec2::new(ahead.y, -ahead.x); + // Beside the guide's line, past the glyph's end along it. + let p = top + ahead * 80.0 + normal * 1.5; + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!((q - top).cross(ahead).abs() < 1e-6, "{q:?} is off the x-height line through {top:?}"); +} + +/// Snap to Glyph › Proximity Guides: the edges of each character's advance width are guides. +#[test] +fn drawn_points_line_up_with_the_edge_of_a_characters_width() { + let (d, t) = glyph_doc("HH", 0.0); + let lay = layout_text(FontDb::global(), &t); + let edge = (t.xf * lay.glyphs[1].origin).x; + let p = Point::new(edge + 0.3, 450.0); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!((q.x - edge).abs() < 1e-9, "{q:?}, edge {edge}"); + let (q, _) = Targets::for_drawing(&d, &[], None, false).snap_point(p, 4.0); + assert_eq!(q.x, p.x); + // Character Rotation turns the glyphs, not their widths along the baseline. + let (d, t) = glyph_doc_with("HH", 0.0, vectorcraft_doc::CharStyle { size: 60.0, rotation: 30.0, ..Default::default() }); + let lay = layout_text(FontDb::global(), &t); + let edge = (t.xf * lay.glyphs[1].origin).x; + let p = Point::new(edge + 0.3, 450.0); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!((q.x - edge).abs() < 1e-9, "{q:?}, edge {edge}"); +} + +/// Snap to Glyph › Angular Guides: in a rotated glyph a straight upright stroke is a guide at its +/// angle, which a drawn point lands on beyond the glyph. +#[test] +fn a_rotated_glyph_has_angular_guides_along_its_strokes() { + let angle = 20f64.to_radians(); + let (d, t) = glyph_doc("H", angle); + let lay = layout_text(FontDb::global(), &t); + let g = lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()).expect("a glyph with an outline"); + let stem = g + .outline + .segments() + .find_map(|s| match s { + PathSeg::Line(l) if (l.p1.x - l.p0.x).abs() < 1e-6 && (l.p1.y - l.p0.y).abs() > 10.0 => Some(l), + _ => None, + }) + .expect("an upright stroke"); + let (a, b) = (t.xf * stem.p0, t.xf * stem.p1); + let dir = (b - a) / (b - a).hypot(); + // Past the far end of the stroke, a little beside its line. + let far = if (a - t.xf * Point::new(0.0, 0.0)).hypot() > (b - t.xf * Point::new(0.0, 0.0)).hypot() { a } else { b }; + let out = if far == a { -dir } else { dir }; + let p = far + out * 30.0 + Vec2::new(-dir.y, dir.x) * 1.5; + let on_line = |q: Point| (q - a).cross(dir).abs(); + let (q, ov) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!(on_line(q) < 1e-9, "{q:?} is {} off the stroke's line", on_line(q)); + assert!(!lines(&ov).is_empty()); + let (q, _) = Targets::for_drawing(&d, &[], None, false).snap_point(p, 4.0); + assert!(on_line(q) > 1e-3, "no angular guide with Snap to Glyph off"); +} + +/// Snap to Glyph: the baseline of type turned slightly runs at its angle, and a point near it +/// lands on it even close to where it starts, far nearer the horizontal through that point. +#[test] +fn a_slightly_rotated_baseline_pulls_points_near_its_start() { + let (d, t) = glyph_doc("H", 2f64.to_radians()); + let lay = layout_text(FontDb::global(), &t); + let m = t.xf * lay.line_xf; + let start = m * Point::new(lay.lines[0].x0, lay.lines[0].baseline); + let dir = (m * Point::new(1.0, 0.0)) - (m * Point::ZERO); + let dir = dir / dir.hypot(); + let p = start - dir * 10.0 + Vec2::new(-dir.y, dir.x) * 1.0; + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_point(p, 4.0); + assert!((q - start).cross(dir).abs() < 1e-9, "{q:?} is off the baseline"); +} + +/// Snap to Glyph: a segment Shift keeps level slides along to where it crosses the baseline of +/// rotated type. +#[test] +fn a_shift_constrained_point_slides_onto_a_rotated_baseline() { + let (d, t) = glyph_doc("H", 20f64.to_radians()); + let lay = layout_text(FontDb::global(), &t); + let m = t.xf * lay.line_xf; + let start = m * Point::new(lay.lines[0].x0, lay.lines[0].baseline); + let dir = (m * Point::new(1.0, 0.0)) - (m * Point::ZERO); + let dir = dir / dir.hypot(); + let crossing = start - dir * 40.0; + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let from = Leave::segment(&c, crossing - Vec2::new(60.0, 0.0), true); + let (q, _) = Targets::for_drawing(&d, &[], None, true).snap_from(crossing + Vec2::new(1.5, 0.3), Some(&from), 4.0); + assert!(q.distance(crossing) < 1e-9, "{q:?} vs {crossing:?}"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index e55bb4069a..c4df0c9467 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -219,6 +219,11 @@ pub trait Tool: Send { fn deactivate(&mut self, _cx: &ToolContext) -> Vec { vec![] } + /// The tool, already active, is chosen again (its toolbar button, its shortcut, `tool.select`). + /// Most tools keep their state; the Blend tool finishes the blend it is adding to. + fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { + vec![] + } /// A command from outside the tool ran (a menu, a panel, an agent): finish work it ended (the /// Type tool stops editing text the command took out of the selection). fn after_command(&mut self, _cx: &ToolContext) -> Vec { diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 230c92ea2e..0ac4242679 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -3,13 +3,14 @@ //! - Blend: click object A, then object B → `object.blend.make {ids: [A, B]}`; clicking an anchor //! point of a path blends from that point (`starts`). Each further click adds the object as one //! more key of the new blend (as does clicking a blend first). Double-click or Alt-click opens -//! Blend Options (dialog `blendOptions`). Clicking empty canvas starts over. +//! Blend Options (dialog `blendOptions`). Clicking empty canvas or pressing Escape starts over. //! - Mesh: click inside a filled path → `object.mesh.create {ids, at}` (1×1 mesh plus lines through //! the click); click inside a mesh or a mesh envelope → `object.mesh.addLine` (a gradient mesh's //! new point takes the current fill color in its own model, unless Shift); drag a mesh point, //! or a handle of the point last clicked → `object.mesh.movePoint` previews ([`MeshEdit`]); //! Alt-click a mesh point → `object.mesh.deletePoint`. Clicking a gradient mesh's point selects -//! the mesh, and the next solid fill color recolors just that point. +//! the mesh, and the next solid fill color recolors just that point. Escape during a drag +//! cancels it. use serde_json::json; use vectorcraft_color::Paint; @@ -17,7 +18,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::Point; use crate::meshedit::{MeshEdit, grid_of}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; @@ -87,6 +88,11 @@ impl Tool for BlendTool { (t.first, t.chained) = (None, false); vec![Action::Dialog(BLEND_OPTIONS.into(), json!({}))] }; + // A first pick whose object is no longer in the document (deleted, or undone away) is + // dropped, so the click picks the object it hits as the new first pick. + if self.first.is_some_and(|(a, _)| cx.doc.node(a).is_none()) { + (self.first, self.chained) = (None, false); + } match ev.kind { PointerKind::DoubleClick => options(self), PointerKind::Down if ev.mods.alt => options(self), @@ -135,10 +141,24 @@ impl Tool for BlendTool { fn busy(&self) -> bool { self.first.is_some() } + /// Escape drops the object picked first and stops adding to the blend just made, so the next + /// click picks a new first object. The document and the selection stay as they are. + fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { + if key == crate::ToolKey::Escape { + (self.first, self.chained) = (None, false); + } + vec![] + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { (self.first, self.chained) = (None, false); vec![] } + /// Choosing the Blend tool again finishes the blend: it drops the object picked first and + /// stops adding to the blend just made, so the next click picks a new first object. The + /// document and the selection stay as they are. + fn chosen_again(&mut self, cx: &ToolContext) -> Vec { + self.deactivate(cx) + } } #[derive(Default)] @@ -252,6 +272,14 @@ impl Tool for MeshTool { fn busy(&self) -> bool { self.edit.dragging() } + /// Escape during a drag of a mesh point or handle cancels it: the point goes back and the + /// release does nothing. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key != ToolKey::Escape { + return vec![]; + } + self.edit.cancel().unwrap_or_default() + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.edit.unfocus(); self.edit.release().unwrap_or_default() @@ -279,6 +307,72 @@ mod tests { assert_eq!(acts, vec![Action::Exec("object.blend.make".into(), json!({"ids": [a.0, b.0]}))]); } + /// Choosing the Blend tool again drops the object picked first and stops adding to the blend + /// just made: the next click is a new first pick. The Mesh tool keeps its state. + #[test] + fn choosing_the_blend_tool_again_finishes_the_blend() { + let (mut d, a) = doc_with_rect(); + let l = d.layers[0].id; + let (b, g) = (d.alloc_id(), d.alloc_id()); + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(300.0, 100.0, 350.0, 150.0)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(b, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + let (k1, k2) = (d.alloc_id(), d.alloc_id()); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 300.0, x + 20.0, 320.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let blend = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 0.0), key(k2, 100.0)], spec: Default::default() }); + d.insert(Some(l), 2, blend).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let picks = |id: NodeId| vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]; + let down = |x: f64, y: f64| PointerEvent::new(PointerKind::Down, x, y); + let mut t = BlendTool::default(); + assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); + assert!(t.busy()); + assert!(t.chosen_again(&c).is_empty(), "choosing the tool again changes nothing in the document"); + assert!(!t.busy() && t.first(&c).is_none() && t.overlays(&c).is_empty(), "and drops the pick"); + assert_eq!(t.pointer(&c, &down(320.0, 120.0)), picks(b), "b is picked first"); + // After a blend is made, the next click no longer adds to it. + let mut s = Selection::default(); + s.set([g]); + let c = cx(&d, &s, &p); + let mut t = BlendTool { first: None, chained: true }; + assert!(t.first(&c).is_some()); + assert!(t.chosen_again(&c).is_empty()); + assert!(t.first(&c).is_none(), "choosing the tool again ends adding to the blend just made"); + assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); + // Other tools keep their state: the default does nothing. + assert!(create("mesh").unwrap().chosen_again(&c).is_empty()); + } + + #[test] + fn blend_tool_picks_again_when_its_first_pick_is_gone() { + let (mut d, a) = doc_with_rect(); + let l = d.layers[0].id; + let (b, e) = (d.alloc_id(), d.alloc_id()); + for (id, y) in [(b, 100.0), (e, 300.0)] { + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(300.0, y, 350.0, y + 50.0)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let mut t = BlendTool::default(); + t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + // The first pick is deleted (or undone away) while the tool waits for the second click. + d.remove(a).unwrap(); + let c = cx(&d, &s, &p); + let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 320.0, 120.0)); + assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [b.0]}))], "the click picks b first"); + let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 320.0, 320.0)); + assert_eq!(acts, vec![Action::Exec("object.blend.make".into(), json!({"ids": [b.0, e.0]}))]); + // After a blend is made, a click while the selected blend is gone picks the object it hits. + let mut s = Selection::default(); + s.set([NodeId(9999)]); + let mut t = BlendTool { first: None, chained: true }; + let acts = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 320.0, 120.0)); + assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [b.0]}))]); + } + #[test] fn blend_tool_anchor_clicks_and_options() { let (mut d, a) = doc_with_rect(); @@ -331,6 +425,49 @@ mod tests { assert!(t.first(&c).is_none()); } + /// Escape drops the object picked first, and stops adding to the blend just made: the next + /// click is a new first pick, and the click after it blends with that one. + #[test] + fn escape_drops_the_blend_tools_first_pick() { + let (mut d, a) = doc_with_rect(); + let l = d.layers[0].id; + let (b, g) = (d.alloc_id(), d.alloc_id()); + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(300.0, 100.0, 350.0, 150.0)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(b, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + let (k1, k2) = (d.alloc_id(), d.alloc_id()); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 300.0, x + 20.0, 320.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let blend = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 0.0), key(k2, 100.0)], spec: Default::default() }); + d.insert(Some(l), 2, blend).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let picks = |id: NodeId| vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]; + let down = |x: f64, y: f64| PointerEvent::new(PointerKind::Down, x, y); + let esc = |t: &mut BlendTool| t.key(&c, crate::ToolKey::Escape, Mods::default()); + let mut t = BlendTool::default(); + assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); + assert!(t.busy() && !t.overlays(&c).is_empty()); + assert!(t.key(&c, crate::ToolKey::Enter, Mods::default()).is_empty()); + assert!(t.busy(), "Enter keeps the pick"); + assert!(esc(&mut t).is_empty(), "Escape changes nothing in the document"); + assert!(!t.busy() && t.first(&c).is_none() && t.overlays(&c).is_empty(), "Escape drops the pick"); + // The next click picks b first instead of blending a with it. + assert_eq!(t.pointer(&c, &down(320.0, 120.0)), picks(b)); + assert_eq!(t.pointer(&c, &down(150.0, 150.0)), vec![Action::Exec("object.blend.make".into(), json!({"ids": [b.0, a.0]}))]); + // After a blend is made, Escape stops the next click adding to it. + let mut s = Selection::default(); + s.set([g]); + let c = cx(&d, &s, &p); + let mut t = BlendTool { first: None, chained: true }; + assert!(t.first(&c).is_some()); + assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made"); + assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a)); + assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop"); + } + #[test] fn mesh_tool_click_path_creates_mesh() { let (d, a) = doc_with_rect(); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 9037968ae2..39f8adcdb7 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -102,6 +102,11 @@ impl MeshEdit { self.drag.take().map(|_| vec![Action::Commit]) } + /// Cancel a drag: the point or handle goes back (`None` when nothing was being dragged). + pub fn cancel(&mut self) -> Option> { + self.drag.take().map(|_| vec![Action::Cancel]) + } + pub fn dragging(&self) -> bool { self.drag.is_some() } @@ -194,6 +199,34 @@ mod tests { ); } + /// Escape during a drag of a mesh point or handle, with the Mesh tool or Direct Selection, + /// cancels it, and the release after it does nothing; the point stays the focused one. + #[test] + fn escape_cancels_a_mesh_point_drag() { + let (d, e) = doc_with_envelope(); + let mut s = Selection::default(); + s.set([e]); + let p = paint(); + let c = cx(&d, &s, &p); + let tools: [(&str, Box); 2] = + [("mesh", crate::meshblend::create("mesh").unwrap()), ("directSelection", Box::new(crate::direct::DirectSelectionTool::new(false)))]; + for (what, mut t) in tools { + // A point, then (once the point is focused) its handle. + for (x, y) in [(200.0, 100.0), (200.0, 133.33333)] { + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)), vec![Action::Begin("Move Mesh Point".into())], "{what}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x + 10.0, y - 10.0)); + assert!(t.key(&c, crate::ToolKey::Enter, crate::Mods::default()).is_empty(), "{what}: Enter leaves the drag alone"); + assert!(t.busy(), "{what}"); + assert_eq!(t.key(&c, crate::ToolKey::Escape, crate::Mods::default()), vec![Action::Cancel], "{what}: Escape cancels the drag"); + assert!(!t.busy(), "{what}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x + 20.0, y - 20.0)).is_empty(), "{what}: the drag is over"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, x + 20.0, y - 20.0)).is_empty(), "{what}: the release does nothing"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Handle { .. })), "{what}: the point stays focused"); + } + assert!(t.key(&c, crate::ToolKey::Escape, crate::Mods::default()).is_empty(), "{what}: nothing to cancel"); + } + } + #[test] fn direct_selection_drags_a_selected_envelopes_points() { let (d, e) = doc_with_envelope(); diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index 57ef477341..af79c1ce46 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -287,6 +287,24 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::Up, Point::new(312.0, 150.0))).is_empty()); } + /// Escape during a pie widget drag with the Selection tool cancels it: the angle readout is removed, + /// and the release after it commits nothing. + #[test] + fn escape_cancels_a_pie_widget_drag() { + let (d, _, s) = doc_with_ellipse((0.0, 360.0)); + let p = paint(); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, Point::new(312.0, 150.0))).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::Drag, Point::new(200.0, 20.0))); + assert_eq!(a[0], Action::Begin("Live Shape".into())); + assert_eq!(t.key(&c, crate::ToolKey::Escape, Mods::default()), vec![Action::Cancel], "Escape cancels the drag"); + assert!(!t.busy() && !t.transforming()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })), "the readout is removed"); + assert!(t.pointer(&c, &ev(PointerKind::Drag, Point::new(100.0, 200.0))).is_empty(), "the drag is over"); + assert!(t.pointer(&c, &ev(PointerKind::Up, Point::new(100.0, 200.0))).is_empty(), "the release commits nothing"); + } + /// On a whole ellipse the two widgets sit at the very same point, whatever its size, place or /// angle, so a press there always takes the End widget. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 3dab80fa3d..8d839602ad 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -17,6 +17,8 @@ //! scaling its type: the text reflows at its size. //! E pressed during a marquee drag makes the marquee take only the objects entirely inside it, and //! E pressed again makes it take the objects it touches. +//! Escape during a drag (a move or an Alt-drag copy, a scale, a rotation, a marquee, a widget or +//! bracket drag) cancels it: the art returns to its state at the press. //! Selected area type and type on a path show an in port and an out port. A click on the out port //! loads the pointer with the text ([`Cursor::LoadedText`]): the next click threads it into the //! closed path, area type or type on a path under the pointer, or into a new frame of the same @@ -35,7 +37,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at}; +use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -118,6 +120,9 @@ pub struct SelectionTool { /// What a bounding-box handle being dragged snaps to. targets: Option, moving: Option, + /// The params of the move's last preview: in Shaper's Construction mode the move ends with + /// them and `releaseOutside` ([`construction`]). + last_move: Option, /// The move snapped to a point or a guide at its last step: the arrow turns hollow. snapped: bool, guide: GuideEdit, @@ -195,6 +200,12 @@ impl MoveSnap { } } + /// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an + /// edge of the box on a gridline, and pixels put its top-left on whole pixels. + pub(crate) fn grid_only(bounds: Option) -> Self { + Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None } + } + /// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its /// guides. pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { @@ -460,6 +471,33 @@ pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)).unwrap_or(p) } +/// While an opacity mask or a pattern is edited, a Shaper double-click selects a Shaper Group's +/// original shape without isolating the group's original shapes. A press at `p` on a selected +/// original shape holds it for a move: the hit inside its Shaper Group's original shapes, and that +/// container. Each selected original shape's Shaper Group is checked, front to back, and an object +/// in front of that group at `p` keeps the press. None otherwise. +fn selected_source_hit(cx: &ToolContext, p: Point) -> Option<(Hit, NodeId)> { + if cx.doc.mask_edit.is_none() && cx.doc.pattern_edit.is_none() { + return None; + } + let is_sources = |g: &NodeId| cx.doc.node(*g).is_some_and(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)); + let mut containers = cx.doc.paint_order(cx.selection.objects.iter().filter_map(|id| cx.doc.parent_of(*id)).filter(is_sources)); + containers.dedup(); + let front = hit_test(cx.doc, p, cx.selection_hit_options()); + containers.into_iter().rev().find_map(|sources| { + let group = cx.doc.parent_of(sources)?; + if let Some(f) = &front + && f.leaf != group + && !f.ancestry.contains(&group) + && cx.doc.paint_order([group, f.leaf]).last() == Some(&f.leaf) + { + return None; + } + let h = hit_test(cx.doc, p, vectorcraft_doc::hit::HitOptions { scope: Some(sources), ..cx.selection_hit_options() })?; + cx.selection.contains(h.top_object(Some(sources))).then_some((h, sources)) + }) +} + impl SelectionTool { fn drag_threshold(cx: &ToolContext) -> f64 { cx.tol(3.0) @@ -559,7 +597,11 @@ impl Tool for SelectionTool { } /// E during a marquee drag switches the marquee between the objects it touches and only the - /// objects inside it. + /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or + /// rotation, a marquee, a corner widget, a pie widget, the brackets of type on a path, a mirror + /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy + /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape + /// drops the text. fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Letter('e') && let State::Marquee { enclosed, .. } = &mut self.state @@ -583,6 +625,13 @@ impl Tool for SelectionTool { self.state = State::Idle; return vec![]; } + if key == ToolKey::Escape && !matches!(self.state, State::Idle) { + self.state = State::Idle; + self.measure = None; + self.guides.clear(); + (self.targets, self.moving, self.snapped) = (None, None, false); + return vec![Action::Cancel]; + } if key == ToolKey::Escape { self.guide.cancel() } else { vec![] } } @@ -662,9 +711,13 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: p, began: false, deselect: None, key: None }; return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } - match hit_test(cx.doc, p, cx.selection_hit_options()) { + let (hit, scope) = match selected_source_hit(cx, p) { + Some((h, sources)) => (Some(h), Some(sources)), + None => (hit_test(cx.doc, p, cx.selection_hit_options()), cx.isolation), + }; + match hit { Some(h) => { - let top = h.top_object(cx.isolation); + let top = h.top_object(scope); let mut out = vec![]; let (mut deselect, mut key) = (None, None); if m.shift { @@ -687,7 +740,7 @@ impl Tool for SelectionTool { out } None => { - self.state = State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false }; + self.press_nothing(cx, p, grab, m); vec![] } } @@ -759,8 +812,17 @@ impl Tool for SelectionTool { self.measure = None; self.guides.clear(); self.moving = None; + let last = self.last_move.take(); match (began, deselect, key) { - (true, ..) => vec![Action::Commit], + // In Construction mode, an original shape dropped wholly outside the group's + // bounds leaves the group, in the move's undo step (`releaseOutside`). + (true, ..) => match last.filter(|p| construction(cx) && p["copy"] != json!(true)) { + Some(mut params) => { + params["releaseOutside"] = json!(true); + vec![Action::Preview("object.transform".into(), params), Action::Commit] + } + None => vec![Action::Commit], + }, (false, Some(id), _) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))], // A click on the key object again: no key. (false, None, Some(id)) if cx.selection.key == Some(id) => vec![Action::Exec("select.key".into(), json!({}))], @@ -883,6 +945,9 @@ impl Tool for SelectionTool { if cx.snap_to_point && matches!(Self::hover_point(cx, p), Some((_, "anchor"))) { return Cursor::ArrowHollow; } + if selected_source_hit(cx, p).is_some() { + return Cursor::Move; + } if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) { if cx.selection.contains(h.top_object(cx.isolation)) || m.alt { return Cursor::Move; @@ -912,6 +977,11 @@ fn can_be_key(cx: &ToolContext, id: NodeId) -> bool { cx.doc.node(id).is_some_and(|n| !n.is_layer()) && !inside_selected && !member } +/// Shaper's Construction mode: a Shaper Group's original shapes are isolated. +fn construction(cx: &ToolContext) -> bool { + cx.isolation.and_then(|id| cx.doc.node(id)).is_some_and(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)) +} + /// Is `n` area type (text in a frame) whose frame the tools reshape? Type in perspective isn't: /// it transforms whole. pub(crate) fn is_area_type(n: &vectorcraft_doc::Node) -> bool { @@ -1121,6 +1191,17 @@ impl SelectionTool { } impl SelectionTool { + /// A press at `p` that hits no object starts a marquee, except where a clipping mask hides + /// the art of a selected object (picked in the Layers panel, say): there, without Shift, it + /// grabs the selection by that art (at `grab`), as a press on its visible part does. + fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, m: Mods) { + self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() { + State::Moving { start: grab, press: p, hold: grab, began: false, deselect: None, key: None } + } else { + State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false } + }; + } + fn drag_moving(&mut self, cx: &ToolContext, p: Point, m: Mods, (start, press, hold, began): (Point, Point, Point, bool)) -> Vec { let mut out = vec![]; if !began { @@ -1139,7 +1220,9 @@ impl SelectionTool { self.snapped = (d - unsnapped).hypot() > 1e-9; self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); - out.push(Action::Preview("object.transform".into(), json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }))); + let params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); + self.last_move = Some(params.clone()); + out.push(Action::Preview("object.transform".into(), params)); out } } diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index f777d59cce..6aace4acde 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2,6 +2,64 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; +/// While an opacity mask is edited, a press on a selected Shaper original shape moves it, over the +/// art the group shows and over a part of the shape the group does not show. A press on an original +/// shape that is not selected selects the Shaper Group or starts a marquee, as before. +#[test] +fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() { + let (mut d, g, sources, _) = doc_with_shaper_group(); + let rect = d.layers[0].children().unwrap()[0].id; + let layer = d.layers[0].id; + d.mask_edit = Some(vectorcraft_doc::MaskEdit { object: rect, layer }); + let ids: Vec = d.node(sources).unwrap().children().unwrap().iter().map(|n| n.id).collect(); + let (mut s, p) = (Selection::default(), paint()); + s.set([ids[1]]); + let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; + for x in [75.0, 125.0] { + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}"); + let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0)); + assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}"); + let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0)); + assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "at {x}: {drag:?}"); + } + s.set([ids[0]]); + let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; + let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0)); + assert!(down.is_empty(), "{down:?}"); + let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 75.0, 350.0)); + assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([g.0]))), "{down:?}"); +} + +/// While an opacity mask is edited, a selected Shaper original shape that is not the first selected +/// object still moves on a press, and an object in front of the Shaper Group keeps the press. +#[test] +fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() { + use vectorcraft_doc::{Appearance, Node}; + let (mut d, _, sources, _) = doc_with_shaper_group(); + let rect = d.layers[0].children().unwrap()[0].id; + let layer = d.layers[0].id; + d.mask_edit = Some(vectorcraft_doc::MaskEdit { object: rect, layer }); + let ids: Vec = d.node(sources).unwrap().children().unwrap().iter().map(|n| n.id).collect(); + let (mut s, p) = (Selection::default(), paint()); + s.set([rect, ids[1]]); + let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move); + let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0)); + assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}"); + let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0)); + assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "{drag:?}"); + let front = d.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(110.0, 340.0, 140.0, 360.0)); + d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap(); + s.set([ids[1]]); + let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) }; + assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move); + let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0)); + assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}"); +} + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { PointerEvent::new(kind, x, y) } @@ -21,6 +79,53 @@ fn a_press_on_a_masks_edge_selects_its_clip_group() { assert!(!a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{a:?}"); } +/// The art of a selected clipped object (picked in the Layers panel), pressed where its mask +/// hides it, is grabbed: a drag moves the selection (the art, not its clip group) and a click +/// keeps it selected. With nothing of it selected, or with Shift, a press there starts a marquee. +#[test] +fn a_press_where_a_mask_hides_a_selected_object_drags_it() { + let (d, _, _, art) = doc_with_masked_square(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(art); + let shift = |kind, x, y| { + let mut e = ev(kind, x, y); + e.mods.shift = true; + e + }; + let changes_selection = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, _) if c.starts_with("select."))); + // (370, 450): on the art, outside the mask (400..500). + let mut t = SelectionTool::default(); + let c = cx(&d, &picked, &p); + assert!(t.pointer(&c, &ev(PointerKind::Down, 370.0, 450.0)).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::Drag, 390.0, 470.0)); + assert!(a.iter().any(|a| matches!(a, Action::Begin(n) if n == "Move")), "{a:?}"); + assert!(a.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "{a:?}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 390.0, 470.0)), vec![Action::Commit]); + // A click there keeps the selection. + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 370.0, 450.0)); + assert!(!changes_selection(&t.pointer(&c, &ev(PointerKind::Up, 370.0, 450.0)))); + // Nothing selected: a marquee, and a click deselects. + let none = Selection::default(); + let c = cx(&d, &none, &p); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 370.0, 450.0)); + assert!(!t.pointer(&c, &ev(PointerKind::Drag, 390.0, 470.0)).iter().any(|a| matches!(a, Action::Begin(_)))); + // Shift: a marquee that adds to the selection. + let c = cx(&d, &picked, &p); + let mut t = SelectionTool::default(); + t.pointer(&c, &shift(PointerKind::Down, 370.0, 450.0)); + assert!(!t.pointer(&c, &shift(PointerKind::Drag, 390.0, 470.0)).iter().any(|a| matches!(a, Action::Begin(_)))); + // An object a click hits there wins: a press on a square over that point selects it. + let mut d = d; + let (front, l) = (d.alloc_id(), d.layers[0].id); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(350.0, 430.0, 390.0, 470.0)); + d.insert(Some(l), 2, vectorcraft_doc::Node::path(front, square, vectorcraft_doc::Appearance::default_art())).unwrap(); + let a = SelectionTool::default().pointer(&cx(&d, &picked, &p), &ev(PointerKind::Down, 370.0, 450.0)); + assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{a:?}"); +} + /// #955: grabbed by an anchor and dropped near another object's anchor, the anchor lands /// exactly on it with Smart Guides, even where lining the bounds up would leave it beside it. #[test] @@ -102,6 +207,44 @@ fn a_corner_drag_counts_as_transforming_once_it_moves() { assert!(t.transforming()); } +/// Escape during a corner widget drag cancels it, and the release after it commits nothing. +/// After an Alt-press on a widget, Escape drops the press, so its release cycles no corner kind. +#[test] +fn escape_cancels_a_corner_widget_drag() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = LiveShape::Rectangle { + w: 100.0, + h: 100.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: vectorcraft_geom::Affine::translate((100.0, 100.0)), + }; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let id = d.alloc_id(); + let mut n = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 190.0, 191.0)).is_empty()); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 175.0, 176.0)); + assert_eq!(a.first(), Some(&Action::Begin("Corner Radius".into())), "{a:?}"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "Escape cancels the drag"); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 171.0)).is_empty(), "the drag is over"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 170.0, 171.0)).is_empty(), "the release commits nothing"); + let alt = Mods { alt: true, ..Default::default() }; + t.pointer(&cx, &ev(PointerKind::Down, 190.0, 191.0).with_mods(alt)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 190.0, 191.0).with_mods(alt)).is_empty(), "the Alt-click cycles no corner kind"); +} + /// A type-on-path bracket drag is a transform, so the sharp selection box hides while the span moves. #[test] fn a_bracket_drag_counts_as_transforming_once_it_moves() { @@ -118,6 +261,25 @@ fn a_bracket_drag_counts_as_transforming_once_it_moves() { assert!(t.transforming()); } +/// Escape during a drag of the brackets of type on a path cancels it, and the release after it +/// commits nothing. +#[test] +fn escape_cancels_a_bracket_drag() { + let (d, id) = crate::testutil::doc_with_path_type(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 280.0, 290.0)).is_empty()); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 320.0, 290.0)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{a:?}"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "Escape cancels the drag"); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 330.0, 290.0)).is_empty(), "the drag is over"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 330.0, 290.0)).is_empty(), "the release commits nothing"); +} + /// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a /// press there grabs the object by that point. #[test] @@ -460,6 +622,30 @@ fn drag_moves_with_single_undo() { assert_eq!(a, vec![Action::Commit]); } +/// Escape during a move, or an Alt-drag copy, cancels it: the release after it commits nothing, +/// and the next drag is a new one. Escape with nothing to cancel sends nothing. +#[test] +fn escape_cancels_a_move_or_an_alt_drag_copy() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + for (what, m) in [("move", Mods::default()), ("copy", Mods { alt: true, ..Default::default() })] { + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0).with_mods(m)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 160.0, 150.0).with_mods(m)); + assert!(matches!(&a[1], Action::Preview(_, v) if v["copy"] == m.alt), "{what}: {a:?}"); + assert!(t.transforming(), "{what}"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{what}: Escape cancels the drag"); + assert!(!t.busy() && !t.transforming(), "{what}"); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Measure { .. })), "{what}: no readout stays"); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 150.0).with_mods(m)).is_empty(), "{what}: the drag is over"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 170.0, 150.0).with_mods(m)).is_empty(), "{what}: the release commits nothing"); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty(), "{what}: nothing to cancel"); + } +} + /// #1534: with Smart Guides on (the default), the point a selection is dragged by still snaps /// to a ruler guide within the Snap to Point distance; not with Snap to Point off. #[test] @@ -907,6 +1093,22 @@ fn marquee_selects() { assert_eq!(a, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } +/// Escape during a marquee drag ends it: the marquee is removed, and its release selects nothing. +#[test] +fn escape_cancels_a_marquee() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 120.0, 120.0)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "Escape cancels the marquee"); + assert!(!t.busy()); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_))), "the marquee is removed"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 120.0, 120.0)).is_empty(), "the release selects nothing"); +} + /// Shift-drag a marquee: the objects it reaches toggle (#483), so selected ones can be /// taken out of the selection; a Shift-click on empty canvas leaves the selection alone. #[test] @@ -1099,6 +1301,28 @@ fn handle_drag_scales() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), vec![Action::Commit]); } +/// Escape during a bounding-box scale or rotation cancels it, and the release after it commits +/// nothing. +#[test] +fn escape_cancels_a_scale_or_a_rotation() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + // (what, the press, its Begin, the drag) + for (what, from, begin, to) in [("scale", (200.0, 200.0), "Scale", (300.0, 300.0)), ("rotate", (210.0, 210.0), "Rotate", (150.0, 230.0))] { + let mut t = SelectionTool::default(); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, from.0, from.1)), vec![Action::Begin(begin.into())], "{what}"); + assert!(matches!(t.pointer(&cx, &ev(PointerKind::Drag, to.0, to.1)).as_slice(), [Action::Preview(..)]), "{what}"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{what}: Escape cancels the drag"); + assert!(!t.busy() && !t.transforming(), "{what}"); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Measure { .. })), "{what}: no readout stays"); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, to.0 + 5.0, to.1)).is_empty(), "{what}: the drag is over"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, to.0 + 5.0, to.1)).is_empty(), "{what}: the release commits nothing"); + } +} + #[test] fn handle_drag_snaps_to_the_other_objects_with_smart_guides() { use vectorcraft_doc::{Appearance, Node}; diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 8548f33124..9e2cb90a9e 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -39,7 +39,7 @@ const ROWS: &[Row] = &[ // Paintbrush has none of them). (&["pencil"], None, &["altSmooth", "livePreview", "liveFit"]), (&["smooth"], None, &["fidelity"]), - (&["blobBrush", "eraser"], None, &["size"]), + (&["blobBrush", "eraser"], None, &["size", "sizeMode", "sizeVariation"]), (&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]), // Eraser Tool Options' tip shape. (&["eraser"], None, &["angle", "roundness"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 62679d99e3..f8594226ce 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -75,12 +75,15 @@ impl ShapeTool { } } - /// Ctrl/Cmd in a star drag from `start` to `p`: the inner radius stays as it was when the key - /// went down, so the ratio follows the outer radius (and stays so once the key is let go). - fn hold_inner(&mut self, start: Point, p: Point, m: Mods) { + /// Ctrl/Cmd in a star drag from `start` to `p`, where the last drag showed a star with the inner + /// radius `shown`: once the star has begun, the inner radius stays as the star showed it when + /// the key went down, so the ratio follows the outer radius (and stays so once the key is let + /// go). When the key goes down before the star has begun, the inner radius stays as the first + /// star the drag shows has it. + fn hold_inner(&mut self, shown: f64, start: Point, p: Point, m: Mods) { let outer = (p - start).hypot(); match (m.cmd, self.inner) { - (true, None) => self.inner = Some(outer * self.star_ratio), + (true, None) if self.began => self.inner = Some(shown), (false, Some(_)) => self.inner = None, _ => {} } @@ -224,17 +227,23 @@ impl Tool for ShapeTool { self.start = Some(p); self.last = ev.pos; self.began = false; + self.inner = None; vec![] } PointerKind::Drag => { let Some(mut s) = self.start else { return vec![] }; let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref()); let ev = &PointerEvent { pos, ..*ev }; + // The inner radius of the star the last drag showed, with the ratio it drew with: + // the canvas sends a drag only once the pointer moves, so a key pressed in between + // first arrives with the next position. + let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio }; + let shown = (self.last - s).hypot() * ratio; space_moves(&mut s, &mut self.last, ev, self.began); self.start = Some(s); self.mods = ev.mods; if self.id == "star" { - self.hold_inner(s, ev.pos, ev.mods); + self.hold_inner(shown, s, ev.pos, ev.mods); } let mut out = vec![]; if !self.began { @@ -299,6 +308,7 @@ impl Tool for ShapeTool { } else if key == ToolKey::Escape { self.start = None; self.began = false; + self.inner = None; self.snap.clear(); vec![Action::Cancel] } else { diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 66a4abad9a..da4916576e 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -106,8 +106,10 @@ fn star_measure_label_matches_the_preview_with_modifiers_and_shrink() { assert_eq!(label(&t), cx.star_radii_label(r1, r2)); } -/// During a star drag, Ctrl/Cmd keeps the inner radius while the outer one follows the pointer -/// (the new ratio stays once the key is let go), and Alt keeps the shoulders straight (#812). +/// During a star drag, Ctrl/Cmd keeps the inner radius the star showed when the key went down +/// while the outer one follows the pointer (the new ratio stays once the key is let go), and Alt +/// keeps the shoulders straight (#812). The canvas sends a drag only once the pointer moves, so +/// the key first arrives with a new position. #[test] fn a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt() { let (d, _) = doc_with_rect(); @@ -123,8 +125,7 @@ fn a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); let (r1, r2) = radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 50.0))); assert_eq!((r1, r2), (40.0, 20.0)); - // Ctrl: the inner radius stays 20 as the outer one grows to 80. - t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 50.0).with_mods(ctrl)); + // Ctrl, pressed with the pointer still: the inner radius stays 20 as the outer one grows to 80. let (r1, r2) = radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 50.0).with_mods(ctrl))); assert!((r1 - 80.0).abs() < 1e-9 && (r2 - 20.0).abs() < 1e-9, "{r1} {r2}"); // Let go: the ratio (a quarter) stays. @@ -138,6 +139,54 @@ fn a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt() { assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 50.0)), vec![Action::Commit]); } +/// Ctrl/Cmd pressed while Alt straightens the shoulders keeps the straightened inner radius, a drag +/// canceled with Escape leaves no held radius for the next star, and Ctrl/Cmd pressed inside the +/// drag threshold keeps the inner radius of the first star the drag shows. The canvas lends a +/// selection tool to a press with Ctrl/Cmd held, so every press here is without it. +#[test] +fn a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let radii = |a: &[Action]| match a.last() { + Some(Action::Preview(_, v)) => (v["radius1"].as_f64().unwrap(), v["radius2"].as_f64().unwrap()), + other => panic!("{other:?}"), + }; + let close = |(r1, r2): (f64, f64), (w1, w2): (f64, f64)| assert!((r1 - w1).abs() < 1e-9 && (r2 - w2).abs() < 1e-9, "{r1} {r2}, not {w1} {w2}"); + let ctrl = Mods { cmd: true, ..Default::default() }; + let alt = Mods { alt: true, ..Default::default() }; + let ctrl_alt = Mods { cmd: true, alt: true, ..Default::default() }; + // Alt shows straight shoulders; Ctrl/Cmd pressed then keeps that inner radius. + let mut t = ShapeTool::new("star"); + let straight = straight_ratio(5).unwrap_or(0.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); + close(radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 50.0).with_mods(alt))), (40.0, 40.0 * straight)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 50.0).with_mods(ctrl_alt)); + close(radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 170.0, 50.0).with_mods(ctrl))), (120.0, 40.0 * straight)); + + // Escape with the key held, then a new press and the key before the first move: the next star + // holds what it shows, not the canceled radius. + let mut t = ShapeTool::new("star"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 50.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 50.0).with_mods(ctrl)); + assert_eq!(t.key(&cx, ToolKey::Escape, ctrl), vec![Action::Cancel]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); + close(radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 50.0).with_mods(ctrl))), (10.0, 2.5)); + close(radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 50.0).with_mods(ctrl))), (20.0, 2.5)); + + // Ctrl/Cmd pressed inside the drag threshold, where no star is shown yet. + let mut t = ShapeTool::new("star"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 51.0, 50.0)), vec![]); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 50.0).with_mods(ctrl)); + assert_eq!(a[0], Action::Begin("Star".into())); + close(radii(&a), (40.0, 20.0)); + close(radii(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 50.0).with_mods(ctrl))), (80.0, 20.0)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 50.0).with_mods(ctrl)), vec![Action::Commit]); +} + #[test] fn shift_square_alt_center() { let t = ShapeTool::new("ellipse"); diff --git a/crates/tools/src/shaperwidget.rs b/crates/tools/src/shaperwidget.rs index 0eb1bcb190..f44a622a1c 100644 --- a/crates/tools/src/shaperwidget.rs +++ b/crates/tools/src/shaperwidget.rs @@ -1,6 +1,7 @@ //! The Shaper Group's mode widget: a small arrow beside the right side of the bounds of a Shaper //! Group's source shapes. It shows while the group or one of its faces is selected (Face Selection -//! mode) and while the group's source shapes are isolated (Construction mode). A click on it +//! mode) and while the group's source shapes are isolated (Construction mode), but not while an +//! opacity mask or a pattern is edited. A click on it //! switches between the two modes: it isolates the source shapes (`object.isolate`), or it leaves //! isolation with the group selected (`object.exitIsolation`). The Shaper and Selection tools hit //! it and the canvas draws it from the same geometry. @@ -33,9 +34,10 @@ impl ShaperWidget { /// The widget at `zoom` (screen px per document point), beside the bounds of the group's source /// shapes in both modes. Construction mode: `isolation` is a Shaper Group's source shapes. Face /// Selection mode: the selection is one Shaper Group, or one face or stroke of it. It returns - /// None otherwise, and when the group, or a layer or group that holds it, is hidden or locked. + /// None otherwise, when the group, or a layer or group that holds it, is hidden or locked, and + /// while an opacity mask or a pattern is edited. pub fn of(doc: &Document, selection: &Selection, isolation: Option, zoom: f64) -> Option { - if !zoom.is_finite() || zoom <= 0.0 { + if !zoom.is_finite() || zoom <= 0.0 || doc.mask_edit.is_some() || doc.pattern_edit.is_some() { return None; } let shaper = |id: NodeId| doc.node(id).is_some_and(|n| n.extras().shaper.is_some()); @@ -153,4 +155,21 @@ mod tests { assert!(widget(&d, &[g]).is_none()); assert!(widget(&d, &[face]).is_none()); } + + #[test] + fn no_widget_shows_while_an_opacity_mask_or_a_pattern_is_edited() { + let (mut d, g, sources, _) = doc_with_shaper_group(); + let rect = d.layers[0].children().unwrap()[0].id; + let layer = d.layers[0].id; + let mut s = Selection::default(); + s.add(g); + assert!(ShaperWidget::of(&d, &s, None, 1.0).is_some()); + d.mask_edit = Some(vectorcraft_doc::MaskEdit { object: rect, layer }); + assert!(ShaperWidget::of(&d, &s, Some(layer), 1.0).is_none(), "mask editing"); + assert!(ShaperWidget::of(&d, &Selection::default(), Some(sources), 1.0).is_none(), "mask editing, sources isolated"); + d.mask_edit = None; + d.pattern_edit = Some(vectorcraft_doc::pattern::PatternEdit { pattern: "P".into(), layer, original: None }); + assert!(ShaperWidget::of(&d, &s, Some(layer), 1.0).is_none(), "pattern editing"); + assert!(ShaperWidget::of(&d, &Selection::default(), Some(sources), 1.0).is_none(), "pattern editing, sources isolated"); + } } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 2daa5a7683..9729985c89 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -202,6 +202,17 @@ pub struct TypeTool { } impl TypeTool { + pub(super) fn step_attribute(&mut self, key: ToolKey, mods: Mods, a: usize, b: usize) -> Option> { + if !mods.alt { + return None; + } + let id = self.editing?; + let (attribute, by) = plain::step_key(key, mods.shift, a == b)?; + let mut out = self.commit(); + let by = if mods.cmd { by * 5.0 } else { by }; + out.push(Action::Exec("type.step".into(), json!({"id": id.0, "start": a, "end": b, "attribute": attribute, "by": by}))); + Some(out) + } pub fn new(id: &str) -> Self { let mode = match id { "areaType" | "verticalAreaType" => Mode::Area, diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 1b2086c301..1502533d55 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1469,3 +1469,22 @@ fn ime_surrounding_reports_the_document_when_it_changed_under_the_session() { assert_eq!(stale, ImeSurrounding::Available { text: "XYZ".into(), cursor: 3, anchor: 3 }); assert!(!tool.ime_session_matches_document(&cx(&d, &sel, &p)), "the commit starts a fresh session"); } + +#[test] +fn shift_enter_inserts_soft_return() { + let (mut d, id, mut tool) = editing("Hello World"); + let (sel, p) = (Selection::default(), paint()); + tool.caret = 5; + tool.anchor = 5; + let snap = d.clone(); + let shift = Mods { shift: true, ..Default::default() }; + let acts = tool.key(&cx(&d, &sel, &p), ToolKey::Enter, shift); + apply(&mut d, &snap, &acts); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!() }; + assert_eq!(t.plain_text(), "Hello\u{2028} World"); + // Plain Enter inserts standard newline + let acts = tool.key(&cx(&d, &sel, &p), ToolKey::Enter, Mods::default()); + apply(&mut d, &snap, &acts); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!() }; + assert_eq!(t.plain_text(), "Hello\u{2028}\n World"); +} diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index f2bfff400b..5307d61758 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -1,6 +1,6 @@ use super::plain::{ char_range_to_bytes, ime_surrounding_window, plain_ceil_boundary, plain_chars_after, plain_chars_before, plain_floor_boundary, plain_is_boundary, - plain_len, step_key, + plain_len, }; use super::ports::{ported, ports, ports_shown}; use super::{ @@ -112,7 +112,7 @@ impl Tool for TypeTool { self.clicks = (None, 0); // Pasting what we copied keeps its formatting (unless pasted text is kept plain). let clip: String = self.clipboard.iter().map(|r| r.text.as_str()).collect(); - if !committing && s.len() > 1 && s == clip && !cx.paste_plain_text { + if !committing && !s.is_empty() && s == clip && !cx.paste_plain_text { let runs = self.clipboard.clone(); return self.replace(cx, "", Some(runs)); } @@ -145,7 +145,7 @@ impl Tool for TypeTool { return false; } let clip: String = self.clipboard.iter().map(|r| r.text.as_str()).collect(); - !(self.preedit.is_none() && normalized.len() > 1 && normalized == clip && !cx.paste_plain_text) + !(self.preedit.is_none() && !normalized.is_empty() && normalized == clip && !cx.paste_plain_text) } /// Whether the typing session still describes the edited document; a session ended by an outside /// command reports false until a replacement commit starts a new one. @@ -175,13 +175,7 @@ impl Tool for TypeTool { self.anchor = self.anchor.min(len); let (a, b) = self.sel(); // Alt+arrows step the type by the Preferences › Type increments (Cmd/Ctrl too: five steps). - if mods.alt - && let Some(id) = self.editing - && let Some((attribute, by)) = step_key(key, mods.shift, a == b) - { - let mut out = self.commit(); - let by = if mods.cmd { by * 5.0 } else { by }; - out.push(Action::Exec("type.step".into(), json!({"id": id.0, "start": a, "end": b, "attribute": attribute, "by": by}))); + if let Some(out) = self.step_attribute(key, mods, a, b) { return out; } let word = mods.cmd || mods.alt; @@ -211,7 +205,7 @@ impl Tool for TypeTool { out.push(Action::SwitchTool(target)); out } - ToolKey::Enter => self.replace(cx, "\n", None), + ToolKey::Enter => self.replace(cx, if mods.shift { "\u{2028}" } else { "\n" }, None), ToolKey::Tab => self.replace(cx, "\t", None), ToolKey::Backspace | ToolKey::Delete if a != b => self.replace(cx, "", None), ToolKey::Backspace if self.caret > 0 => { @@ -514,7 +508,7 @@ impl Tool for TypeTool { // Transient selection transferred between Type and Eyedropper; never a saved setting. "textSelection" => { if let (Some(id), Some(a), Some(b)) = ( - v.get("editing").and_then(Value::as_u64), + v.get("editing").or_else(|| v.get("id")).and_then(Value::as_u64), v.get("anchor").or_else(|| v.get("start")).and_then(Value::as_u64), v.get("caret").or_else(|| v.get("end")).and_then(Value::as_u64), ) && let (Ok(a), Ok(b)) = (usize::try_from(a), usize::try_from(b)) diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index ecdb79d43b..09933d2a44 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -426,7 +426,7 @@ impl Tool for ArtboardTool { vec![Action::Commit] } Drag::Resize { began: true, .. } => vec![Action::Commit], - Drag::Create { toggle: Some((i, at)), .. } if p.distance(at) < cx.tol(3.0) => { + Drag::Create { toggle: Some((i, at)), .. } if p.distance(at) < cx.tol(5.0) => { self.toggle(cx, i); vec![] } @@ -562,9 +562,14 @@ impl Tool for ArtboardTool { if let Some(Drag::Marquee { start, cur }) = self.drag { o.push(Overlay::Marquee(Rect::from_points(start, cur))); } - // The other selected artboards: dashed bounds (in a drag the document shows them moved). - for r in self.others.iter().filter_map(|i| cx.doc.artboards.get(*i)).map(|a| a.rect) { - o.push(Overlay::Path { path: polygon(&rect_corners(r), true), color: BLUE, width: 1.0, dashed: true }); + // The other selected artboards: dashed bounds and labels. + for &i in &self.others { + if let Some(ab) = cx.doc.artboards.get(i) { + let r = ab.rect; + o.push(Overlay::Path { path: polygon(&rect_corners(r), true), color: BLUE, width: 1.0, dashed: true }); + let at = Point::new(r.x0 - cx.tol(8.0), r.y0 - cx.tol(4.0)); + o.push(Overlay::Label { p: at, text: format!("{:02} - {}", i + 1, ab.name), color: BLUE }); + } } let Some(ab) = cx.doc.artboards.get(self.active) else { return o }; let r = self.preview.unwrap_or(ab.rect); diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index 15b956bae7..3f2b350e01 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -1,17 +1,20 @@ //! Measure tool: drag between two points to read distance, angle, dX and dY (Shift constrains to //! 45°). The result stays on screen (and in the tool options, for agents) until the next drag; the -//! document is never changed. +//! document is never changed. Escape during a drag cancels it: the result of the drag before +//! comes back. use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; use super::CYAN; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] pub struct MeasureTool { line: Option<(Point, Point)>, dragging: bool, + /// The line measured before the drag under way, which Escape puts back. + before: Option<(Point, Point)>, } /// (distance, angle in degrees counter-clockwise, dx, dy) @@ -33,6 +36,7 @@ impl Tool for MeasureTool { match ev.kind { PointerKind::Down => { let (p, _) = crate::guides::snap_draw(cx, ev.pos, &[]); + self.before = self.line; self.line = Some((p, p)); self.dragging = true; } @@ -52,6 +56,14 @@ impl Tool for MeasureTool { vec![] } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.dragging { + self.dragging = false; + self.line = self.before; + } + vec![] + } + fn overlays(&self, cx: &ToolContext) -> Vec { let Some((a, b)) = self.line else { return vec![] }; if a == b { @@ -128,4 +140,39 @@ mod tests { assert!(!ov.iter().any(|o| matches!(o, Overlay::Measure { .. })), "Measurement Labels off hides the readout"); assert!(ov.iter().any(|o| matches!(o, Overlay::Line { .. })), "the measured line stays"); } + + /// Escape during a drag ends it and brings back the result of the drag before (none at + /// first); the release after it measures nothing. + #[test] + fn escape_cancels_a_measure_drag() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let mut t = MeasureTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 40.0, -30.0)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!t.busy()); + assert_eq!(t.options(), Value::Null, "no earlier result"); + assert!(t.overlays(&cx).is_empty()); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 40.0, -30.0)); + assert_eq!(t.options(), Value::Null, "the release measures nothing"); + // A measurement, then a second drag canceled: the first one's result is back. + for (kind, x, y) in [(PointerKind::Down, 10.0, 10.0), (PointerKind::Drag, 40.0, -30.0), (PointerKind::Up, 40.0, -30.0)] { + t.pointer(&cx, &PointerEvent::new(kind, x, y)); + } + let first = t.options(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 100.0)); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert!(t.busy(), "Enter leaves the drag alone"); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy()); + assert_eq!(t.options(), first); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 100.0)); + assert_eq!(t.options(), first); + assert!((t.options()["distance"].as_f64().unwrap() - 50.0).abs() < 1e-9); + } } diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 85e6373c6b..e68118d634 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -79,7 +79,7 @@ use layers::parallel_map_at_most; #[cfg(test)] pub(crate) use layers::shift_probe; pub use params::{Method, Mode, PRESET_NAMES, Palette, TraceParams, enhanced_preset, preset, presets}; -pub use pipeline::{TraceResult, TracedPath, trace, trace_within}; +pub use pipeline::{TraceResult, TracedPath, trace, trace_watched, trace_within}; #[cfg(test)] use raster::fit_size; pub use raster::{MAX_PIXELS, MAX_SOURCE_PIXELS, Raster, TraceError}; diff --git a/crates/trace/src/pipeline.rs b/crates/trace/src/pipeline.rs index b857e73aeb..486eb9c0a3 100644 --- a/crates/trace/src/pipeline.rs +++ b/crates/trace/src/pipeline.rs @@ -1,3 +1,5 @@ +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use super::layers::{Layers, parallel_map_at_most}; use super::params::{Method, Mode, TraceParams}; use super::raster::{Raster, TraceError}; @@ -68,11 +70,24 @@ pub fn trace(img: &Raster, params: &TraceParams) -> TraceResult { /// than `max_anchors` anchor points (a photo traced at high fidelity can make millions). The /// colour layers are traced in parallel where threads are available. pub fn trace_within(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result { + trace_watched(img, params, max_anchors, &|_, _| true) +} + +/// [`trace_within`], telling `steps` how far it has got: `steps(done, total)` after each stage +/// that prepares the colour layers (`total` 0 while they aren't known yet) and after each colour +/// layer, from whichever thread traced it. Once `steps` answers `false` the trace stops at the +/// next stage or layer with [`TraceError::Cancelled`]. +pub fn trace_watched( + img: &Raster, + params: &TraceParams, + max_anchors: usize, + steps: &(dyn Fn(u64, u64) -> bool + Sync), +) -> Result { let (w, h) = (img.width as usize, img.height as usize); if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { return Ok(TraceResult::default()); } - let mut out = trace_paths(img, params, max_anchors)?; + let mut out = trace_paths(img, params, max_anchors, steps)?; if params.auto_grouping { // Abutting areas cannot overlap; stacked layers, Logo's shapes and stroked lines can. let stacked = params.method == Method::Overlapping || params.mode == Mode::Logo || params.strokes; @@ -81,9 +96,12 @@ pub fn trace_within(img: &Raster, params: &TraceParams, max_anchors: usize) -> R Ok(out) } -fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result { +fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { let (w, h) = (img.width as usize, img.height as usize); + // After each stage before the colour layers, whose number isn't known yet. + let go_on = || if steps(0, 0) { Ok(()) } else { Err(TraceError::Cancelled) }; if params.mode == Mode::Logo { + go_on()?; return logo::trace_logo(img, params, max_anchors); } // The colour Ignore Color leaves out, if not white. @@ -94,6 +112,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result // A photo is traced from a copy with its noise smoothed away (see `smooth`). let smoothed = (params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img)).then(|| smooth::smoothed(img)); let img = smoothed.as_ref().unwrap_or(img); + go_on()?; // Gradients are found first and kept out of the palette: no colour is spent on bands of them. // Grayscale finds them in the image's grays (as its flat colours are), so their stops are gray. let grays = (params.gradients && params.mode == Mode::Grayscale).then(|| { @@ -106,6 +125,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result }); let traced_as = grays.as_ref().unwrap_or(img); let found = (params.gradients && params.mode != Mode::BlackAndWhite).then(|| gradient::detect(traced_as)).filter(|f| !f.1.is_empty()); + go_on()?; let without = found.as_ref().map(|(of, _)| { let mut rest = img.clone(); for (p, &g) in rest.rgba.as_chunks_mut::<4>().0.iter_mut().zip(of) { @@ -116,6 +136,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result rest }); let (mut q, rare) = quantize::quantize_keeping(without.as_ref().unwrap_or(img), params); + go_on()?; // The semi-transparent edge of a cut-out image traces as the color beside it. if matches!(params.mode, Mode::Color | Mode::Grayscale) { quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale); @@ -138,6 +159,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result // Noise clears specks, not the regions of a rare colour Automatic kept on purpose. let keep: Vec = q.palette.iter().map(|c| rare.contains(c)).collect(); quantize::denoise_keeping(&mut q.labels, w, h, params.noise as usize, &keep); + go_on()?; // Pixel count per palette entry, and the box its pixels lie in. let mut counts = vec![0usize; q.palette.len()]; let mut boxes: Vec> = vec![None; q.palette.len()]; @@ -194,7 +216,26 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result // freed before the trace starts.) let largest = job.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1); let at_a_time = ((512 << 20) / (largest * 10)).max(1); - for (paths, &(_, ci)) in parallel_map_at_most(at_a_time, &layers, |&(r, ci)| job.layer(r, ci)).into_iter().zip(&layers) { + let total = layers.len() as u64; + if !steps(0, total) { + return Err(TraceError::Cancelled); + } + // Once stopped, the layers not started yet are skipped. + let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false)); + let traced = parallel_map_at_most(at_a_time, &layers, |&(r, ci)| { + if stopped.load(Ordering::Relaxed) { + return None; + } + let paths = job.layer(r, ci); + if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) { + stopped.store(true, Ordering::Relaxed); + } + paths + }); + if stopped.load(Ordering::Relaxed) { + return Err(TraceError::Cancelled); + } + for (paths, &(_, ci)) in traced.into_iter().zip(&layers) { let paths = paths.ok_or(TraceError::TooComplex { max: max_anchors })?; // A layer with no paths adds no color to the palette. if paths.is_empty() { diff --git a/crates/trace/src/raster.rs b/crates/trace/src/raster.rs index f096a97d0c..fc7cd10f67 100644 --- a/crates/trace/src/raster.rs +++ b/crates/trace/src/raster.rs @@ -15,6 +15,9 @@ pub enum TraceError { "this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset" )] TooComplex { max: usize }, + /// The caller of [`crate::trace_watched`] stopped the trace. + #[error("the trace was cancelled")] + Cancelled, } /// The most pixels an image to trace may have (64 megapixels: 256 MB decoded); larger images are diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 6ad9094954..f5a10d494a 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -586,6 +586,28 @@ fn a_trace_past_its_anchor_budget_is_refused() { assert_eq!(trace_within(&img, &p, anchors).unwrap(), full); } +/// #3098: a watched trace says how far it has got, layer by layer, and stops when told to. +#[test] +fn a_watched_trace_counts_its_layers_and_stops_when_told() { + let img = stripes(120, 8); + let p = TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() }; + let seen = std::sync::Mutex::new(vec![]); + let watched = trace_watched(&img, &p, usize::MAX, &|done, total| { + seen.lock().unwrap().push((done, total)); + true + }); + assert_eq!(watched.unwrap(), trace(&img, &p), "watching changes nothing"); + let seen = seen.into_inner().unwrap(); + let total = seen.last().unwrap().1; + assert!(total > 1, "{seen:?}"); + let mut layers: Vec = seen.iter().filter(|s| s.1 == total && s.0 > 0).map(|s| s.0).collect(); + layers.sort_unstable(); + assert_eq!(layers, (1..=total).collect::>(), "each layer once: {seen:?}"); + // Stopped before the layers, and after the first. + assert!(matches!(trace_watched(&img, &p, usize::MAX, &|_, _| false), Err(TraceError::Cancelled))); + assert!(matches!(trace_watched(&img, &p, usize::MAX, &|done, _| done == 0), Err(TraceError::Cancelled))); +} + /// Layers traced in parallel come out in the same order every time: bottom (largest) first. #[test] fn parallel_layers_keep_their_order() { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a708a70c15..6e2527fb68 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -12,7 +12,7 @@ use super::{ Arc, AutomationRoots, ControlRequest, Ordering, Receiver, Session, UiState, Value, VectorcraftApp, View, ViewInfo, background, canvas, chrome, clipboard_probe, dialogs, export_progress, file_access, fileio, font_menu, graphics, i18n, io, json, menus, native_menu, opening, palette, panel_docking, panels, picks, place, placing, plugin_runs, prefs_dialog, recovery, screen_color, scrub, shortcut_editor, shortcuts, theme, - titlebar, toolbar, tools_float, unsaved, updates_ui, widgets, + titlebar, toolbar, tools_float, trace_runs, unsaved, updates_ui, widgets, }; mod clipboard; @@ -59,6 +59,8 @@ impl VectorcraftApp { from_worker: false, waits_for_still: cfg!(target_arch = "wasm32"), still: None, + fill: None, + fill_worker: None, worker: None, worker_started: false, slices: None, @@ -77,6 +79,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_warp: None, + character_focus: None, run_count: 0, clipboard_out: None, clipboard_published: None, @@ -118,6 +121,7 @@ impl VectorcraftApp { opening: Default::default(), plugin_runs: Default::default(), placing: Default::default(), + trace_runs: Default::default(), recovery: Default::default(), host_modifiers: Default::default(), forwarded: Vec::new(), @@ -286,6 +290,7 @@ impl VectorcraftApp { screen_color::poll(self, ctx); opening::poll(self); plugin_runs::poll(self); + trace_runs::poll(self); placing::poll(self); #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); @@ -293,6 +298,7 @@ impl VectorcraftApp { || !self.opening.pending.is_empty() || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() + || !self.trace_runs.running.is_empty() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -484,6 +490,7 @@ impl VectorcraftApp { updates_ui::show(self, &ctx); export_progress::show(self, &ctx); plugin_runs::show(self, &ctx); + trace_runs::show(self, &ctx); palette::show(self, &ctx); if self.custom_titlebar { titlebar::resize_zones(ui); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index b32c64c4f0..9c9e41e7d8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -24,6 +24,12 @@ pub struct CanvasCache { /// The cache key the canvas last asked for and when it first asked for it (seconds, egui's /// input time), kept while [`Self::waits_for_still`] is set. pub still: Option<(CacheKey, f64)>, + /// The low-resolution frame that covers the parts of the canvas the frame shown leaves + /// uncovered while it is drawn for a view it was not rendered for ([`canvas::Fill`]). + pub fill: Option, + /// The thread that renders [`Self::fill`], beside [`Self::worker`]. None on wasm, which has no + /// fill. + pub fill_worker: Option, pub worker: Option, pub worker_started: bool, /// The slices as laid out for (document uid, revision): the canvas draws them every frame. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 400a32d03f..4482a12838 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1,6 +1,7 @@ //! The document canvas: rendering, rulers, navigation, pointer routing to tools and on-canvas //! selection visuals (bounding box, anchors, handles, smart-guide style labels). +use egui::emath::GuiRounding as _; use egui::{Color32, CornerRadius, Pos2, Sense, Shape, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use serde_json::json; use vectorcraft_doc::text::TextKind; @@ -18,6 +19,7 @@ mod artboards; mod context; mod cursor; mod drag; +mod fill; mod grid; mod home; mod input; @@ -39,6 +41,10 @@ pub use drag::{apply_requests, dispatch, mods}; pub(crate) use drag::{end_document_drag, release_art_in_window, release_over_panel}; #[cfg(test)] use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id}; +pub use fill::Fill; +use fill::fill_uncovered; +#[cfg(test)] +use fill::{fill_view, polygon_area}; #[cfg(test)] use grid::ruler_rects; use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, textured_quad, view_bounds}; @@ -196,6 +202,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let bars = app.ui.screen_mode < 2; let full = if bars { egui::Rect::from_min_max(full.min, full.max - vec2(SCROLL_BAR, SCROLL_BAR)) } else { full }; let rect = if app.ui.view.rulers && app.ui.screen_mode < 3 { egui::Rect::from_min_max(full.min + vec2(RULER, RULER), full.max) } else { full }; + // Dock layout can differ by fractions of a device pixel between fresh windows. + // Use one pixel-aligned rectangle for drawing, inspection and pointer transforms. + let rect = rect.round_to_pixels(ui.ctx().pixels_per_point()); app.canvas_rect = Some(rect); let fitted = app.view().is_some_and(|v| v.fitted); if !fitted { @@ -277,6 +286,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if undecoded > 0 { app.status(format!("{undecoded} image(s) couldn't be decoded and show as crossed boxes")); } + fill_uncovered(app, ui.ctx(), &painter, &key, &doc, rect, &xf); reproject_frame(app, &painter, &xf, rect, (key.doc, v.rotation)); if let Some(look) = grid_look.filter(|_| !grids_in_back) { grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look); @@ -317,8 +327,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.view.rulers && app.ui.screen_mode < 3 { ruler_bands(app, ui, &xf, (full, rect), origin_preview, &t); } - // The task bar is not drawn while the Simplify slider shows. - if app.ui.task_bar && !revolve_edit && !app.session.tool_busy() && app.ui.screen_mode < 3 && !crate::dialogs::simplify_slider::showing(app) { + // The task bar is not drawn while the Simplify or Smooth slider shows. + let strip = crate::dialogs::simplify_slider::showing(app) || crate::dialogs::smooth_slider::showing(app); + if app.ui.task_bar && !revolve_edit && !app.session.tool_busy() && app.ui.screen_mode < 3 && !strip { task_bar(app, ui, &xf); } if app.ui.screen_mode < 3 { @@ -343,9 +354,12 @@ fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: handle_input(app, ui, resp, rect); // `hover_doc` is the document point under the pointer in the view `handle_input` left. The // wheel, a pan, a Rotate View drag, the Zoom tool and a Presentation Mode click move the view - // there. + // there. A dialog, floating panel or menu over the canvas hides it (Object Highlighting + // showed through them: #4518), unless a drag that began on the canvas goes on there. let moved = Xf::new(rect, app.view().unwrap_or(&View::default())); - app.hover_doc = ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p)).map(|p| moved.to_doc(p)); + let dragging = ui.data(|d| d.get_temp::(drag_id()).is_some()); + app.hover_doc = + ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p) && (dragging || drag::on_canvas(ui, resp, *p))).map(|p| moved.to_doc(p)); } } @@ -359,9 +373,12 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin let space = ui.input(|i| i.key_down(egui::Key::Space)); let drag = ui.data(|d| d.get_temp::(drag_id())); let panning = matches!(drag, Some(Drag::Pan { .. })); - let zooming = if space { m.command } else { app.session.tool_id() == "zoom" }; + // A zoom drag keeps its cursor when Space is pressed (with or without Shift) or Cmd is let go. + let zoom_drag = matches!(drag, Some(Drag::ZoomBox { .. } | Drag::ZoomScrub { .. })); + let zooming = zoom_drag || if space { m.command } else { app.session.tool_id() == "zoom" }; // A rotating drag keeps its cursor when Shift is let go. - let rotating = matches!(drag, Some(Drag::RotateView { .. })) || if space { m.shift && !m.command } else { app.session.tool_id() == "rotateView" }; + let rotating = matches!(drag, Some(Drag::RotateView { .. })) + || (!zoom_drag && if space { m.shift && !m.command } else { app.session.tool_id() == "rotateView" }); // The hand and the magnifier are drawn like the tool cursors below: Windows has no // system cursor for them (winit shows the four-headed move cursor for Grab). let view_cursor = if panning { @@ -485,6 +502,7 @@ fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { app.canvas.worker_started = true; if std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() { app.canvas.worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); + app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); } } // Upload finished background renders. @@ -695,11 +713,11 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: &Xf, t: &Tokens) { let Some(st) = app.session.active() else { return }; let doc = &st.doc; - // Artboard edges and names. The Artboard tool labels its active artboard itself (following - // a move or resize): that one isn't named twice. + // Artboard edges and names. The Artboard tool labels its selected artboards itself (following + // a move or resize): those aren't named twice. let active_ab = crate::panels::artboards::selected(app, doc.artboards.len()); let artboard_tool = app.session.tool_id() == "artboard"; - let tool_labelled = artboard_tool.then(|| app.session.tool_options()["active"].as_u64()).flatten(); + let tool_selected = artboards::tool_labelled(app); let editing_name = ui.data(|d| d.get_temp::(name_edit_id()).map(|e| e.index)); for (i, ab) in doc.artboards.iter().enumerate() { let c = if i == active_ab { Color32::from_gray(0) } else { Color32::from_gray(120) }; @@ -711,7 +729,8 @@ fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: // Show Center Mark, Show Cross Hairs and Show Video Safe Areas (Artboard Options). Only the // canvas draws them, as it does the edges: exports and print leave them out. artboard_marks(painter, xf, ab, t.artboard_mark); - if editing_name != Some(i) && (artboard_tool || doc.artboards.len() > 1) && tool_labelled != u64::try_from(i).ok() { + let labelled_by_tool = u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx)); + if editing_name != Some(i) && (artboard_tool || doc.artboards.len() > 1) && !labelled_by_tool { // At the artboard's own top-left corner, which a rotated view turns away from its // bounding box's (#1095). let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0)); diff --git a/crates/ui-egui/src/canvas/artboards.rs b/crates/ui-egui/src/canvas/artboards.rs index 4f803ef0c0..2e62fff4a3 100644 --- a/crates/ui-egui/src/canvas/artboards.rs +++ b/crates/ui-egui/src/canvas/artboards.rs @@ -1,4 +1,6 @@ -use super::{Color32, Point, Pos2, Rect, Shape, Stroke, Ui, VectorcraftApp, Xf, json, vec2}; +use serde_json::{Value, json}; + +use super::{Color32, Point, Pos2, Rect, Shape, Stroke, Ui, VectorcraftApp, Xf, vec2}; /// The width an artboard needs on screen for its name to show (px): narrower, the name is left /// out rather than spilling over its neighbours. @@ -89,6 +91,15 @@ pub(super) fn tool_name_rect(painter: &egui::Painter, xf: &Xf, rect: Rect, index egui::Rect::from_min_size(sp, galley.size()).expand(2.0) } +/// The artboards the Artboard tool labels itself, following a move or resize (its selected +/// ones): the canvas doesn't name them again. Empty with another tool. +pub(super) fn tool_labelled(app: &VectorcraftApp) -> Vec { + if app.session.tool_id() != "artboard" { + return vec![]; + } + app.session.tool_options()["selected"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() +} + /// The artboard whose on-canvas name contains `screen`, if that name is being drawn. pub(super) fn artboard_name_at(app: &VectorcraftApp, ui: &Ui, xf: &Xf, screen: Pos2) -> Option { let st = app.session.active()?; @@ -96,11 +107,12 @@ pub(super) fn artboard_name_at(app: &VectorcraftApp, ui: &Ui, xf: &Xf, screen: P if !artboard_tool && st.doc.artboards.len() <= 1 { return None; } - let tool_labelled = artboard_tool.then(|| app.session.tool_options()["active"].as_u64()).flatten(); + let tool_selected = tool_labelled(app); let painter = ui.painter(); let mut hit = None; for (i, ab) in st.doc.artboards.iter().enumerate() { - if tool_labelled == u64::try_from(i).ok() { + let is_tool_labelled = u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx)); + if is_tool_labelled { continue; } let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0)); @@ -110,16 +122,18 @@ pub(super) fn artboard_name_at(app: &VectorcraftApp, ui: &Ui, xf: &Xf, screen: P hit = Some(i); } } - if let Some(i) = tool_labelled.and_then(|i| usize::try_from(i).ok()) - && let Some(ab) = st.doc.artboards.get(i) - && tool_name_rect(painter, xf, ab.rect, i, &ab.name).contains(screen) - { - return Some(i); + for &idx in &tool_selected { + if let Some(i) = usize::try_from(idx).ok() + && let Some(ab) = st.doc.artboards.get(i) + && tool_name_rect(painter, xf, ab.rect, i, &ab.name).contains(screen) + { + return Some(i); + } } hit } -pub(super) fn select_named_artboard(app: &mut VectorcraftApp, index: usize) { +pub(super) fn select_named_artboard(app: &mut VectorcraftApp, index: usize, shift: bool) { let n = app.session.active().map(|st| st.doc.artboards.len()).unwrap_or(0); if index >= n { return; @@ -128,7 +142,11 @@ pub(super) fn select_named_artboard(app: &mut VectorcraftApp, index: usize) { v.artboard = index; } if app.session.tool_id() == "artboard" { - app.session.set_tool_option("active", &json!(index)); + if shift { + crate::panels::artboards::toggle(app, index, n); + } else { + app.session.set_tool_option("active", &json!(index)); + } } } @@ -194,10 +212,10 @@ pub(super) fn artboard_name_editor(app: &mut VectorcraftApp, ui: &mut Ui, xf: &X pub(super) fn artboard_name_field_rect(app: &VectorcraftApp, ui: &Ui, xf: &Xf, index: usize) -> Option { let st = app.session.active()?; let ab = st.doc.artboards.get(index)?; - let artboard_tool = app.session.tool_id() == "artboard"; - let tool_labelled = artboard_tool.then(|| app.session.tool_options()["active"].as_u64()).flatten(); + let tool_selected = tool_labelled(app); let painter = ui.painter(); - let rect = if tool_labelled == u64::try_from(index).ok() { + let is_tool_labelled = u64::try_from(index).ok().is_some_and(|idx| tool_selected.contains(&idx)); + let rect = if is_tool_labelled { tool_name_rect(painter, xf, ab.rect, index, &ab.name) } else { let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0)); diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index abd4e0cf88..6d39883be8 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -66,7 +66,7 @@ pub(super) fn still_wait(still: &mut Option<(CacheKey, f64)>, shown: Option<&Cac /// Whether two cache keys differ only in the view (zoom, center, rotation, canvas size, pixel /// density and Pixel Preview's document pixels), with Pixel Preview on in both or off in both. -fn only_view_differs(a: &CacheKey, b: &CacheKey) -> bool { +pub(super) fn only_view_differs(a: &CacheKey, b: &CacheKey) -> bool { a.pixel.is_some() == b.pixel.is_some() && *a == CacheKey { zoom: a.zoom, cx: a.cx, cy: a.cy, w: a.w, h: a.h, ppp: a.ppp, rot: a.rot, pixel: a.pixel, ..b.clone() } } diff --git a/crates/ui-egui/src/canvas/fill.rs b/crates/ui-egui/src/canvas/fill.rs new file mode 100644 index 0000000000..f68c175585 --- /dev/null +++ b/crates/ui-egui/src/canvas/fill.rs @@ -0,0 +1,198 @@ +use super::cursor::only_view_differs; +use super::{Affine, CacheKey, Color32, Point, Pos2, Shape, VectorcraftApp, Xf, color_image, pos2, vec2}; + +/// The fraction of the canvas's resolution, each way, that [`Fill`] is rendered at. +const FILL_SCALE: f64 = 0.25; +/// How many times the canvas's width and height [`Fill`] covers, around the view it is rendered +/// for. A pan or zoom-out that stays within it draws it again without rendering it. +const FILL_REACH: f64 = 2.0; + +/// [`crate::CanvasCache::fill`]: a frame of the art from [`crate::CanvasCache::fill_worker`], +/// rendered for the canvas key `key` as [`fill_view`] gives, and its texture. +pub struct Fill { + /// The document, revision and view it was rendered for. + pub(super) key: CacheKey, + /// Document → its pixels. + pub(super) view: Affine, + /// Its size in pixels. + pub(super) size: (u32, u32), + pub(super) tex: egui::TextureHandle, +} + +/// The size in pixels and the view (document → its pixels) of the fill for the canvas key `key`: +/// [`FILL_SCALE`] of the canvas's resolution, covering [`FILL_REACH`] times the canvas's width and +/// height around the view of `key`. +pub(super) fn fill_view(key: &CacheKey) -> (u32, u32, Affine) { + let fw = (f64::from(key.w) * FILL_REACH * FILL_SCALE).ceil().clamp(1.0, f64::from(u16::MAX)) as u32; + let fh = (f64::from(key.h) * FILL_REACH * FILL_SCALE).ceil().clamp(1.0, f64::from(u16::MAX)) as u32; + let ppp = if key.ppp > 0.0 { f64::from(key.ppp) } else { 1.0 }; + let view = Affine::translate((f64::from(fw) / 2.0, f64::from(fh) / 2.0)) + * Affine::rotate(key.rot.to_radians()) + * Affine::scale(key.zoom * ppp * FILL_SCALE) + * Affine::translate((-key.cx, -key.cy)); + (fw, fh, view) +} + +/// While the frame shown is drawn for a view it was not rendered for, and its key differs from +/// `key` in the view alone (the frame for `key` is on its way from the render worker), the parts +/// of the canvas `rect` it leaves uncovered show `doc` from [`crate::CanvasCache::fill`]. The fill +/// worker ([`crate::CanvasCache::fill_worker`]) renders it with the frame shown's options and these +/// changes: images draw only from pixels already decoded +/// ([`vectorcraft_render::RenderOptions::kept_images_only`]) and draw mips +/// ([`vectorcraft_render::RenderOptions::image_mips`]), raster effects render within a drag's +/// budget ([`vectorcraft_render::RenderOptions::dragging`]), and rasters cached for moved objects +/// are not reused ([`vectorcraft_render::RenderOptions::interacting`] off). This thread only copies a +/// finished fill into its texture and draws it. A fill is asked for again when the one shown or on +/// its way does not cover the canvas, when the view's zoom is more than twice or less than half +/// its own, and when the document, its revision or anything but the view changed; until it +/// arrives, the fill shown is drawn where it reaches. It is dropped once the canvas shows the frame +/// for `key`, and while the frame shown differs from `key` in more than the view. +pub(super) fn fill_uncovered( + app: &mut VectorcraftApp, + ctx: &egui::Context, + painter: &egui::Painter, + key: &CacheKey, + doc: &std::sync::Arc, + rect: egui::Rect, + xf: &Xf, +) { + // Taken every frame, so a fill that is no longer needed does not stay queued. + let done = app.canvas.fill_worker.as_mut().and_then(|w| w.poll()); + let (Some(k), Some((_, opts))) = (&app.canvas.key, &app.canvas.shown) else { + app.canvas.fill = None; + return; + }; + // The fill takes the frame shown's options, which match `key`'s only when the two keys differ + // in the view alone. + if k == key || !only_view_differs(k, key) || app.canvas.texture.is_none() { + app.canvas.fill = None; + return; + } + let screen_to_doc = xf.affine().inverse(); + let corners = + [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()].map(|p| screen_to_doc * Point::new(p.x as f64, p.y as f64)); + let usable = |f: &CacheKey| only_view_differs(f, key) && (0.5..=2.0).contains(&(key.zoom / f.zoom)); + let covers = |f: &CacheKey| { + let (w, h, view) = fill_view(f); + usable(f) + && corners.iter().all(|c| { + let p = view * *c; + (-0.5..=f64::from(w) + 0.5).contains(&p.x) && (-0.5..=f64::from(h) + 0.5).contains(&p.y) + }) + }; + let opts = vectorcraft_render::RenderOptions { kept_images_only: true, image_mips: true, interacting: false, dragging: true, ..opts.clone() }; + let gaps = shown_frame(k, rect, xf).map_or_else(Vec::new, |shown| uncovered(shown, rect)); + if let Some(done) = done.filter(|d| usable(&d.key)) { + let color = color_image(&done.img); + let tex = match app.canvas.fill.take() { + Some(mut f) => { + f.tex.set(color, egui::TextureOptions::LINEAR); + f.tex + } + None => ctx.load_texture("canvas-fill", color, egui::TextureOptions::LINEAR), + }; + let (_, _, view) = fill_view(&done.key); + app.canvas.fill = Some(Fill { key: done.key, view, size: (done.img.width, done.img.height), tex }); + } + let Some(worker) = app.canvas.fill_worker.as_mut().filter(|_| !gaps.is_empty()) else { return }; + if !app.canvas.fill.as_ref().is_some_and(|f| covers(&f.key)) && !worker.pending.as_ref().is_some_and(covers) { + let (w, h, view) = fill_view(key); + worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), w, h, view, opts }); + } + let Some(f) = app.canvas.fill.as_ref().filter(|f| usable(&f.key)) else { return }; + let to_uv = Affine::scale_non_uniform(1.0 / f64::from(f.size.0.max(1)), 1.0 / f64::from(f.size.1.max(1))) * f.view * screen_to_doc; + let from_uv = to_uv.inverse(); + let mut mesh = egui::Mesh::with_texture(f.tex.id()); + for gap in gaps { + // Only where the fill reaches: its pixels are 0..1 each way in uv. + let uv: Vec = gap.iter().map(|p| to_uv * Point::new(p.x as f64, p.y as f64)).collect(); + let uv = clip_polygon(&clip_polygon(&uv, |p| p.x, 0.0, false), |p| p.x, 1.0, true); + let uv = clip_polygon(&clip_polygon(&uv, |p| p.y, 0.0, false), |p| p.y, 1.0, true); + if uv.len() < 3 { + continue; + } + let first = mesh.vertices.len() as u32; + for p in &uv { + let pos = from_uv * *p; + mesh.vertices.push(egui::epaint::Vertex { + pos: pos2(pos.x as f32, pos.y as f32), + uv: pos2(p.x as f32, p.y as f32), + color: Color32::WHITE, + }); + } + for i in 1..uv.len() as u32 - 1 { + mesh.indices.extend([first, first + i, first + i + 1]); + } + } + painter.add(Shape::mesh(mesh)); +} + +/// Where the canvas draws the frame shown (its key `k`) in the view `xf` of the canvas `rect`: +/// the unit square (the frame's texture coordinates) → screen points. None when the mapping is +/// degenerate. +fn shown_frame(k: &CacheKey, rect: egui::Rect, xf: &Xf) -> Option { + let to_screen = match k.pixel { + Some([x0, y0, x1, y1]) => { + xf.affine() * Affine::translate((x0 as f64, y0 as f64)) * Affine::scale_non_uniform((x1 - x0) as f64, (y1 - y0) as f64) + } + None => { + let ppp = if k.ppp > 0.0 { k.ppp } else { 1.0 }; + let old_rect = egui::Rect::from_center_size(rect.center(), vec2(k.w as f32 / ppp, k.h as f32 / ppp)); + let old = Xf { rect: old_rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: k.rot.to_radians() }; + xf.affine() + * old.affine().inverse() + * Affine::translate((old_rect.min.x as f64, old_rect.min.y as f64)) + * Affine::scale_non_uniform(old_rect.width() as f64, old_rect.height() as f64) + } + }; + let det = to_screen.determinant(); + (det.is_finite() && det.abs() > 1e-12).then_some(to_screen) +} + +/// The parts of `rect` outside the parallelogram `shown` maps the unit square to, as convex +/// polygons of screen points, leaving out those thinner than half a point (a frame whose pixel +/// size was rounded from the canvas's leaves such slivers along its edges). +fn uncovered(shown: Affine, rect: egui::Rect) -> Vec> { + // In the unit square's coordinates the canvas is a convex polygon and the frame shown is + // 0..1 each way: the parts left of it, right of it, and above and below it in between. + let inv = shown.inverse(); + let canvas: Vec = [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()] + .iter() + .map(|p| inv * Point::new(p.x as f64, p.y as f64)) + .collect(); + let left = clip_polygon(&canvas, |p| p.x, 0.0, true); + let right = clip_polygon(&canvas, |p| p.x, 1.0, false); + let between = clip_polygon(&clip_polygon(&canvas, |p| p.x, 0.0, false), |p| p.x, 1.0, true); + let above = clip_polygon(&between, |p| p.y, 0.0, true); + let below = clip_polygon(&between, |p| p.y, 1.0, false); + [left, right, above, below] + .into_iter() + .map(|part| part.into_iter().map(|p| shown * p).map(|p| pos2(p.x as f32, p.y as f32)).collect::>()) + .filter(|part| { + // Twice the area over the perimeter: about the width of a thin strip. + let perimeter: f32 = part.iter().zip(part.iter().cycle().skip(1)).map(|(a, b)| a.distance(*b)).sum(); + perimeter > 0.0 && 2.0 * polygon_area(part) / perimeter > 0.5 + }) + .collect() +} + +/// The part of convex polygon `poly` where `along(p)` is below `at` (`below`) or above it. +fn clip_polygon(poly: &[Point], along: impl Fn(&Point) -> f64, at: f64, below: bool) -> Vec { + let inside = |p: &Point| if below { along(p) <= at } else { along(p) >= at }; + let mut out = Vec::with_capacity(poly.len() + 1); + for (a, b) in poly.iter().zip(poly.iter().cycle().skip(1)) { + if inside(a) { + out.push(*a); + } + if inside(a) != inside(b) { + let t = (at - along(a)) / (along(b) - along(a)); + out.push(a.lerp(*b, t)); + } + } + out +} + +/// The area of polygon `poly` (shoelace formula). +pub(super) fn polygon_area(poly: &[Pos2]) -> f32 { + poly.iter().zip(poly.iter().cycle().skip(1)).map(|(a, b)| a.x * b.y - b.x * a.y).sum::().abs() / 2.0 +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index e07ba12dc3..6141707e9c 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -91,7 +91,15 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo // The artboard's name sits above its corner. A press there renames on a double-click // and does not start a tool gesture (a fitted artboard, a new one, Artboard Options). if let Some(i) = artboard_name_at(app, ui, &xf, p) { - ui.data_mut(|dd| dd.insert_temp(name_press_id(), i)); + let press_shift = ui + .input(|inp| { + inp.events.iter().rev().find_map(|event| match event { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, modifiers, .. } => Some(modifiers.shift), + _ => None, + }) + }) + .unwrap_or(m.shift); + ui.data_mut(|dd| dd.insert_temp(name_press_id(), (i, press_shift))); } else { begin_drag(app, ui, &f, p); } @@ -134,9 +142,17 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo ui.ctx().request_repaint_after(std::time::Duration::from_millis(16)); } if pointer.primary_released() - && let Some(i) = ui.data_mut(|d| d.remove_temp::(name_press_id())) + && let Some((i, shift)) = ui.data_mut(|d| d.remove_temp::<(usize, bool)>(name_press_id())) { - select_named_artboard(app, i); + let release_shift = ui + .input(|inp| { + inp.events.iter().rev().find_map(|event| match event { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(modifiers.shift), + _ => None, + }) + }) + .unwrap_or(m.shift); + select_named_artboard(app, i, shift || release_shift); } if resp.double_clicked() && let Some(p) = at @@ -170,11 +186,12 @@ fn wheel_view( ) -> (egui::PointerState, egui::Modifiers, bool, Option) { let line = ui.ctx().options(|o| o.input_options.line_scroll_speed); let wheel_zooms = app.session.prefs.zoom_with_mouse_wheel; + let animate = animated_zoom(&app.session.prefs); let turn_id = egui::Id::unique("canvas-wheel-turn"); let turn_before: WheelTurn = ui.data(|d| d.get_temp(turn_id)).unwrap_or_default(); let mut turn = turn_before; let (pointer, m, space, (factor, scroll)) = - ui.input(|i| (i.pointer.clone(), i.modifiers, i.key_down(egui::Key::Space), wheel(i, wheel_zooms, line, rect.height(), &mut turn))); + ui.input(|i| (i.pointer.clone(), i.modifiers, i.key_down(egui::Key::Space), wheel(i, wheel_zooms, animate, line, rect.height(), &mut turn))); if turn != turn_before { ui.data_mut(|d| d.insert_temp(turn_id, turn)); } @@ -261,12 +278,19 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { // A new press has not dragged yet, whatever an interrupted one left behind. dd.remove::(tool_drag_doc_id()); dd.insert_temp(tool_press_doc_id(), xf.to_doc(p)); + // Space held at the press (Cmd+Space lends the Zoom tool) sizes the marquee until + // it is let go ([`zoom_marquee_start`]). + if matches!(d, Drag::ZoomBox { .. }) { + dd.insert_temp(zoom_space_free_id(), !space); + } }); } /// A gesture held at `p`: the view follows, or the tool gets drag events. fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) { let Pointing { resp, rect, pointer, m, space, xf, view, .. } = *f; + // Where the pointer was in the frame before: a zoom marquee moved with Space follows it. + let before: Option = ui.data(|dd| dd.get_temp(drag_pos_id())); ui.data_mut(|dd| dd.insert_temp(drag_pos_id(), p)); match d { Drag::Pan { start, center, .. } => { @@ -287,7 +311,11 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) vm.rotation = vectorcraft_geom::normalize_deg(deg); } } - Drag::ZoomBox { start } => marquee(ui.painter(), egui::Rect::from_two_pos(start, p)), + Drag::ZoomBox { start } => { + let start = zoom_marquee_start(ui, start, before, p, space); + ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::ZoomBox { start })); + marquee(ui.painter(), egui::Rect::from_two_pos(start, p)); + } Drag::ZoomScrub { start, held, moved } => { let dt = ui.input(|i| i.unstable_dt).min(0.25); let (held, moved) = (held + dt, moved || (p - start).length() > SCRUB_SLOP); @@ -354,6 +382,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let Pointing { resp, rect, m, space, xf, view, .. } = *f; // The last position the tool's drag got: none if the press never dragged. let last_drag: Option = ui.data(|dd| dd.get_temp(tool_drag_doc_id())); + // Where the pointer was in the frame before: a zoom marquee moved with Space follows it. + let before: Option = ui.data(|dd| dd.get_temp(drag_pos_id())); ui.data_mut(|dd| { dd.remove::(drag_id()); dd.remove::(drag_pos_id()); @@ -362,6 +392,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po }); match d { Drag::ZoomBox { start } => { + let start = zoom_marquee_start(ui, start, before, p, space); + ui.data_mut(|dd| dd.remove::(zoom_space_free_id())); let r = egui::Rect::from_two_pos(start, p); if let Some(vm) = app.view_mut() { if r.width() > 8.0 && r.height() > 8.0 { @@ -441,6 +473,60 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { } } +/// Whether Space moves the Zoom tool's marquee in the drag under way ([`zoom_marquee_start`]). +fn zoom_space_free_id() -> egui::Id { + egui::Id::unique("canvas-zoom-space-free") +} + +/// The start corner of the Zoom tool's marquee in this frame. With Space held, the marquee moves +/// as far as the pointer did since `before` and keeps its size; with Space let go, the drag sizes +/// it again from where it moved to. Space held since the press (Cmd+Space lends the Zoom tool) +/// sizes the marquee until it is let go. A marquee with no size yet is sized by the movement, so +/// Space pressed before the pointer moves does not keep it at the press point. The frame's pointer +/// moves and Space presses and releases are taken in the order they came, so each move follows the +/// Space state it came with. +fn zoom_marquee_start(ui: &Ui, start: Pos2, before: Option, p: Pos2, space: bool) -> Pos2 { + enum Step { + Space(bool), + Move(Pos2), + } + let id = zoom_space_free_id(); + let steps: Vec = ui.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key: egui::Key::Space, pressed, repeat: false, .. } => Some(Step::Space(*pressed)), + egui::Event::PointerMoved(q) => Some(Step::Move(*q)), + _ => None, + }) + .collect() + }); + // Space as it was when the frame began: the opposite of its first press or release, else as it is now. + let mut held = steps.iter().find_map(|s| if let Step::Space(down) = s { Some(!down) } else { None }).unwrap_or(space); + let mut free = !held || ui.data(|d| d.get_temp::(id)).unwrap_or(true); + let (mut start, mut at) = (start, before); + for s in steps.into_iter().chain(std::iter::once(Step::Move(p))) { + match s { + Step::Space(down) => { + held = down; + free |= !down; + } + Step::Move(q) => { + if let Some(b) = at + && held + && free + && b != start + { + start += q - b; + } + at = Some(q); + } + } + } + ui.data_mut(|d| d.insert_temp(id, free)); + start +} + /// A marquee around screen rectangle `r`: dark dashes over a light line, so it shows on a white /// artboard and on the grey pasteboard alike (#725). fn marquee(p: &egui::Painter, r: egui::Rect) { diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index a81d8307f4..461730c6ed 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -117,7 +117,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { items.push((tl!("Release Clipping Mask"), "ungroup", "object.clippingMask.release", none())); } else if is_group { items.push((tl!("Ungroup"), "ungroup", "object.ungroup", none())); - items.push((tl!("Isolate"), "square-dashed", "object.isolate", none())); + // Isolate is left out while Enter Isolation Mode is off, as it is while an opacity mask is edited. + if crate::menus::enabled(app, "object.isolate") { + items.push((tl!("Isolate"), "square-dashed", "object.isolate", none())); + } } else if is_compound { items.push(edit_path()); items.push((tl!("Release Compound Path"), "ungroup", "object.compoundPath.release", none())); @@ -141,14 +144,16 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } items.push((tl!("Duplicate"), "copy", "edit.duplicate", none())); } - let fill = first.as_ref().map(|f| f.appearance.fill_paint()).unwrap_or_default(); + // The paints the Fill and Stroke proxies show, "?" when the selected objects' paints differ. + let (fill, stroke) = crate::panels::current_paints(app); + let (fill_mixed, stroke_mixed) = crate::panels::mixed_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; // Under the selection's lowest corner on screen, centered on the selection (the view may be // rotated). let lowest = xf.quad(b).iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); let anchor = pos2(xf.to_screen(b.center()).x, lowest); - let est_w = 118.0 + items.iter().map(|(l, _, _, _)| l.len() as f32 * 7.2 + 44.0).sum::(); + let est_w = 150.0 + items.iter().map(|(l, _, _, _)| l.len() as f32 * 7.2 + 44.0).sum::(); // Its place under the selection, then where the handle moved it, kept on the canvas (with the // bar's size last frame, the estimate before it first shows). let under = pos2(anchor.x - est_w / 2.0, anchor.y + 28.0); @@ -175,6 +180,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { 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) @@ -207,19 +213,24 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((*cmd, params.clone())); } } - // The selected objects' Fill, Recolor Artwork and Lock, left out with the Artboard tool. + // The selected objects' Fill, Stroke, Recolor Artwork and Lock, left out with the Artboard tool. if !on_artboards { let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); - widgets::paint_chip(ui, egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)), &fill); - ui.painter().rect_stroke( - egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)), - 0.0, - Stroke::new(1.0, t.button_border), - StrokeKind::Outside, - ); + let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); + widgets::proxy_chip(ui, chip, &fill, fill_mixed, None); + ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); if resp.on_hover_text(tl!("Fill")).clicked() { app.session.fill_active = true; - app.ui.open_panel = Some("swatches".into()); + show_swatches = true; + } + // The Stroke chip, drawn as a ring as the Control bar's is. + 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, &stroke, stroke_mixed, Some(4.0)); + ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); + if resp.on_hover_text(tl!("Stroke")).clicked() { + app.session.fill_active = false; + show_swatches = true; } // Recolor Artwork, when the selection has colours to recolour. if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 30.0).clicked() { @@ -262,6 +273,14 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } ui.ctx().request_repaint(); } + // 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. + if show_swatches + && app.ui.open_panel.as_deref() != Some("swatches") + && let Err(e) = app.run("window.panel.activate", json!({ "panel": "swatches" })) + { + app.ui.status = e; + } match run { // Image Trace traces the image at once with the Default preset. As a quick trace from // Properties or the Control bar, it leaves the Image Trace panel as it was. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index bb76684dc6..6a30f248f1 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2,6 +2,32 @@ use super::*; use vectorcraft_engine::Session; use vectorcraft_geom::Shape as _; +#[test] +fn subpixel_dock_layout_does_not_change_pointer_document_coordinates() { + let mut observed = Vec::new(); + for width in [1324.0 + 29.0 / 32.0, 1324.875, 1325.875] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 800, "height": 600, "created": 0})).unwrap(); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1800.0, 900.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + let area = egui::Rect::from_min_size(pos2(54.0, 72.0), vec2(width + SCROLL_BAR, 636.0 + SCROLL_BAR)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + show(&mut app, &mut child); + }); + out.textures_delta.clear(); + let rect = app.canvas_rect.unwrap(); + observed.push((rect, Xf::new(rect, app.view().unwrap()).to_doc(pos2(440.0, 330.0)))); + } + assert_eq!(observed[0], observed[1], "the same physical canvas must map the same pointer identically"); + assert_ne!(observed[0], observed[2], "a real device-pixel resize must still change the mapping"); +} + /// A rendered raster becomes the image egui's own conversion makes of it, half-transparent /// edges and all; one whose bytes don't match its size becomes an empty image of that size. #[test] @@ -679,6 +705,57 @@ fn the_artboard_tool_names_its_active_artboard_once() { assert!((active[0].1 - other[0].1).abs() < 2.0, "on the artboard's top edge like the other name: {active:?} vs {other:?}"); } +#[test] +fn shift_clicking_canvas_artboard_label_toggles_multi_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + if let Some(v) = app.view_mut() { + v.center = Point::new(320.0, 50.0); + v.zoom = 0.8; + v.fitted = true; + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.tool_options()["selected"], json!([0])); + + let drawn = shapes(&mut app, &ctx); + let label_pos = |name: &str| { + drawn + .iter() + .find_map(|s| match s { + Shape::Text(t) if t.galley.text() == name => Some(t.pos + vec2(10.0, 5.0)), + _ => None, + }) + .unwrap() + }; + let at1 = label_pos("02 - Artboard 2"); + + // Shift-click artboard 2's name label (Shift held on press, released before mouse release) + let shift = egui::Modifiers::SHIFT; + let button = |pressed| egui::Event::PointerButton { pos: at1, button: egui::PointerButton::Primary, pressed, modifiers: shift }; + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(shift), egui::Event::PointerMoved(at1), button(true)]); + frame( + &mut app, + &ctx, + vec![ + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + egui::Event::PointerButton { pos: at1, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ], + ); + + assert_eq!(app.session.tool_options()["selected"], json!([1, 0]), "Shift-clicking artboard label adds it to selection"); + + // Click artboard 3's name label without Shift + let at2 = label_pos("03 - Artboard 3"); + let plain_btn = + |pressed| egui::Event::PointerButton { pos: at2, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE), egui::Event::PointerMoved(at2), plain_btn(true)]); + frame(&mut app, &ctx, vec![plain_btn(false)]); + + assert_eq!(app.session.tool_options()["selected"], json!([2]), "Plain click selects that artboard alone"); +} + /// Enable Touch Gestures (#585): a two-finger tap undoes and a three-finger one redoes, and the /// first finger's press (the pointer egui makes of it) draws nothing. Off, a tap does nothing. #[test] @@ -2309,6 +2386,144 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { app.canvas.worker = None; } +/// While the worker renders the frame for a panned view, the fill worker renders a +/// low-resolution frame, and the part of the canvas the last frame no longer covers shows the +/// art from it, drawn only there. When the worker's frame arrives, it covers the canvas and the +/// fill is dropped. +#[test] +fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { + // The canvas key holds the global placed-document bitmap clock, which tests on other threads + // move: a frame whose key changed by more than the view drops the fill. An attempt that fails + // while the clock moved runs again; one that fails while it stood still is a real failure. + for _ in 0..20 { + let clock = vectorcraft_render::placed_document::generation(); + match std::panic::catch_unwind(pan_fills_the_area_the_last_frame_leaves) { + Ok(()) => return, + Err(_) if vectorcraft_render::placed_document::generation() != clock => {} + Err(e) => std::panic::resume_unwind(e), + } + } + pan_fills_the_area_the_last_frame_leaves(); +} + +fn pan_fills_the_area_the_last_frame_leaves() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 300, "y": 100, "width": 80, "height": 100})).unwrap(); + app.canvas.worker_started = true; // render on this thread + app.ui.view.rulers = false; + app.ui.screen_mode = 2; // no scroll bars: the canvas is the window + // One frame → the meshes drawn and the fill's pixels, when this frame uploaded them. + let frame = |app: &mut VectorcraftApp| { + let (shapes, mut delta) = frame_output(app, &ctx); + let fill = app.canvas.fill.as_ref().map(|f| f.tex.id()); + let pixels = delta.set.iter().find(|(id, _)| Some(**id) == fill).and_then(|(_, d)| d.last()).map(|d| match &d.image { + egui::ImageData::Color(img) => img.clone(), + }); + delta.clear(); + let meshes: Vec = shapes + .into_iter() + .filter_map(|s| match s { + Shape::Mesh(m) => Some(std::sync::Arc::unwrap_or_clone(m)), + _ => None, + }) + .collect(); + (meshes, pixels) + }; + frame(&mut app); + { + let v = app.view_mut().unwrap(); + v.zoom = 4.0; + v.center = Point::new(100.0, 150.0); + } + frame(&mut app); // the art from about x 0 to 200, without the rectangle + let old = app.canvas.key.clone().unwrap(); + let before = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + assert!(app.canvas.fill.is_none()); + let (worker, jobs, completed) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let (fill_worker, fill_jobs, fill_completed) = crate::render_worker::Worker::test_channel(); + app.canvas.fill_worker = Some(fill_worker); + app.canvas.last_ms = 50.0; + // Pan right by 150 pt: the last frame covers the canvas's left quarter, and the rectangle + // comes into its right quarter. + app.view_mut().unwrap().center = Point::new(250.0, 150.0); + frame(&mut app); + assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown"); + let job = jobs.try_recv().expect("the frame for the new view is on the worker"); + let fill_job = fill_jobs.try_recv().expect("the fill is on the fill worker"); + let (fw, fh, _) = fill_view(&job.key); + assert!(fill_job.opts.kept_images_only && (fill_job.w, fill_job.h) == (fw, fh), "{:?}", (fill_job.w, fill_job.h)); + assert!(app.canvas.fill.is_none(), "nothing to draw until the fill arrives"); + // The fill arrives; the next frame draws it, and asks for no other fill. + let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); + let (doc, opts) = (fill_job.doc, fill_job.opts); + fill_completed.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0 }).unwrap(); + let (meshes, pixels) = frame(&mut app); + assert!(fill_jobs.try_recv().is_err(), "the fill covers the canvas"); + assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown"); + let fill = app.canvas.fill.as_ref().expect("the fill is kept"); + let mesh = meshes.iter().find(|m| m.texture_id == fill.tex.id()).expect("the fill is drawn"); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let edge = xf.to_screen(before.to_doc(rect.right_top())).x; // the last frame's right edge + assert!(edge > rect.left() + 100.0 && edge < xf.to_screen(Point::new(300.0, 0.0)).x, "{edge} in {rect:?}"); + assert!( + mesh.vertices.iter().all(|v| v.pos.x >= edge - 1e-3 && rect.expand(1e-3).contains(v.pos)), + "only right of the last frame: {:?}", + mesh.vertices + ); + let area: f32 = mesh.indices.as_chunks::<3>().0.iter().map(|t| polygon_area(&t.map(|i| mesh.vertices[i as usize].pos))).sum(); + let uncovered = (rect.right() - edge) * rect.height(); + assert!((area - uncovered).abs() < 1.0, "the whole uncovered area, {uncovered} square points: {area}"); + // The fill's pixel under a point of the canvas, from the uv the mesh gives that point. + let img = pixels.expect("the fill's pixels were uploaded"); + let to_uv = Affine::scale_non_uniform(1.0 / fill.size.0 as f64, 1.0 / fill.size.1 as f64) * fill.view * xf.affine().inverse(); + let alpha = |p: Pos2| { + let uv = to_uv * Point::new(p.x as f64, p.y as f64); + img.pixels[(uv.y * img.size[1] as f64) as usize * img.size[0] + (uv.x * img.size[0] as f64) as usize].a() + }; + assert!(alpha(xf.to_screen(Point::new(340.0, 150.0))) > 0, "the rectangle, in the uncovered area"); + assert_eq!(alpha(xf.to_screen(Point::new(250.0, 150.0))), 0, "no art there"); + for v in &mesh.vertices { + assert!((to_uv * Point::new(v.pos.x as f64, v.pos.y as f64) - Point::new(v.uv.x as f64, v.uv.y as f64)).hypot() < 1e-4); + } + // Panned until the fill reaches only the canvas's left half: it is drawn only there, and the + // fill for the new view is asked for. + let fill_tex = fill.tex.id(); + let reach = fill.view.inverse() * Point::new(fill.size.0 as f64, 0.0); // the fill's right edge + app.view_mut().unwrap().center = Point::new(reach.x, 150.0); + let (meshes, _) = frame(&mut app); + let right = Xf::new(rect, app.view().unwrap()).to_screen(reach).x; + assert!((right - rect.center().x).abs() < 1.0, "{right} in {rect:?}"); + let mesh = meshes.iter().find(|m| m.texture_id == fill_tex).expect("the fill is drawn where it reaches"); + assert!(mesh.vertices.iter().all(|v| v.pos.x <= right + 1e-3), "only where the fill reaches: {:?}", mesh.vertices); + let next = fill_jobs.try_recv().expect("the next fill"); + assert_eq!(Some(&next.key), app.canvas.worker.as_ref().unwrap().pending.as_ref()); + app.view_mut().unwrap().center = Point::new(250.0, 150.0); + // That fill finishes after the worker's frame: it is taken and not kept. + let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts); + fill_completed.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0 }).unwrap(); + // The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept. + let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); + let expected = job.key.clone(); + completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0 }).unwrap(); + let (meshes, _) = frame(&mut app); + assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame is shown"); + assert!(app.canvas.fill.is_none() && meshes.iter().all(|m| m.texture_id != fill_tex), "the fill is dropped"); + assert!(app.canvas.fill_worker.as_ref().unwrap().pending.is_none(), "the late fill was taken"); + // A pan with Outline turned on: the frame shown's options are not the ones asked for, and + // no fill is asked for. + app.ui.view.outline = true; + app.view_mut().unwrap().center = Point::new(400.0, 150.0); + frame(&mut app); + assert!(jobs.try_iter().last().is_some_and(|j| j.key.outline), "the outline frame is on the worker"); + assert!(fill_jobs.try_recv().is_err() && app.canvas.fill.is_none(), "no fill"); + app.canvas.worker = None; + app.canvas.fill_worker = None; +} + /// With the web build's setting (`waits_for_still`, no render worker), a heavy document's canvas /// is not rendered while the view moves: each frame draws the frame shown moved and scaled with /// the view and asks for a frame within STILL_SECS. The canvas renders once the view has been @@ -3765,6 +3980,60 @@ fn wheel_notches_zoom_in_a_glide() { assert_eq!(app.view().unwrap().zoom / before, done, "and it stops"); } +/// #4283: with Performance › Animated Zoom off, or on without GPU Performance (which it needs), a +/// wheel notch zooms the whole step on the frame it arrives, both the plain wheel with Zoom with +/// Mouse Wheel and Alt-wheel without it. +#[test] +fn wheel_notches_zoom_at_once_without_animated_zoom() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let run = |app: &mut VectorcraftApp| { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app); + let at = app.canvas_rect.unwrap().center(); + for (animated, gpu, wheel_zooms, alt) in + [(false, true, true, false), (false, true, false, true), (true, false, true, false), (true, false, false, true)] + { + app.session.execute("prefs.set", &json!({"key": "animatedZoom", "value": animated})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "gpuPerformance", "value": gpu})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": wheel_zooms})).unwrap(); + // Any glide or spread scroll a case before left behind dies down first. + for _ in 0..30 { + run(&mut app); + } + let before = app.view().unwrap().zoom; + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1, "alt": alt})); + // One line notch's whole zoom. + let expected = ctx.options(|o| f64::from(o.input_options.line_scroll_speed) * 0.01).exp(); + // The first frame the zoom moves (the event may land a frame later). + let mut first = 1.0; + for _ in 0..3 { + run(&mut app); + first = app.view().unwrap().zoom / before; + if first != 1.0 { + break; + } + } + assert!( + (first - expected).abs() < 1e-9, + "the whole notch arrives at once (animated {animated}, gpu {gpu}, wheel zooms {wheel_zooms}, alt {alt}: expected {expected}, got {first})" + ); + for _ in 0..30 { + run(&mut app); + } + let done = app.view().unwrap().zoom / before; + assert!( + (done - first).abs() < 1e-9, + "all of it on the first frame (animated {animated}, gpu {gpu}, wheel zooms {wheel_zooms}, alt {alt}: {first} then {done})" + ); + } +} + /// In each frame where a wheel scroll moves the view, the hover point (read by the rulers' /// pointer marks, the Info panel, the hover highlight and the tool cursor) is the document point /// under the pointer in the view the canvas draws in that frame. @@ -4095,6 +4364,168 @@ fn the_zoom_tool_zooms_a_rotated_view_to_the_area_dragged_across() { } } +/// Space held while the Zoom tool drags a marquee moves the marquee and keeps its size. When Space +/// is let go, the drag sizes the marquee again from where it moved to, and the release zooms to the +/// moved marquee. +/// Space held since a Cmd+Space press sizes the marquee. +#[test] +fn space_moves_the_zoom_marquee_while_dragging() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let space = |pressed, modifiers| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers }; + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let drawn = |app: &mut VectorcraftApp| -> Vec { + let lines: Vec> = shapes(app, &ctx) + .into_iter() + .filter_map(|s| match s { + Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(Color32::from_white_alpha(230)) => Some(p.points), + _ => None, + }) + .collect(); + let [line] = &lines[..] else { panic!("one marquee: {lines:?}") }; + line.clone() + }; + let z0 = app.view().unwrap().zoom; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true, Modifiers::NONE)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(100.0, 50.0))]); + frame(&mut app, &ctx, vec![space(true, Modifiers::NONE), Event::PointerMoved(at + vec2(140.0, 70.0))]); + let moved = drawn(&mut app); + assert_eq!(moved[0], at + vec2(40.0, 20.0), "Space moves the marquee: {moved:?}"); + assert_eq!(moved[2], at + vec2(140.0, 70.0), "and keeps its 100 × 50 size: {moved:?}"); + frame(&mut app, &ctx, vec![space(false, Modifiers::NONE), Event::PointerMoved(at + vec2(180.0, 95.0))]); + let sized = drawn(&mut app); + assert_eq!((sized[0], sized[2]), (at + vec2(40.0, 20.0), at + vec2(180.0, 95.0)), "let go, the drag sizes it again: {sized:?}"); + let middle = Xf::new(rect, app.view().unwrap()).to_doc(at + vec2(110.0, 57.5)); + frame(&mut app, &ctx, vec![button(at + vec2(180.0, 95.0), false, Modifiers::NONE)]); + let v = *app.view().unwrap(); + let want = z0 * f64::from((rect.width() / 140.0).min(rect.height() / 75.0)); + assert!((v.zoom - want).abs() < 1e-6, "the release zooms to the moved marquee: {z0} → {}, not {want}", v.zoom); + assert!(v.center.distance(middle) < 1e-6, "centered on it: {:?}, not {middle:?}", v.center); + // A Cmd+Space press: Space held from the press on sizes the marquee, also once Cmd is let go. + app.select_tool("selection"); + app.view_mut().unwrap().zoom = z0; + frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::COMMAND), space(true, Modifiers::COMMAND), Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(50.0, 25.0))]); + frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::NONE), Event::PointerMoved(at + vec2(100.0, 50.0))]); + let held = drawn(&mut app); + assert_eq!((held[0], held[2]), (at, at + vec2(100.0, 50.0)), "Space held since the press sizes it: {held:?}"); + frame(&mut app, &ctx, vec![button(at + vec2(100.0, 50.0), false, Modifiers::NONE)]); + frame(&mut app, &ctx, vec![space(false, Modifiers::NONE)]); + let want = z0 * f64::from((rect.width() / 100.0).min(rect.height() / 50.0)); + assert!((app.view().unwrap().zoom - want).abs() < 1e-6, "{z0} → {}, not {want}", app.view().unwrap().zoom); +} + +/// Space pressed after the Zoom tool's press and before the drag moves: the first movement sizes +/// the marquee, Space then moves it, and the release zooms to it instead of stepping the zoom. +#[test] +fn space_before_the_zoom_drag_moves_sizes_the_marquee_first() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let z0 = app.view().unwrap().zoom; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true)]); + frame(&mut app, &ctx, vec![space(true), Event::PointerMoved(at + vec2(120.0, 60.0))]); + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(140.0, 70.0))]); + let middle = Xf::new(rect, app.view().unwrap()).to_doc(at + vec2(80.0, 40.0)); + frame(&mut app, &ctx, vec![button(at + vec2(140.0, 70.0), false)]); + frame(&mut app, &ctx, vec![space(false)]); + let v = *app.view().unwrap(); + let want = z0 * f64::from((rect.width() / 120.0).min(rect.height() / 60.0)); + assert!((v.zoom - want).abs() < 1e-6, "the release zooms to the 120 × 60 marquee: {z0} → {}, not {want}", v.zoom); + assert!(v.center.distance(middle) < 1e-6, "moved by Space and centered on it: {:?}, not {middle:?}", v.center); +} + +/// Space pressed or let go between two pointer moves in one frame: the move before the change and +/// the move after it each follow the Space state they came with. +#[test] +fn the_zoom_marquee_follows_space_and_the_pointer_in_the_order_they_came() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let corners = |app: &mut VectorcraftApp| -> (Pos2, Pos2) { + let lines: Vec> = shapes(app, &ctx) + .into_iter() + .filter_map(|s| match s { + Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(Color32::from_white_alpha(230)) => Some(p.points), + _ => None, + }) + .collect(); + let [line] = &lines[..] else { panic!("one marquee: {lines:?}") }; + (line[0], line[2]) + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(100.0, 50.0))]); + frame(&mut app, &ctx, vec![space(true), Event::PointerMoved(at + vec2(140.0, 70.0))]); + // Moved with Space held, then sized after it was let go. + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(160.0, 80.0)), space(false), Event::PointerMoved(at + vec2(200.0, 100.0))]); + assert_eq!(corners(&mut app), (at + vec2(60.0, 30.0), at + vec2(200.0, 100.0)), "moved, then sized"); + // Sized before Space was pressed, then moved with it held. + frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(210.0, 105.0)), space(true), Event::PointerMoved(at + vec2(230.0, 115.0))]); + assert_eq!(corners(&mut app), (at + vec2(80.0, 40.0), at + vec2(230.0, 115.0)), "sized, then moved"); + frame(&mut app, &ctx, vec![button(at + vec2(230.0, 115.0), false)]); + frame(&mut app, &ctx, vec![space(false)]); +} + +/// Space pressed while the Zoom tool drags keeps the zoom cursor: the drag does not turn into a +/// Hand tool pan, and with Shift also held it does not show the rotate cursor. +#[test] +fn space_during_a_zoom_drag_keeps_the_zoom_cursor() { + use egui::{CursorIcon, Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + app.select_tool("zoom"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let c = app.canvas_rect.unwrap().center(); + // `shown` returns the system cursor the canvas sets over a window without the focus, as in + // `the_rotate_cursor_shows_for_space_shift_and_the_rotate_view_tool`. + let shown = |app: &mut VectorcraftApp, events: Vec| { + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, focused: false, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + assert_eq!(shown(&mut app, vec![Event::PointerMoved(c)]), CursorIcon::ZoomIn); + shown(&mut app, vec![button(c, true)]); + shown(&mut app, vec![Event::PointerMoved(c + vec2(40.0, 30.0))]); + assert_eq!(shown(&mut app, vec![space(true), Event::PointerMoved(c + vec2(60.0, 40.0))]), CursorIcon::ZoomIn, "Space during the drag"); + assert_eq!(shown(&mut app, vec![Event::ModifiersChanged(Modifiers::SHIFT)]), CursorIcon::ZoomIn, "Space+Shift during the drag"); + shown(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE)]); + shown(&mut app, vec![button(c + vec2(60.0, 40.0), false)]); + assert_eq!(shown(&mut app, vec![]), CursorIcon::Grab, "after the drag, Space shows the hand"); + shown(&mut app, vec![space(false)]); +} + /// In a rotated view the Selection tool's marquee is drawn where the tool selects: through the /// screen corners of the document rectangle between the press and the pointer. #[test] @@ -6067,6 +6498,121 @@ fn a_pen_tap_within_one_frame_clicks_where_it_tapped() { assert_eq!(doc.doc.art_bounds(), before, "the tap moved nothing"); } +/// The Contextual Task Bar shows a Stroke chip beside the Fill chip, drawn with the selection's +/// stroke paint. A click on it brings the Stroke proxy forward and opens Swatches, as a click on +/// the Fill chip does for the Fill proxy. +#[test] +fn the_task_bar_shows_a_stroke_chip_beside_fill() { + 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": 180, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.session.execute("paint.setFill", &json!({"ids": [id], "color": "#cc3322"})).unwrap(); + app.session.execute("paint.setStroke", &json!({"ids": [id], "color": "#2244cc"})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + // Past the bar's fade-in, so its chips draw at full opacity. + for _ in 0..30 { + frame(&mut app, &ctx, vec![]); + } + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let bar = task_bar_rect(&ctx).expect("the task bar shows"); + // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + let stroke_x = bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; + let fill_x = stroke_x - 26.0 - 6.0; + let blue = Color32::from_rgb(0x22, 0x44, 0xcc); + let chip_with = |x: f32| { + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.fill == blue && bar.contains(r.rect.center()) && (r.rect.center().x - x).abs() < 4.0, + _ => false, + }) + }; + assert!(chip_with(stroke_x), "the Stroke chip is drawn with the stroke color"); + assert!(!chip_with(fill_x), "the Fill chip is not"); + + let click = |app: &mut VectorcraftApp, x: f32| { + let at = pos2(x, bar.center().y); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, &ctx, vec![button(true)]); + frame(app, &ctx, vec![button(false)]); + }; + app.session.fill_active = true; + click(&mut app, stroke_x); + assert!(!app.session.fill_active, "the Stroke proxy is in front"); + assert_eq!(app.ui.open_panel.as_deref(), Some("swatches")); + app.ui.open_panel = None; + click(&mut app, fill_x); + assert!(app.session.fill_active, "the Fill proxy is in front"); + assert_eq!(app.ui.open_panel.as_deref(), Some("swatches")); +} + +/// The Contextual Task Bar's Fill and Stroke chips show the paints the proxies show: a group's +/// painted art, and "?" when the selected objects' paints differ. A click on a chip shows the +/// Swatches panel wherever it is, closed included. +#[test] +fn the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut square = |x: f64, stroke: &str| { + let id = app.session.execute("shape.rectangle", &json!({"x": x, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.session.execute("paint.setFill", &json!({"ids": [id], "color": "#cc3322"})).unwrap(); + app.session.execute("paint.setStroke", &json!({"ids": [id], "color": stroke})).unwrap(); + id + }; + square(160.0, "#2244cc"); + let second = square(220.0, "#22cc44"); + app.select_tool("selection"); + app.session.execute("select.all", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let shapes = |app: &mut VectorcraftApp| { + for _ in 0..30 { + frame(app, &ctx, vec![]); + } + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + }; + // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + let stroke_x = |bar: egui::Rect| bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; + let chip_with = |shapes: &[egui::epaint::ClippedShape], bar: egui::Rect, x: f32, color: Color32| { + shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.fill == color && bar.contains(r.rect.center()) && (r.rect.center().x - x).abs() < 4.0, + _ => false, + }) + }; + let (blue, green) = (Color32::from_rgb(0x22, 0x44, 0xcc), Color32::from_rgb(0x22, 0xcc, 0x44)); + + // Two strokes that differ: "?" on white, as the proxy shows them. + let out = shapes(&mut app); + let bar = task_bar_rect(&ctx).expect("the task bar shows"); + assert!(chip_with(&out, bar, stroke_x(bar), Color32::WHITE), "the Stroke chip shows the strokes differ"); + assert!(!chip_with(&out, bar, stroke_x(bar), blue), "the Stroke chip does not show the first object's stroke"); + + // A group shows its painted art's stroke, as the proxy does. + app.session.execute("paint.setStroke", &json!({"ids": [second], "color": "#2244cc"})).unwrap(); + app.session.execute("select.all", &json!({})).unwrap(); + app.session.execute("object.group", &json!({})).unwrap(); + let out = shapes(&mut app); + let bar = task_bar_rect(&ctx).expect("the task bar shows"); + assert!(chip_with(&out, bar, stroke_x(bar), blue), "the Stroke chip shows the group's art's stroke"); + assert!(!chip_with(&out, bar, stroke_x(bar), green)); + + // Swatches closed: a click on the Stroke chip shows it. + app.run("window.panel.close", json!({"panel": "swatches"})).unwrap(); + assert!(!crate::panel_docking::showing(&app.ui, "swatches")); + let at = pos2(stroke_x(bar), bar.center().y); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + frame(&mut app, &ctx, vec![]); + assert!(!app.session.fill_active, "the Stroke proxy is in front"); + assert!(crate::panel_docking::showing(&app.ui, "swatches"), "the Swatches panel shows"); +} + /// The Contextual Task Bar shows Recolor Artwork (a palette) when the selection has colours, /// and it opens the Recolor Artwork dialog; art painted with None has no button. #[test] @@ -6237,6 +6783,32 @@ fn the_task_bar_offers_the_artboard_tools_actions() { assert_eq!(names(&mut app), ["Resize", "Duplicate", "Export"]); } +/// A selected group's Contextual Task Bar offers Ungroup and Isolate. While an opacity mask is +/// edited, when Enter Isolation Mode is off, a group in the mask art gets Ungroup without Isolate. +#[test] +fn the_task_bar_leaves_isolate_out_while_an_opacity_mask_is_edited() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let names = |app: &mut VectorcraftApp| task_bar_labels(app, &ctx).into_iter().map(|(t, _)| t).collect::>(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone() + }; + let group = |app: &mut VectorcraftApp, x: f64| { + let (a, b) = (rect(app, x), rect(app, x + 50.0)); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + app.session.execute("object.group", &json!({})).unwrap(); + }; + group(&mut app, 20.0); + assert_eq!(names(&mut app), ["Ungroup", "Isolate", "Duplicate"]); + let (obj, m) = (rect(&mut app, 200.0), rect(&mut app, 200.0)); + app.session.execute("transparency.makeOpacityMask", &json!({"ids": [obj, m]})).unwrap(); + app.session.execute("transparency.editOpacityMask", &json!({"id": obj})).unwrap(); + group(&mut app, 200.0); + assert_eq!(names(&mut app), ["Ungroup", "Duplicate"]); +} + /// The Artboard tool's Contextual Task Bar buttons act on its selected artboards: Resize opens /// Artboard Options for the active one, Rearrange All opens Rearrange All Artboards, Export opens /// Export for Screens with the selected artboards checked, and Duplicate copies each selected @@ -6328,7 +6900,7 @@ fn the_task_bar_is_dragged_by_its_handle_pinned_and_reset() { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); let mut square = |x: f64, y: f64| app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 40, "height": 40})).unwrap()["id"].clone(); - let (a, b) = (square(120.0, 40.0), square(160.0, 150.0)); + let (a, b) = (square(140.0, 40.0), square(160.0, 150.0)); app.select_tool("selection"); let ctx = egui::Context::default(); let bar = || task_bar_rect(&ctx).expect("the task bar shows"); @@ -6807,6 +7379,28 @@ fn distance_guides_follow_what_lies_under_a_still_pointer() { assert_eq!(gap_label(&run(&mut app, vec![])), None, "another document"); } +/// #4518: a floating panel or a modal dialog over the canvas hides the pointer from it, so Object +/// Highlighting, the rulers and the Info panel don't follow a pointer that is over the dialog. +#[test] +fn a_panel_or_dialog_over_the_canvas_hides_the_pointer_from_it() { + let (mut app, ctx, _, over, _) = distance_scene(true); + let run = |app: &mut VectorcraftApp, events, cover| distance_frame_covered(app, &ctx, events, cover); + run(&mut app, vec![egui::Event::PointerMoved(over)], None); + run(&mut app, vec![], None); + assert!(app.hover_doc.is_some(), "over the canvas"); + for cover in [Cover::Panel(egui::Rect::from_center_size(over, vec2(120.0, 120.0))), Cover::Dialog] { + // A new window takes a sizing pass before it covers anything, as in the test above. + for _ in 0..3 { + run(&mut app, vec![], Some(cover)); + } + assert_eq!(app.hover_doc, None, "under it"); + for _ in 0..3 { + run(&mut app, vec![], None); + } + assert!(app.hover_doc.is_some(), "back once it closes"); + } +} + /// The 800 × 600 window [`frame`] draws the canvas in. const WINDOW: egui::Rect = egui::Rect { min: Pos2::ZERO, max: Pos2 { x: 800.0, y: 600.0 } }; diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index d1b3cff274..add1716110 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -64,7 +64,8 @@ pub(super) const HOLD_DELAY: f32 = 0.3; pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2; /// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms -/// as it is dragged sideways or held, instead of zooming to the area dragged across. +/// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel +/// notch's zoom glides in ([`wheel`]). pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { p.animated_zoom && p.gpu_performance } @@ -336,11 +337,19 @@ struct ThumbDrag { /// a zoom factor (about the pointer) and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option /// on the Mac) zoom. With General › Zoom with Mouse Wheel (`wheel_zooms`) the wheel and Alt-wheel /// zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points -/// per wheel line and page. `turn`: kept by the caller across frames. A mouse wheel's notches zoom -/// in a glide over a few frames, as scrolling does (#888); a trackpad's fine steps at once. -pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, turn: &mut WheelTurn) -> (f64, egui::Vec2) { +/// per wheel line and page. `turn`: kept by the caller across frames. With Performance › Animated +/// Zoom (`animate`) a mouse wheel's notches zoom in a glide over a few frames, as scrolling does +/// (#888); off, each notch zooms on the frame it arrives (#4283). A trackpad's fine steps zoom at +/// once either way. +pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, animate: bool, line: f32, page: f32, turn: &mut WheelTurn) -> (f64, egui::Vec2) { // Fingers on a touch screen pan the content with them (a trackpad sends scrolls instead). let pan = i.multi_touch().map_or(egui::Vec2::ZERO, |t| t.translation_delta); + // A wheel event's motion in points. + let points = |unit: &egui::MouseWheelUnit, delta: egui::Vec2| match unit { + egui::MouseWheelUnit::Point => delta, + egui::MouseWheelUnit::Line => delta * line, + egui::MouseWheelUnit::Page => delta * page, + }; if !wheel_zooms { // egui makes Cmd-wheel (and a pinch) its zoom and the rest a scroll it spreads over a few // frames: the rest of an Alt-wheel turn zooms too, however soon Alt is let go. @@ -348,6 +357,17 @@ pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f3 turn.alt = m.alt && !m.command; } let (zoom, scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta); + if turn.alt && !animate { + // Without Animated Zoom, Alt-wheel zooms by the wheel events themselves, on the frame + // they arrive; the rest of egui's spread scroll is dropped. + let d: f32 = i + .events + .iter() + .filter_map(|e| if let egui::Event::MouseWheel { unit, delta, .. } = e { Some(points(unit, *delta)) } else { None }) + .map(|d| d.x + d.y) + .sum(); + return (zoom * (f64::from(d) * WHEEL_ZOOM).exp(), pan); + } return if turn.alt && scroll != egui::Vec2::ZERO { (zoom * (f64::from(scroll.x + scroll.y) * WHEEL_ZOOM).exp(), pan) } else { @@ -360,16 +380,12 @@ pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f3 for e in &i.events { match e { egui::Event::MouseWheel { unit, delta, modifiers, .. } => { - let d = match unit { - egui::MouseWheelUnit::Point => *delta, - egui::MouseWheelUnit::Line => *delta * line, - egui::MouseWheelUnit::Page => *delta * page, - }; + let d = points(unit, *delta); if modifiers.command { scroll.x += d.x + d.y; } else if modifiers.shift { scroll.y += d.x + d.y; - } else if *unit == egui::MouseWheelUnit::Point { + } else if *unit == egui::MouseWheelUnit::Point || !animate { zoom *= (f64::from(d.y) * WHEEL_ZOOM).exp(); scroll.x += d.x; } else { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 2000aaacba..b453cc6858 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -29,7 +29,7 @@ pub use status_bar::status_bar; use status_bar::{StatusReadoutWidths, status_readouts}; #[cfg(test)] use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; -pub use tabs::{doc_tabs, isolation_bar}; +pub use tabs::{doc_tabs, isolation_bar, step_document}; /// The application bar's height, in points (compact, as in PhotoCraft). pub const APP_BAR_HEIGHT: f32 = 32.0; diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index a53062be8b..06d2964a7c 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -114,21 +114,47 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } } else if let Some(i) = activate { - app.ui.home = None; - let changed = app.session.active_index() != Some(i); - if app.session.set_active(i) - && changed - && app.session.tool_id() == "artboard" - && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()) - { - // A document switch recreates the tool; restore the displayed board as its target. - // Clicking the current tab keeps its existing multiselection and tool options. - let selected = crate::panels::artboards::selected(app, n); - crate::panels::artboards::select(app, selected); - } + show_document(app, i); } } +/// Makes document `i` the current one, as a click on its tab does: the Home screen closes, and +/// with the Artboard tool the artboard the document shows becomes the tool's target. +fn show_document(app: &mut VectorcraftApp, i: usize) { + app.ui.home = None; + let changed = app.session.active_index() != Some(i); + if app.session.set_active(i) + && changed + && app.session.tool_id() == "artboard" + && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()) + { + // A document switch recreates the tool; restore the displayed board as its target. + // Clicking the current tab keeps its existing multiselection and tool options. + let selected = crate::panels::artboards::selected(app, n); + crate::panels::artboards::select(app, selected); + } +} + +/// `window.nextDocument` (`forward`) and `window.previousDocument`: makes the open document after +/// the current one in tab order (before it) the current one, as a click on its tab does. After the +/// last document comes the first, and before the first document comes the last. On the Home +/// screen, where no tab is the current one, the next document is the first and the previous +/// document is the last. Returns `{index}`. +pub fn step_document(app: &mut VectorcraftApp, forward: bool) -> Result { + let n = app.session.documents().len(); + if n == 0 { + return Err("no document open".into()); + } + let i = match (app.session.active_index().filter(|_| app.ui.home.is_none()), forward) { + (Some(a), true) => (a + 1) % n, + (Some(a), false) => (a + n - 1) % n, + (None, true) => 0, + (None, false) => n - 1, + }; + show_document(app, i); + Ok(json!({ "index": i })) +} + /// The isolation mode breadcrumb bar. It is drawn over the top of `area` (the canvas), after the /// canvas, so entering isolation mode does not change the canvas's size (#3126). pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { @@ -136,12 +162,20 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if let Some(st) = app.session.active() && let Some(iso) = st.isolation { - let mut crumbs: Vec = - st.doc.ancestry(iso).unwrap_or_default().iter().filter_map(|id| st.doc.node(*id)).map(|n| n.display_name()).collect(); + let ancestry = st.doc.ancestry(iso).unwrap_or_default(); + struct Crumb { + id: Option, + is_layer: bool, + name: String, + } + let mut crumbs: Vec = ancestry + .iter() + .filter_map(|id| st.doc.node(*id).map(|n| Crumb { id: Some(*id), is_layer: n.is_layer(), name: n.display_name() })) + .collect(); // Pattern editing mode: the pattern's name, and Save a Copy / Done / Cancel at the right. let pattern_edit = st.doc.pattern_edit.as_ref().map(|e| e.pattern.clone()); if let Some(pn) = &pattern_edit { - crumbs.push(pn.clone()); + crumbs.push(Crumb { id: None, is_layer: false, name: pn.clone() }); } let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0)); ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::click_and_drag()); @@ -149,13 +183,41 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click()); icons::paint(ui, "chevron-left", back, if bresp.hovered() { t.text } else { t.icon }); - ui.painter().text( - bar.left_center() + vec2(30.0, 0.0), - egui::Align2::LEFT_CENTER, - crumbs.join(" › "), - egui::FontId::proportional(12.0), - t.text, - ); + + let mut x = bar.left() + 30.0; + let y_center = bar.center().y; + let font_id = egui::FontId::proportional(12.0); + let mut nav_cmd = None; + let total = crumbs.len(); + for (i, crumb) in crumbs.iter().enumerate() { + let is_leaf = i + 1 == total; + let galley = ui.painter().layout_no_wrap(crumb.name.clone(), font_id.clone(), t.text); + let w = galley.size().x; + let text_pos = egui::pos2(x, y_center - galley.size().y * 0.5); + if !is_leaf { + let crumb_rect = egui::Rect::from_min_max(egui::pos2(x - 3.0, bar.top() + 3.0), egui::pos2(x + w + 3.0, bar.bottom() - 3.0)); + let resp = ui.interact(crumb_rect, ui.scope_id().with(("iso-crumb", i)), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(crumb_rect, 3.0, t.hover); + } + if resp.clicked() { + if crumb.is_layer { + nav_cmd = Some(("object.exitIsolation", json!({}))); + } else if let Some(target) = crumb.id { + nav_cmd = Some(("object.isolate", json!({ "id": target.0 }))); + } + } + ui.painter().galley(text_pos, galley, if resp.hovered() { t.text } else { t.text_dim }); + x += w + 6.0; + let sep = ui.painter().layout_no_wrap("›".to_string(), font_id.clone(), t.text_dim); + let sw = sep.size().x; + ui.painter().galley(egui::pos2(x, y_center - sep.size().y * 0.5), sep, t.text_dim); + x += sw + 6.0; + } else { + ui.painter().galley(text_pos, galley, t.text); + x += w; + } + } let mut pattern_cmd = None; if pattern_edit.is_some() { let mut x = bar.right() - 6.0; @@ -176,9 +238,16 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - app.run("object.exitIsolation", json!({})).ok(); + // Up one level: the isolated object's parent, or out of isolation mode from a layer. + nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + Some(parent) => ("object.isolate", json!({ "id": parent.0 })), + None => ("object.exitIsolation", json!({})), + }); } } + if let Some((cmd, params)) = nav_cmd { + app.run(cmd, params).ok(); + } if let Some(cmd) = pattern_cmd { app.run(cmd, json!({})).ok(); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 362854a5f3..929034a72b 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -902,6 +902,77 @@ fn the_isolation_bar_does_not_take_layout_height_from_the_canvas() { assert_eq!(top(&mut app), before, "isolation mode leaves the canvas where it was"); } +/// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, +/// and clicking ancestor breadcrumbs navigates directly to that isolation level. +#[test] +fn isolation_bar_navigation_and_back_button_steps_up() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + // Group 1 contains a and b + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g1 = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + let c = rect(&mut app, 90.0); + // Group 2 contains g1 and c + app.run("select.set", json!({"ids": [g1, c]})).unwrap(); + let g2 = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + + // Isolate path a (deepest level: Layer 1 > > > ) + app.run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(a))); + + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + egui_extras::install_image_loaders(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + + let click_at = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| { + let button = egui::PointerButton::Primary; + let mut run_frame = |events| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| { + super::isolation_bar(app, ui, screen); + }); + out.textures_delta.clear(); + }; + run_frame(vec![egui::Event::PointerMoved(pos)]); + run_frame(vec![egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() }]); + run_frame(vec![egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() }]); + }; + + // Clicking back from `a` steps up to parent group `g1` + click_at(&mut app, egui::pos2(15.0, 12.0)); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g1))); + + // Clicking back from `g1` steps up to grandparent group `g2` + click_at(&mut app, egui::pos2(15.0, 12.0)); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); + + // Clicking back from `g2` (parent is layer) exits isolation mode completely + click_at(&mut app, egui::pos2(15.0, 12.0)); + assert_eq!(app.session.active().unwrap().isolation, None); + + // Deep isolate again to test clicking ancestor breadcrumb directly + app.run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(a))); + + // First crumb is Layer 1 (at x ~ 30..80). Clicking it exits isolation directly. + click_at(&mut app, egui::pos2(45.0, 12.0)); + assert_eq!(app.session.active().unwrap().isolation, None); + + // Deep isolate again to test clicking an intermediate ancestor group breadcrumb directly + app.run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(a))); + + // Second crumb is g2 ("") at x ~ 95..140. + // Clicking g2 isolates g2 directly. + click_at(&mut app, egui::pos2(115.0, 12.0)); + assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern @@ -1223,6 +1294,127 @@ fn artboard_document_tab_roundtrip_preserves_other_tools() { } } +/// Press F6 with `modifiers` through the shortcut handler. +fn press_f6(app: &mut crate::VectorcraftApp, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + let ev = egui::Event::Key { key: egui::Key::F6, physical_key: None, pressed: true, repeat: false, modifiers }; + let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Cmd+F6 is Next Document and Cmd+Shift+F6 is Previous Document by default: Ctrl+F6 and +/// Ctrl+Shift+F6 on Windows and Linux, Command+F6 and Shift+Command+F6 on macOS. Keyboard +/// Shortcuts lists both under Window. F6 and Shift+F6 are still the Color and Appearance panels' +/// keys, and no other command, tool or panel has either key by default. +#[test] +fn cmd_f6_and_cmd_shift_f6_are_next_and_previous_document() { + use crate::shortcut_editor::{command_for_key, default_command_shortcut, panel_shortcut}; + assert_eq!(default_command_shortcut("window.nextDocument"), Some("Cmd+F6")); + assert_eq!(default_command_shortcut("window.previousDocument"), Some("Cmd+Shift+F6")); + assert_eq!(command_for_key("Cmd+F6"), Some("window.nextDocument")); + assert_eq!(command_for_key("Cmd+Shift+F6"), Some("window.previousDocument")); + assert_eq!((panel_shortcut("color"), panel_shortcut("appearance")), (Some("F6"), Some("Shift+F6"))); + let chord = crate::shortcuts::parse("Cmd+Shift+F6").expect("parses"); + assert_eq!((chord.modifiers, chord.logical_key), (egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::F6)); + let shown = (crate::menus::pretty_shortcut("Cmd+F6"), crate::menus::pretty_shortcut("Cmd+Shift+F6")); + let want = if cfg!(target_os = "macos") { ("⌘F6", "⇧⌘F6") } else { ("Ctrl+F6", "Ctrl+Shift+F6") }; + assert_eq!((shown.0.as_str(), shown.1.as_str()), want); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let listed = app.run("shortcuts.list", json!({"query": "Document"})).unwrap(); + let rows: Vec<_> = listed + .as_array() + .expect("rows") + .iter() + .filter(|r| r["id"].as_str().is_some_and(|id| id.ends_with("Document") && id.starts_with("window."))) + .map(|r| (r["label"].clone(), r["group"].clone(), r["default"].clone())) + .collect(); + assert_eq!( + rows, + [(json!("Next Document"), json!("Window"), json!("Cmd+F6")), (json!("Previous Document"), json!("Window"), json!("Cmd+Shift+F6"))], + "Keyboard Shortcuts lists both" + ); + assert_eq!(app.run("shortcuts.conflicts", json!({})).unwrap(), json!([]), "no other default has the keys"); +} + +/// Cmd+F6 makes the next open document in tab order the current one, and Cmd+Shift+F6 makes the +/// previous one the current one. After the last document comes the first, and before the first document comes the +/// last. From the Home screen the keys go to the first and the last document and close the screen. +/// With no document open the commands are disabled and fail with "no document open". +#[test] +fn cmd_f6_goes_to_the_next_document_and_cmd_shift_f6_to_the_previous_one() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + assert!(!crate::menus::enabled(&app, "window.nextDocument") && !crate::menus::enabled(&app, "window.previousDocument")); + assert_eq!(app.run("window.nextDocument", json!({})).unwrap_err(), "no document open"); + assert_eq!(app.run("window.previousDocument", json!({})).unwrap_err(), "no document open"); + for name in ["A", "B", "C"] { + app.run("file.new", json!({"width": 100, "height": 100, "name": name})).unwrap(); + } + assert!(crate::menus::enabled(&app, "window.nextDocument") && crate::menus::enabled(&app, "window.previousDocument")); + assert_eq!(app.session.active_index(), Some(2)); + let mut seen = vec![]; + for modifiers in [egui::Modifiers::COMMAND; 4] { + press_f6(&mut app, modifiers); + seen.push(app.session.active_index()); + } + assert_eq!(seen, [Some(0), Some(1), Some(2), Some(0)], "Cmd+F6 goes right and wraps from the last to the first"); + seen.clear(); + for modifiers in [egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; 4] { + press_f6(&mut app, modifiers); + seen.push(app.session.active_index()); + } + assert_eq!(seen, [Some(2), Some(1), Some(0), Some(2)], "Cmd+Shift+F6 goes left and wraps from the first to the last"); + assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 0})); + assert_eq!(app.run("window.previousDocument", json!({})).unwrap(), json!({"index": 2})); + app.session.set_active(1); + app.run("app.home", json!({})).unwrap(); + press_f6(&mut app, egui::Modifiers::COMMAND); + assert_eq!((app.session.active_index(), app.ui.home), (Some(0), None), "from the Home screen Cmd+F6 shows the first"); + app.session.set_active(1); + app.run("app.home", json!({})).unwrap(); + press_f6(&mut app, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!((app.session.active_index(), app.ui.home), (Some(2), None), "and Cmd+Shift+F6 the last"); + // One document: the keys keep it current. + let mut one = crate::VectorcraftApp::new(Session::new(), Default::default()); + one.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + press_f6(&mut one, egui::Modifiers::COMMAND); + press_f6(&mut one, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!(one.session.active_index(), Some(0)); +} + +/// With the Artboard tool, Cmd+F6 and Cmd+Shift+F6 switch documents as a click on a tab does: the +/// document switched back to keeps the artboard it shows as the tool's target, so the Properties +/// panel's Delete Artboard then removes that artboard. Switching is not an edit. +#[test] +fn cmd_f6_switches_documents_as_a_tab_click_does_with_the_artboard_tool() { + let (mut app, ctx) = artboard_document_app(); + app.select_tool("artboard"); + artboard_navigation_next(&mut app, &ctx); + assert_eq!(app.session.tool_options()["selected"], json!([1])); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + press_f6(&mut app, egui::Modifiers::COMMAND); + assert_eq!(app.session.active_index(), Some(1)); + // The app draws frames while the other document is the current one. + artboard_navigation_properties_frame(&mut app, &ctx, vec![]); + artboard_document_tabs_frame(&mut app, &ctx, vec![]); + press_f6(&mut app, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!(app.session.active_index(), Some(0)); + app.sync_views(); + assert_eq!(app.session.tool_options()["selected"], json!([1]), "the tool targets the displayed artboard"); + assert_eq!(app.view().unwrap().artboard, 1, "the document keeps its displayed artboard"); + assert_eq!(app.session.active().unwrap().doc, before, "switching documents is not a document edit"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + artboard_navigation_properties_frame(&mut app, &ctx, vec![]); + let texts = artboard_navigation_properties_frame(&mut app, &ctx, vec![]); + let at = texts.iter().find(|(label, _)| label == "Delete Artboard").map(|(_, r)| r.center()).expect("Properties Delete button"); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for event in [egui::Event::PointerMoved(at), button(true), button(false)] { + artboard_navigation_properties_frame(&mut app, &ctx, vec![event]); + } + let names: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Keep"], "Delete Artboard after the keys removes the artboard the document shows"); +} + /// One history entry: its label, document and selection. type HistoryRow = (String, Arc, Arc); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 14d6fe8312..68bba9ade6 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -327,7 +327,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); } for (f, value) in fields { - d.fields.insert(f, value); + crate::dialogs::set_field(d, f, value); } ok(serde_json::to_value(&*d).unwrap_or_default()) } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 49dfe37b9a..3ca9da699c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -62,6 +62,7 @@ pub mod new_brush; pub mod new_color_group; mod new_document; pub mod new_swatch; +pub mod new_text_style; pub mod office_export; pub mod package; pub(crate) mod path_ops; @@ -99,6 +100,7 @@ pub(crate) mod shapes; pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; +pub(crate) mod smooth_slider; pub mod spot_colors; pub(crate) mod svg_options; pub mod swatch_conflict; @@ -110,6 +112,7 @@ pub mod text_import; mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; +pub mod trace_presets; pub(crate) mod transform; pub mod transform_each; pub mod variables; @@ -176,6 +179,10 @@ pub(crate) struct DialogSpec { /// A button left of Cancel, as (label, field), that sets `field: true` and confirms, as OK /// does otherwise (Transform Each's Copy). pub alternate: Option<(&'static str, &'static str)>, + /// Puts the fields back to their defaults. While Alt (Option on macOS) is held, the Cancel + /// button of a dialog with an `ok` reads Reset; Reset (or `ui.dialogReset`) runs this and the + /// dialog stays open. + pub reset: Option, pub min_width: f32, pub max_width: Option, /// The body runs a live preview interaction that Cancel rolls back. @@ -211,6 +218,7 @@ impl DialogSpec { ok: Some("OK"), discard: None, alternate: None, + reset: None, min_width: 320.0, max_width: None, preview: false, @@ -291,6 +299,7 @@ registry! { GradientStop: ["gradientStop"] => gradient_stop::SPEC, ColorPicker: [color_picker::KIND] => color_picker::SPEC, GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, + NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, ColorBalance: [color_balance::KIND] => color_balance::SPEC, @@ -300,6 +309,7 @@ registry! { EyedropperOptions: [eyedropper::KIND] => eyedropper::SPEC, FlattenTransparency: [flatten::KIND] => flatten::SPEC, FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC, + ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC, SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC, SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC, SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC, @@ -352,6 +362,7 @@ registry! { ScriptCheck: [script_check::KIND] => script_check::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, + SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, LiquifyOptions: [liquify::KIND] => liquify::SPEC, @@ -377,14 +388,15 @@ registry! { ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } -/// The button labels the shared dialog frame can show (OK, discard and the fixed Cancel/Close), -/// so the catalog tests can insist they are translated. +/// The button labels the shared dialog frame can show (OK, discard, the fixed Cancel/Close and +/// Reset), so the catalog tests can insist they are translated. pub fn button_labels() -> Vec<&'static str> { let mut v = vec!["Cancel", "Close"]; for spec in std::iter::once(&DialogSpec::FORM).chain(DialogKind::ALL.iter().map(|k| k.spec())) { v.extend(spec.ok); v.extend(spec.discard); v.extend(spec.alternate.map(|(label, _)| label)); + v.extend(spec.reset.map(|_| "Reset")); } v.sort_unstable(); v.dedup(); @@ -410,6 +422,15 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { || (spec.passes)(d, field) } +/// Set `field` of `d` to `value` for `ui.dialog.set`, as the dialog's own control for it does: a +/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is. +pub fn set_field(d: &mut Dialog, field: String, value: Value) { + if d.kind == brush_options::KIND { + brush_art_options::note_set(d, &field); + } + d.fields.insert(field, value); +} + /// The fields `ui.dialog.set` can set on `d`, sorted, without the `__` ones: those it holds, /// `discard`, `preview` and the spec's `inputs` for its kind. pub fn field_names(d: &Dialog) -> Vec { @@ -444,7 +465,10 @@ pub(crate) fn parent(d: &Dialog) -> Option { pub fn cancel(app: &mut VectorcraftApp) { missing_fonts::requeue_replaced(app); if let Some(d) = app.ui.dialog.take() { - if spec(&d.kind).preview { + // Toolbar-only Flare options start no preview and must not cancel a gesture + // that was already active before opening them. + let owns_preview = d.kind != flare_options::KIND || d.fields.contains_key(form::PREVIEWED); + if spec(&d.kind).preview && owns_preview { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); @@ -452,6 +476,23 @@ pub fn cancel(app: &mut VectorcraftApp) { settle(app); } +/// Whether the open dialog has a Reset ([`DialogSpec::reset`]). +pub(crate) fn can_reset(app: &VectorcraftApp) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| spec(&d.kind).reset.is_some()) +} + +/// Reset (`ui.dialogReset`, or Cancel while Alt or Option is held): the open dialog's fields go +/// back to their defaults and it stays open → the dialog; an error when no dialog is open or the +/// open one has no Reset. +pub(crate) fn reset(app: &mut VectorcraftApp) -> DialogResult { + let Some(mut d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; + let Some(reset) = spec(&d.kind).reset else { return Err("the open dialog has no Reset".into()) }; + reset(app, &mut d); + let out = serde_json::to_value(&d).unwrap_or_default(); + app.ui.dialog = Some(d); + Ok(out) +} + /// Apply the open dialog (OK). pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { missing_fonts::requeue_replaced(app); @@ -527,6 +568,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut ok = false; let mut ok_enabled = true; let mut cancel = false; + let mut reset = false; let mut discard = false; let mut alternate = false; // Opened as a save panel closed: the Enter that closed it isn't this dialog's, until it is let go. @@ -587,8 +629,21 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ok = true; } ui.add_space(8.0); - if widgets::secondary_button(ui, if spec.ok.is_some() { "Cancel" } else { "Close" }).clicked() { - cancel = true; + // While Alt (Option) is held, Cancel reads Reset on a dialog that has one. + let resets = spec.ok.is_some() && spec.reset.is_some() && ui.input(|i| i.modifiers.alt); + let label = if resets { + "Reset" + } else if spec.ok.is_some() { + "Cancel" + } else { + "Close" + }; + if widgets::secondary_button(ui, label).clicked() { + if resets { + reset = true; + } else { + cancel = true; + } } if let Some((label, _)) = spec.alternate { ui.add_space(8.0); @@ -614,6 +669,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.ui.dialog = Some(d); if cancel { self::cancel(app); + } else if reset { + if let Err(e) = self::reset(app) { + app.status(e); + } } else if ok && let Err(e) = confirm(app) { app.status(e); } diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 1898172a84..f9b5bf5584 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -14,14 +14,17 @@ //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, //! `overlap` (bend on each run between sharp corners). //! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, -//! `flipAcross`, `__tiles` (slot → preview key, for the tiles the brush has). +//! `flipAcross`, `outerCornerTile` and `innerCornerTile` (`original`: the corner art the brush +//! draws there | `none` | `autoCentered` | `autoBetween` | `autoSliced` | `autoOverlap`: a tile +//! made from the side tile), +//! `__tiles` (slot → preview key, for the tiles the brush has). use std::hash::{Hash, Hasher}; use std::sync::Arc; use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; -use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, Direction, PatternBrush, PatternFit, Scatter, Variation}; +use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; @@ -41,6 +44,43 @@ const DIRECTIONS: [Direction; 4] = [Direction::LeftToRight, Direction::RightToLe const TILES: [(&str, &str); 5] = [("outer_corner", "outerCorner"), ("side", "side"), ("inner_corner", "innerCorner"), ("start", "start"), ("end", "end")]; +/// Pattern brush corner tiles: (dialog field, art field of the definition, source field, art field +/// of the other kind of corner). +const CORNER_TILES: [(&str, &str, &str, &str); 2] = + [("outerCornerTile", "outer_corner", "outer_source", "inner_corner"), ("innerCornerTile", "inner_corner", "inner_source", "outer_corner")]; + +/// The art field that corner tile `field` draws with in definition `def`: its own art, or, with +/// neither art nor a source, the other kind of corner's art (as [`PatternBrush`] draws it). +fn corner_art_field<'a>(def: Option<&Value>, field: &'a str) -> Option<&'a str> { + let set = |f: &str| def.and_then(|d| d.get(f)).is_some_and(|v| !v.is_null()); + let (_, art, source, other) = CORNER_TILES.into_iter().find(|(_, art, _, _)| *art == field)?; + if set(art) { + Some(art) + } else if !set(source) && set(other) { + Some(other) + } else { + None + } +} + +/// The dialog field that records that corner tile `key`'s menu was set. +fn corner_set_key(key: &str) -> String { + format!("__{key}Set") +} + +/// Sets corner tile `key` to `choice` from its menu. +pub(super) fn choose_corner(d: &mut Dialog, key: &str, choice: &str) { + d.fields.insert(key.into(), json!(choice)); + note_set(d, key); +} + +/// Records that field `field` was set, from its menu or `ui.dialog.set`, when it is a corner tile. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if CORNER_TILES.iter().any(|(key, ..)| *key == field) { + d.fields.insert(corner_set_key(field), json!(true)); + } +} + /// The most key colours offered. const MAX_COLORS: usize = 16; @@ -121,6 +161,10 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { f.insert("fit".into(), json!(id_of(&p.fit))); f.insert("flipAlong".into(), json!(p.flip_along)); f.insert("flipAcross".into(), json!(p.flip_across)); + for ((key, art, _, _), source) in CORNER_TILES.into_iter().zip([p.outer_source, p.inner_source]) { + let choice = if corner_art_field(Some(&def), art).is_some() { "original" } else { source.map_or("none", CornerSource::id) }; + f.insert(key.into(), json!(choice)); + } // A preview key per tile the brush has: its art's hash, so a changed tile redraws. let tiles: Map = TILES .iter() @@ -200,13 +244,37 @@ pub(super) fn params(d: &Dialog) -> Value { "overlap": d.bool("overlap"), }) } - _ => json!({ - "scale": clamped(d, "scale", PatternBrush::SCALE_RANGE), - "spacing": clamped(d, "spacing", PatternBrush::SPACING_RANGE), - "fit": id_of(&parse_field::(d, "fit")), - "flip_along": d.bool("flipAlong"), - "flip_across": d.bool("flipAcross"), - }), + _ => { + let mut p = json!({ + "scale": clamped(d, "scale", PatternBrush::SCALE_RANGE), + "spacing": clamped(d, "spacing", PatternBrush::SPACING_RANGE), + "fit": id_of(&parse_field::(d, "fit")), + "flip_along": d.bool("flipAlong"), + "flip_across": d.bool("flipAcross"), + }); + // None or an automatic tile replaces the corner art. Original keeps the art the corner + // draws, the other kind of corner's art included, so changing the other kind leaves it. + // A None the menu was not set to, on a corner without art or a source, leaves the + // definition as it is: that corner still draws the other kind's art when it gets some. + let def = d.fields.get("__def"); + for (key, art, source, other) in CORNER_TILES { + let choice = d.str(key); + let unset = |f: &str| def.and_then(|d| d.get(f)).is_none_or(Value::is_null); + if choice == CornerSource::None.id() && !d.bool(&corner_set_key(key)) && unset(source) && corner_art_field(def, art).is_none() { + continue; + } + if let Some(s) = CornerSource::parse(&choice) { + p[art] = Value::Null; + p[source] = json!(s.id()); + } else if choice == "original" + && let Some(from) = corner_art_field(def, art).filter(|f| *f != art) + && CORNER_TILES.iter().find(|(_, a, _, _)| *a == other).is_some_and(|(k, ..)| d.str(k) != "original") + { + p[art] = def.and_then(|d| d.get(from)).cloned().unwrap_or_default(); + } + } + p + } }; p["colorization"] = serde_json::to_value(colorization(d)).unwrap_or_default(); p @@ -379,21 +447,44 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { radios(ui, d, "fit", &fits); } -/// The pattern's five tiles, each with its art (or None when the brush has no such tile). -fn tiles(ui: &mut egui::Ui, d: &Dialog) { +/// What a corner tile can be: (choice, label). Original (the corner art the brush draws there) is +/// offered only when the brush draws corner art there. +fn corner_choices() -> [(&'static str, &'static str); 6] { + [ + ("original", tl!("Original")), + (CornerSource::None.id(), tl!("None")), + (CornerSource::AutoCentered.id(), tl!("Auto-Centered")), + (CornerSource::AutoBetween.id(), tl!("Auto-Between")), + (CornerSource::AutoSliced.id(), tl!("Auto-Sliced")), + (CornerSource::AutoOverlap.id(), tl!("Auto-Overlap")), + ] +} + +/// The pattern's five tiles, each with its art (or None when the brush has no such tile). Below +/// each corner tile, a menu sets it to the brush's art, None or a tile made from the side tile. +fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let names = [tl!("Outer Corner Tile"), tl!("Side Tile"), tl!("Inner Corner Tile"), tl!("Start Tile"), tl!("End Tile")]; - let keys = d.fields.get("__tiles"); + let keys = d.fields.get("__tiles").cloned(); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; for ((field, slot), name) in TILES.into_iter().zip(names) { + let corner = CORNER_TILES.iter().find(|(_, art, _, _)| *art == field).map(|(key, ..)| *key); + // The art the tile draws with: its own, or a corner's that falls back on the other's. + let drawn = if corner.is_some() { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; + let drawn_slot = drawn.and_then(|f| TILES.iter().find(|(tf, _)| *tf == f)).map_or(slot, |(_, s)| *s); + let choices: Vec<(&str, &str)> = corner_choices().into_iter().filter(|(c, _)| drawn.is_some() || *c != "original").collect(); + let choice = corner.map(|key| d.str(key)); + // The label of the corner's choice when it shows no art. + let shown = choice.as_deref().filter(|c| *c != "original"); + let label = shown.and_then(|c| choices.iter().find(|(id, _)| *id == c)).map_or(tl!("None"), |(_, l)| *l); ui.vertical(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(76.0, 44.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, Color32::WHITE); - let key = keys.and_then(|k| k.get(slot)).and_then(Value::as_str); + let key = keys.as_ref().filter(|_| shown.is_none()).and_then(|k| k.get(drawn_slot)).and_then(Value::as_str); let tex = key.and_then(|key| { widgets::doc_preview(ui, key, r.size(), |w, h| { - let art: Node = serde_json::from_value(d.fields.get("__def")?.get(field)?.clone()).ok()?; + let art: Node = serde_json::from_value(d.fields.get("__def")?.get(drawn?)?.clone()).ok()?; tile_doc(&art, w, h) }) }); @@ -402,18 +493,21 @@ fn tiles(ui: &mut egui::Ui, d: &Dialog) { ui.painter().image(tex.id(), r, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } None => { - ui.painter().text( - r.center(), - egui::Align2::CENTER_CENTER, - tl!("None"), - egui::FontId::proportional(11.5), - Color32::from_gray(140), - ); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(10.5), Color32::from_gray(140)); } } ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); resp.on_hover_text(name); ui.add_sized(vec2(76.0, 14.0), egui::Label::new(egui::RichText::new(name).size(10.5).color(t.text_dim)).truncate()); + if let (Some(key), Some(cur)) = (corner, &choice) { + let current = choices.iter().find(|(id, _)| id == cur).map_or(tl!("None"), |(_, l)| *l); + let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); + if let Some((id, _)) = + widgets::dropdown_named(ui, ("brush-pattern-corner", key), Some(name), current, &labels, 76.0).and_then(|i| choices.get(i)) + { + choose_corner(d, key, id); + } + } }); } }); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 7ca4b316ce..9adeffed1b 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -443,6 +443,110 @@ fn pattern_options_show_the_tiles_and_set_scale_spacing_fit() { assert!((drawn_height(&app, id) / before - 2.0).abs() < 1e-6, "tiles twice the size"); } +/// Each corner tile has a menu below it: Original (only when the brush has corner art), None and +/// the four automatic tiles. OK saves the choice, and an automatic tile or None replaces the art. +#[test] +fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() { + use crate::widgets::accessibility_tests::tree; + let mut app = app(); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("outerCornerTile"), d.str("innerCornerTile")), ("none".into(), "none".into()), "Diamonds has no corner art"); + let shown_tree = tree(|ui| super::super::show(&mut app, ui.ctx())); + for name in ["Outer Corner Tile", "Inner Corner Tile"] { + let roles: Vec<_> = shown_tree.iter().filter(|n| n.label() == Some(name)).map(|n| n.role()).collect(); + assert!(roles.contains(&egui::accesskit::Role::ComboBox), "a menu named {name}: {roles:?}"); + } + for name in ["Side Tile", "Start Tile", "End Tile"] { + assert!(!shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "no menu for {name}"); + } + set(&mut app, json!({"outerCornerTile": "autoBetween", "innerCornerTile": "autoOverlap"})); + let text = shown(&mut app); + assert!(text.contains("Auto-Between") && text.contains("Auto-Overlap"), "{text}"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert_eq!((&def["outer_source"], &def["inner_source"]), (&json!("autoBetween"), &json!("autoOverlap"))); + // Chain has corner art: Original keeps it, None and an automatic tile replace it, one corner + // at a time. + app.run("ui.brushOptions", json!({"name": "Chain"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("outerCornerTile"), d.str("innerCornerTile")), ("original".into(), "original".into())); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + assert!(def["outer_corner"].is_object() && def["inner_corner"].is_object() && def.get("outer_source").is_none(), "{def}"); + app.run("ui.brushOptions", json!({"name": "Chain"})).unwrap(); + set(&mut app, json!({"innerCornerTile": "none"})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + assert!(def["outer_corner"].is_object() && def.get("inner_corner").is_none(), "{def}"); + assert_eq!(def["inner_source"], json!("none")); + app.run("ui.brushOptions", json!({"name": "Chain"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("outerCornerTile"), d.str("innerCornerTile")), ("original".into(), "none".into())); + set(&mut app, json!({"outerCornerTile": "autoSliced"})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + assert!(def.get("outer_corner").is_none() && def.get("inner_corner").is_none(), "{def}"); + assert_eq!((&def["outer_source"], &def["inner_source"]), (&json!("autoSliced"), &json!("none"))); + app.run("ui.brushOptions", json!({"name": "Chain"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("outerCornerTile"), "autoSliced"); +} + +/// A pattern brush with art for one kind of corner draws it at both kinds. Its other corner tile +/// shows that art as Original, and OK keeps it there when the first corner tile changes. +#[test] +fn pattern_options_keep_the_corner_art_a_corner_borrows() { + let mut app = app(); + let art = app.run("brush.get", json!({"name": "Chain"})).unwrap()["outer_corner"].clone(); + app.run("brush.new", json!({"type": "pattern", "name": "One Corner", "params": {"side": art.clone(), "outer_corner": art}})).unwrap(); + app.run("ui.brushOptions", json!({"name": "One Corner"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("outerCornerTile"), d.str("innerCornerTile")), ("original".into(), "original".into())); + set(&mut app, json!({"outerCornerTile": "none"})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "One Corner"})).unwrap(); + assert!(def.get("outer_corner").is_none() && def["inner_corner"].is_object(), "{def}"); + assert_eq!(def["outer_source"], json!("none")); +} + +/// OK leaves the corner fields of a corner tile the menus were not set to as they were: a corner +/// without art keeps borrowing the other kind's art when it gets some, and a corner that borrows +/// art still borrows it. A None picked from the menu is saved, after another choice too. +#[test] +fn pattern_options_ok_leaves_corner_tiles_the_menus_were_not_set_to() { + let mut app = app(); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scale": 150})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("outer_source").is_none() && def.get("inner_source").is_none(), "{def}"); + let art = app.run("brush.get", json!({"name": "Chain"})).unwrap()["outer_corner"].clone(); + app.run("brush.options", json!({"name": "Diamonds", "params": {"outer_corner": art.clone()}})).unwrap(); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("innerCornerTile"), "original", "the inner corners draw the outer art"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def["outer_corner"].is_object() && def.get("inner_corner").is_none(), "{def}"); + + app.run("brush.new", json!({"type": "pattern", "name": "Plain", "params": {"side": art}})).unwrap(); + app.run("ui.brushOptions", json!({"name": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "outerCornerTile", "autoCentered"); + crate::dialogs::brush_art_options::choose_corner(d, "outerCornerTile", "none"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Plain"})).unwrap(); + assert_eq!(def["outer_source"], json!("none")); + assert!(def.get("inner_source").is_none(), "{def}"); + // None set through the control channel is saved too. + app.run("ui.brushOptions", json!({"name": "Plain"})).unwrap(); + let (set, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "innerCornerTile", "value": "none"})); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &egui::Context::default(), &set) else { panic!("not done") }; + assert!(r.get("error").is_none(), "{r}"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Plain"})).unwrap(); + assert_eq!(def["inner_source"], json!("none")); +} + /// Art Brush Options' Width and Pattern Brush Options' Scale each have a slider beside their /// field, which screen readers name as the row, with the field's number and text over the /// value's whole range. diff --git a/crates/ui-egui/src/dialogs/color_guide_options.rs b/crates/ui-egui/src/dialogs/color_guide_options.rs index faeb11e0d2..1fe685e605 100644 --- a/crates/ui-egui/src/dialogs/color_guide_options.rs +++ b/crates/ui-egui/src/dialogs/color_guide_options.rs @@ -45,7 +45,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(10.0); // Preview: the base colour's row of variations. let o = options(app, d); - let base = base_color(app, ui.ctx()); + let base = base_color(app); let n = o.steps as i32; let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::hover()); let w = row.width() / (2 * n + 1) as f32; diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index eb72ae7bb4..60c037597b 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -3,7 +3,8 @@ //! the out-of-gamut and out-of-web warnings (click to correct); New/Original chips; an eyedropper //! button that samples a color anywhere on the screen ([`crate::screen_color`]); and a Color //! Swatches list. With art selected the colour shows on it live as it is picked; OK keeps it as one -//! undo step through `paint.setFill` / `paint.setStroke`, Cancel puts the art back. +//! undo step through `paint.setFill` / `paint.setStroke` and makes the color the Color Guide's +//! base color; Cancel puts the art back. //! Opened for an artboard (Properties › Artboards › Fill), it shows the color on the artboard's //! paper live, and OK keeps it as one undo step through `artboard.setProps {index, color}`. //! Opened over Recolor Artwork (double-click a row's new color), its OK sets that row's new color @@ -636,7 +637,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { return Ok(Value::Null); } let (cmd, params) = paint_command(app, d); - super::form::commit_preview(app, cmd, params) + let c = in_document_model(app, picked(d).color); + let r = super::form::commit_preview(app, cmd, params)?; + // A color picked for the fill or stroke also becomes the Color Guide's base color. + if !d.fields.contains_key("artboard") { + crate::panels::color_guide::choose_base(app, c); + } + Ok(r) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index cc650978b6..4d678b1069 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -275,6 +275,30 @@ fn open_set_hex_and_confirm_fills() { assert_eq!(crate::panels::current_paints(&app).0.color(), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0))); } +/// OK makes the picked fill or stroke color the Color Guide's base color (#3137); Cancel and a +/// color picked for an artboard leave the base as it is. +#[test] +fn ok_makes_the_picked_color_the_color_guides_base() { + let mut app = app(); + let base = |app: &VectorcraftApp| crate::panels::color_guide::base_color(app).to_hex(); + app.ui.color_guide_base = Some(Color::WHITE); + app.run("ui.colorPicker", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("2050a0")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(base(&app), "#2050a0"); + app.run("ui.colorPicker", json!({"stroke": true})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("a02050")); + frame(&mut app); + super::super::cancel(&mut app); + assert_eq!(base(&app), "#2050a0", "Cancel keeps the base"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("artboard.new", json!({})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("00ff00")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(base(&app), "#2050a0", "an artboard's color leaves the base"); +} + /// #1692: Tab goes through one color model's fields before the next: H, S, B, then R, G, B, the /// hex field, then L, a, b, then C, M, Y, K. Each Lab or CMYK field is level with the field on /// its left. diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 06f89ce28f..9e84b39f89 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -131,7 +131,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { ui.horizontal(|ui| { widgets::label_row(ui, tl!("Scale:"), 96.0, |ui| { let mut scale = f.get("scale").and_then(Value::as_str).unwrap_or_default().to_owned(); - let changed = ui.name_inputs(tl!("Scale"), |ui| ui.add(egui::TextEdit::singleline(&mut scale).desired_width(72.0))).changed(); + let changed = ui + .name_inputs(tl!("Scale"), |ui| { + ui.add(egui::TextEdit::singleline(&mut scale).align(egui::Align2::LEFT_CENTER).desired_width(72.0)) + }) + .changed(); if changed { f.insert("scale".into(), json!(scale)); } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index b668f07919..02346ab1f7 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -166,7 +166,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { None if id == TEXTURIZER => glass_fields(app, ui, d, TEXTURIZER), None if id == TRANSFORM => transform_fields(ui, d, app.session.general_unit()), None if id == SCRIBBLE => scribble_fields(ui, d, app.session.general_unit()), - None if id == ZIG_ZAG => zig_zag_fields(ui, d, app.session.general_unit()), + None if id == ZIG_ZAG || id == ROUGHEN => size_fields(ui, d, &id, app.session.general_unit()), + None if id == PUCKER_BLOAT => pucker_bloat_fields(ui, d), + None if id == TWEAK => tweak_fields(ui, d, app.session.general_unit()), None if id == DROP_SHADOW => drop_shadow_fields(ui, d, app.session.general_unit()), None if id == "artistic.filmGrain" => film_grain_fields(ui, d), None if id == free_distort::FREE_DISTORT => { @@ -559,49 +561,77 @@ fn transform_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Un /// The Zig Zag effect (Effect › Distort & Transform › Zig Zag…). const ZIG_ZAG: &str = "distort.zigZag"; -/// Zig Zag's dialog (#1133): Size and Ridges per segment as sliders with their fields, Relative or -/// Absolute and the Points as radio buttons. Returns whether the values differ from those last -/// previewed. -fn zig_zag_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool { - const LABEL_W: f32 = 124.0; - const FIELD_W: f32 = 70.0; +/// The Roughen effect (Effect › Distort & Transform › Roughen…). +const ROUGHEN: &str = "distort.roughen"; + +/// The Pucker & Bloat effect (Effect › Distort & Transform › Pucker & Bloat…). +const PUCKER_BLOAT: &str = "distort.puckerBloat"; + +/// The second slider of [`size_fields`]: Zig Zag's Ridges per segment, Roughen's Detail (per inch), +/// as (key, label, default, suffix). +fn second_slider(effect: &str) -> (&'static str, &'static str, f64, &'static str) { + if effect == ROUGHEN { ("detail", "Detail:", 10.0, "/in") } else { ("ridges", "Ridges per segment:", 4.0, "") } +} + +/// Zig Zag's and Roughen's dialog (#1133, #4488): Size and Ridges per segment (Roughen: Detail) as +/// sliders with their fields, Relative or Absolute and the Points as radio buttons. Returns +/// whether the values differ from those last previewed. +/// The label column and field width of [`relative_rows`] and the sliders under them. +const DISTORT_LABEL_W: f32 = 124.0; +const DISTORT_FIELD_W: f32 = 70.0; + +/// A slider with its field for each of `rows` (key, label, default), each a share of the object's +/// size with Relative or a distance with Absolute, then the Relative and Absolute radio buttons. +fn relative_rows(ui: &mut egui::Ui, d: &mut Dialog, rows: &[(&str, &str, f64)], unit: vectorcraft_doc::Unit) { let rail = Tokens::get(ui.ctx()).input_border; let track = move |_| rail; let relative = d.bool("relative"); - widgets::subheader(ui, tl!("Options")); - // Size is a share of the object's size (Relative) or a distance (Absolute). - widgets::label_row(ui, tl!("Size:"), LABEL_W, |ui| { - let shown = if relative { - Some(widgets::SliderValue::field(d.f64("size", 10.0).clamp(0.0, 100.0), 0.0..=100.0, "%", 0)) - } else { - form::length_value(d, "size", unit, 0.0..=100.0) - }; - form::slider_rail_valued(ui, d, "size", tl!("Size:"), 0.0..=100.0, shown, &track); - if !relative { - form::length(ui, d, "size", unit, FIELD_W); - } else if let Some(n) = widgets::range_field(ui, ("zz", "size"), d.f64("size", 10.0), 0.0..=100.0, "%", 0, FIELD_W) { - d.fields.insert("size".into(), json!(n)); - } - }); + for &(key, label, default) in rows { + widgets::label_row(ui, tl!(label), DISTORT_LABEL_W, |ui| { + let shown = if relative { + Some(widgets::SliderValue::field(d.f64(key, default).clamp(0.0, 100.0), 0.0..=100.0, "%", 0)) + } else { + form::length_value(d, key, unit, 0.0..=100.0) + }; + form::slider_rail_valued(ui, d, key, tl!(label), 0.0..=100.0, shown, &track); + if !relative { + form::length(ui, d, key, unit, DISTORT_FIELD_W); + } else if let Some(n) = widgets::range_field(ui, ("zz", key), d.f64(key, default), 0.0..=100.0, "%", 0, DISTORT_FIELD_W) { + d.fields.insert(key.into(), json!(n)); + } + }); + } ui.horizontal(|ui| { - ui.add_space(LABEL_W + ui.spacing().item_spacing.x); + ui.add_space(DISTORT_LABEL_W + ui.spacing().item_spacing.x); for (label, on) in [(tl!("Relative"), true), (tl!("Absolute"), false)] { if widgets::radio(ui, label, relative == on, true) { d.fields.insert("relative".into(), json!(on)); } } }); - widgets::label_row(ui, tl!("Ridges per segment:"), LABEL_W, |ui| { - form::slider_rail_named(ui, d, "ridges", tl!("Ridges per segment:"), 0.0..=100.0, &track); - if let Some(n) = widgets::range_field(ui, ("zz", "ridges"), d.f64("ridges", 4.0), 0.0..=100.0, "", 0, FIELD_W) { - d.fields.insert("ridges".into(), json!(n)); +} + +fn size_fields(ui: &mut egui::Ui, d: &mut Dialog, effect: &str, unit: vectorcraft_doc::Unit) -> bool { + const LABEL_W: f32 = DISTORT_LABEL_W; + const FIELD_W: f32 = DISTORT_FIELD_W; + let rail = Tokens::get(ui.ctx()).input_border; + let track = move |_| rail; + let size = if effect == ROUGHEN { 5.0 } else { 10.0 }; + widgets::subheader(ui, tl!("Options")); + // Size is a share of the object's size (Relative) or a distance (Absolute). + relative_rows(ui, d, &[("size", "Size:", size)], unit); + let (key, label, default, suffix) = second_slider(effect); + widgets::label_row(ui, tl!(label), LABEL_W, |ui| { + form::slider_rail_named(ui, d, key, tl!(label), 0.0..=100.0, &track); + if let Some(n) = widgets::range_field(ui, ("zz", key), d.f64(key, default), 0.0..=100.0, suffix, 0, FIELD_W) { + d.fields.insert(key.into(), json!(n)); } }); ui.add_space(4.0); widgets::subheader(ui, crate::i18n::tr_ctx(crate::i18n::current(), "effect", "Points")); let points = d.str("points"); ui.horizontal(|ui| { - for (label, value) in choices(ZIG_ZAG, "points").unwrap_or_default() { + for (label, value) in choices(effect, "points").unwrap_or_default() { if widgets::radio(ui, crate::i18n::tr_ctx(crate::i18n::current(), "effect", label), points == *value, true) { d.fields.insert("points".into(), json!(value)); } @@ -610,6 +640,32 @@ fn zig_zag_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit values_changed(d) } +/// The Tweak effect (Effect › Distort & Transform › Tweak…). +const TWEAK: &str = "distort.tweak"; + +/// Tweak's dialog (#4488): Horizontal and Vertical as sliders with their fields (a share of the +/// object's size with Relative, a distance with Absolute), then which points it moves. Returns +/// whether the values differ from those last previewed. +fn tweak_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool { + widgets::subheader(ui, tl!("Amount")); + relative_rows(ui, d, &[("h", "Horizontal:", 10.0), ("v", "Vertical:", 10.0)], unit); + ui.add_space(4.0); + widgets::subheader(ui, tl!("Modify")); + form::check(ui, d, "anchors", tl!("Anchor Points")); + form::check(ui, d, "in", tl!("\"In\" Control Points")); + form::check(ui, d, "out", tl!("\"Out\" Control Points")); + values_changed(d) +} + +/// Pucker & Bloat's dialog (#4488): its amount as a slider from Pucker (−200 %) to Bloat (200 %) +/// with its field. Returns whether the value differs from the one last previewed. +fn pucker_bloat_fields(ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let rail = Tokens::get(ui.ctx()).input_border; + form::slider(ui, d, "amount", tl!("Amount:"), -200.0..=200.0, "%", &move |_| rail); + form::slider_ends(ui, form::SLIDER_LABEL, (tl!("Pucker"), tl!("Bloat"))); + values_changed(d) +} + /// Drop Shadow (Effect › Stylize › Drop Shadow…). const DROP_SHADOW: &str = "stylize.dropShadow"; diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 85be7ab1bd..7d0bfd1099 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -24,9 +24,20 @@ const OPTIONS: [(&str, &str); 3] = [("object", "Object"), ("fill", "Fill"), ("st pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Expand").into(), body, confirm, min_width: 260.0, ..DialogSpec::FORM }; -/// Open Expand for the selection, every option on (as `object.expand {}` does). +/// Why Object › Expand… is dimmed: the selection has appearance attributes, which Expand Appearance +/// turns into plain art first (#3089). +pub(crate) fn appearance_first() -> &'static str { + tl!("Expand Appearance first (Object › Expand Appearance)") +} + +/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with +/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]: +/// the menu item is dimmed for it. pub fn open(app: &mut VectorcraftApp) -> Result { let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; + if info["appearance"] == json!(true) { + return Err(appearance_first().into()); + } let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}); for (key, _) in OPTIONS { fields[format!("__{key}")] = info[key].clone(); @@ -169,4 +180,49 @@ mod tests { let st = app.session.doc().unwrap(); assert!(matches!(st.doc.node(st.selection.objects[0]).unwrap().kind, NodeKind::Path { live: None, .. })); } + + /// A line with a stroke and a Zig Zag effect is selected (#3089). + fn zig_zag_line(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("path.create", json!({"d": "M 20 100 L 180 100"})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("paint.setStroke", json!({"color": "#000000"})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.zigZag", "params": {"size": 10, "ridges": 6, "relative": false}})).unwrap(); + } + + #[test] + fn expand_waits_for_expand_appearance_on_a_line_with_an_effect() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + zig_zag_line(&mut app); + assert!(!crate::menus::enabled(&app, "ui.expandDialog"), "Expand… is dimmed for the Zig Zag effect"); + assert!(crate::menus::enabled(&app, "effect.expandAppearance")); + // A shortcut or the command palette doesn't open it either; the status bar says why. + let before = app.session.doc().unwrap().doc.clone(); + crate::menus::invoke(&mut app, "object.expand", json!({})); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.status, appearance_first()); + assert_eq!(app.run("ui.expandDialog", json!({})).unwrap_err(), appearance_first()); + assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); + // Expand Appearance first: the line stays a stroked line, and Expand… is available for it. + crate::menus::invoke(&mut app, "effect.expandAppearance", json!({})); + let st = app.session.doc().unwrap(); + let line = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(line.appearance.effects.is_empty() && !line.appearance.stroke_paint().is_none()); + assert!(crate::menus::enabled(&app, "ui.expandDialog")); + crate::menus::invoke(&mut app, "object.expand", json!({})); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + } + + #[test] + fn expand_is_dimmed_for_two_fills_but_not_for_a_plain_rectangle() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + assert!(crate::menus::enabled(&app, "ui.expandDialog"), "a basic appearance"); + app.run("appearance.addFill", json!({})).unwrap(); + assert!(!crate::menus::enabled(&app, "ui.expandDialog"), "two fills"); + // Nothing selected: dimmed as before. + app.run("select.none", json!({})).unwrap(); + assert!(!crate::menus::enabled(&app, "ui.expandDialog")); + } } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index ee918ecf4e..32ee696afd 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -103,7 +103,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("all".into(), json!(all)); } let mut range = d.str("range"); - if ui.add_enabled(!all, egui::TextEdit::singleline(&mut range).desired_width(90.0)).changed() { + if ui.add_enabled(!all, egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0)).changed() { d.fields.insert("range".into(), json!(range)); } }); diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index 6db57091fd..b85b67634f 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -67,9 +67,14 @@ fn opened_without(app: &mut VectorcraftApp, root: &Path, names: &[&str]) -> Vec< files } -/// Draw the dialog until its search ends (10 seconds at most). +/// How long a test waits for the dialog's search to end. The wait only ends a test whose search +/// never ends. A machine busy with other builds can hold a walker for seconds. It is shorter than a +/// search's default `maxSeconds` of 60, which would end a search that does not end by itself. +const WAIT: Duration = Duration::from_secs(30); + +/// Draw the dialog until its search ends ([`WAIT`] at most). fn searched(app: &mut VectorcraftApp) { - let until = Instant::now() + Duration::from_secs(10); + let until = Instant::now() + WAIT; while app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching") && Instant::now() < until { frame(app); std::thread::sleep(Duration::from_millis(5)); diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 44ae5eb586..b94f6a7c2e 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -1,13 +1,15 @@ //! Flare Tool Options (double-click the Flare tool, or click with it): the options the Flare tool //! keeps, which draw the next flare dragged out, last across tool switches and are saved with the //! preferences. OK sets them with `tool.setOption {tool: "flare", values}`; opened by a click, it -//! then draws a flare there with them (`shape.flare`, on the active perspective plane while the -//! grid shows). +//! accepts a flare preview there with them (`shape.flare`, on the active perspective plane while the +//! grid shows). While Alt (Option on macOS) is held, Cancel reads Reset, which puts every option +//! back to the tool's default and leaves the dialog open (`ui.dialogReset`). A click-opened +//! dialog previews its settings live; Reset refreshes that preview and Cancel rolls it back. //! //! Fields: the options (`vectorcraft_tools::extra::FLARE_OPTIONS`): `diameter` and `pathLength` //! (points), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and //! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; and -//! `x`, `y` where a click opened it. +//! `x`, `y` where a click opened it, with `preview` on initially for that click. use serde_json::{Map, Value, json}; use vectorcraft_geom::Point; @@ -21,7 +23,15 @@ use crate::{VectorcraftApp, widgets}; /// The dialog kind of the Flare Tool Options. pub const KIND: &str = "flareOptions"; -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Flare Tool Options").into(), body, confirm, min_width: 440.0, ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Flare Tool Options").into(), + body, + confirm, + reset: Some(reset), + preview: true, + min_width: 440.0, + ..DialogSpec::FORM +}; /// Width of the label column and of the fields. const LABEL_W: f32 = 78.0; @@ -35,6 +45,7 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { _ => Map::new(), }; if let Some(p) = at { + fields.insert("preview".into(), json!(true)); fields.insert("x".into(), json!(p.x)); fields.insert("y".into(), json!(p.y)); } @@ -102,23 +113,53 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.end_row(); }); + if let Some((cmd, params)) = preview_command(app, d) { + form::preview(app, ui, d, "Flare", &cmd, params); + } false } +/// A click-created flare previews at that original click; toolbar options draw no artwork. +fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)> { + let at = Point::new(d.fields.get("x")?.as_f64().filter(|v| v.is_finite())?, d.fields.get("y")?.as_f64().filter(|v| v.is_finite())?); + // Use the same clamping and whole-count conversion as accepted tool settings. + let mut tool = vectorcraft_tools::create("flare"); + for (key, default, ..) in FLARE_OPTIONS { + tool.set_option(key, &json!(d.f64(key, default))); + } + for key in ["raysOn", "ringsOn"] { + tool.set_option(key, &json!(d.bool(key))); + } + let params = flare_params(&tool.options(), at); + Some(vectorcraft_engine::perspective_click(&app.session, "shape.flare", ¶ms, at).unwrap_or_else(|| ("shape.flare".into(), params))) +} + +/// Reset (Cancel with Alt or Option held): every option goes back to the Flare tool's default +/// (`FLARE_OPTIONS`, with Rays and Rings on). The dialog keeps a click's `x` and `y`, so OK still draws there. +fn reset(_: &VectorcraftApp, d: &mut Dialog) { + if let Value::Object(defaults) = vectorcraft_tools::create("flare").options() { + d.fields.extend(defaults); + } +} + /// OK: set the tool's options; opened by a click, draw a flare there with them. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let command = preview_command(app, d); + if command.is_none() && (d.fields.contains_key("x") || d.fields.contains_key("y") || d.fields.contains_key(form::PREVIEWED)) { + return Err("Flare click coordinates must be finite numbers".into()); + } let mut values: Map = FLARE_OPTIONS.iter().filter(|(k, ..)| d.fields.contains_key(*k)).map(|(k, default, ..)| (k.to_string(), json!(d.f64(k, *default)))).collect(); for key in ["raysOn", "ringsOn"] { values.insert(key.into(), json!(d.bool(key))); } - let at = d.fields.get("x").and_then(Value::as_f64).zip(d.fields.get("y").and_then(Value::as_f64)).map(|(x, y)| Point::new(x, y)); - let options = run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values }))?; - let Some(at) = at else { return Ok(options) }; - let params = flare_params(&options, at); - match vectorcraft_engine::perspective_click(&app.session, "shape.flare", ¶ms, at) { - Some((id, p)) => app.run(&id, p), - None => app.run("shape.flare", params), + if let Some((cmd, params)) = command { + // Accept the preview once; option persistence follows successful artwork creation. + let result = form::commit_preview(app, &cmd, params)?; + app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; + Ok(result) + } else { + run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) } } @@ -148,6 +189,81 @@ mod tests { children.iter().filter_map(|c| c.name.clone()).collect() } + /// Invalid control-channel coordinates must not turn a click dialog into toolbar options. + #[test] + fn invalid_click_coordinates_keep_the_dialog_and_preview_cancellable() { + for (key, value) in [("x", Value::Null), ("y", Value::Null), ("x", json!("invalid"))] { + let mut app = app(); + let original = app.session.doc().unwrap().doc.layers.clone(); + let depth = app.session.doc().unwrap().history.undo.len(); + let options = app.session.tool_options_of("flare"); + open(&mut app, Some(Point::new(220.0, 330.0))); + painted(&mut app); + let preview = app.session.doc().unwrap().doc.layers.clone(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(key.into(), value); + d.fields.insert("rings".into(), json!(4)); + assert_eq!(super::super::confirm(&mut app).unwrap_err(), "Flare click coordinates must be finite numbers"); + assert!(app.ui.dialog.is_some()); + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc.layers, preview); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth); + assert_eq!(app.session.tool_options_of("flare"), options); + super::super::cancel(&mut app); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc.layers, original); + } + } + + #[test] + fn cancelling_toolbar_options_preserves_an_existing_interaction() { + let mut app = app(); + app.session.begin_interaction("Existing gesture").unwrap(); + app.session.preview("shape.rectangle", &json!({"x":10,"y":10,"width":40,"height":40})).unwrap(); + let previewed = app.session.doc().unwrap().doc.layers.clone(); + open(&mut app, None); + painted(&mut app); + super::super::cancel(&mut app); + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc.layers, previewed); + app.session.cancel_interaction().unwrap(); + } + + #[test] + fn reset_updates_live_preview_and_cancel_discards_art_and_options() { + let mut app = app(); + app.run("tool.setOption", json!({"tool":"flare", "values":{"rings":3}})).unwrap(); + let original = app.session.doc().unwrap().doc.layers.clone(); + let depth = app.session.doc().unwrap().history.undo.len(); + let options = app.session.tool_options_of("flare"); + open(&mut app, Some(Point::new(220.0, 330.0))); + let text = painted(&mut app); + assert!(text.contains("Preview")); + assert_eq!(flare_parts(&app).iter().filter(|s| *s == "Ring").count(), 3); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth); + app.ui.dialog.as_mut().unwrap().fields.insert("rings".into(), json!(4.0)); + painted(&mut app); + assert_eq!(flare_parts(&app).iter().filter(|s| *s == "Ring").count(), 4); + app.run("ui.dialogReset", json!({})).unwrap(); + painted(&mut app); + assert_eq!(flare_parts(&app).iter().filter(|s| *s == "Ring").count(), 10); + assert_eq!(app.session.tool_options_of("flare"), options, "preview doesn't persist options"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc.layers, original); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth); + assert_eq!(app.session.tool_options_of("flare"), options); + // Accepting the same reset preview produces one flare and one Undo step. + open(&mut app, Some(Point::new(220.0, 330.0))); + painted(&mut app); + app.run("ui.dialogReset", json!({})).unwrap(); + painted(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1); + assert_eq!(flare_parts(&app).iter().filter(|s| *s == "Ring").count(), 10); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.layers, original); + } + #[test] fn the_toolbar_opens_the_options_and_ok_keeps_them_for_the_next_drag() { let mut app = app(); @@ -200,4 +316,24 @@ mod tests { let o = app.session.tool_options_of("flare"); assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); } + + #[test] + fn ui_dialog_reset_puts_the_defaults_back_and_keeps_where_a_click_opened_it() { + let mut app = app(); + assert_eq!(app.run("ui.dialogReset", json!({})).unwrap_err(), "no dialog open"); + app.run("tool.setOption", json!({"tool": "flare", "values": {"rings": 3, "raysOn": false, "largest": 120}})).unwrap(); + crate::dialogs::open_tool_dialog(&mut app, "flare", json!({"x": 300, "y": 300})); + let d = app.run("ui.dialogReset", json!({})).unwrap(); + assert_eq!((d["kind"].as_str(), d["fields"]["rings"].as_f64(), d["fields"]["raysOn"].as_bool()), (Some(KIND), Some(10.0), Some(true))); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!((d.f64("largest", 0.0), d.f64("x", 0.0), d.f64("y", 0.0)), (50.0, 300.0, 300.0)); + // The tool keeps its options until OK, which draws the flare with the defaults where the click was. + assert_eq!(app.session.tool_options_of("flare")["rings"].as_u64(), Some(3)); + super::super::confirm(&mut app).unwrap(); + let parts = flare_parts(&app); + assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (10, true), "{parts:?}"); + // A dialog without a Reset refuses it. + app.ui.dialog = Some(Dialog::new("move", json!({"dx": 1}))); + assert_eq!(app.run("ui.dialogReset", json!({})).unwrap_err(), "the open dialog has no Reset"); + } } diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index b4c54ed2ff..3cd0a51110 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -319,16 +319,14 @@ mod tests { #[test] fn ok_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; - // A PNG whose header reads (so it places at its size) but whose pixel data is cut short. + // A PNG whose header reads but whose pixel data is cut short. let mut png = Vec::new(); image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) .unwrap(); - let idat = png.windows(4).position(|w| w == b"IDAT").unwrap(); - png.truncate(idat + 8); for preview in [true, false] { let mut app = scene(); - let placed = app.run("file.place", json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + let placed = vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); // The image is half transparent itself, so Flatten Transparency flattens it wherever it was placed. app.run("transparency.set", json!({"ids": placed["ids"], "opacity": 50})).unwrap(); app.run("select.all", json!({})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f1c45cf184..b82fe54f89 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -181,7 +181,14 @@ fn text_edit_limited_name(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f .inner_margin(egui::Margin::symmetric(6, 3)) .show(ui, |ui| { crate::theme::strong_selected_text(ui); - ui.add(egui::TextEdit::singleline(&mut s).id(id).frame(egui::Frame::NONE).desired_width(width).char_limit(max_chars)) + ui.add( + egui::TextEdit::singleline(&mut s) + .id(id) + .frame(egui::Frame::NONE) + .align(egui::Align2::LEFT_CENTER) + .desired_width(width) + .char_limit(max_chars), + ) }); if r.inner.changed() { d.fields.insert(key.into(), Value::String(s)); @@ -404,7 +411,7 @@ pub(super) fn param_fields( } } Value::String(mut s) => { - if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { + if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(140.0)).changed() { d.fields.insert(k.clone(), json!(s)); changed = true; } diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index fa60dce6e2..783e79093a 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -7,8 +7,10 @@ //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Eraser), `livePreview` (Pencil: the stroke shows -//! with its fill and stroke while it is drawn, or as a thin line until the release) and `size` -//! (points; Blob Brush and Eraser). +//! with its fill and stroke while it is drawn, or as a thin line until the release), `size` +//! (points; Blob Brush and Eraser), and `sizeMode` (`fixed` or `pressure`) and `sizeVariation` +//! (points; Blob Brush and Eraser: with Pressure the tip is Size − Variation wide at the lightest +//! pen pressure and Size + Variation at the heaviest). use serde_json::{Map, Value, json}; @@ -27,11 +29,13 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_wid pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"]; /// The options the dialog edits, in the order it shows them (a tool has those it reports). -const KEYS: [&str; 12] = [ +const KEYS: [&str; 14] = [ "fidelity", "angle", "roundness", "size", + "sizeMode", + "sizeVariation", "fill", "altSmooth", "keepSelected", @@ -134,6 +138,28 @@ fn number(ui: &mut egui::Ui, d: &mut Dialog, (key, label): (&str, &str), suffix: }); } +/// Width of the Blob Brush's and the Eraser's Size mode menu. +const MODE_W: f32 = 96.0; + +/// The Blob Brush's and the Eraser's Size rows: Size with its Fixed or Pressure menu before the +/// field, then the Variation that Pressure adds and takes (greyed while Size is Fixed). +fn blob_size(ui: &mut egui::Ui, d: &mut Dialog) { + const MODES: [&str; 2] = ["fixed", "pressure"]; + let pressure = d.str("sizeMode") == "pressure"; + let labels = ["Fixed", "Pressure"]; + let label_w = label_w(ui) - MODE_W - ui.spacing().item_spacing.x; + let size = d.f64("size", 10.0); + widgets::label_row(ui, tl!("Size:"), label_w, |ui| { + if let Some(m) = widgets::dropdown(ui, "freehand-size-mode", labels[usize::from(pressure)], &labels, MODE_W).and_then(|i| MODES.get(i)) { + d.fields.insert("sizeMode".into(), json!(m)); + } + if let Some(x) = widgets::range_field(ui, ("freehand-field", "size"), size, 0.1..=1000.0, "pt", 1, FIELD_W) { + d.fields.insert("size".into(), json!(x)); + } + }); + ui.add_enabled_ui(pressure, |ui| number(ui, d, ("sizeVariation", tl!("Variation:")), "pt", 1, (0.0, 1000.0))); +} + /// The Fidelity rows: the label on a line of its own, then a logarithmic slider from the tool's /// lowest Fidelity to [`FIDELITY_MAX`] across the row with the field at its end, both to two /// decimals, and Accurate and Smooth under the slider's ends. @@ -182,7 +208,9 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("roundness") { number(ui, d, ("roundness", tl!("Roundness:")), "%", 0, (1.0, 100.0)); } - if d.fields.contains_key("size") { + if d.fields.contains_key("sizeMode") { + blob_size(ui, d); + } else if d.fields.contains_key("size") { number(ui, d, ("size", tl!("Size:")), "pt", 1, (0.1, 1000.0)); } if d.fields.contains_key("fill") { diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 53623a63d8..6d316ef024 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -313,6 +313,30 @@ fn the_blob_brush_options_set_what_a_stroke_merges_with_and_selects() { /// Eraser Tool Options' Angle and Roundness shape the tip the next Eraser drag erases with, /// and the tool keeps them while another tool is chosen. +/// The Blob Brush's and the Eraser's Size is Fixed or Pressure (#4590, #3961), with the Variation +/// Pressure adds and takes; OK sets both, each tool keeping its own, and the Pencil has neither. +#[test] +fn the_blob_brush_and_eraser_size_can_follow_the_pen_pressure() { + let mut app = app(); + for (tool, variation) in [("blobBrush", 6.0), ("eraser", 4.0)] { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let text = painted(&mut app); + assert!(text.contains("Fixed") && text.contains("Variation:"), "{tool}: {text}"); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("sizeMode"), d.f64("sizeVariation", -1.0)), ("fixed".to_string(), 0.0), "{tool}: Fixed with no variation by default"); + d.fields.insert("sizeMode".into(), json!("pressure")); + d.fields.insert("sizeVariation".into(), json!(variation)); + super::super::confirm(&mut app).unwrap(); + let o = app.session.tool_options_of(tool); + assert_eq!((o["sizeMode"].clone(), o["sizeVariation"].as_f64()), (json!("pressure"), Some(variation)), "{tool}"); + app.run("tool.options", json!({"tool": tool})).unwrap(); + assert!(painted(&mut app).contains("Pressure"), "{tool}"); + } + app.run("tool.options", json!({"tool": "pencil"})).unwrap(); + let text = painted(&mut app); + assert!(!text.contains("Variation:") && !text.contains("Fixed"), "{text}"); +} + #[test] fn the_eraser_options_set_the_tips_angle_and_roundness() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index a747353632..c5b7d7e58a 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -379,7 +379,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mut text = d.str("entry"); // The entry box has the keys when the window opens, so Enter moves down instead of applying. widgets::take_dialog_focus(ui, entry_id, &text); - let r = ui.add(egui::TextEdit::singleline(&mut text).id(entry_id).desired_width(260.0)); + let r = ui.add(egui::TextEdit::singleline(&mut text).id(entry_id).align(egui::Align2::LEFT_CENTER).desired_width(260.0)); if r.changed() { d.fields.insert("entry".into(), json!(clean(&text))); } diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 45ec6850f7..eb30028b09 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -297,7 +297,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn password_row(ui: &mut egui::Ui, d: &mut Dialog) { widgets::label_row(ui, tl!("Password"), LABEL_WIDTH, |ui| { let mut s = d.str("password"); - let r = ui.add(egui::TextEdit::singleline(&mut s).password(true).desired_width(180.0)); + let r = ui.add(egui::TextEdit::singleline(&mut s).password(true).align(egui::Align2::LEFT_CENTER).desired_width(180.0)); if r.changed() { d.fields.insert("password".into(), json!(s)); } diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 2dbfdf8101..20266d97b3 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -55,6 +55,11 @@ fn open(app: &mut VectorcraftApp, path: &Path) { crate::io::open_path(app, &path.to_string_lossy()).unwrap(); } +/// How long a test waits for the dialog's search to end. The wait only ends a test whose search +/// never ends. A machine busy with other builds can hold a walker for seconds. It is shorter than a +/// search's default `maxSeconds` of 60, which would end a search that does not end by itself. +const WAIT: Duration = Duration::from_secs(30); + fn kind(app: &VectorcraftApp) -> Option<&str> { app.ui.dialog.as_ref().map(|d| d.kind.as_str()) } @@ -101,7 +106,7 @@ fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() { let r = super::super::confirm(&mut app).unwrap(); assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}"); assert_eq!(kind(&app), Some(KIND), "the dialog stays open while it searches"); - let until = Instant::now() + Duration::from_secs(10); + let until = Instant::now() + WAIT; while app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching") && Instant::now() < until { frame(&mut app); std::thread::sleep(Duration::from_millis(5)); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs new file mode 100644 index 0000000000..1949f00545 --- /dev/null +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -0,0 +1,60 @@ +//! New Character Style and New Paragraph Style: the new style's name. OK makes the style from the +//! text that was selected when the dialog opened (`charStyle.new`, `paraStyle.new`). +//! +//! Fields: `name`, `__para` (true for a paragraph style) and `__target` (the `id`, `start` and +//! `end` of the Type tool's selection, empty for the selected objects, and the `attrs` that text had +//! when the dialog opened). + +use serde_json::{Value, json}; + +use super::swatch_options::{grid, label}; +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of New Character Style and New Paragraph Style. +pub const KIND: &str = "newTextStyle"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +fn para(d: &Dialog) -> bool { + d.fields.get("__para").and_then(Value::as_bool).unwrap_or(false) +} + +fn heading(d: &Dialog) -> String { + if para(d) { tl!("New Paragraph Style") } else { tl!("New Character Style") }.into() +} + +/// Open New Character Style (`para`: New Paragraph Style) with the name `charStyle.new` would give +/// the style, to make it from the text `target` names. +pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result { + let d = &app.session.active().ok_or("no document open")?.doc; + let name = vectorcraft_engine::cmd::textstyles::new_style_name(d, para); + let mut target = target; + if let Some(attrs) = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para) { + target["attrs"] = Value::Object(attrs); + } + app.ui.dialog = Some(Dialog::new(KIND, json!({ "name": name, "__para": para, "__target": target }))); + Ok(json!({ "dialog": KIND })) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + grid(ui, |ui| { + label(ui, tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + false +} + +/// OK: make the style with the name. A name another style has, or an empty one, keeps the dialog +/// open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut params = d.fields.get("__target").filter(|t| t.is_object()).cloned().unwrap_or_else(|| json!({})); + params["name"] = json!(d.str("name")); + let r = app.run(if para(d) { "paraStyle.new" } else { "charStyle.new" }, params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index b767f8dae4..5355ef0f62 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -582,7 +582,7 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } } let mut range = get(d, "range").as_str().unwrap_or_default().to_string(); - let edit = egui::TextEdit::singleline(&mut range).desired_width(140.0).hint_text("1-3, 5"); + let edit = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(140.0).hint_text("1-3, 5"); if ui.add_enabled(artboards == PrintArtboards::Range, edit).changed() { set(d, "range", json!(range)); } diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 7a619878cd..6fa90910a4 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -30,6 +30,15 @@ pub fn fields() -> Value { json!({"layout": "gridByRow", "order": "leftToRight", "columns": 2, "spacing": 20, "moveArtwork": true}) } +/// The fields the menu item opens with, retaining the spacing from its last confirmation. +pub fn open_fields(app: &VectorcraftApp) -> Value { + let mut fields = fields(); + if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { + fields["spacing"] = json!(spacing); + } + fields +} + /// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to /// right. fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) { @@ -110,7 +119,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - run_and_close(app, CMD, params(d)) + let result = run_and_close(app, CMD, params(d))?; + app.ui.rearrange_artboards_spacing = json!(d.f64("spacing", 20.0)); + Ok(result) } #[cfg(test)] @@ -169,6 +180,19 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + /// The spacing confirmed last is the one the dialog opens with next time (#4558). + #[test] + fn keeps_spacing_when_reopening_after_rearranging() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("spacing".into(), json!(37)); + crate::dialogs::confirm(&mut app).unwrap(); + + app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("spacing", 20.0), 37.0); + } + /// Clicking the layout and order toggles sets the fields (the toggles' rects from the frame). #[test] fn the_toggles_set_layout_and_order() { diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index b320897dee..cbf450a6aa 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -87,6 +87,9 @@ fn shown(f: &Format) -> impl Iterator { || (range && o.name == "artboard") || (separate && o.name == "range") || (matches!(f.id, "ai" | "ait") && o.name == "useArtboards") + // EPS Save keeps a page and the complete editing document; cropped and + // selected-only output belongs to Export, never this save dialog. + || (f.id == "eps" && matches!(o.name, "useArtboards" | "selectedOnly")) || (f.id == "ait" && o.name == "aiVersion")) }) } @@ -121,7 +124,7 @@ fn artboard_range(ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("all".into(), json!(all)); } let mut range = d.str("range"); - let field = egui::TextEdit::singleline(&mut range).desired_width(90.0).hint_text("1-3, 5"); + let field = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0).hint_text("1-3, 5"); if ui.add_enabled(!all, field).changed() { d.fields.insert("range".into(), json!(range)); } diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 9c8ae60bb1..fe46331a5e 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -72,7 +72,7 @@ fn save_as_svg_opens_svg_options_then_writes_svg() { // The save panel offers every save format, the document's own first. let pick = &picks.borrow()[0]; let labels: Vec<&str> = pick.filters.iter().map(|f| f.0.as_str()).collect(); - assert_eq!(labels, ["VectorCraft", "VectorCraft Template", "PDF", "SVG", "SVG Compressed", "PDF-compatible .ai"]); + assert_eq!(labels, ["VectorCraft", "VectorCraft Template", "PDF", "SVG", "SVG Compressed", "PDF-compatible .ai", "EPS"]); assert_eq!(pick.name, "Untitled-1.vectorcraft"); let d = dialog(&app); assert_eq!((d.kind.as_str(), d.str("path").as_str(), d.str("mode").as_str()), ("svgOptions", "art.svg", "save")); @@ -332,3 +332,18 @@ fn save_as_pdf_asks_with_the_save_pdf_dialog_and_remembers_its_options() { assert_eq!(dialog(&app).str("compatibility"), "1.5"); assert_eq!(dialog(&app).str("__save"), "file.saveCopy"); } + +#[test] +fn eps_save_as_keeps_page_options_and_writes_eps_without_export_only_switches() { + let (mut app, written, _) = desktop("art.eps"); + app.run("file.saveAs", json!({})).unwrap(); + let names: Vec<_> = shown(fileio::format("eps").unwrap()).map(|option| option.name).collect(); + assert!(!names.contains(&"useArtboards") && !names.contains(&"selectedOnly")); + assert!(names.contains(&"previewFormat")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let saved = written.borrow(); + assert_eq!(saved[0].0, "art.eps"); + assert!(vectorcraft_eps::native(&saved[0].1).is_some()); + assert_eq!(app.session.active().unwrap().format, "eps"); +} diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 4b8fc33c6d..72a8d64ac9 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -321,7 +321,7 @@ pub(super) fn length(ui: &mut egui::Ui, d: &mut Dialog, path: &str, unit: Unit, pub(super) fn text(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) { let mut s = get(d, path).as_str().unwrap_or_default().to_string(); - if ui.add_enabled(enabled, egui::TextEdit::singleline(&mut s).desired_width(240.0)).changed() { + if ui.add_enabled(enabled, egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(240.0)).changed() { set(d, path, json!(s)); } } @@ -493,7 +493,10 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) { d.fields.insert("__allArtboards".into(), json!(all)); } let mut range = d.str("range"); - if ui.add_enabled(!all, egui::TextEdit::singleline(&mut range).desired_width(140.0).hint_text("1-3, 5")).changed() { + if ui + .add_enabled(!all, egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(140.0).hint_text("1-3, 5")) + .changed() + { d.fields.insert("range".into(), json!(range)); } }); @@ -700,7 +703,7 @@ fn password_check(ui: &mut egui::Ui, d: &mut Dialog, path: &str, flag: &str, lab fn password_field(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) { let mut s = get(d, path).as_str().unwrap_or_default().to_string(); - if ui.add_enabled(enabled, egui::TextEdit::singleline(&mut s).password(true).desired_width(200.0)).changed() { + if ui.add_enabled(enabled, egui::TextEdit::singleline(&mut s).password(true).align(egui::Align2::LEFT_CENTER).desired_width(200.0)).changed() { set(d, path, json!(s)); } } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index fc766c6d6e..6ef85620a8 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -131,15 +131,13 @@ fn warnings_reach_the_status_and_errors_keep_the_dialog_open() { #[test] fn an_image_that_couldnt_be_decoded_is_named_in_the_status() { let (mut app, written, _) = app(); - // A PNG whose header reads (so it places at its size) but whose pixel data is cut short. - let mut cut = vec![]; + // A PNG whose header reads but whose pixel data is cut short. + let mut png = vec![]; image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut cut), image::ImageFormat::Png) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) .unwrap(); - let idat = cut.windows(4).position(|w| w == b"IDAT").unwrap(); - cut.truncate(idat + 8); // The image is placed on the first artboard. - app.run("file.place", json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(&cut), "at": [60, 50]})).unwrap(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [60, 50]})); app.run("ui.savePdfDialog", json!({"path": "/tmp/cut.pdf"})).unwrap(); super::super::confirm(&mut app).unwrap(); assert_eq!(app.ui.status, "Saved /tmp/cut.pdf with 1 note(s): an image couldn't be decoded and is missing from the picture"); diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index bc9f2916ff..392c043f35 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -181,6 +181,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); } else if d.kind == "arc" { arc_form(ui, d, unit); + } else if LINKED.contains(&d.kind.as_str()) { + linked_size_form(ui, d, unit); } else { form::grid(ui, d, unit); } @@ -227,7 +229,17 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { if d.f64("lengthY", 100.0) != ly0 { arc_pin_to_anchor(d); } - form::choice(ui, d, "arcType", tl!("Type:"), (form::FIELD_W, form::FIELD_W - 12.0), &[("open", tl!("Open")), ("closed", tl!("Closed"))]); + form::choice( + ui, + d, + "arcType", + tl!("Type:"), + (form::FIELD_W, form::FIELD_W - 12.0), + &[ + ("open", crate::i18n::tr_ctx(crate::i18n::current(), "shape", "Open")), + ("closed", crate::i18n::tr_ctx(crate::i18n::current(), "shape", "Closed")), + ], + ); form::choice( ui, d, @@ -250,6 +262,102 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { form::check(ui, d, "fillArc", tl!("Fill Arc")); } +/// The click dialogs whose Width and Height share a Constrain Width and Height Proportions link +/// (, +/// ): the same +/// link as the Transform panel's ([`crate::panels::transform::constrain_link`]), drawn the same way. +const LINKED: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"]; + +/// The dialog field holding the link's state (UI-only, as every `__` field is). +const LINK: &str = "__constrain"; + +/// The dialog field holding the link state the dialog last applied ([`link_changed`]): a change of +/// [`LINK`], by its button or from outside (`ui.dialog.set`), shows as a difference from it. +const APPLIED: &str = "__constrainApplied"; + +/// The dialog field holding height ÷ width while the link is on: the proportions it keeps. +const RATIO: &str = "__ratio"; + +/// Where the link's state waits for the next of these dialogs (egui memory, this run only). +const LINK_STATE: &str = "shape-size-link"; + +/// Width and Height (then a rounded rectangle's radius) with the Constrain Width and Height +/// Proportions link beside the two size rows. While it is on, typing one side sets the other, so +/// the shape keeps the proportions it had when the link was turned on. The next of these dialogs +/// opens with the link as this one left it. +fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { + if !d.fields.contains_key(LINK) { + d.fields.insert(LINK.into(), json!(crate::panels::pstate::(ui.ctx(), LINK_STATE))); + } + sync_link(ui.ctx(), d); + const BUTTON: f32 = 22.0; + let mut rows: Option = None; + egui::Grid::new("shape-size-dlg").num_columns(3).spacing([10.0, 8.0]).show(ui, |ui| { + for (key, label) in [("width", "Width:"), ("height", "Height:")] { + let row = form::row_label(ui, label); + if ui.label_inputs_by(row.id, |ui| form::length(ui, d, key, unit, form::FIELD_W)) { + follow_link(d, key); + } + // The link's column: the button is drawn over both rows' cells once the grid is laid out. + let (_, cell) = ui.allocate_space(egui::vec2(BUTTON, BUTTON)); + rows = Some(rows.map_or(cell, |r| r.union(cell))); + ui.end_row(); + } + if d.kind == "roundedRectangle" { + form::length_field(ui, d, "radius", &form::humanized("radius"), unit); + } + }); + let Some(rows) = rows else { return }; + let on = d.bool(LINK); + let rect = egui::Rect::from_center_size(rows.center(), egui::vec2(BUTTON, BUTTON)); + let resp = ui.interact(rect, ui.scope_id().with("shape-size-link"), egui::Sense::click()); + let icon = if on { "link" } else { "link-2-off" }; + if widgets::paint_icon_button(ui, resp, icon, "Constrain Width and Height Proportions", on).clicked() { + d.fields.insert(LINK.into(), json!(!on)); + sync_link(ui.ctx(), d); + } +} + +/// Apply a change of the link's state, however it was made ([`link_changed`]), and keep the new +/// state for the next of these dialogs. +fn sync_link(ctx: &egui::Context, d: &mut Dialog) { + if let Some(on) = link_changed(d) { + crate::panels::set_pstate(ctx, LINK_STATE, on); + } +} + +/// When the link's state differs from the one the dialog last applied (or none was applied yet), +/// apply it and return it: turned on, the link keeps the proportions of the sizes the dialog shows +/// then; turned off, it forgets them. A side of zero when it turns on leaves nothing to keep, so +/// typing changes only the side typed until the link is turned off and on again. +fn link_changed(d: &mut Dialog) -> Option { + let on = d.bool(LINK); + if d.fields.get(APPLIED).and_then(Value::as_bool) == Some(on) { + return None; + } + d.fields.insert(APPLIED.into(), json!(on)); + let ratio = d.f64("height", 100.0) / d.f64("width", 100.0); + if on && ratio.is_finite() && ratio != 0.0 { + d.fields.insert(RATIO.into(), json!(ratio)); + } else { + d.fields.remove(RATIO); + } + Some(on) +} + +/// After the side `typed` ("width" or "height") was typed with the link on, set the other side +/// from the proportions the link keeps. +fn follow_link(d: &mut Dialog, typed: &str) { + let ratio = d.f64(RATIO, 0.0); + if !d.bool(LINK) || !ratio.is_finite() || ratio == 0.0 { + return; + } + let (other, v) = if typed == "width" { ("height", d.f64("width", 100.0) * ratio) } else { ("width", d.f64("height", 100.0) / ratio) }; + if v.is_finite() { + d.fields.insert(other.into(), json!(v)); + } +} + /// The top-left corner of a rectangle or ellipse: the click itself, or with Alt held (draw from centre) the click minus half the size. fn box_origin(d: &Dialog) -> (f64, f64) { let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); @@ -402,6 +510,145 @@ mod tests { assert_eq!(box_origin(&fields(true)), (80.0, 40.0)); } + /// Turn the link on or off as its button or `ui.dialog.set` does, then apply it as the form + /// does on its next frame; what [`link_changed`] returned. + fn turn(d: &mut Dialog, on: bool) -> Option { + d.fields.insert(LINK.into(), json!(on)); + link_changed(d) + } + + fn type_size(d: &mut Dialog, typed: &str, value: f64) -> (f64, f64) { + d.fields.insert(typed.into(), json!(value)); + follow_link(d, typed); + // The form applies the link's state again on every frame: an unchanged state changes nothing. + assert_eq!(link_changed(d), None); + (d.f64("width", -1.0), d.f64("height", -1.0)) + } + + #[test] + fn the_link_keeps_the_proportions_it_had_when_turned_on() { + let mut d = Dialog::new("rectangle", json!({"x": 0.0, "y": 0.0, "width": "40 pt", "height": "20 pt"})); + // Off: a typed side changes only itself. + assert_eq!(turn(&mut d, false), Some(false)); + assert_eq!(type_size(&mut d, "width", 80.0), (80.0, 20.0)); + // On at 80 × 20: each side follows the other at 4 : 1, also through a zero and back. + assert_eq!(turn(&mut d, true), Some(true)); + for (typed, value, expected) in + [("width", 100.0, (100.0, 25.0)), ("height", 50.0, (200.0, 50.0)), ("width", 0.0, (0.0, 0.0)), ("width", 40.0, (40.0, 10.0))] + { + assert_eq!(type_size(&mut d, typed, value), expected, "{typed} = {value}"); + } + } + + /// Turned off and on again from outside the dialog (`ui.dialog.set`), the link forgets the old + /// proportions and keeps the ones the dialog shows when it comes back on. + #[test] + fn the_link_follows_changes_made_from_outside_the_dialog() { + let mut d = Dialog::new("rectangle", json!({"width": 80.0, "height": 20.0})); + assert_eq!(turn(&mut d, true), Some(true)); + assert_eq!(turn(&mut d, false), Some(false)); + assert!(!d.fields.contains_key(RATIO)); + assert_eq!(type_size(&mut d, "width", 30.0), (30.0, 20.0)); + assert_eq!(type_size(&mut d, "height", 60.0), (30.0, 60.0)); + assert_eq!(turn(&mut d, true), Some(true)); + assert_eq!(type_size(&mut d, "width", 10.0), (10.0, 20.0)); + // Set to what it already is: nothing to apply, the proportions stay. + assert_eq!(turn(&mut d, true), None); + assert_eq!(type_size(&mut d, "height", 40.0), (20.0, 40.0)); + } + + /// A side of zero when the link turns on leaves nothing to keep (no NaN): typing changes only + /// the side typed, even once both sides are sizes again, until the link is turned on again. + #[test] + fn a_link_turned_on_at_a_zero_side_stays_unconstrained_until_turned_on_again() { + let mut d = Dialog::new("ellipse", json!({"width": 0.0, "height": 30.0})); + assert_eq!(turn(&mut d, true), Some(true)); + assert!(!d.fields.contains_key(RATIO)); + assert_eq!(type_size(&mut d, "width", 50.0), (50.0, 30.0)); + assert_eq!(type_size(&mut d, "height", 60.0), (50.0, 60.0)); + assert!(!d.fields.contains_key(RATIO)); + assert_eq!((turn(&mut d, false), turn(&mut d, true)), (Some(false), Some(true))); + assert_eq!(type_size(&mut d, "width", 100.0), (100.0, 120.0)); + } + + /// The real dialog: Width comes before Height, the link is a named button that turns on with a + /// click, and the next Rectangle dialog opens with it on. + #[test] + fn the_rectangle_dialog_shows_width_then_height_and_a_link_button() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + const LINK_NAME: &str = "Constrain Width and Height Proportions"; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 10.0, "y": 10.0})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h.check_accessibility(); + let (w, ht) = (h.get_by_role_and_label(Role::TextInput, "Width:").rect(), h.get_by_role_and_label(Role::TextInput, "Height:").rect()); + assert!(w.center().y < ht.center().y, "Width is above Height: {w:?} {ht:?}"); + assert!(!h.state().ui.dialog.as_ref().unwrap().bool(LINK)); + let link = h.get_by_role_and_label(Role::Button, LINK_NAME).rect(); + assert!(link.left() > w.right() && link.top() < ht.center().y && link.bottom() > w.center().y, "the link sits beside both rows: {link:?}"); + h.get_by_role_and_label(Role::Button, LINK_NAME).click(); + h.run_steps(2); + let d = h.state().ui.dialog.as_ref().unwrap(); + assert!(d.bool(LINK)); + assert_eq!(d.f64(RATIO, 0.0), 1.0); + // Cancel, then click again: the link is still on. + let reopen = |h: &mut egui_kittest::Harness<'_, VectorcraftApp>| { + h.state_mut().ui.dialog = None; + h.run_steps(2); + super::super::open_tool_dialog(h.state_mut(), "rectangle", json!({"x": 10.0, "y": 10.0})); + h.run_steps(2); + h.state().ui.dialog.as_ref().unwrap().bool(LINK) + }; + assert!(reopen(&mut h)); + // Turned off from outside the dialog (`ui.dialog.set`): the next dialog opens with it off. + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert(LINK.into(), json!(false)); + h.run_steps(2); + assert!(!h.state().ui.dialog.as_ref().unwrap().fields.contains_key(RATIO)); + assert!(!reopen(&mut h)); + } + + /// With the link on, typing a width over a 40 × 20 rectangle's and pressing Enter draws it + /// 80 × 40. + #[test] + fn typing_a_width_with_the_link_on_draws_the_shape_in_proportion() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "rectangle"})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 10.0, "y": 10.0})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("width".into(), json!(40.0)); + d.fields.insert("height".into(), json!(20.0)); + d.fields.insert(LINK.into(), json!(true)); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("80 pt".into())]); + frame(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none()); + let doc = &app.session.doc().unwrap().doc; + let b = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((b.width() - 80.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "{b:?}"); + } + #[test] fn a_negative_line_length_draws_and_keeps_the_same_direction() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index ab32ada066..c65b4e6022 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -667,7 +667,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Name:")).color(t.text_dim)); let mut name = d.str("name"); - if ui.add(egui::TextEdit::singleline(&mut name).desired_width(260.0)).changed() { + if ui.add(egui::TextEdit::singleline(&mut name).align(egui::Align2::LEFT_CENTER).desired_width(260.0)).changed() { d.fields.insert("name".into(), json!(name)); } }); @@ -867,7 +867,7 @@ fn rows_section(ui: &mut egui::Ui, d: &mut Dialog, review: &mut Review, statuses } ui.add_space(8.0); let mut q = d.str("__query"); - if ui.add(egui::TextEdit::singleline(&mut q).hint_text(tl!("Search")).desired_width(180.0)).changed() { + if ui.add(egui::TextEdit::singleline(&mut q).align(egui::Align2::LEFT_CENTER).hint_text(tl!("Search")).desired_width(180.0)).changed() { d.fields.insert("__query".into(), json!(q)); } }); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index caf898fddc..cf38660188 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -8,6 +8,8 @@ //! (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html). //! `vectorcraft_pathops::simplify_level_tolerance` maps levels to tolerances. //! +//! The strip itself ([`Strip`]) is shared with Object › Path › Smooth's slider (`smooth_slider`). +//! //! Fields: `level` (0..=100, the command's parameter). use egui::{Color32, CornerRadius, Order, Pos2, Sense, Stroke, vec2}; @@ -25,9 +27,122 @@ pub(crate) const KIND: &str = "simplifySlider"; pub(super) const SPEC: DialogSpec = DialogSpec { window: Some(show), confirm, preview: true, ..DialogSpec::FORM }; -/// The command the slider previews, and its undo label. -const CMD: &str = "object.path.simplify"; -const LABEL: &str = "Simplify"; +/// What the Simplify slider previews, and its buttons. +const STRIP: Strip = Strip { + kind: KIND, + cmd: "object.path.simplify", + label: "Simplify", + default_level: SIMPLIFY_LEVEL, + auto: ("Auto-Simplify", auto), + more_options: Some(more_options), +}; + +/// A UI command a button of a strip runs. +type Button = fn(&mut VectorcraftApp) -> Result; + +/// A slider strip under the selection that previews `cmd {level}` while it is open: its first +/// button picks the level `cmd {auto: true}` does, and an optional last one, More Options, opens a +/// dialog in its place. Enter or a click outside the strip keeps the result as one undo step, and +/// Escape puts the paths back. +pub(super) struct Strip { + /// The dialog kind. + pub kind: &'static str, + /// The command previewed. + pub cmd: &'static str, + /// The undo step's name, and the slider's. + pub label: &'static str, + /// The level when the field holds no number. + pub default_level: f64, + /// The auto button's tip, and what it runs. + pub auto: (&'static str, Button), + /// What More Options runs, when the strip has it. + pub more_options: Option