diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 054395d796..b9fd0b98e6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -865,11 +865,11 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; -#[cfg(test)] -pub(crate) use paint::PAINTS_READ; /// What the fill and stroke proxies read from the selected objects, kept with the selection /// ([`crate::doc_state::SelectionRecord`]). pub(crate) use paint::SelectionPaints; +#[cfg(test)] +pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ}; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see /// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`. diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b8136e8cf5..9bb39e1e96 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -398,21 +398,26 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' thread_local! { /// Tests: how many fills [`SelectionPaints`] read or took out on this thread. pub(crate) static PAINTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many stroke weights [`SelectionPaints`] read or took out on this thread. + pub(crate) static WEIGHTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]): /// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group, -/// as [`painted`] expands them. An id with no object and a ruler guide count once each. +/// as [`painted`] expands them. An id with no object and a ruler guide count once each. A type +/// object counts once for each of its runs, since the stroke weights are read run by run. struct Reads<'a> { doc: &'a Document, ids: std::slice::Iter<'a, NodeId>, /// The contents not counted yet of the objects met, innermost last. left: Vec>>, + /// The runs not counted yet of the type object met last. + runs: usize, } impl<'a> Reads<'a> { fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self { - Self { doc, ids: ids.iter(), left: vec![] } + Self { doc, ids: ids.iter(), left: vec![], runs: 0 } } } @@ -420,6 +425,10 @@ impl Iterator for Reads<'_> { type Item = (); fn next(&mut self) -> Option<()> { + if self.runs > 0 { + self.runs -= 1; + return Some(()); + } loop { let (n, top) = match self.left.last_mut() { Some(contents) => match contents.next() { @@ -447,6 +456,9 @@ impl Iterator for Reads<'_> { if let Some(contents) = n.children().filter(|_| expand) { self.left.push(contents.iter()); } + if let NodeKind::Text(t) = &n.kind { + self.runs = t.runs.len().saturating_sub(1); + } return Some(()); } } @@ -618,6 +630,8 @@ impl SelectionPaints { NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(), _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; + #[cfg(test)] + WEIGHTS_READ.with(|c| c.set(c.get() + widths.len())); for w in widths { if add { self.weight.add(w, |a, b| a == b); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 9fc02b0e88..0394fb18fa 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -788,3 +788,28 @@ fn deselecting_a_small_group_beside_a_large_one_takes_out_only_its_objects() { let fills = read() - before; assert!(fills <= 100, "read or took out {fills} fills"); } + +/// Taking a type object of 10,000 runs out of a selection that keeps two squares reads the two +/// squares' stroke weights again instead of taking the 10,000 run weights out of them. +#[test] +fn deselecting_type_of_many_runs_reads_the_objects_left() { + let mut s = session(3, |d, k| match k { + 0 => { + let style = vectorcraft_doc::CharStyle::default(); + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "x", style.clone()); + t.runs = (0..10_000).map(|_| vectorcraft_doc::TextRun::new("x", style.clone())).collect(); + Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))) + } + _ => square(d, k), + }); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let read = || crate::cmd::WEIGHTS_READ.with(std::cell::Cell::get); + let before = read(); + s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap(); + assert!(selected(&s, &ids[1..])); + let weights = read() - before; + assert!(weights <= 100, "read or took out {weights} stroke weights"); +} diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 307f2c988e..cd5cacac97 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -9,12 +9,19 @@ use vectorcraft_geom::BezPath; /// Vello flattens the two sides of a filled stroke independently at 0.25 device pixels. /// For strokes narrower than four times the raster tolerance, fit and preflatten the /// band more tightly. Wider strokes and the document/export geometry are unchanged. +/// +/// A plain stroke (no dashes, no width profile) along a line with curves is drawn as lines first +/// ([`thin_line`]) and outlined by [`thin_band`], with one line on each side for each line of the +/// path. Other thin strokes are fitted and flattened at the fine tolerance. pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> BezPath { if width >= tol * 4.0 { return effects::stroke::line_outline(line, st, width, tol); } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + return band; + } let outline = effects::stroke::line_outline(line, st, width, fine); let mut flat = BezPath::new(); // Keep upstream's per-curve work cap for untrusted or extreme coordinates. @@ -22,6 +29,169 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> flat } +/// The lines a thin stroke's curves are drawn with lie within about this share of its width of the +/// curve, before their ends are moved out ([`draw_lines`]). +const THIN_CHORD: f64 = 1.0 / 6.0; +/// Where two lines of a thin stroke meet at an angle whose sine is at most this, and turn by less +/// than a right angle, [`thin_band`] offsets both sides to where the two lines' offsets cross, +/// whatever the stroke's join. +const THIN_SMOOTH: f64 = 0.8; + +/// `line` with all its curves drawn as lines within about [`THIN_CHORD`] of `width` of them, for a +/// stroke `st` narrower than four raster tolerances ([`outline`]). `None` for a stroke with a width +/// profile or dashes, for a line with no curves, and when a curve can't be drawn as lines +/// ([`lines`]). +fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { + if st.profile.is_some() || st.dash.is_some() || !(width > 0.0 && width.is_finite()) { + return None; + } + let lines = lines(line, 0.0, width * THIN_CHORD)?; + lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) +} + +/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill +/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the +/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a +/// point that isn't finite, or is closed and no wider or taller than the stroke: those take +/// [`effects::stroke::line_outline`]. +fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { + let h = width / 2.0; + // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. + let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); + let mut out = BezPath::new(); + let mut pts: Vec = Vec::new(); + let mut closed = false; + let flush = |pts: &mut Vec, closed: bool, out: &mut BezPath| -> Option<()> { + if pts.is_empty() { + return Some(()); + } + if closed && pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + if pts.len() < 2 || !pts.iter().all(|p| p.is_finite()) { + return None; + } + if closed { + let (lo, hi) = + pts.iter().fold((pts[0], pts[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))); + if (hi.x - lo.x).min(hi.y - lo.y) <= width { + return None; + } + } + band_sub(out, pts, closed, st, h, step); + pts.clear(); + Some(()) + }; + for el in lines.elements() { + match *el { + PathEl::MoveTo(p) => { + flush(&mut pts, closed, &mut out)?; + closed = false; + pts.push(p); + } + PathEl::LineTo(p) => { + if pts.last() != Some(&p) { + pts.push(p); + } + } + PathEl::ClosePath => closed = true, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, + } + } + flush(&mut pts, closed, &mut out)?; + Some(out) +} + +/// Adds the outline of one subpath with the distinct points `pts` (at least two, the last not +/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, +/// the end cap, its right side backward and the start cap; for a closed one its left side and its +/// right side backward, as two contours. `h` is half the width and `step` the angle between the +/// points of a round join or cap. +fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { + use vectorcraft_doc::{LineCap, LineJoin}; + let n = pts.len(); + let chords = if closed { n } else { n - 1 }; + // The direction of line `i` (from point `i` to the next) as a unit vector, and its normal. + let dir = |i: usize| (pts[(i + 1) % n] - pts[i % n]).normalize(); + let norm = |u: Vec2| Vec2::new(-u.y, u.x); + // Points on an arc of radius `h` around `c` from `from` to `to` (both of length `h`), turning + // by `angle` (positive: from `from` toward its normal), without its first point. + let arc = |side: &mut Vec, c: Point, from: Vec2, angle: f64| { + let k = (angle.abs() / step).ceil().max(1.0) as usize; + for j in 1..=k { + let a = angle * j as f64 / k as f64; + let (s, co) = a.sin_cos(); + side.push(c + Vec2::new(from.x * co - from.y * s, from.x * s + from.y * co)); + } + }; + let (mut left, mut right) = (Vec::with_capacity(n + 2), Vec::with_capacity(n + 2)); + let join = |left: &mut Vec, right: &mut Vec, p: Point, ua: Vec2, ub: Vec2| { + let (na, nb) = (norm(ua) * h, norm(ub) * h); + let (cross, dot) = (ua.cross(ub), ua.dot(ub)); + // Where the offsets of the two lines cross, on the right side; the left one is opposite. + let miter = (na + nb) / (1.0 + dot); + if dot > 0.0 && cross.abs() <= THIN_SMOOTH { + left.push(p - miter); + right.push(p + miter); + return; + } + // The outer side of the turn: the left side when the path turns toward its normal. + let (outer, inner, sign) = if cross > 0.0 { (left, right, -1.0) } else { (right, left, 1.0) }; + inner.push(p - na * sign); + inner.push(p); + inner.push(p - nb * sign); + outer.push(p + na * sign); + match st.join { + LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), + LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), + LineJoin::Miter | LineJoin::Bevel => {} + } + outer.push(p + nb * sign); + }; + if closed { + for (i, &p) in pts.iter().enumerate() { + join(&mut left, &mut right, p, dir(i + n - 1), dir(i)); + } + contour(out, left.iter().copied()); + contour(out, right.iter().rev().copied()); + return; + } + let (first, last) = (dir(0), dir(chords - 1)); + let square = |u: Vec2| if st.cap == LineCap::Square { u * h } else { Vec2::ZERO }; + left.push(pts[0] - norm(first) * h - square(first)); + right.push(pts[0] + norm(first) * h - square(first)); + for (i, &p) in pts.iter().enumerate().take(chords).skip(1) { + join(&mut left, &mut right, p, dir(i - 1), dir(i)); + } + let end = pts[n - 1]; + left.push(end - norm(last) * h + square(last)); + right.push(end + norm(last) * h + square(last)); + let mut ring = left; + if st.cap == LineCap::Round { + arc(&mut ring, end, -norm(last) * h, std::f64::consts::PI); + ring.pop(); + } + ring.extend(right.iter().rev().copied()); + if st.cap == LineCap::Round { + arc(&mut ring, pts[0], norm(first) * h, std::f64::consts::PI); + ring.pop(); + } + contour(out, ring.into_iter()); +} + +/// Adds the closed contour through `pts` to `out`. +fn contour(out: &mut BezPath, mut pts: impl Iterator) { + if let Some(p) = pts.next() { + out.move_to(p); + for p in pts { + out.line_to(p); + } + out.close_path(); + } +} + /// Strokes at least this many tolerances wide (8 device pixels at a tolerance of 0.25 px) have /// their long curves drawn as lines by [`wide`]. const WIDE: f64 = 32.0; @@ -63,7 +233,7 @@ pub(crate) fn wide(outline: BezPath, width: f64, tol: f64) -> BezPath { if !(tol > 0.0 && tol.is_finite() && width >= tol * WIDE) { return outline; } - lines(&outline, tol).unwrap_or(outline) + lines(&outline, tol * SPAN, tol * CHORD).unwrap_or(outline) } /// One subpath: where it starts, its segments, each with the most steps it is drawn with as lines @@ -74,11 +244,11 @@ struct Sub { closed: bool, } -/// `path` with its long curves drawn as lines ([`wide`]); `None` when it has no long curve, would +/// `path` with its curves whose control points span at least `span` across or down drawn as lines +/// within about `chord` of them ([`wide`], [`thin_line`]); `None` when it has no such curve, would /// take more than [`MAX_LINES`] lines, or does not start each subpath with a move. -fn lines(path: &BezPath, tol: f64) -> Option { - let chord = tol * CHORD; - let subs = subpaths(path.elements(), tol, chord)?; +fn lines(path: &BezPath, span: f64, chord: f64) -> Option { + let subs = subpaths(path.elements(), span, chord)?; let mut total = 0usize; for (_, steps) in subs.iter().flat_map(|s| &s.segs) { if *steps > 0 { @@ -98,7 +268,7 @@ fn lines(path: &BezPath, tol: f64) -> Option { /// The subpaths of `els`, each segment with its steps ([`steps`]). A close adds a line back to the /// start when the subpath ends elsewhere. `None` when a segment comes before any move or after a /// close without a move. -fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option> { +fn subpaths(els: &[PathEl], span: f64, chord: f64) -> Option> { let mut subs: Vec = Vec::new(); for el in els { if let PathEl::MoveTo(p) = *el { @@ -122,7 +292,7 @@ fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option> { continue; } }; - sub.segs.push((seg, steps(seg, tol, chord))); + sub.segs.push((seg, steps(seg, span, chord))); } Some(subs) } @@ -137,10 +307,10 @@ fn cubic(seg: PathSeg) -> Option { } /// How many equal steps of its parameter keep the chords of curve `seg` within `chord` of it (by -/// the second differences of its control points), when its control points span at least [`SPAN`] -/// times `tol`; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a curve -/// that would take more than [`MAX_LINES`] steps. -fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize { +/// the second differences of its control points), when its control points span at least `min` +/// across or down; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a +/// curve that would take more than [`MAX_LINES`] steps. +fn steps(seg: PathSeg, min: f64, chord: f64) -> usize { let Some(c) = cubic(seg) else { return 0 }; let pts = [c.p0, c.p1, c.p2, c.p3]; if !pts.iter().all(|p| p.is_finite()) { @@ -150,7 +320,7 @@ fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize { (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) }); let span = (hi.x - lo.x).max(hi.y - lo.y); - if !span.is_finite() || span < tol * SPAN { + if !span.is_finite() || span < min { return 0; } let second = |a: Point, b: Point, c: Point| (a.to_vec2() - b.to_vec2() * 2.0 + c.to_vec2()).hypot(); @@ -175,13 +345,19 @@ fn end_tangent(c: &CubicBez) -> Option { /// How many pieces of a curve [`params`] measures its bending on. const SAMPLES: usize = 32; +/// A chord whose curve lies more than this many times `chord` from it ([`off_chord`]) is drawn with +/// more steps ([`params`]). +const FIT: f64 = 2.0; + /// The parameters curve `c` has its line ends at, and whether its first and its last step are /// halves. Each step holds an equal share of the curve's bending (the integral of the square root /// of its curvature along it), and there are as many as keep each chord within about `chord` of the -/// curve, at most `most` (its equal steps, [`steps`]). The steps are equal when the bending can't -/// be measured (a cusp, or a point that isn't finite) or is 0. The first or last step is halved -/// when that end stays on the curve (`pin_start`, `pin_end`); a curve of one step is then drawn -/// in two halves. +/// curve, at most `most` (its equal steps, [`steps`]). When the curve between two line ends lies +/// more than [`FIT`] times `chord` from their chord ([`off_chord`]), as where a curve turns back +/// within a step, the count doubles, up to `most`; when `most` such steps still don't fit, the +/// steps are equal. The steps are also equal when the bending can't be measured (a cusp, or a point +/// that isn't finite) or is 0. The first or last step is halved when that end stays on the curve +/// (`pin_start`, `pin_end`); a curve of one step is then drawn in two halves. fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) -> (Vec, (bool, bool)) { let (d1, d2) = (c.deriv(), c.deriv().deriv()); let bend = |u: f64| { @@ -197,39 +373,109 @@ fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) } let total = sums[SAMPLES]; let most = most.max(1); - let n = if total.is_finite() && total > 0.0 { ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most) } else { most }; // The parameter at which a share `s` (0 to 1) of the bending lies before it. let at = |s: f64| -> f64 { - if !(total.is_finite() && total > 0.0) { - return s; - } let want = s * total; let j = sums.partition_point(|&x| x <= want).clamp(1, SAMPLES); let (lo, hi) = (sums[j - 1], sums[j]); let part = if hi > lo { ((want - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 }; (j as f64 - 1.0 + part) / SAMPLES as f64 }; - if n == 1 && (pin_start || pin_end) { - return (vec![0.0, at(0.5), 1.0], (true, true)); + // The line ends of `n` steps, each holding a share `step(s)` of the curve. + let cut = |n: usize, step: &dyn Fn(f64) -> f64| -> (Vec, (bool, bool)) { + if n == 1 && (pin_start || pin_end) { + return (vec![0.0, step(0.5), 1.0], (true, true)); + } + let h = 1.0 / n as f64; + let mut t = Vec::with_capacity(n + 3); + t.push(0.0); + if pin_start { + t.push(step(h / 2.0)); + } + t.extend((1..n).map(|k| step(k as f64 * h))); + if pin_end { + t.push(step(1.0 - h / 2.0)); + } + t.push(1.0); + (t, (pin_start, pin_end)) + }; + if total.is_finite() && total > 0.0 { + let mut n = ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most); + loop { + let fit = cut(n, &at); + if fit.0.windows(2).all(|w| off_chord(c, w[0], w[1]) <= FIT * chord) { + return fit; + } + if n >= most { + break; + } + n = n.saturating_mul(2).min(most); + } } - let h = 1.0 / n as f64; - let mut t = Vec::with_capacity(n + 3); - t.push(0.0); - if pin_start { - t.push(at(h / 2.0)); + cut(most, &|s| s) +} + +/// How far curve `c` between parameters `a` and `b` lies from the chord between its points there: +/// the farthest it lies to either side of the chord's line, or before the chord's start or past its +/// end along it. For a chord of no length, the farthest the curve's control points between `a` and +/// `b` lie from it. +fn off_chord(c: &CubicBez, a: f64, b: f64) -> f64 { + let (p, q) = (c.eval(a), c.eval(b)); + let along = q - p; + let len = along.hypot(); + if !(len > 0.0 && len.is_finite()) { + let s = c.subsegment(a..b); + return [s.p1, s.p2, s.p3].iter().map(|x| (*x - p).hypot()).fold(0.0, f64::max); } - t.extend((1..n).map(|k| at(k as f64 * h))); - if pin_end { - t.push(at(1.0 - h / 2.0)); + let u = along / len; + // The derivative, t² k2 + t k1 + k0. + let d = c.deriv(); + let (k2, k1, k0) = (d.p0.to_vec2() - d.p1.to_vec2() * 2.0 + d.p2.to_vec2(), (d.p1 - d.p0) * 2.0, d.p0.to_vec2()); + let mut far: f64 = 0.0; + // Where the curve moves along the chord's line or across it, its distance across it or its + // position along it is largest or smallest. + for (a2, a1, a0) in [(k2.cross(u), k1.cross(u), k0.cross(u)), (k2.dot(u), k1.dot(u), k0.dot(u))] { + for t in roots(a2, a1, a0) { + if t > a && t < b { + let v = c.eval(t) - p; + let ahead = v.dot(u); + far = far.max(v.cross(u).abs()).max(-ahead).max(ahead - len); + } + } } - t.push(1.0); - (t, (pin_start, pin_end)) + far +} + +/// The real roots of `a2 t² + a1 t + a0`, with NaN in place of a root that doesn't exist (none when +/// every coefficient is 0). +fn roots(a2: f64, a1: f64, a0: f64) -> [f64; 2] { + if a2 == 0.0 { + return [-a0 / a1, f64::NAN]; + } + let disc = a1 * a1 - 4.0 * a2 * a0; + if disc < 0.0 { + return [f64::NAN; 2]; + } + // The root that adds two numbers of the same sign, and the other from their product. + let r = -(a1 + a1.signum() * disc.sqrt()) / 2.0; + if r == 0.0 { + return [0.0, f64::NAN]; + } + [r / a2, a0 / r] } /// How far the curve `c` lies from the chord between parameters `a` and `b`, at its parameter -/// midway: the curve's point there minus the chord's middle. +/// midway: the part across the chord of the curve's point there minus the chord's middle. A chord +/// of no length keeps the whole difference. fn bulge(c: &CubicBez, a: f64, b: f64) -> Vec2 { - c.eval((a + b) / 2.0) - c.eval(a).midpoint(c.eval(b)) + let (p, q) = (c.eval(a), c.eval(b)); + let gap = c.eval((a + b) / 2.0) - p.midpoint(q); + let along = q - p; + let len2 = along.hypot2(); + if !(len2 > 0.0 && len2.is_finite()) { + return gap; + } + gap - along * (gap.dot(along) / len2) } /// A curve of a subpath drawn as lines: the curve, its line ends' parameters, whether its first and diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 05bbc23573..4017448fd9 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -1,6 +1,137 @@ use super::*; use crate::stroke::outline as raster_stroke_outline; -use vectorcraft_doc::StrokeLayer; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer}; + +/// How many lines a fill of `path` takes once flattened at `tol`. +fn lines_at(path: &BezPath, tol: f64) -> usize { + let mut n = 0; + vectorcraft_geom::flatten(path.iter(), tol, |el| n += usize::from(matches!(el, kurbo::PathEl::LineTo(_) | kurbo::PathEl::ClosePath))); + n +} + +/// Whether `path` holds lines only. +fn lines_only(path: &BezPath) -> bool { + path.elements().iter().all(|el| !matches!(el, kurbo::PathEl::QuadTo(..) | kurbo::PathEl::CurveTo(..))) +} + +/// A thin curved stroke's outline takes at most twice the lines the stroke's plain outline takes +/// at the raster tolerance (#7257). 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_curved_strokes_take_at_most_twice_the_lines_of_their_plain_outline() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let mut paths = Vec::new(); + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + paths.push(path); + } + let tol = 0.25; + for width in [0.5, 0.75, 0.99] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + let (mut plain, mut thin) = (0, 0); + for path in &paths { + plain += lines_at(&crate::effects::stroke::line_outline(path, &st, width, tol), tol); + let outline = raster_stroke_outline(path, &st, width, tol); + assert!(lines_only(&outline), "width {width}: lines only"); + thin += lines_at(&outline, tol); + } + assert!(thin <= plain * 2, "width {width}: {thin} lines, plain outline {plain}"); + } +} + +/// A thin stroke drawn as lines keeps its caps, its joins and the hole of a closed path. +#[test] +fn thin_strokes_drawn_as_lines_keep_caps_joins_and_holes() { + let (w, tol) = (0.5, 0.25); + // A quarter circle from (100, 100) heading right, then a right-angle corner at (200, 200). + let mut open = BezPath::new(); + open.move_to((100.0, 100.0)); + open.curve_to((155.23, 100.0), (200.0, 144.77), (200.0, 200.0)); + open.line_to((100.0, 200.0)); + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + for join in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel] { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.cap = cap; + st.join = join; + let o = raster_stroke_outline(&open, &st, w, tol); + assert!(lines_only(&o), "{cap:?} {join:?}: lines only"); + let inside = |x: f64, y: f64| o.winding(kurbo::Point::new(x, y)) != 0; + assert_eq!(inside(100.0 - 0.4 * w, 100.0), cap != LineCap::Butt, "{cap:?} {join:?}: start cap"); + assert!(!inside(100.0 - 0.6 * w, 100.0), "{cap:?} {join:?}: past the start cap"); + assert_eq!(inside(100.0 - 0.45 * w, 100.0 + 0.45 * w), cap == LineCap::Square, "{cap:?} {join:?}: cap corner"); + assert!( + inside(200.0 + 0.4 * w, 199.0) && inside(200.0 - 0.4 * w, 199.0) && !inside(200.0 + 0.6 * w, 199.0), + "{cap:?} {join:?}: curve end" + ); + assert_eq!(inside(200.0 + 0.3 * w, 200.0 + 0.3 * w), join != LineJoin::Bevel, "{cap:?} {join:?}: corner"); + assert_eq!(inside(200.0 + 0.45 * w, 200.0 + 0.45 * w), join == LineJoin::Miter, "{cap:?} {join:?}: miter tip"); + assert!(inside(150.0, 200.0 + 0.4 * w) && !inside(150.0, 200.0 + 0.6 * w), "{cap:?} {join:?}: line"); + } + } + let ring = kurbo::Circle::new((300.0, 300.0), 50.0).to_path(0.01); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&ring, &st, w, tol); + assert!(lines_only(&o), "closed: lines only"); + for k in 0..36 { + let a = f64::from(k) * 10f64.to_radians(); + let at = |r: f64| o.winding(kurbo::Point::new(300.0 + r * a.cos(), 300.0 + r * a.sin())); + assert!(at(50.0 - 0.4 * w) != 0 && at(50.0 + 0.4 * w) != 0, "ring band at {k}"); + assert!(at(50.0 - 0.6 * w) == 0 && at(50.0 + 0.6 * w) == 0, "ring edges at {k}"); + } + assert_eq!(o.winding(kurbo::Point::new(300.0, 300.0)), 0, "the hole"); +} + +/// A thin curve that runs out and back along almost the same line ends where the curve turns +/// back. The curve goes from (0, 0) to x = 75 and back; its outline reaches no further than half +/// the stroke's width past that. +#[test] +fn thin_strokes_drawn_as_lines_stop_where_a_curve_turns_back() { + let (w, tol, e) = (0.5, 0.25, 1e-9); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((100.0, e / 3.0), (100.0, 2.0 * e / 3.0), (0.0, e)); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let inside = |x: f64| o.winding(kurbo::Point::new(x, 0.0)) != 0; + assert!(inside(10.0) && inside(70.0), "the band"); + let far = o.bounding_box().x1; + assert!(far <= 75.0 + w / 2.0 + 1e-6, "the outline reaches x = {far}"); +} + +/// A thin curve that turns back twice keeps both of its turns. The curve runs from (0, 0) out to +/// x = 28.87, back past its start to x = -28.87, and back to (0, 0.001). Its outline covers every +/// point of the curve more than a third of the stroke's width from a turn, reaches both turns to +/// within that, and reaches no further than two thirds of the stroke's width past either turn. +#[test] +fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { + let (w, tol, e) = (0.5, 0.25, 1e-3); + let c = kurbo::CubicBez::new((0.0, 0.0), (100.0, e / 3.0), (-100.0, 2.0 * e / 3.0), (0.0, e)); + let mut path = BezPath::new(); + path.move_to(c.p0); + path.curve_to(c.p1, c.p2, c.p3); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + assert!(lines_only(&o), "lines only"); + let turn = kurbo::ParamCurve::eval(&c, (3.0 - 3f64.sqrt()) / 6.0).x; + let near = w / 3.0; + for k in 1..200 { + let p = kurbo::ParamCurve::eval(&c, f64::from(k) / 200.0); + assert!(p.x.abs() > turn - near || o.winding(p) != 0, "the curve at {p:?}"); + } + let (bounds, past) = (o.bounding_box(), w * 2.0 / 3.0); + assert!(bounds.x1 >= turn - near && bounds.x0 <= -turn + near, "the outline reaches both turns: {bounds:?}"); + assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); +} /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 6a922f0c41..51834cb232 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -14,6 +14,7 @@ use craft::ui::pickers::{Select, SelectLook}; use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; +use vectorcraft_engine::WindowView; /// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop, /// the background-work progress and last the message, so a narrow bar elides the message before anything else. @@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); let busy = busy_labels(app); + let shown_zoom = view.map(|v| crate::state::zoom_display_percent(v.zoom, print)); let (mut show_pick, mut stop) = (None, false); let mut snapping = None; @@ -95,6 +97,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { document, scaling, print, + shown_zoom, has_view: view.is_some(), turned, degrees, @@ -140,11 +143,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, id, params); } // The last choice of each kind counts, as the controls report one choice of each in a pass. - let (mut zoom_to, mut invalid_zoom, mut rotate_to, mut go) = (None, None, None, None); + let (mut zoom_to, mut invalid_zoom, mut preset_pick, mut rotate_to, mut go) = (None, None, None, None, None); for pick in picks { match pick { NavigationPick::Zoom(zoom) => zoom_to = Some(zoom), NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message), + NavigationPick::Preset(preset) => preset_pick = Some(preset), NavigationPick::Rotate(i) => rotate_to = Some(i), NavigationPick::Artboard(to) => go = Some(to), } @@ -153,6 +157,18 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); } + match preset_pick { + Some(ZoomPreset::Percent(zoom)) => { + app.run("view.setZoom", json!({ "zoom": zoom })).ok(); + } + Some(ZoomPreset::FitOnScreen) => { + app.run("view.fitArtboard", json!({})).ok(); + } + Some(ZoomPreset::FitAll) => { + app.run("view.fitAll", json!({})).ok(); + } + None => {} + } if let Some(&(_, angle)) = rotate_to.and_then(|i| ROTATE_VIEW_ANGLES.get(i)) { app.run("view.rotate", json!({"angle": angle})).ok(); } @@ -184,6 +200,8 @@ struct Navigation<'a> { scaling: f32, /// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]). print: Option, + /// The view's zoom percentage, which the Zoom Presets menu checks. + shown_zoom: Option, /// Whether the active document has a view to turn. has_view: bool, /// The Rotate View preset the view is turned to, else `usize::MAX`. @@ -208,6 +226,8 @@ enum NavigationPick { Zoom(f64), /// The message of a zoom the Zoom field could not read. InvalidZoom(String), + /// The entry chosen in the Zoom Presets menu. + Preset(ZoomPreset), /// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]). Rotate(usize), /// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last. @@ -232,6 +252,11 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); } } + let presets = zoom_presets(p.shown_zoom, p.print); + let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); + if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { + p.picked.send(NavigationPick::Preset(preset)); + } let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); let mut rotate_to = None; @@ -287,6 +312,7 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { mod tests { use super::*; use crate::tests::panel_harness::Panel; + use craft::ui::canvas::ViewCommands; use craft::ui::contract::Role; #[test] @@ -397,6 +423,83 @@ mod tests { assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); } + #[test] + fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + app.run("view.setZoom", json!({"zoom": 800})).unwrap(); + app.view_mut().unwrap().request = None; + // The canvas applies a fit on its next frame; the status bar alone leaves the request queued. + let requested = |panel: &Panel| panel.app().view().and_then(|v| v.request.map(|(r, _)| r.command())); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + // Room for the whole menu, so the entries at its foot are on screen. + panel.room(egui::vec2(1200.0, 1600.0)); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("200%", Role::MENU_ITEM_RADIO); + let print = panel.app().print_ppi(); + assert!((crate::state::zoom_display_percent(panel.app().view().unwrap().zoom, print) - 200.0).abs() < 1e-6, "a stop sets its zoom"); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit on Screen", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitArtboard), "Fit on Screen runs view.fitArtboard"); + panel.app().view_mut().unwrap().request = None; + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit All", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitOnScreen), "Fit All runs view.fitAll"); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "zooming records no undo step"); + } + + #[test] + fn the_zoom_presets_list_the_stops_from_the_highest_and_check_the_shown_zoom() { + let presets = zoom_presets(Some(200.0), None); + let labels: Vec = presets.iter().filter(|e| e.is_item()).map(|e| e.label().as_str().to_owned()).collect(); + assert_eq!(labels.first().map(String::as_str), Some("64000%")); + assert_eq!(labels.iter().rev().take(3).rev().map(String::as_str).collect::>(), ["3.13%", "Fit on Screen", "Fit All"]); + let checked: Vec<_> = presets.iter().filter(|e| e.is_checked()).filter_map(|e| e.value().copied()).collect(); + assert_eq!(checked, [ZoomPreset::Percent(200.0)]); + assert!(zoom_presets(None, None).iter().all(|e| !e.is_checked()), "without a view no stop is checked"); + } + + /// With Display Print Size on, 100% is more or less than one screen point per document point, so the stops at + /// the ends of the list can fall outside the view's zoom range; the menu lists only the stops a pick sets exactly. + #[test] + fn the_zoom_presets_leave_out_stops_outside_the_zoom_range_at_print_size() { + let percents = |print: Option| -> Vec { + zoom_presets(None, print) + .iter() + .filter_map(|e| match e.value() { + Some(ZoomPreset::Percent(pct)) => Some(*pct), + _ => None, + }) + .collect() + }; + let stops: Vec = crate::state::zoom_stop_percents().collect(); + let n = stops.len(); + assert_eq!(percents(None).len(), n, "at 1:1 every stop is in range"); + let dense = crate::state::print_ppi(true, Some(96.0)); + assert_eq!(percents(dense).first(), Some(&stops[n - 2]), "64000% at 96 PPI is past the highest zoom, 25600% is not"); + assert_eq!(percents(dense).last(), Some(&stops[0]), "3.13% at 96 PPI is in range"); + let sparse = crate::state::print_ppi(true, Some(40.0)); + assert_eq!(percents(sparse).first(), Some(&stops[n - 1]), "64000% at 40 PPI is in range"); + assert_eq!(percents(sparse).last(), Some(&stops[2]), "3.13% and 4.17% at 40 PPI are below the lowest zoom, 6.25% is not"); + let (min, max) = WindowView::ZOOM_RANGE; + for print in [None, dense, sparse] { + for pct in percents(print) { + let zoom = crate::state::zoom_from_display_percent(pct, print); + let set = crate::state::zoom_display_percent(zoom.clamp(min, max), print); + assert!((set - pct).abs() < 1e-6, "{pct}% at {print:?} sets {set}%"); + } + } + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -420,6 +523,41 @@ fn busy_labels(app: &VectorcraftApp) -> Vec<&str> { .collect() } +/// An entry of the Zoom Presets menu beside the status bar's zoom field. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ZoomPreset { + /// A zoom stop, in the percent `view.setZoom` takes. + Percent(f64), + /// Fit on Screen (`view.fitArtboard`). + FitOnScreen, + /// Fit All (`view.fitAll`). + FitAll, +} + +/// The Zoom Presets menu: the zoom stops from the highest, the one at the `shown` percent checked, then Fit on Screen +/// and Fit All. A stop whose zoom falls outside the view's zoom range ([`WindowView::ZOOM_RANGE`]) at the `print` +/// setting is left out, since `view.setZoom` would set the nearest end of the range instead. +fn zoom_presets(shown: Option, print: Option) -> Vec> { + let (min, max) = WindowView::ZOOM_RANGE; + let reachable = |pct: &f64| { + let zoom = crate::state::zoom_from_display_percent(*pct, print); + zoom >= min * (1.0 - 1e-9) && zoom <= max * (1.0 + 1e-9) + }; + let stops = crate::state::zoom_stop_percents(); + let mut entries: Vec> = stops + .rev() + .filter(reachable) + .map(|pct| { + let label = crate::state::zoom_label(crate::state::zoom_from_display_percent(pct, print), print); + Entry::new(ZoomPreset::Percent(pct), label).checked(shown.is_some_and(|s| (s - pct).abs() < 0.01)) + }) + .collect(); + entries.push(Entry::separator()); + entries.push(Entry::new(ZoomPreset::FitOnScreen, tl!("Fit on Screen"))); + entries.push(Entry::new(ZoomPreset::FitAll, tl!("Fit All"))); + entries +} + /// What the status bar's info field shows, chosen from the Show menu that a click on the field /// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index f7dfc22951..e89c22b337 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1121,8 +1121,7 @@ fn a_group_dragged_out_of_the_icon_column_floats_expanded_and_its_tabs_switch() .filter(|(_, node)| node.label() == Some("Move tab group")) .filter_map(|(_, node)| node.bounds()) .map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) - .filter(|grip| (grip.center().y - tab.center().y).abs() < 20.0) - .last() + .rfind(|grip| (grip.center().y - tab.center().y).abs() < 20.0) .expect("the flyout's grip"); h.drag(grip.center(), h.canvas().center()); h.frames(2); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f283714902..10172f2c5a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1255,6 +1255,8 @@ mod tests_maskview; #[cfg(test)] mod tests_panel_rows; #[cfg(test)] +mod tests_panel_spacing; +#[cfg(test)] mod tests_script_console; #[cfg(test)] mod tests_stroke; diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index c4de2fb9ea..3d95d2c28d 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -30,10 +30,10 @@ use craft::ui::contract::{ Bind, CollectionEvent, CollectionResponse, ColumnSpec, FieldLabelRole, ItemCx, ListDrag, MemoProps, PopupKind, Props as _, ReorderMove, ReorderRule, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, ToggleColumn, Trigger, clicked, }; -use craft::ui::display::{Picture, Shade, Text}; +use craft::ui::display::{Elide, Picture, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Stack; -use craft::ui::list::{List, ListRow, RowDragSpot, RowEvent, RowInk, ThumbAspect, ThumbSize, ThumbTarget, ToggleCell}; +use craft::ui::list::{List, ListRow, RowDragSpot, RowEvent, RowInk, ThumbAspect, ThumbSize, ThumbTarget, ToggleCell, TreeLeaves}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamRows}; use craft::ui::patterns::presets::{ @@ -403,6 +403,9 @@ const SWATCH_COLUMNS: u16 = 12; const SWATCH_ROWS: u16 = 12; /// The width and height of a stroke row's profile picture, as its aspect. const PROFILE_ASPECT: (u16, u16) = (14, 5); +/// The most characters of a stroke's notes that set the notes' column width on every fill and stroke row; longer notes +/// are cut at the end and show whole in a tooltip. +const NOTES_SAMPLE_CHARS: usize = 16; /// The eye column. const EYE: ColumnKey = ColumnKey::new("eye"); @@ -543,6 +546,9 @@ fn show_list( let mut list = List::new(tl!("Appearance")) .id(list_id) .tree(true) + // The top-level rows without a disclosure (Opacity, an object's effects) keep its column, so their labels + // start where the Stroke and Fill labels do. + .tree_leaves(TreeLeaves::Aligned) .columns(columns) .deletable(true) .selection(Bind::bound(selection)) @@ -827,21 +833,36 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> { link_output(cx.pass, key), ); // The first trailing part added is the outermost: the profile closes the row, the swatch sits - // nearest the label. - if let AppearanceItem::Stroke(st) = it { - if let Some(points) = st.profile.as_ref().filter(|p| p.preset_id() != Some("uniform")).map(|p| p.points.clone()) { - let aspect = ThumbAspect::new(PROFILE_ASPECT.0, PROFILE_ASPECT.1); - let profile = Picture::painter(Label::Empty, aspect, move |painter, rect| stroke::paint_profile(painter, rect, Some(points.as_slice()))); + // nearest the label. Every fill and stroke row of the stack takes the same room for the profile, the notes and the + // weight, kept empty where the row has none, so all their swatches stand in one column. + let (any_profile, widest_notes) = trailing_room(stack.map_or(&[], |ap| ap.items.as_slice())); + let stroke_layer = match it { + AppearanceItem::Stroke(st) => Some(st), + _ => None, + }; + match stroke_layer.and_then(shown_profile) { + Some(points) => { + let profile = + Picture::painter(Label::Empty, profile_aspect(), move |painter, rect| stroke::paint_profile(painter, rect, Some(points.as_slice()))); row = row.trailing_field(profile, |_| {}); } - if let Some(notes) = stroke_notes(st) { - row = row.trailing_field(Text::new(notes).shade(Shade::Muted), |_| {}); - } + None if any_profile => row = row.trailing_space(Picture::painter(Label::Empty, profile_aspect(), |_, _| {})), + None => {} + } + if let Some(widest) = widest_notes { + row = match stroke_layer.and_then(stroke_notes) { + Some(notes) => row.trailing_field(Text::new(notes).shade(Shade::Muted).sample(widest).elide(Elide::End), |_| {}), + None => row.trailing_space(Text::new(Label::Empty).shade(Shade::Muted).sample(widest)), + }; + } + if let Some(st) = stroke_layer { let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) }; let pass = cx.pass; row = row.trailing_field(stroke::weight_number(cx.app, Some(st.width)), move |out| { pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))) }); + } else { + row = row.trailing_space(stroke::weight_number(cx.app, None)); } let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) }; let pass = cx.pass; @@ -874,6 +895,31 @@ fn stroke_notes(st: &vectorcraft_doc::StrokeLayer) -> Option { (!notes.is_empty()).then(|| notes.join(", ")) } +/// The points of a stroke's width profile, when it has one other than Uniform, which its row draws. +fn shown_profile(st: &vectorcraft_doc::StrokeLayer) -> Option> { + st.profile.as_ref().filter(|p| p.preset_id() != Some("uniform")).map(|p| p.points.clone()) +} + +/// The shape of a stroke row's profile picture. +fn profile_aspect() -> ThumbAspect { + ThumbAspect::new(PROFILE_ASPECT.0, PROFILE_ASPECT.1) +} + +/// The trailing room every fill and stroke row of `items` keeps before its weight: whether a stroke there shows a +/// profile, and the longest of the strokes' notes, up to [`NOTES_SAMPLE_CHARS`] characters, which sets the notes' width +/// on every row. +fn trailing_room(items: &[AppearanceItem]) -> (bool, Option) { + let strokes = || { + items.iter().filter_map(|it| match it { + AppearanceItem::Stroke(st) => Some(st), + _ => None, + }) + }; + let any_profile = strokes().any(|st| shown_profile(st).is_some()); + let widest = strokes().filter_map(stroke_notes).max_by_key(|notes| notes.chars().count()); + (any_profile, widest.map(|notes| notes.chars().take(NOTES_SAMPLE_CHARS).collect())) +} + /// An Opacity row: of the object or, under it, of a fill/stroke. "Opacity:" opens the /// Transparency panel on it. A mixed selection whose objects' opacity or blend mode differ /// reads "Mixed". diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 41ec089303..ad8b8ce9f7 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use craft::keymap::CommandRef; -use craft::ui::contract::{Show as _, ShowContainer as _}; +use craft::ui::contract::{Gap, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::layout::RowAlign; use craft::ui::layout_components::{Row, Stack}; @@ -35,7 +35,8 @@ pub struct DocInfoView { /// the second or third click of a double or triple click. pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { let mut clicked = false; - Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| { + // A wrapping row places its children as `Start` does, so the row does not wrap and the value stands at its end. + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(label.to_string()).shade(Shade::Muted).show(ui); // The value can be selected and copied, and a click copies all of it (#8432). A drag selects // and a Shift-click extends the selection, so neither copies. @@ -154,7 +155,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone(); let mut copy = None; - Stack::new().show(ui, |ui, _| { + // The sections fill the panel's width, so each row's value stands at its end, and a section gap sets the + // dividers apart from the sections around them. + Stack::new().fill_width().gap(Gap::Section).show(ui, |ui, _| { if sel_only && no_artwork_selected(app) { Text::new(tl!("(No artwork selected)").to_string()).shade(Shade::Muted).show(ui); } @@ -164,38 +167,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if n > 0 { Divider::horizontal().show(ui); } - let title = s["title"].as_str().unwrap_or_default(); - let rows = s["rows"].as_array().map_or(&[][..], Vec::as_slice); - // Lists show how many they hold; the selection scope shows on the first. - let title = match s["id"].as_str() { - Some("document" | "objects") => tl!(title).to_string(), - _ => format!("{} ({})", tl!(title), rows.len()), - }; - let title = - if sel_only && n == 0 && category.is_empty() { crate::i18n::fmt(tl!("{title} (selection)"), &[("title", &title)]) } else { title }; - Text::new(title).role(TypeRole::Heading).show(ui); - if rows.is_empty() { - Text::new(tl!("None").to_string()).shade(Shade::Muted).show(ui); - } - let id = s["id"].as_str().unwrap_or_default(); - let named = named_rows(id, rows); - for (k, r) in rows.iter().enumerate() { - let (label, value) = (r[0].as_str().unwrap_or_default(), r[1].as_str().unwrap_or_default()); - if value.is_empty() { - if named.contains(&k) && !label.is_empty() { - if copy_value(ui, label, label, false) { - copy = Some(label.to_string()); + Stack::new().fill_width().show(ui, |ui, _| { + let title = s["title"].as_str().unwrap_or_default(); + let rows = s["rows"].as_array().map_or(&[][..], Vec::as_slice); + // Lists show how many they hold; the selection scope shows on the first. + let title = match s["id"].as_str() { + Some("document" | "objects") => tl!(title).to_string(), + _ => format!("{} ({})", tl!(title), rows.len()), + }; + let title = if sel_only && n == 0 && category.is_empty() { + crate::i18n::fmt(tl!("{title} (selection)"), &[("title", &title)]) + } else { + title + }; + Text::new(title).role(TypeRole::Heading).show(ui); + if rows.is_empty() { + Text::new(tl!("None").to_string()).shade(Shade::Muted).show(ui); + } + let id = s["id"].as_str().unwrap_or_default(); + let named = named_rows(id, rows); + for (k, r) in rows.iter().enumerate() { + let (label, value) = (r[0].as_str().unwrap_or_default(), r[1].as_str().unwrap_or_default()); + if value.is_empty() { + if named.contains(&k) && !label.is_empty() { + if copy_value(ui, label, label, false) { + copy = Some(label.to_string()); + } + } else { + Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui); } } else { - Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui); - } - } else { - let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); - if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) { - copy = Some(shown); + let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); + if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) { + copy = Some(shown); + } } } - } + }); } }); if let Some(text) = copy { diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index e99898605f..76b17c33be 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1574,9 +1574,10 @@ mod tests { let mut p = PanelHarness::new(app, appearance_and_styles); let hold = |p: &mut PanelHarness| { - // The thumbnail is the first part of the object row, at its start. + // The thumbnail is the first part of the object row, after the empty disclosure column that lines the row's + // label up with the Stroke and Fill labels. let row = p.rect("Rectangle: Drop Target"); - let (from, to) = (row.left_center() + egui::vec2(14.0, 0.0), p.rect("Drop Target").center()); + let (from, to) = (row.left_center() + egui::vec2(34.0, 0.0), p.rect("Drop Target").center()); p.drag_hold_between(from, to); let carried = drag::active::(p.ctx()); assert!( diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs index 98aa304d2e..73f3034177 100644 --- a/crates/ui-egui/src/panels/image_trace/rows.rs +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -10,7 +10,7 @@ use craft::color_ui::ui::{ColorPopover, PickedColor}; use craft::theme::Srgba; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _}; use craft::ui::form::{Field, SliderField, SliderFieldLayout}; use craft::ui::layout_components::Row; use craft::ui::pickers::Select; @@ -265,7 +265,14 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ Row::new().show(ui, |ui, _| { let mut hit = None; for (key, on, other, label) in [("fills", fills, strokes, tl!("Fills")), ("strokes", strokes, fills, tl!("Strokes"))] { - if check(ui, label, on, !on || other) { + // Inside the Create field a check box's own label is not drawn, so each box takes a field of + // its own with the label after it. + let enabled = !on || other; + let mut value = on; + Field::new(label).layout(FieldLayout::After).enabled(enabled).show(ui, |ui, _| { + Checkbox::new(Bind::bound(&mut value)).enabled(enabled).show(ui); + }); + if value != on { hit = Some(key); } } diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 3c2df76111..c0986e921d 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -5,7 +5,7 @@ use craft::behavior::ColumnWidth; use craft::keymap::CommandRef; -use craft::ui::contract::{Show as _, ShowContainer as _}; +use craft::ui::contract::{Gap, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Picture}; use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::list::ThumbAspect; @@ -249,34 +249,43 @@ const HALVES: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 2]; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let l = lines(app, ui.ctx()); let mut copy = None; - // Two equal halves of the panel, as the reference app's columns were. - let _ = Grid::new(HALVES).show(ui, |ui, _| { - for column in [&l.left, &l.right] { - Stack::new().show(ui, |ui, _| { - for s in column { - if mono(ui, s) { - copy = Some(s.clone()); + // The numbers, the paints and the type are groups a section gap sets apart from the dividers between them. + Stack::new().fill_width().gap(Gap::Section).show(ui, |ui, _| { + Stack::new().fill_width().show(ui, |ui, _| { + // Two equal halves of the panel, as the reference app's columns were. + let _ = Grid::new(HALVES).show(ui, |ui, _| { + for column in [&l.left, &l.right] { + Stack::new().show(ui, |ui, _| { + for s in column { + if mono(ui, s) { + copy = Some(s.clone()); + } + } + }); + } + }); + for s in l.zoom.iter().chain(&l.brush) { + if mono(ui, s) { + copy = Some(s.clone()); + } + } + }); + Divider::horizontal().show(ui); + Stack::new().fill_width().show(ui, |ui, _| { + copy = paint_block(ui, &l.fill).or(copy.take()); + copy = paint_block(ui, &l.stroke).or(copy.take()); + }); + if let Some((font, size)) = &l.type_block { + Divider::horizontal().show(ui); + Stack::new().fill_width().show(ui, |ui, _| { + for value in [font, size] { + if mono(ui, value) { + copy = Some(value.clone()); } } }); } }); - for s in l.zoom.iter().chain(&l.brush) { - if mono(ui, s) { - copy = Some(s.clone()); - } - } - Divider::horizontal().show(ui); - copy = paint_block(ui, &l.fill).or(copy); - copy = paint_block(ui, &l.stroke).or(copy); - if let Some((font, size)) = &l.type_block { - Divider::horizontal().show(ui); - for value in [font, size] { - if mono(ui, value) { - copy = Some(value.clone()); - } - } - } if let Some(text) = copy { app.clipboard_out = Some(text); app.status("Copied the value"); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 881129e87f..ba3723a24e 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -786,8 +786,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }) .show(ui, |ui, _| { - let empty = if o.show == "all" { tl!("No images") } else { tl!("Nothing matches the Show filter.") }; - let mut list = List::::new(tl!("Links")).selection(Bind::bound(&mut selection)).empty(empty).row_menu(); + // With no rows the body says how to bring an image in, as the other panels' empty states do; + // under a Show filter the document can still hold images that the filter hides. + if row_ids.is_empty() { + let (title, detail) = if o.show == "all" { + (tl!("No images"), tl!("File › Place… brings in an image, linked or embedded.")) + } else { + (tl!("No matching images"), tl!("Nothing matches the Show filter.")) + }; + super::empty_state(ui, "link", title, detail); + return; + } + let mut list = List::::new(tl!("Links")).selection(Bind::bound(&mut selection)).row_menu(); if let Some(id) = reveal { list = list.reveal(id); } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 4f49283464..e51b4b9072 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -5,7 +5,7 @@ use std::sync::LazyLock; -use craft::behavior::{IconId, Mixed}; +use craft::behavior::{ColumnWidth, IconId, Mixed}; use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSections}; use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; @@ -13,7 +13,8 @@ use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec}; use craft::ui::display::Divider; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Grid, Row}; +use craft::ui::list::ThumbAspect; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -34,6 +35,12 @@ use crate::VectorcraftApp; // PLAN: assumed `crate::edits::{apply_edits, EditPath}` (wg.A16). use crate::edits::{EditPath, apply_edits}; +/// The Arrowheads row's columns: the start and end heads share the width, and Swap keeps its own. +const ARROWHEAD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + +/// The width and height ratio of an arrowhead picture on a closed Arrowheads field, which shows the picture alone. +const ARROWHEAD_ASPECT: (u16, u16) = (2, 1); + /// The key of [`StrokePanel::brushed`]: (document uid, revision, active Appearance row). type BrushedKey = (u64, u64, Option); @@ -409,14 +416,14 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { (st.and_then(|s| s.end_arrow.clone()), false, tl!("End arrowhead"), "endArrow"), ]; Field::new(tl!("Arrowheads")).show(ui, |ui, _| { - // The two heads share the width the Swap button leaves; a field too narrow for all three puts Swap on a - // new line. - Row::new().fill_width().wrap(true).show(ui, |ui, _| { + // The two heads share the width the Swap button leaves, on one line. + Grid::new(&ARROWHEAD_COLUMNS).sizing(Sizing::FillWidth).show(ui, |ui, _| { for (head, start, label, key) in &heads { let (start, key) = (*start, *key); let out = Select::new(*label, Bind::given(head.clone()), &entries) .picture(move |a, cx, rect| arrow_thumb(cx, rect, a.as_ref(), start)) - .sizing(Sizing::FillWidth) + .picture_only() + .picture_aspect(ThumbAspect::new(ARROWHEAD_ASPECT.0, ARROWHEAD_ASPECT.1)) .show(ui); // A custom head goes with its art, as document.inspect reports it. if let Some(a) = out.events.landed() { @@ -432,20 +439,28 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { let (arrow_align, has_head) = arrow_align_state(st); let scale = st.map_or((100.0, 100.0), |s| s.arrow_scale); let linked = app.ui.stroke_panel.scale_linked; - let out = LinkedFields::new(tl!("Scale"), Bind::given(Mixed::each([Some(scale.0), Some(scale.1)])), Bind::given(linked)) - .mode(LinkMode::Equal) - .unit_kind(UnitKind::Percent) + let out = Field::new(tl!("Scale")) .enabled(has_head) - .show(ui); - if let Some(on) = out.link.landed() { + .show(ui, |ui, _| { + LinkedFields::new(tl!("Scale"), Bind::given(Mixed::each([Some(scale.0), Some(scale.1)])), Bind::given(linked)) + .mode(LinkMode::Equal) + .unit_kind(UnitKind::Percent) + .enabled(has_head) + .show(ui) + }) + .inner; + if let Some(on) = out.as_ref().and_then(|out| out.link.landed()) { app.ui.stroke_panel.scale_linked = *on; } - if let Some([a, b]) = out.edit.events.landed().map(|p| (*p).map(|m| m.same().copied().flatten())) { + if let Some([a, b]) = out.as_ref().and_then(|out| out.edit.events.landed()).map(|p| (*p).map(|m| m.same().copied().flatten())) { app.run("stroke.setAdvanced", json!({"arrowScale": [a.unwrap_or(scale.0), b.unwrap_or(scale.1)]})).ok(); } let aligns: Vec> = ARROW_ALIGN.iter().map(|(v, _, icon, tip)| Entry::new(*v, *tip).icon(IconId::new(icon))).collect(); - let out = Segmented::new(tl!("Align"), Bind::given(arrow_align), &aligns).enabled(has_head).show(ui); - if let Some(v) = out.events.landed() + let out = Field::new(tl!("Align")) + .enabled(has_head) + .show(ui, |ui, _| Segmented::new(tl!("Align"), Bind::given(arrow_align), &aligns).enabled(has_head).show(ui)) + .inner; + if let Some(v) = out.as_ref().and_then(|out| out.events.landed()) && let Some((_, name, _, _)) = ARROW_ALIGN.iter().find(|(a, ..)| a == v) { set(app, json!({"arrowAlign": name})); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index d3ba15ab86..a179e07a53 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -7,7 +7,6 @@ //! proxy's paint command with the object's id) and onto the Gradient panel's ramp; a Fill/Stroke //! proxy or the Gradient panel's thumbnail dropped on the panel becomes a swatch (`swatch.new`). -use std::cell::RefCell; use std::sync::Arc; use craft::behavior::{EditEvent, IconId, Selection}; @@ -220,8 +219,13 @@ fn name_of(key: &SwatchKey) -> &str { /// The swatches and colour groups selected in the panel, in click order, without names that no longer exist /// (deleted, renamed or undone). pub(crate) fn selected(app: &VectorcraftApp) -> Vec { + selected_in(app, &app.ui.swatches_panel) +} + +/// The swatches and colour groups selected in `model`, as [`selected`] reads them from the app's panel. +fn selected_in(app: &VectorcraftApp, model: &Model) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - let mut names = app.ui.swatches_panel.names(); + let mut names = model.names(); names.retain(|n| n == REGISTRATION || st.doc.swatch_name_taken(n)); names } @@ -384,7 +388,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { super::color_guide::choose_base(app, c); apply_click(app, ui, json!({"color": color_json(&c)})); } - let (footer_state, footer_actions) = footer_actions(app); // The model leaves the app while the browser borrows the document, and comes back before the events run. let mut model = std::mem::take(&mut app.ui.swatches_panel); let view = app.ui.swatches_view; @@ -404,25 +407,29 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.swatches_panel = model; return; }; - let thumbs = Thumbs { - revision: (st.uid, st.revision), - lit: highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(), - doc: Arc::clone(&st.doc), - }; - let dragged_doc = Arc::clone(&thumbs.doc); + let revision = (st.uid, st.revision); + let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); + let doc = Arc::clone(&st.doc); let document = st.uid; let reverts = st.reverts; + let foot = Footer::of(app, &model); let shown_app: &VectorcraftApp = app; - // The footer stays under the browser, which fills the room left above it. - let footer_out: RefCell> = RefCell::new(None); - let shown = Stack::new() + let search = model.show_find; + let state = &mut model.state; + // The browser fills the room the footer leaves, so the footer stays in view under the swatches. The body can run + // more than once in a pass, so each run builds its own browser. A list drag is keyed by its browser ID. Each + // document has its own browser. + let mut footed = None; + let out = Stack::new() + .label(tl!("Swatches")) .fill() - .footer(|ui, _| *footer_out.borrow_mut() = Some(FooterBar::actions(footer_actions.clone()).at_start(EDIT + 1).show_footer(ui))) + .footer(|ui, _| footed = Some(foot.show(ui))) .show(ui, |ui, _| { - let dragged_doc = Arc::clone(&dragged_doc); - let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) + let dragged_doc = Arc::clone(&doc); + let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; + let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) - .thumb(thumbs.clone(), thumb) + .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), _ => vec![], @@ -431,26 +438,26 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts)) .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts)) .select(SelectMode::Multi) - .search(model.show_find) + .search(search) .reveal(focus.clone().map(SwatchKey::Swatch)) .footer(None); - // A list drag is keyed by its browser ID. Each document has its own browser. ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner - }); + }) + .inner; app.ui.swatches_panel = model; - let shown_rows = shown_keys(&data); - if let Some(out) = shown.inner { + let shown = shown_keys(&data); + if let Some(out) = out { if let Some((at, _, alt)) = out.used && let Some(entry) = data.get(at.group).and_then(|g| g.entries.get(at.index)) { apply(app, &entry.name, alt); } for event in out.events { - on_event(app, &shown_rows, event); + on_event(app, &shown, event); } } - if let Some(out) = footer_out.into_inner() { - on_footer(app, ui, footer_state, out); + if let Some(out) = footed { + on_footer(app, ui, foot, out); } } @@ -523,7 +530,7 @@ fn menu_command(app: &mut VectorcraftApp, key: &SwatchKey, command: &str) { } /// What the swatch thumbnails read: the active document at its revision and the names drawn selected. -#[derive(Clone, MemoProps)] +#[derive(MemoProps)] struct Thumbs { /// The document's uid and revision. revision: (u64, u64), @@ -772,54 +779,68 @@ const DELETE: usize = 3; const NEW: usize = 4; const NEW_GROUP: usize = 5; -/// What the footer's actions act on, read before the panel is drawn. -struct FooterState { +/// The panel's footer: Swatch Libraries, Show Swatch Kinds, Edit Color Group or Swatch Options, New Color Group, New +/// Swatch and Delete. Alt-click on Delete deletes without asking; Cmd/Ctrl-click on New Swatch makes a spot color, and +/// Cmd/Ctrl+Shift-click a global process color. Swatches dragged from the list and dropped on New Swatch are +/// duplicated, and rows dropped on Delete are deleted, also with nothing selected. +struct Footer { sel: Vec, kind: Kind, del: Vec, opts: Option, group: Option, + libraries_open: bool, + document: Option, } -/// The panel's footer: Swatch Libraries, Show Swatch Kinds, Edit Color Group or Swatch Options, New Color Group, New -/// Swatch and Delete. Alt-click on Delete deletes without asking; Cmd/Ctrl-click on New Swatch makes a spot color, and -/// Cmd/Ctrl+Shift-click a global process color. Swatches dragged from the list and dropped on New Swatch are -/// duplicated, and rows dropped on Delete are deleted, also with nothing selected. -fn footer_actions(app: &VectorcraftApp) -> (FooterState, [FooterAction; 6]) { - let sel = selected(app); - let kind = app.ui.swatches_panel.kind; - let del = actions::deletable(app, &sel); - let opts = actions::editable(app, &sel); - let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); - let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); - let document = app.session.active().map(|state| state.uid); - let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); - let edit = if group.is_some() { - FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) - } else { - FooterAction::new(icon("dc-options"), tl!("Swatch Options")).enabled(opts.is_some()) - }; - // Libraries, Show Swatch Kinds and the edit action sit at the start edge; Delete at the end edge, then New Swatch - // and New Color Group before it. - let actions = [ - FooterAction::new(icon("library"), tl!(SwatchLibraries::MENU)) - .popup(PopupKind::Menu) - .pressed(library_panel::any_open::(&app.ui)), - FooterAction::new(icon("dc-swatch-kinds"), tl!("Show Swatch Kinds")).popup(PopupKind::Menu).pressed(kind != Kind::All), - edit, - FooterAction::new(icon("trash-2"), tl!("Delete Swatch")) - .enabled(!del.is_empty()) - .takes_drops_disabled(del.is_empty()) - .accepts_drops::(rows_drag), - FooterAction::new(icon("dc-new-item"), tl!("New Swatch")).accepts_drops::(rows_drag), - FooterAction::new(icon("dc-folder"), tl!("New Color Group")), - ]; - (FooterState { sel, kind, del, opts, group }, actions) +impl Footer { + /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it. + fn of(app: &VectorcraftApp, model: &Model) -> Self { + let sel = selected_in(app, model); + let del = actions::deletable(app, &sel); + let opts = actions::editable(app, &sel); + let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); + Footer { + kind: model.kind, + libraries_open: library_panel::any_open::(&app.ui), + document: app.session.active().map(|state| state.uid), + sel, + del, + opts, + group, + } + } + + /// The footer bar, in the room the panel keeps for it under the swatches. + fn show(&self, ui: &mut Ui) -> FooterOutput { + let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); + let document = self.document; + let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let edit = if self.group.is_some() { + FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) + } else { + FooterAction::new(icon("dc-options"), tl!("Swatch Options")).enabled(self.opts.is_some()) + }; + // Libraries, Show Swatch Kinds and the edit action sit at the start edge; Delete at the end edge, then New + // Swatch and New Color Group before it. + let actions = [ + FooterAction::new(icon("library"), tl!(SwatchLibraries::MENU)).popup(PopupKind::Menu).pressed(self.libraries_open), + FooterAction::new(icon("dc-swatch-kinds"), tl!("Show Swatch Kinds")).popup(PopupKind::Menu).pressed(self.kind != Kind::All), + edit, + FooterAction::new(icon("trash-2"), tl!("Delete Swatch")) + .enabled(!self.del.is_empty()) + .takes_drops_disabled(self.del.is_empty()) + .accepts_drops::(rows_drag), + FooterAction::new(icon("dc-new-item"), tl!("New Swatch")).accepts_drops::(rows_drag), + FooterAction::new(icon("dc-folder"), tl!("New Color Group")), + ]; + FooterBar::actions(actions).at_start(EDIT + 1).show_footer(ui) + } } -/// Runs what the footer's `out` reports and shows the menus its buttons open. -fn on_footer(app: &mut VectorcraftApp, ui: &mut Ui, state: FooterState, out: FooterOutput) { - let FooterState { sel, kind, del, opts, group } = state; +/// Runs what the footer reported: a pressed action, a drop on New Swatch or Delete, or a menu it opened. +fn on_footer(app: &mut VectorcraftApp, ui: &mut Ui, footer: Footer, out: FooterOutput) { + let Footer { sel, kind, del, opts, group, .. } = footer; match out.picked { Some(DELETE) if !del.is_empty() => actions::delete(app, del, out.mods.alt), Some(NEW) => actions::new_swatch(app, &sel, out.mods), diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index e45e0f3132..617fb83a35 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -184,6 +184,22 @@ fn the_footer_menu_buttons_report_that_they_open_a_menu() { } } +/// The footer reads the panel's selection while the browser holds the panel's model: with one swatch selected, Swatch +/// Options and Delete Swatch are enabled. +#[test] +fn the_footer_acts_on_the_panels_selection() { + use crate::tests::panel_harness::Panel; + + let mut app = app(); + select_rows(&mut app, &["Red"]); + let mut panel = Panel::new(app, show); + panel.frame(); + assert_eq!(selected(&panel.app()), vec!["Red".to_string()]); + for name in ["Swatch Options", "Delete Swatch"] { + assert!(panel.enabled(name), "{name}"); + } +} + /// Art `ids` dragged off the canvas. fn art_drag(app: &VectorcraftApp, ids: Vec) -> PanelDrag { let (document, reverts) = app.session.active().map_or((0, 0), |st| (st.uid, st.reverts)); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a3ed7d9528..11f805bad5 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -578,9 +578,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Art dropped anywhere on the list becomes a symbol; dropped on a symbol, the browser's // own target takes it. DropAction::::new(move |drag| art_of(drag, uid, reverts).is_some()).show(ui, |ui, _| { + // With no symbols the body says how to make one, as the other panels' empty states do. + if doc.symbols.is_empty() { + super::empty_state(ui, "spray-can", tl!("No symbols in this document"), tl!("Select art and click New Symbol to make one.")); + return None; + } let mut state = PresetState::new(); state.zoom = zoom; - PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source) + let shown = PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source) .browser_id(browser_id) .selection(Bind::given(selection.clone())) .select(select) @@ -591,13 +596,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .takes_drop(PresetDrop::new::(DropPlace::Onto, move |drag: &PanelDrag, _: &DropAt| { art_of(drag, uid, reverts).is_some() })) - .empty(tl!("No symbols in this document")) - .show(ui) + .show(ui); + Some(shown) }) }); let taken = shown.settle(|_, list| { let dropped = list.output.dropped.take().map(|drag| (drag, list.output.mods)); - (dropped, list.inner.take().map(|out| out.events).unwrap_or_default()) + (dropped, list.inner.take().flatten().map(|out| out.events).unwrap_or_default()) }); let footer = footer.into_inner(); if let Some(opener) = footer.as_ref().and_then(|out| out.responses.get(AT_LIBRARY)) { diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index e1a60e1c45..e817ac9f36 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -203,6 +203,20 @@ fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() { assert_eq!(h.state().ui.links.show, None, "the request is dropped"); } +/// A Show filter that hides every image titles the empty panel "No matching images", since the +/// document still holds images; "No images" stays for a document with none. +#[test] +fn a_filter_that_hides_every_image_says_no_matching_images() { + let dir = Folder::new("empty-filter-title"); + let (app, _, _) = app(&dir); + let mut h = rig(app); + command(&mut h, "ui.links.show", json!({"show": "missing"})); + assert!(shown(&h, "No matching images"), "Show Missing with nothing missing"); + assert!(!shown(&h, "No images"), "the document holds two images"); + command(&mut h, "ui.links.show", json!({"show": "all"})); + assert!(shown(&h, "linked.png") && !shown(&h, "No matching images"), "Show All lists the rows"); +} + /// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the /// two-second recheck, another first selected image and an edit each store a new cache. #[test] diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index 01ed51a6a6..15554da438 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -1,6 +1,8 @@ //! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. -use super::tests_appearance::app_with_rect; +use serde_json::json; + +use super::tests_appearance::{app_with_rect, run}; use super::*; use crate::panel_docking::PANEL_MIN_WIDTH; use crate::tests::panel_harness::{Panel, Place, ROOM, floated}; @@ -96,6 +98,50 @@ fn the_color_wheel_box_and_its_strip_stay_inside_the_panel() { assert!(field.right() <= ROOM.x && strip.right() <= ROOM.x, "the box {field:?} or its strip {strip:?} runs past the panel"); } +#[test] +fn the_symbols_panel_with_no_symbols_says_how_to_make_one() { + let panel = Panel::new(app_with_rect(), symbols::show); + assert!(panel.shows("No symbols in this document")); + assert!(panel.shows("Select art and click New Symbol to make one."), "the empty panel has no hint"); +} + +#[test] +fn the_appearance_swatches_and_labels_line_up() { + let panel = Panel::new(app_with_rect(), appearance::show); + let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch")); + assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns"); + let opacity = panel.rect("Opacity:"); + for name in ["Stroke:", "Fill:"] { + let at = panel.rect(name); + assert!((at.left() - opacity.left()).abs() < 1.0, "Opacity: at {opacity:?} does not start where {name} at {at:?} does"); + } +} + +#[test] +fn the_fill_swatch_lines_up_with_a_dashed_stroke_that_has_a_profile() { + let mut panel = Panel::new(app_with_rect(), appearance::show); + run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2], "profile": "lens"})); + panel.frame(); + assert!(panel.shows("Dashed"), "the stroke row shows no notes"); + let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch")); + assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns"); +} + +#[test] +fn long_stroke_notes_stay_inside_a_narrow_appearance_panel() { + let mut panel = Panel::new(app_with_rect(), appearance::show); + let name = "A calligraphic brush with a very long name for the notes"; + run(&mut panel.app(), "brush.new", json!({"type": "calligraphic", "name": name})); + run(&mut panel.app(), "brush.apply", json!({"name": name})); + run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2]})); + panel.room(egui::vec2(PANEL_MIN_WIDTH, ROOM.y)).frame(); + let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch")); + assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns"); + for at in [stroke, fill] { + assert!(at.right() <= PANEL_MIN_WIDTH, "the swatch at {at:?} runs past the {PANEL_MIN_WIDTH} pt panel"); + } +} + #[test] fn align_to_shares_the_distribute_spacing_line_inside_the_align_panel() { let panel = Panel::new(app_with_rect(), align::show); @@ -104,3 +150,45 @@ fn align_to_shares_the_distribute_spacing_line_inside_the_align_panel() { assert!((field.top()..=field.bottom()).contains(&to.center().y), "Align To at {to:?} is off the spacing field's line {field:?}"); assert!(to.right() <= ROOM.x, "Align To at {to:?} runs past the panel"); } + +#[test] +fn the_swatches_footer_stays_inside_a_short_panel() { + let height = 400.0; + let mut panel = Panel::new(app_with_rect(), swatches::show); + panel.room(egui::vec2(ROOM.x, height)).frame(); + // The swatch browser fills the room the footer leaves, so every footer action is in the panel. + for name in ["Show Swatch Kinds", "New Swatch", "New Color Group", "Delete Swatch"] { + let at = panel.rect(name); + assert!(at.bottom() <= height && at.top() >= 0.0, "{name} at {at:?} is outside the panel's {height} pt"); + } +} + +#[test] +fn the_arrowhead_heads_and_swap_share_one_line_in_the_stroke_panel() { + let names = ["Start arrowhead", "End arrowhead", "Swap start and end arrowheads"]; + let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(340.0), &names); + let middles = panel.middles(&names); + let rects: Vec<&(String, egui::Rect)> = panel.nodes.iter().filter(|(name, _)| names.contains(&name.as_str())).collect(); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?} {rects:?} in {:?}", panel.body); + assert!(panel.past_named(&names).is_empty(), "past the panel: {:?}", panel.past_named(&names)); +} + +#[test] +fn the_arrowhead_scale_and_align_rows_show_their_labels() { + let mut panel = Panel::new(app_with_rect(), stroke::show); + let (shapes, _) = panel.paint_at(1.0); + let texts: Vec<(String, egui::Rect)> = shapes + .iter() + .filter_map(|s| match s { + egui::Shape::Text(t) => Some((t.galley.text().trim_end_matches(':').to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect(); + // Each label sits at the start of its row, before the row's controls. + for (label, control) in [("Scale", "Scale"), ("Align", "Align")] { + let field = panel.rect(control); + let shown = + texts.iter().find(|(text, at)| text == label && at.right() <= field.right() && (field.top()..=field.bottom()).contains(&at.center().y)); + assert!(shown.is_some(), "no {label:?} label on its row at {field:?}; painted: {:?}", texts.iter().map(|t| &t.0).collect::>()); + } +} diff --git a/crates/ui-egui/src/panels/tests_panel_spacing.rs b/crates/ui-egui/src/panels/tests_panel_spacing.rs new file mode 100644 index 0000000000..d93eefca3a --- /dev/null +++ b/crates/ui-egui/src/panels/tests_panel_spacing.rs @@ -0,0 +1,75 @@ +//! Headless frames of the Document Info, Info, Image Trace and Links panels: values line up, groups stand apart from +//! their dividers, every check box shows its label, and an empty Links panel says how to bring an image in. + +use egui::Rect; +use serde_json::json; + +use super::tests_appearance::{app_with_rect, run}; +use super::*; +use crate::tests::panel_harness::{Panel, ROOM}; + +/// The first run the latest frame painted that starts with `prefix`. +fn run_starting(panel: &Panel, prefix: &str) -> Rect { + let texts = panel.texts(); + texts.iter().find(|(t, _)| t.starts_with(prefix)).map(|(_, r)| *r).unwrap_or_else(|| panic!("no run starting {prefix:?} in {texts:?}")) +} + +/// The single run of `text` the latest frame painted. +fn one(panel: &Panel, text: &str) -> Rect { + let rects = panel.painted(text); + assert_eq!(rects.len(), 1, "{text:?} painted {} times in {:?}", rects.len(), panel.texts()); + rects[0] +} + +#[test] +fn document_info_values_end_at_one_edge() { + let mut panel = Panel::new(app_with_rect(), doc_info::show); + panel.frame(); + let ends: Vec = ["Untitled-1", "RGB", "Points"].iter().map(|v| one(&panel, v).right()).collect(); + for end in &ends { + assert!((end - ends[0]).abs() < 1.0, "the values end at {ends:?}, not at one edge"); + } + let (label, value) = (one(&panel, "Color Mode"), one(&panel, "RGB")); + assert!(value.left() > label.right() + label.width(), "the value {value:?} sits against its label {label:?}"); +} + +#[test] +fn info_paints_stand_a_section_apart_from_the_numbers() { + let mut app = app_with_rect(); + run(&mut app, "shape.rectangle", json!({"x": 150, "y": 60, "width": 80, "height": 50})); + run(&mut app, "select.all", json!({})); + let mut panel = Panel::new(app, info::show); + panel.frame(); + let numbers = run_starting(&panel, "D:"); + let paint = run_starting(&panel, "R:"); + let gap = paint.top() - numbers.bottom(); + assert!(gap >= numbers.height(), "the paints start {gap} below the numbers, closer than a line"); + // The two columns split the panel in halves: the right column starts at the panel's middle. + let (x, w) = (run_starting(&panel, "X:"), run_starting(&panel, "W:")); + let half = (ROOM.x - x.left()) / 2.0; + assert!(w.left() - x.left() >= half - 1.0, "W: starts {} in, before the half at {half}", w.left() - x.left()); +} + +#[test] +fn image_trace_create_shows_fills_and_strokes() { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + app.ui.image_trace_advanced = true; + let mut panel = Panel::new(app, image_trace::show); + panel.frame(); + let create = one(&panel, "Create:"); + for label in ["Fills", "Strokes"] { + let at = one(&panel, label); + assert!(at.left() > create.right() && (at.center().y - create.center().y).abs() < create.height(), "{label} at {at:?}"); + } +} + +#[test] +fn empty_links_panel_says_how_to_bring_an_image_in() { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let mut panel = Panel::new(app, links::show); + panel.frame(); + one(&panel, "No images"); + one(&panel, "File › Place… brings in an image, linked or embedded."); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4265351f6a..5ac49daeb9 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -230,6 +230,11 @@ fn zoom_stops(print: Option) -> ZoomScheme { ZoomScheme::ILLUSTRATOR.with_hundred(zoom_baseline(print)) } +/// The zoom stops in the percent the status bar shows, lowest first. +pub fn zoom_stop_percents() -> impl DoubleEndedIterator { + zoom_stops(None).rungs.iter().map(|rung| rung * 100.0) +} + /// The zoom `z` as the status bar shows it, in percent of [`zoom_baseline`]. pub fn zoom_display_percent(z: f64, print: Option) -> f64 { zoom_stops(print).percent(z) diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 7a5dff1202..75801d93fe 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -373,6 +373,16 @@ impl Panel { (shapes, images) } + /// The runs of text the latest frame painted, with their rects. + pub(crate) fn texts(&self) -> Vec<(String, Rect)> { + self.fixture.texts().iter().map(|t| (t.text.clone(), t.rect)).collect() + } + + /// Where the latest frame painted `text` as a whole run. + pub(crate) fn painted(&self, text: &str) -> Vec { + self.texts().into_iter().filter(|(t, _)| t == text).map(|(_, r)| r).collect() + } + /// Where the control of `role` named `name` is, where nodes of other roles share the name. pub(crate) fn rect_role(&self, name: &str, role: craft::ui::contract::Role) -> Rect { self.look_role(name, role).rect