mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
framework-01-w12: net change of 5 commits
- framework-01-w12: written from its sheet - framework-01-w12: repair 1 - Integration: icons.toml lines owed by tools-w16 (dash_align_exact, dash_align_corners) - framework-01-w12: review fixes (review-1) - framework-01-w12: corner dashes put each run's first dash back in front, so the halves at a corner join (fw01 round 2)
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
//! Tests of dash alignment.
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use kurbo::{BezPath, PathEl, Point};
|
||||
|
||||
use super::{DashAlign, DashUnit, StrokeStyle};
|
||||
|
||||
fn style() -> StrokeStyle {
|
||||
StrokeStyle { width: 1.0, dashes: vec![4.0, 2.0], dash_unit: DashUnit::Document, dash_align: DashAlign::Corners, ..StrokeStyle::default() }
|
||||
}
|
||||
|
||||
/// The dashes of `path` as their points.
|
||||
fn dashes(path: &BezPath) -> Vec<Vec<Point>> {
|
||||
let mut out: Vec<Vec<Point>> = Vec::new();
|
||||
for el in path.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => out.push(vec![p]),
|
||||
PathEl::LineTo(p) => {
|
||||
if let Some(d) = out.last_mut() {
|
||||
d.push(p);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn length(d: &[Point]) -> f64 {
|
||||
d.windows(2).map(|w| w[0].distance(w[1])).sum()
|
||||
}
|
||||
|
||||
/// Half a dash (2 at the given pattern) within the bound the fit allows.
|
||||
fn half_dash(l: f64) -> bool {
|
||||
(1.5..2.5).contains(&l)
|
||||
}
|
||||
|
||||
/// Whether a dash runs through `c` with half a dash on each side. The two halves may differ: each
|
||||
/// run is fitted to whole periods on its own, so the runs on either side of a corner scale differently.
|
||||
fn dash_on(dashes: &[Vec<Point>], c: Point) -> bool {
|
||||
dashes.iter().any(|d| {
|
||||
d.iter().position(|p| p.distance(c) < 1e-6).is_some_and(|i| {
|
||||
let (before, after) = (length(&d[..=i]), length(&d[i..]));
|
||||
i > 0 && i + 1 < d.len() && half_dash(before) && half_dash(after)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn corners_alignment_puts_a_dash_on_each_corner() {
|
||||
let style = style();
|
||||
|
||||
let (a, corner, b) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0));
|
||||
let mut open = BezPath::new();
|
||||
open.move_to(a);
|
||||
open.line_to(corner);
|
||||
open.line_to(b);
|
||||
let cut = dashes(&style.dashed(&open, 1.0));
|
||||
assert!(dash_on(&cut, corner), "a dash runs through the corner");
|
||||
let (head, tail) = (cut.first().expect("dashes"), cut.last().expect("dashes"));
|
||||
assert!(head[0].distance(a) < 1e-6 && half_dash(length(head)), "the path starts in the middle of a dash");
|
||||
assert!(tail[tail.len() - 1].distance(b) < 1e-6 && half_dash(length(tail)), "the path ends in the middle of a dash");
|
||||
let starts: Vec<f64> =
|
||||
cut.iter().filter(|d| d.len() == 2 && d[0].y.abs() < 1e-9 && d[1].y.abs() < 1e-9 && length(d) > 3.0).map(|d| d[0].x).collect();
|
||||
assert!(starts.len() > 2, "the first run holds whole dashes");
|
||||
let period = starts[1] - starts[0];
|
||||
assert!((5.0..7.0).contains(&period), "the pattern is scaled within a bound of the given lengths");
|
||||
assert!(starts.windows(2).all(|w| (w[1] - w[0] - period).abs() < 1e-6), "one period along the run");
|
||||
let periods = 100.0 / period;
|
||||
assert!((periods - periods.round()).abs() < 1e-6, "the run holds whole periods");
|
||||
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)];
|
||||
let mut closed = BezPath::new();
|
||||
closed.move_to(corners[0]);
|
||||
for c in &corners[1..] {
|
||||
closed.line_to(*c);
|
||||
}
|
||||
closed.close_path();
|
||||
let cut = dashes(&style.dashed(&closed, 1.0));
|
||||
for c in corners {
|
||||
assert!(dash_on(&cut, c), "a dash runs through the corner {c:?} of the rectangle");
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,23 @@
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, QuadBez, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(test)]
|
||||
mod dash_tests;
|
||||
|
||||
/// The shortest run (between corners and path ends) and the smallest pattern total `Corners` fits.
|
||||
const MIN_RUN: f64 = 1e-6;
|
||||
/// The length and sine below which segments and tangents count as degenerate.
|
||||
const EPS: f64 = 1e-9;
|
||||
/// The accuracy of arc lengths, in document units.
|
||||
const ARCLEN_ACCURACY: f64 = 1e-6;
|
||||
/// The distance within which two dash ends count as the same point, so a dash across a corner joins.
|
||||
const JOIN_EPS: f64 = 1e-6;
|
||||
/// The most dashes one call produces; a path that would need more stays solid.
|
||||
const MAX_OUTPUT_DASHES: usize = 200_000;
|
||||
|
||||
/// Where the stroke sits on the path. Only a closed path aligns; an open one is always centred.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -301,10 +316,28 @@ impl StrokeStyle {
|
||||
|
||||
/// The path cut into its dashes, lengths in document units as [`to_kurbo`](Self::to_kurbo)
|
||||
/// scales them times `length_scale` (1 for a document; a preview passes its sample-to-style
|
||||
/// width ratio). A solid style returns the path.
|
||||
/// width ratio). A solid style returns the path, as does a style that fails
|
||||
/// [`validate`](Self::validate) and a pattern that would give more than 200,000 dashes.
|
||||
///
|
||||
/// [`DashAlign::Exact`] dashes from the dash offset. [`DashAlign::Corners`] ignores the
|
||||
/// offset: each run between corners and path ends is fitted to a whole number of periods and
|
||||
/// starts and ends in the middle of a dash, so a dash is centred on each corner and each end
|
||||
/// of an open path.
|
||||
pub fn dashed(&self, path: &kurbo::BezPath, length_scale: f64) -> kurbo::BezPath {
|
||||
let _ = (path, length_scale);
|
||||
todo!("fx.F59")
|
||||
if self.dashes.is_empty() || self.validate().is_err() {
|
||||
return path.clone();
|
||||
}
|
||||
let scale = self.dash_scale() * length_scale;
|
||||
let pattern: Vec<f64> = self.dashes.iter().map(|&d| f64::from(d) * scale).collect();
|
||||
// `!(x > y)` also refuses a NaN total.
|
||||
if !(pattern.iter().sum::<f64>() > MIN_RUN) {
|
||||
return path.clone();
|
||||
}
|
||||
let cut = match self.dash_align {
|
||||
DashAlign::Exact => dash_exact(path, f64::from(self.dash_offset) * scale, &pattern),
|
||||
DashAlign::Corners => dash_corners(path, &pattern),
|
||||
};
|
||||
cut.unwrap_or_else(|| path.clone())
|
||||
}
|
||||
|
||||
/// The style as a kurbo stroke, for an engine and the editor's line samples: width, join,
|
||||
@@ -312,15 +345,14 @@ impl StrokeStyle {
|
||||
/// width under [`DashUnit::Widths`], taken as they are under [`DashUnit::Document`]. Alignment
|
||||
/// and opacity are not part of a kurbo stroke: an engine strokes an aligned closed path twice
|
||||
/// as wide and clips to its inside ([`StrokeAlign::Inside`]) or outside
|
||||
/// ([`StrokeAlign::Outside`]), and applies the opacity itself.
|
||||
/// ([`StrokeAlign::Outside`]), and applies the opacity itself. The pattern is the
|
||||
/// [`DashAlign::Exact`] one: a [`DashAlign::Corners`] caller strokes the path of
|
||||
/// [`dashed`](Self::dashed) solid.
|
||||
pub fn to_kurbo(&self) -> kurbo::Stroke {
|
||||
// new: kurbo `Stroke::new(width).with_join(..).with_miter_limit(..).with_caps(..)
|
||||
// .with_dashes(offset, pattern)`. PhotoCraft strokes with its own engine
|
||||
// (crates/ui-egui/src/tools/shape_stroke_ui/editor.rs:329-343 renders through it).
|
||||
let scale = match self.dash_unit {
|
||||
DashUnit::Widths => f64::from(self.width),
|
||||
DashUnit::Document => 1.0,
|
||||
};
|
||||
let scale = self.dash_scale();
|
||||
let cap = match self.cap {
|
||||
LineCap::Butt => kurbo::Cap::Butt,
|
||||
LineCap::Round => kurbo::Cap::Round,
|
||||
@@ -337,4 +369,209 @@ impl StrokeStyle {
|
||||
.with_caps(cap)
|
||||
.with_dashes(f64::from(self.dash_offset) * scale, self.dashes.iter().map(|&d| f64::from(d) * scale))
|
||||
}
|
||||
|
||||
/// What one stored dash length is in document units.
|
||||
fn dash_scale(&self) -> f64 {
|
||||
match self.dash_unit {
|
||||
DashUnit::Widths => f64::from(self.width),
|
||||
DashUnit::Document => 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` dashed by `pattern` from `offset`; `None` when it would give too many dashes.
|
||||
fn dash_exact(path: &BezPath, offset: f64, pattern: &[f64]) -> Option<BezPath> {
|
||||
let mut out = BezPath::new();
|
||||
let mut count = 0usize;
|
||||
for el in kurbo::dash(path.iter(), offset, pattern) {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
count += 1;
|
||||
if count > MAX_OUTPUT_DASHES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
out.push(el);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `path` dashed with every run between corners and path ends fitted to whole periods; `None` when
|
||||
/// it would give too many dashes.
|
||||
fn dash_corners(path: &BezPath, pattern: &[f64]) -> Option<BezPath> {
|
||||
let mut pattern = pattern.to_vec();
|
||||
// An odd pattern repeats with its roles swapped, as kurbo reads it.
|
||||
if pattern.len() % 2 == 1 {
|
||||
pattern.extend_from_within(..);
|
||||
}
|
||||
let period: f64 = pattern.iter().sum();
|
||||
let mut out = BezPath::new();
|
||||
let mut count = 0usize;
|
||||
for (segs, closed) in subpaths(path) {
|
||||
for dash in fit_subpath(segs, closed, &pattern, period, &mut count)? {
|
||||
for el in dash {
|
||||
out.push(el);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The subpaths of `path` as segments, each with whether it closes.
|
||||
fn subpaths(path: &BezPath) -> Vec<(Vec<PathSeg>, bool)> {
|
||||
let mut out = Vec::new();
|
||||
let mut segs: Vec<PathSeg> = Vec::new();
|
||||
let (mut start, mut cur) = (Point::ZERO, Point::ZERO);
|
||||
for el in path.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if !segs.is_empty() {
|
||||
out.push((std::mem::take(&mut segs), false));
|
||||
}
|
||||
(start, cur) = (p, p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
segs.push(PathSeg::Line(Line::new(cur, p)));
|
||||
cur = p;
|
||||
}
|
||||
PathEl::QuadTo(a, p) => {
|
||||
segs.push(PathSeg::Quad(QuadBez::new(cur, a, p)));
|
||||
cur = p;
|
||||
}
|
||||
PathEl::CurveTo(a, b, p) => {
|
||||
segs.push(PathSeg::Cubic(CubicBez::new(cur, a, b, p)));
|
||||
cur = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if cur.distance(start) > EPS {
|
||||
segs.push(PathSeg::Line(Line::new(cur, start)));
|
||||
}
|
||||
if !segs.is_empty() {
|
||||
out.push((std::mem::take(&mut segs), true));
|
||||
}
|
||||
cur = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !segs.is_empty() {
|
||||
out.push((segs, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The unit direction of `seg` at its end or start; zero for a degenerate segment.
|
||||
fn tangent(seg: &PathSeg, at_end: bool) -> Vec2 {
|
||||
let pts: Vec<Point> = match seg {
|
||||
PathSeg::Line(l) => vec![l.p0, l.p1],
|
||||
PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
|
||||
PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
|
||||
};
|
||||
let direction = if at_end {
|
||||
let anchor = pts[pts.len() - 1];
|
||||
pts[..pts.len() - 1].iter().rev().map(|p| anchor - *p).find(|d| d.hypot() > EPS)
|
||||
} else {
|
||||
let anchor = pts[0];
|
||||
pts[1..].iter().map(|p| *p - anchor).find(|d| d.hypot() > EPS)
|
||||
};
|
||||
direction.map_or(Vec2::ZERO, Vec2::normalize)
|
||||
}
|
||||
|
||||
/// Whether the path turns where `a` ends and `b` starts.
|
||||
fn is_kink(a: &PathSeg, b: &PathSeg) -> bool {
|
||||
let (ta, tb) = (tangent(a, true), tangent(b, false));
|
||||
if ta.hypot() < EPS || tb.hypot() < EPS {
|
||||
return false;
|
||||
}
|
||||
ta.cross(tb).abs() > EPS || ta.dot(tb) < 0.0
|
||||
}
|
||||
|
||||
fn end_point(el: &PathEl) -> Option<Point> {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p),
|
||||
PathEl::ClosePath => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ends_at(dash: &[PathEl], p: Point) -> bool {
|
||||
dash.last().and_then(end_point).is_some_and(|q| q.distance(p) < JOIN_EPS)
|
||||
}
|
||||
|
||||
fn starts_at(dash: &[PathEl], p: Point) -> bool {
|
||||
dash.first().and_then(end_point).is_some_and(|q| q.distance(p) < JOIN_EPS)
|
||||
}
|
||||
|
||||
/// The dashes of one subpath, each as path elements from a `MoveTo`. Every run between kinks (and
|
||||
/// the path's ends) is stretched to whole periods and dashed from the middle of the first dash, so
|
||||
/// the two half dashes that meet at a corner are joined into one dash; a closed subpath joins its
|
||||
/// last dash to its first the same way. A closed subpath without a kink is one run starting at its
|
||||
/// first point. `None` when `count` passes [`MAX_OUTPUT_DASHES`].
|
||||
fn fit_subpath(segs: Vec<PathSeg>, closed: bool, pattern: &[f64], period: f64, count: &mut usize) -> Option<Vec<Vec<PathEl>>> {
|
||||
let segs: Vec<PathSeg> = segs.into_iter().filter(|s| s.arclen(ARCLEN_ACCURACY) > EPS).collect();
|
||||
let n = segs.len();
|
||||
if n == 0 {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let kink_after = |i: usize| (closed || i + 1 < n) && is_kink(&segs[i], &segs[(i + 1) % n]);
|
||||
let first = if closed { (0..n).find(|&i| kink_after(i)).map_or(0, |i| (i + 1) % n) } else { 0 };
|
||||
let origin = segs[first].start();
|
||||
|
||||
let mut runs: Vec<Vec<PathSeg>> = Vec::new();
|
||||
let mut current: Vec<PathSeg> = Vec::new();
|
||||
for step in 0..n {
|
||||
let i = (first + step) % n;
|
||||
current.push(segs[i]);
|
||||
if step + 1 < n && kink_after(i) {
|
||||
runs.push(std::mem::take(&mut current));
|
||||
}
|
||||
}
|
||||
runs.push(current);
|
||||
|
||||
let mut dashes: Vec<Vec<PathEl>> = Vec::new();
|
||||
for run in &runs {
|
||||
let length: f64 = run.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).sum();
|
||||
if length <= MIN_RUN {
|
||||
continue;
|
||||
}
|
||||
let periods = (length / period).round().max(1.0);
|
||||
let fit = length / (periods * period);
|
||||
let scaled: Vec<f64> = pattern.iter().map(|p| p * fit).collect();
|
||||
let begin = run[0].start();
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(begin);
|
||||
for seg in run {
|
||||
path.push(seg.as_path_el());
|
||||
}
|
||||
let mut fresh: Vec<Vec<PathEl>> = Vec::new();
|
||||
for el in kurbo::dash(path.iter(), scaled[0] / 2.0, &scaled) {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
*count += 1;
|
||||
if *count > MAX_OUTPUT_DASHES {
|
||||
return None;
|
||||
}
|
||||
fresh.push(vec![el]);
|
||||
} else if let Some(dash) = fresh.last_mut() {
|
||||
dash.push(el);
|
||||
}
|
||||
}
|
||||
// `kurbo::dash` holds back a subpath's first dash, to join it with a dash that wraps through a `ClosePath`,
|
||||
// and emits it last. A run never closes, so its first dash goes back to the front.
|
||||
if fresh.len() > 1 && fresh.last().is_some_and(|dash| starts_at(dash, begin)) {
|
||||
fresh.rotate_right(1);
|
||||
}
|
||||
let mut fresh = fresh.into_iter().peekable();
|
||||
if let Some(prev) = dashes.last_mut()
|
||||
&& ends_at(prev, begin)
|
||||
&& fresh.peek().is_some_and(|d| starts_at(d, begin))
|
||||
&& let Some(head) = fresh.next()
|
||||
{
|
||||
prev.extend(head.into_iter().skip(1));
|
||||
}
|
||||
dashes.extend(fresh);
|
||||
}
|
||||
if closed && dashes.len() > 1 && dashes.last().is_some_and(|d| ends_at(d, origin)) && starts_at(&dashes[0], origin) {
|
||||
let head = dashes.remove(0);
|
||||
if let Some(last) = dashes.last_mut() {
|
||||
last.extend(head.into_iter().skip(1));
|
||||
}
|
||||
}
|
||||
Some(dashes)
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ use egui::{Rect, Response, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{
|
||||
DashUnit, LineCap, LineJoin, LineStyle, StrokeAlign, StrokeChoiceRow, StrokeField, StrokeMixed, StrokePreview, StrokeSections, StrokeStyle,
|
||||
DashAlign, DashUnit, LineCap, LineJoin, LineStyle, StrokeAlign, StrokeChoiceRow, StrokeField, StrokeMixed, StrokePreview, StrokeSections, StrokeStyle,
|
||||
StrokeWords,
|
||||
};
|
||||
|
||||
@@ -45,10 +45,9 @@ const PRESETS: [LineStyle; 3] = [LineStyle::Solid, LineStyle::Dashed, LineStyle:
|
||||
pub struct StrokeEditorOutput {
|
||||
/// The editor's whole area.
|
||||
pub response: Response,
|
||||
/// The valid changes, in order, each the whole new style: a preset row, a select, a segmented button, the check,
|
||||
/// Add pair and Remove pair are `Set`s; a number field's typed value is a `Set` and its scrub a gesture (Escape
|
||||
/// cancels). A style that fails [`StrokeStyle::validate`] is never reported. A binding that writes through has
|
||||
/// them already.
|
||||
/// The valid changes, in order, each the whole new style: a preset row, a select, a segmented button and the check
|
||||
/// are `Set`s; a number field's typed value is a `Set` and its scrub a gesture (Escape cancels). A style that fails
|
||||
/// [`StrokeStyle::validate`] is never reported. A binding that writes through has them already.
|
||||
pub events: EditEvents<StrokeStyle>,
|
||||
/// The control the events came from, so the host coalesces one field's edits into one undo step.
|
||||
pub field: Option<StrokeField>,
|
||||
@@ -81,7 +80,8 @@ impl Outcome for StrokeEditorOutput {
|
||||
/// three, dash, gap, dash / gap, dash, gap (0–10000, `×`, or `pt` for document units), each with its word under
|
||||
/// it. A field shows its entry of [`StrokeStyle::dashes`] or is blank; typing in the blank after the pattern adds
|
||||
/// an entry, the blanks after it are off, and clearing a field after the first ends the pattern there. A pattern
|
||||
/// longer than six continues in further rows of three. Then "Dash offset" (±1,000,000).
|
||||
/// longer than six continues in further rows of three. Then "Dash offset" (±1,000,000) and, with
|
||||
/// [`StrokeSections::DASH_ALIGN`], "Align dashes" (Exact, Corners).
|
||||
/// - While the style fails [`StrokeStyle::validate`], the invalid word shows at the end and nothing is reported.
|
||||
/// - [`mixed`](Self::mixed): a mixed field shows the mixed state and lights no button or preset; the first edit sets it
|
||||
/// for all.
|
||||
@@ -449,6 +449,15 @@ impl Body<'_> {
|
||||
number(ui, &words.dash_offset, "dash-offset", f64::from(style.dash_offset), self.mixed.dash_offset, range, self.dash_unit(), true);
|
||||
found.push(StrokeField::DashOffset, event.map(|v| StrokeStyle { dash_offset: v as f32, ..style.clone() }));
|
||||
});
|
||||
if self.sections.contains(StrokeSections::DASH_ALIGN) {
|
||||
let align = [
|
||||
(DashAlign::Exact, "dash_align_exact", &words.dash_exact),
|
||||
(DashAlign::Corners, "dash_align_corners", &words.dash_corners),
|
||||
];
|
||||
let icons = self.sections.contains(StrokeSections::ICONS);
|
||||
let event = choice(ui, &words.dash_align, "dash-align", held(self.mixed.dash_align, style.dash_align), &align, true, icons);
|
||||
found.push(StrokeField::DashAlign, event.map(|dash_align| StrokeStyle { dash_align, ..style.clone() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,10 @@ const MARGIN_SHARE: f32 = 0.15;
|
||||
|
||||
/// A line sample of a [`StrokeStyle`] in a rect: a horizontal line through the rect's centre, drawn
|
||||
/// left to right in every reading direction and centred whatever the style's alignment. The line
|
||||
/// is dashed with `kurbo::dash` from [`StrokeStyle::to_kurbo`] (the dashes scaled to the sample's
|
||||
/// width), then each dash is filled as convex pieces: a quad for the dash, a fan for round caps, a
|
||||
/// quad for square caps.
|
||||
/// is dashed with [`StrokeStyle::dashed`] (the dashes scaled to the sample's width, so
|
||||
/// [`DashAlign::Corners`](crate::stroke::DashAlign::Corners) shows as a dash at both ends), then
|
||||
/// each dash is filled as convex pieces: a quad for the dash, a fan for round caps, a quad for
|
||||
/// square caps.
|
||||
///
|
||||
/// It is a helper of content painters, not a component: [`paint`](Self::paint) fills
|
||||
/// [`shapes`](Self::shapes) in the text ink of the painter's surface.
|
||||
@@ -63,27 +64,24 @@ impl<'a> StrokePreview<'a> {
|
||||
let Some((start, end)) = self.line(rect) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let stroke = self.sample_stroke();
|
||||
if stroke.dash_pattern.is_empty() {
|
||||
pieces.run(&[start, end]);
|
||||
} else {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(start);
|
||||
path.line_to(end);
|
||||
let mut run: Vec<Point> = Vec::new();
|
||||
for el in kurbo::dash(path.iter(), stroke.dash_offset, &stroke.dash_pattern) {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
pieces.run(&run);
|
||||
run.clear();
|
||||
run.push(p);
|
||||
}
|
||||
PathEl::LineTo(p) => run.push(p),
|
||||
_ => {}
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(start);
|
||||
path.line_to(end);
|
||||
// A solid style comes back as the one line, which is a single run.
|
||||
let dashed = self.value.dashed(&path, f64::from(self.width / self.value.width));
|
||||
let mut run: Vec<Point> = Vec::new();
|
||||
for el in dashed.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
pieces.run(&run);
|
||||
run.clear();
|
||||
run.push(p);
|
||||
}
|
||||
PathEl::LineTo(p) => run.push(p),
|
||||
_ => {}
|
||||
}
|
||||
pieces.run(&run);
|
||||
}
|
||||
pieces.run(&run);
|
||||
pieces.out.into_iter().map(|points| PaintShape::Polygon(points.into_iter().map(to_pos).collect())).collect()
|
||||
}
|
||||
|
||||
@@ -95,17 +93,6 @@ impl<'a> StrokePreview<'a> {
|
||||
(right > left).then(|| (Point::new(left, y), Point::new(right, y)))
|
||||
}
|
||||
|
||||
/// The style's kurbo stroke with the dashes rescaled from the style's width to the sample's, so
|
||||
/// the sample keeps the pattern's proportions.
|
||||
fn sample_stroke(&self) -> kurbo::Stroke {
|
||||
let mut stroke = self.value.to_kurbo();
|
||||
let scale = f64::from(self.width / self.value.width);
|
||||
stroke.dash_offset *= scale;
|
||||
for d in &mut stroke.dash_pattern {
|
||||
*d *= scale;
|
||||
}
|
||||
stroke
|
||||
}
|
||||
|
||||
/// Fills [`shapes`](Self::shapes) for `rect` in the painter's ink at the style's opacity.
|
||||
pub fn paint(&self, cx: &ContentPainterCx, rect: Rect) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! selection and the app's choice rows.
|
||||
|
||||
use super::{
|
||||
ChoicePainter, LineCap, LineJoin, StrokeAlign, StrokeButton, StrokeChoice, StrokeChoiceRow, StrokeEditor, StrokeMixed, StrokeSections,
|
||||
ChoicePainter, DashAlign, LineCap, LineJoin, StrokeAlign, StrokeButton, StrokeChoice, StrokeChoiceRow, StrokeEditor, StrokeMixed, StrokeSections,
|
||||
StrokeStyle,
|
||||
};
|
||||
use craft_behavior::Mixed;
|
||||
@@ -36,6 +36,7 @@ fn other_than(base: &StrokeStyle) -> StrokeStyle {
|
||||
miter_limit: base.miter_limit / 2.0,
|
||||
dashes: StrokeStyle::DASHED.to_vec(),
|
||||
dash_offset: 3.0,
|
||||
dash_align: DashAlign::Corners,
|
||||
opacity: base.opacity / 2.0,
|
||||
..base.clone()
|
||||
}
|
||||
@@ -54,7 +55,15 @@ fn with_readout(data: &mut StoryData, output: impl Into<StoryOutput>, latest: Op
|
||||
#[story(StrokeEditor<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn stroke_editor_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let style = data.value("panel", StrokeStyle::default());
|
||||
let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::PANEL).show(ui);
|
||||
let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN).show(ui);
|
||||
let latest = out.events.last().map(|event| format!("{event:?}"));
|
||||
with_readout(data, out, latest)
|
||||
}
|
||||
|
||||
#[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)]
|
||||
fn stroke_editor_popover_dash_align(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let style = data.value("popover-align", StrokeStyle::default().with_line_style(super::LineStyle::Dashed));
|
||||
let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).show(ui);
|
||||
let latest = out.events.last().map(|event| format!("{event:?}"));
|
||||
with_readout(data, out, latest)
|
||||
}
|
||||
@@ -89,7 +98,7 @@ fn stroke_editor_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let base = StrokeStyle::default();
|
||||
StrokeMixed::of([&base, &other_than(&base)]).expect("two styles")
|
||||
});
|
||||
let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).mixed(mixed).show(ui);
|
||||
let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).mixed(mixed).show(ui);
|
||||
let latest = out.events.last().map(|event| format!("{event:?}"));
|
||||
with_readout(data, out, latest)
|
||||
}
|
||||
|
||||
@@ -30,8 +30,8 @@ kind = "fill"
|
||||
base = true
|
||||
drawing_stroke_width = 16.0
|
||||
stroke_drawings = [
|
||||
"adjustment-layer", "bandage-sparkle", "brush-replace", "clip-below", "clip-release", "convert-point",
|
||||
"direct-select", "distribute-bottom", "distribute-hcenter", "distribute-horizontal", "distribute-left",
|
||||
"adjustment-layer", "bandage-sparkle", "brush-replace", "clip-below", "clip-release", "convert-point", "dash-align-corners",
|
||||
"dash-align-exact", "direct-select", "distribute-bottom", "distribute-hcenter", "distribute-horizontal", "distribute-left",
|
||||
"distribute-right", "distribute-top", "distribute-vcenter", "distribute-vertical", "eraser-background",
|
||||
"eraser-magic", "extract-clip", "font-similar", "fx", "gradient-angle", "gradient-diamond", "gradient-linear",
|
||||
"gradient-radial", "gradient-reflected", "insert-clip", "key-auto-bezier", "key-bezier", "key-continuous-bezier",
|
||||
@@ -1526,6 +1526,16 @@ name = "stroke_align_outside"
|
||||
directional = false
|
||||
phosphor = "stroke-align-outside"
|
||||
|
||||
[[icon]]
|
||||
name = "dash_align_exact"
|
||||
directional = false
|
||||
phosphor = "dash-align-exact"
|
||||
|
||||
[[icon]]
|
||||
name = "dash_align_corners"
|
||||
directional = false
|
||||
phosphor = "dash-align-corners"
|
||||
|
||||
[[icon]]
|
||||
name = "stroke_cap_butt"
|
||||
directional = false
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M32 64h16"/><path d="M88 64h32"/><path d="M168 64h32v32"/><path d="M200 144v32"/><path d="M200 208v-16"/></svg>
|
||||
|
After Width: | Height: | Size: 282 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M32 64h32"/><path d="M104 64h32"/><path d="M176 64h24v8"/><path d="M200 112v32"/><path d="M200 184v32"/></svg>
|
||||
|
After Width: | Height: | Size: 281 B |
Reference in New Issue
Block a user