Merge main into fix/craft-libs-07a8c47

This commit is contained in:
dotCooCoo committed 2026-11-28 19:36:20 -08:00
commit ea69457f1a
19 files changed
+331 -47

No files matched your search

+1
View File
@@ -630,6 +630,7 @@ impl Session {
freeform_point: self.selected_freeform_point(),
raster_sample: self.prefs.eyedropper.sample_size,
preview_bounds: self.prefs.use_preview_bounds,
scale_strokes: self.prefs.scale_strokes,
glyph_bounds: self.prefs.type_glyph_bounds,
preview_memo: Some(&self.preview_memo),
unit,
+2
View File
@@ -253,6 +253,8 @@ pub struct ToolContext<'a> {
pub raster_sample: u32,
/// General → Use Preview Bounds: the bounding box measures visual bounds (strokes included).
pub preview_bounds: bool,
/// General → Scale Strokes & Effects: a scale scales the strokes and effects with the art.
pub scale_strokes: bool,
/// Type › Measure Type by Glyph Bounds: the bounding box measures each point type object
/// selected as an object (not inside a selected group) by the ink of its glyphs
/// ([`vectorcraft_effects::preview::Measure`]).
+26 -6
View File
@@ -116,6 +116,10 @@ pub struct PointSnap {
/// The kind of edit the point serves: whether Snap to Pixel rounds it
/// ([`ToolContext::snaps_to_pixel`]).
op: PixelOp,
/// For a scale with Smart Guides and Use Preview Bounds on: the selection's geometric bounds,
/// whose edges line up with the other art's geometric bounds while the handle drags the visual
/// box ([`Self::snap_scale`]).
edges: Option<OrientedBox>,
}
impl PointSnap {
@@ -134,6 +138,17 @@ impl PointSnap {
Self::for_op(cx, PixelOp::Scaling, targets)
}
/// [`Self::scaling`] for the selection's bounding box: with Smart Guides and Use Preview
/// Bounds on, the selection's geometric bounds are the edges that line up.
pub fn scaling_selection(cx: &ToolContext) -> Self {
let mut snap = Self::scaling(cx, || Targets::for_scale(cx));
if snap.targets.is_some() && cx.smart_guides && cx.preview_bounds {
let geometric = vectorcraft_effects::preview::Measure { preview: false, ..cx.bounds_measure() };
snap.edges = vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, geometric);
}
snap
}
fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self {
let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid {
None
@@ -147,7 +162,7 @@ impl PointSnap {
} else {
None
};
Self { targets, op }
Self { targets, op, edges: None }
}
/// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the
@@ -182,7 +197,10 @@ impl PointSnap {
/// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole
/// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that
/// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`]
/// gathered.
/// gathered. With Smart Guides and Use Preview Bounds on, the edges of the selection's
/// geometric bounds line up with the targets, which are the other art's geometric bounds, while
/// the handle stays on the visual box (#6436). The margins between the two boxes keep their
/// size unless Scale Strokes & Effects is on.
pub fn snap_scale(
&self,
cx: &ToolContext,
@@ -205,8 +223,10 @@ impl PointSnap {
// one step always finds one.
return (Targets::grid_lines(moved, step).snap_scale(bx, handle, a, proportional, from_center, step).0, vec![]);
}
// The geometric box lines up when it turns with the box the handle drags.
let edges = self.edges.filter(|g| (g.angle - bx.angle).abs() <= 1e-9).map(|g| (g.rect, !cx.scale_strokes));
match &self.targets {
Some((t, tol)) => t.snap_scale(bx, handle, a, proportional, from_center, cx.tol(*tol)),
Some((t, tol)) => t.snap_scale_edges(bx, edges, handle, a, proportional, from_center, cx.tol(*tol)),
None => (a, vec![]),
}
}
@@ -448,7 +468,7 @@ impl DrawSnap {
/// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only.
pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point {
let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths();
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing }));
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing, edges: None }));
self.snap(cx, p, None)
}
@@ -467,7 +487,7 @@ impl DrawSnap {
/// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in
/// reach, or an anchor, center or crossing in reach of `p` or at `corner`.
pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option<f64> {
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None };
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return None };
if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid {
return None;
}
@@ -517,7 +537,7 @@ impl DrawSnap {
/// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides
/// off, with no targets, and while pixels or the grid snap instead.
pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool {
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false };
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return false };
cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2
}
+75 -9
View File
@@ -1583,12 +1583,39 @@ impl Targets {
/// the nearest target or ruler guide ("align"), whatever the box's angle. A handle with one way
/// to go (a side, or a proportional corner) slides along it until one of them is on a target.
pub fn snap_scale(&self, bx: &OrientedBox, handle: Handle, a: Affine, proportional: bool, from_center: bool, tol: f64) -> (Affine, Vec<Overlay>) {
self.snap_scale_edges(bx, None, handle, a, proportional, from_center, tol)
}
/// [`Self::snap_scale`], with the edges of `edges` landing on the targets in place of the
/// edges of `bx`. `edges` is a box in `bx`'s frame, such as the selection's geometric bounds
/// inside the visual bounds that Use Preview Bounds shows. With its `true`, the margins between
/// the two boxes keep their size as `bx` scales, as `object.setBounds` keeps them; with `false`
/// they scale with it, as `object.transform` scales them. The scale stays one of `bx`.
#[allow(clippy::too_many_arguments)]
pub fn snap_scale_edges(
&self,
bx: &OrientedBox,
edges: Option<(Rect, bool)>,
handle: Handle,
a: Affine,
proportional: bool,
from_center: bool,
tol: f64,
) -> (Affine, Vec<Overlay>) {
type Hit = Option<(f64, Point)>;
// Where a snap lands: in line with a target's x and/or y, or on an anchor or centre.
type Snap = (Hit, Hit, Option<(Point, Kind)>);
let r = bx.rect;
let origin = if from_center { r.center() } else { handle.opposite().pos(r) };
let (d0, [sx, _, _, sy, _, _]) = (handle.pos(r) - origin, a.as_coeffs());
// Margins that keep their size are only measured on a box that does not flip.
let edges = edges.filter(|(g, keep)| g.is_finite() && (!keep || (sx > 0.0 && sy > 0.0)));
let lands = |h: Handle| scale_lands(r, edges, origin, h);
let at = |nx: f64, ny: f64, h: Handle| {
let (v, off) = lands(h);
origin + Vec2::new(nx * v.x, ny * v.y) + off
};
let landed = |out: Affine| scale_landed(bx, edges, out);
let (to_doc, to_local) = (bx.to_doc(), bx.to_doc().inverse());
// A scale that collapses or flips the box is no snap.
let valid = |n: f64, s: f64| n.is_finite() && n * s > 0.0;
@@ -1610,7 +1637,8 @@ impl Targets {
if handle.is_corner() && !proportional {
// The corner goes anywhere: onto an anchor or centre, else it takes the target's x, its
// y, or both.
let p = to_doc * (a * handle.pos(r));
let (v, off) = lands(handle);
let p = to_doc * at(sx, sy, handle);
let (hx, hy) = (nearest(p, true), nearest(p, false));
let on = self.nearest_point(p, tol).map(|(q, k)| (Some((q.x, q)), Some((q.y, q)), Some((q, k))));
for (tx, ty, at) in on.into_iter().chain([(hx, hy, None), (hx, None, None), (None, hy, None)]) {
@@ -1618,7 +1646,7 @@ impl Targets {
continue;
}
let q = to_local * Point::new(tx.map_or(p.x, |h| h.0), ty.map_or(p.y, |h| h.0));
let (mut cx, mut cy) = ((q.x - origin.x) / d0.x, (q.y - origin.y) / d0.y);
let (mut cx, mut cy) = ((q.x - off.x - origin.x) / v.x, (q.y - off.y - origin.y) / v.y);
// Square to the page, the axis without a target stays exactly where it was.
if bx.angle == 0.0 {
(cx, cy) = (if tx.is_some() { cx } else { sx }, if ty.is_some() { cy } else { sy });
@@ -1654,8 +1682,8 @@ impl Targets {
}
};
for h in std::iter::once(handle).chain(ends.into_iter().flatten().copied()) {
let v = h.pos(r) - origin;
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y));
let (v, off) = lands(h);
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y) + off);
let dir = (to_doc * Point::new(e.0 * v.x, e.1 * v.y)).to_vec2();
let p = base + dir * s0;
// An anchor or centre beside its way: it stops at the nearest point of the way.
@@ -1683,7 +1711,7 @@ impl Targets {
return (out, self.label(q, k.label()).into_iter().collect());
}
// The lines run from the target's own point across the resized box, on the page.
let mut nr = (to_doc * out).transform_rect_bbox(r);
let mut nr = landed(out);
let mut ov = vec![];
if let Some((x, from)) = hit_x {
ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1))));
@@ -1692,7 +1720,7 @@ impl Targets {
ov.extend(self.line(Point::new(from.x.min(nr.x0), y), Point::new(from.x.max(nr.x1), y)));
}
if hit_x.is_some() || hit_y.is_some() {
ov.extend(self.label(to_doc * (out * handle.pos(r)), "align"));
ov.extend(self.label(to_doc * at(nx, ny, handle), "align"));
}
if !self.boxes.is_empty() && !from_center {
let aligned = [hit_x.is_some(), hit_y.is_some()];
@@ -1705,8 +1733,7 @@ impl Targets {
let (lo, hi) = span(&nr, is_x);
let len = hi - lo;
let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo };
if len > 1e-9 && new_len > 1e-9 {
let f = new_len / len;
if let Some(f) = spacing_factor(bx, edges, out, is_x, len, new_len) {
let (ax, ay) = handle.axes();
if is_x {
nx *= f;
@@ -1720,7 +1747,7 @@ impl Targets {
}
}
out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2());
nr = (to_doc * out).transform_rect_bbox(r);
nr = landed(out);
ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol)));
}
}
@@ -1729,3 +1756,42 @@ impl Targets {
(out, ov)
}
}
/// Where a point `h` of the box `r` scaled about `origin` goes when the box `edges` lines up in
/// its place ([`Targets::snap_scale_edges`]): to `origin + scale·v + off` for the `(v, off)` given.
fn scale_lands(r: Rect, edges: Option<(Rect, bool)>, origin: Point, h: Handle) -> (Vec2, Vec2) {
match edges {
Some((g, true)) => (h.pos(r) - origin, h.pos(g) - h.pos(r)),
Some((g, false)) => (h.pos(g) - origin, Vec2::ZERO),
None => (h.pos(r) - origin, Vec2::ZERO),
}
}
/// What the scale `out` of `bx` is multiplied by along x (`is_x`) or y for the box whose edges
/// line up to go from length `len` to `new_len` ([`Targets::snap_scale_edges`]). When the margins
/// between `bx` and those edges keep their size, the scale multiplies `bx`'s own length, which
/// changes by as much. None for a length that would collapse.
fn spacing_factor(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine, is_x: bool, len: f64, new_len: f64) -> Option<f64> {
let scaled = if matches!(edges, Some((_, true))) {
let (lo, hi) = span(&(bx.to_doc() * out).transform_rect_bbox(bx.rect), is_x);
hi - lo
} else {
len
};
let grown = scaled + new_len - len;
(len > 1e-9 && new_len > 1e-9 && scaled > 1e-9 && grown > 1e-9).then(|| grown / scaled)
}
/// The box whose edges line up ([`Targets::snap_scale_edges`]), on the page, after the scale `out`
/// of `bx`.
fn scale_landed(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine) -> Rect {
let r = bx.rect;
match edges {
Some((g, true)) => {
let n = out.transform_rect_bbox(r);
bx.to_doc().transform_rect_bbox(Rect::new(n.x0 + g.x0 - r.x0, n.y0 + g.y0 - r.y0, n.x1 - (r.x1 - g.x1), n.y1 - (r.y1 - g.y1)))
}
Some((g, false)) => (bx.to_doc() * out).transform_rect_bbox(g),
None => (bx.to_doc() * out).transform_rect_bbox(r),
}
}
+1
View File
@@ -652,6 +652,7 @@ pub(crate) mod testutil {
freeform_point: None,
raster_sample: 1,
preview_bounds: false,
scale_strokes: false,
glyph_bounds: false,
preview_memo: None,
unit: Unit::Points,
+1 -1
View File
@@ -1985,7 +1985,7 @@ impl SelectionTool {
// What the handle moves snaps as a dragged point does: to pixels or the
// grid, else with Smart Guides to the other objects, else with Snap to
// Point to their anchors; the ruler guides with Snap to Point.
self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.targets = Some(PointSnap::scaling_selection(cx));
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Scaling { handle, bx, areas };
+42
View File
@@ -1291,6 +1291,48 @@ fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() {
}
}
/// With Use Preview Bounds on, a scale handle drags the visual box, and Smart Guides line up the
/// selection's geometric edge with the other art's geometric edge, as a move does.
#[test]
fn a_scale_lines_up_geometric_edges_with_use_preview_bounds_on() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node};
// An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt.
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let mut add = |r: Rect| {
let id = d.alloc_id();
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
id
};
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
add(Rect::new(300.0, 100.0, 400.0, 200.0));
let s = Selection { objects: vec![a], ..Default::default() };
let p = paint();
// The right edge of the box the right-middle handle leaves: the geometric edge with the option
// off, the visual edge 10 pt outside it with the option on.
let right = |preview: bool, from: f64, to: f64| {
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
t.pointer(&c, &ev(PointerKind::Down, from, 150.0));
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
match a.last() {
Some(Action::Preview(cmd, v)) if cmd == "object.setBounds" => 90.0 + v["width"].as_f64().unwrap(),
Some(Action::Preview(_, v)) => v["matrix"][0].as_f64().unwrap() * 200.0 + v["matrix"][4].as_f64().unwrap(),
_ => panic!("{a:?}"),
}
};
let near = |got: f64, want: f64| (got - want).abs() < 1e-9;
// Option off: the edge 1 pt short of the other rectangle's left edge (x = 300) lands on it.
assert!(near(right(false, 200.0, 299.0), 300.0), "{}", right(false, 200.0, 299.0));
assert!(near(right(false, 200.0, 291.0), 291.0), "{}", right(false, 200.0, 291.0));
// Option on: the geometric edge 1 pt short lands on it, which leaves the visual edge at 310.
assert!(near(right(true, 210.0, 309.0), 310.0), "{}", right(true, 210.0, 309.0));
// The visual edge 1 pt past it does not pull the box there: the geometric edge is 9 pt short.
assert!(near(right(true, 210.0, 301.0), 301.0), "{}", right(true, 210.0, 301.0));
}
/// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it
/// began goes back there, labeled "last location", a Shift move too; farther out, with the option
/// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the
+2 -2
View File
@@ -41,7 +41,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag};
use crate::corners::{self, CornerDrag};
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square};
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, square};
use crate::pie::{self, PieDrag};
use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box};
use crate::sidewidget::{self, SideDrag};
@@ -363,7 +363,7 @@ impl ShapeTool {
self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) {
let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type);
let areas = cx.selection.objects.iter().any(is_area);
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None })
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling_selection(cx)), last: None })
} else {
match hit_center(cx, ev.pos, cx.point_tol()) {
Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }),
+34 -2
View File
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use super::{BLUE, polygon, rect_corners};
use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag};
use crate::guides::{PointSnap, Targets};
use crate::guides::PointSnap;
use crate::select::{handle_cursor, matrix_json, screen_handle, selection_box};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -273,7 +273,7 @@ impl Tool for FreeTransformTool {
self.drag = None;
let Some(bx) = selection_box(cx) else { return vec![] };
if let Some(op) = self.classify(cx, &bx, p, ev.mods) {
self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.targets = op.handle().is_some().then(|| PointSnap::scaling_selection(cx));
self.drag = Some(Drag { op, bx, start: p, began: false });
}
vec![]
@@ -454,6 +454,38 @@ mod tests {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 213.0, 150.0)), vec![Action::Commit]);
}
/// With Use Preview Bounds on, a handle drags the visual box, and Smart Guides line up the
/// selection's geometric edge with the other art's geometric edge.
#[test]
fn handle_drag_lines_up_geometric_edges_with_use_preview_bounds_on() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node};
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let mut add = |r: Rect| {
let id = d.alloc_id();
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
id
};
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
add(Rect::new(300.0, 100.0, 400.0, 200.0));
let s = Selection { objects: vec![a], ..Default::default() };
let p = paint();
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
// The right edge of the visual box (90 to 210) after a drag of its right-middle handle.
let right = |to: f64| {
let mut t = FreeTransformTool::default();
t.pointer(&c, &ev(PointerKind::Down, 210.0, 150.0));
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
v["matrix"][0].as_f64().unwrap() * 210.0 + v["matrix"][4].as_f64().unwrap()
};
// The geometric edge 1 pt short of x = 300 lands on it; the visual edge 1 pt past does not.
assert!((right(309.0) - 310.0).abs() < 1e-9, "{}", right(309.0));
assert!((right(301.0) - 301.0).abs() < 1e-9, "{}", right(301.0));
}
/// In a view turned 90° the handles' cursors turn with the view.
#[test]
fn handle_cursors_turn_with_the_view() {
@@ -164,8 +164,10 @@ impl StackDialog for Manager {
// PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them.
ui.scope(|ui| {
ui.disable();
rows::main_rows(ui, &mut params, data, RowsHost::Dialog);
rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None);
rows::settings_group(ui, |ui| {
rows::main_rows(ui, &mut params, data, RowsHost::Dialog);
rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None);
});
});
if builtin {
Text::new(tl!("Built-in presets don't change: New makes a copy you can edit."))
@@ -472,9 +474,11 @@ fn build(data: Arc<RowsData>) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamD
_ => json!({}),
};
let shown = ui.scope(|ui| {
let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog);
let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None);
main.changed || advanced.changed
rows::settings_group(ui, |ui| {
let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog);
let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None);
main.changed || advanced.changed
})
});
if shown.inner {
fields.set("params", FieldValue::Json(params));
+4 -2
View File
@@ -22,7 +22,7 @@ use std::sync::{Arc, OnceLock};
use craft::behavior::overlay::{Align, Side};
use craft::behavior::{ColumnKey, ColumnWidth, CopyKeys, DisplayOrder, EditEvent, IconId, ItemSource, Selection};
use craft::theme::Srgba;
use craft::theme::{ControlSize, Srgba};
use craft::ui::buttons::{Button, ButtonOutput};
use craft::ui::choice::{Swatch, SwatchOutput};
use craft::ui::contract::overlay::{Anchor, Place};
@@ -876,7 +876,8 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> {
}
/// The well of a fill (`fill`) or stroke row, named for it: `paint` as its face, its colour (a solid paint's) as its
/// value.
/// value. The well is a small control, so it stands inside its control-high row and the wells of neighboring rows do
/// not touch.
fn paint_swatch(fill: bool, paint: &Paint) -> Swatch {
let color = paint.color().map_or(Srgba::BLACK, |c| {
let [r, g, b] = c.to_rgb();
@@ -885,6 +886,7 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch {
let row = if fill { tl!("Fill") } else { tl!("Stroke") };
Swatch::new(crate::i18n::fmt(tl!("{row} swatch"), &[("row", row)]), color)
.face(paint_preview::rect_face(paint))
.size(ControlSize::Sm)
.tooltip(tl!("Click to choose a swatch, Shift-click to mix a colour"))
}
+9 -6
View File
@@ -1032,13 +1032,16 @@ fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list:
split_row(app, ui);
let data = RowsData::of(app);
let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel);
let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() };
let advanced = Section::new(tl!("Advanced"))
.open(Bind::bound(&mut app.ui.image_trace_advanced))
.show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler)))
.inner
.unwrap_or_default();
let (main, advanced) = rows::settings_group(ui, |ui| {
let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel);
let advanced = Section::new(tl!("Advanced"))
.open(Bind::bound(&mut app.ui.image_trace_advanced))
.show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler)))
.inner
.unwrap_or_default();
(main, advanced)
});
// A setting is settled when its pick, check or drag ends. Switching to Custom while a slider
// still drags would remove the preset's Enhanced row from under it.
for RowsOutput { committed, .. } in [main, advanced] {
@@ -11,7 +11,7 @@ use craft::theme::Srgba;
use craft::ui::buttons::ToggleButton;
use craft::ui::choice::{Checkbox, Segmented};
use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _};
use craft::ui::form::{Field, SliderField, SliderFieldLayout};
use craft::ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use craft::ui::layout_components::Row;
use craft::ui::pickers::Select;
// PLAN: assumed `IconId` is re-exported from `craft::ui::primitives`.
@@ -132,6 +132,12 @@ fn select_row(ui: &mut Ui, label: &'static str, entries: &[Entry<String>], curre
.flatten()
}
/// Shows `rows` (one host's [`main_rows`] and [`advanced_rows`]) in one field group, so every row's label takes the
/// width of the widest and the selects and sliders start at the same x.
pub(crate) fn settings_group<R: Default>(ui: &mut Ui, mut rows: impl FnMut(&mut Ui) -> R) -> R {
FieldGroup::new(tl!("Tracing Settings")).show(ui, |ui, _| rows(ui)).inner.unwrap_or_default()
}
/// One number setting: its key, name, range, unit and the value shown when the setting is absent.
struct Slider {
key: &'static str,
@@ -706,6 +706,25 @@ fn advanced_is_a_section_that_stays_as_it_was_left() {
assert!(panel.app().ui.image_trace_advanced && panel.shows("Corners"));
}
#[test]
fn the_sliders_and_selects_start_in_one_column() {
use craft::ui::contract::Role;
let mut panel = panel_over(traced_app());
panel.room(egui::vec2(320.0, 1400.0));
panel.frame();
panel.frame();
assert!(panel.app().ui.image_trace_advanced);
// Threshold sits with the main rows and the others in Advanced; the Stroke slider shows dimmed.
let sliders: Vec<(&str, egui::Rect)> =
["Threshold", "Paths", "Corners", "Noise", "Stroke"].into_iter().map(|n| (n, panel.rect_role(n, Role::SLIDER))).collect();
let (_, first) = sliders[0];
for (name, rect) in &sliders {
assert_eq!(rect.left(), first.left(), "the {name} slider starts where Threshold's does");
assert_eq!(rect.width(), first.width(), "the {name} slider is as long as Threshold's");
}
assert_eq!(panel.rect_role("Mode:", Role::COMBO_BOX).left(), first.left(), "the Mode select starts in the sliders' column");
}
#[test]
fn the_palette_shows_in_color_mode_and_traces_again() {
let mut panel = panel_over(traced_app());
@@ -117,6 +117,14 @@ fn the_appearance_swatches_and_labels_line_up() {
}
}
#[test]
fn the_appearance_swatches_of_neighboring_rows_do_not_touch() {
let panel = Panel::new(app_with_rect(), appearance::show);
let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch"));
let gap = (fill.top() - stroke.bottom()).max(stroke.top() - fill.bottom());
assert!(gap >= 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} touch or overlap (gap {gap})");
}
#[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);
+25 -10
View File
@@ -13,8 +13,9 @@ use craft::behavior::Mixed;
use craft::behavior::item_source::keyed;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::contract::{Bind, CollectionEvent, FieldLayout, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft::ui::display::{Divider, Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow, RowEvent, ThumbSize, ThumbTarget};
use craft::ui::menu::PanelRow;
@@ -247,15 +248,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut opacity = None;
Row::new().show(ui, |ui, _| {
Select::new(tl!("Blend Mode"), Bind::bound_mixed(&mut shown_blend).policy(EditPolicy::OnCommit), &entries).enabled(has).show(ui);
opacity = Some(
NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0)))
.unit_kind(UnitKind::Percent)
.range(0.0..=100.0)
.popup_slider(0.0..=100.0)
.enabled(has)
.show(ui)
.edit,
);
opacity = Field::new(tl!("Opacity"))
.layout(FieldLayout::Line)
.sizing(Sizing::Content)
.show(ui, |ui, _| {
NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0)))
.unit_kind(UnitKind::Percent)
.range(0.0..=100.0)
.popup_slider(0.0..=100.0)
.enabled(has)
.show(ui)
.edit
})
.inner;
});
if let (Mixed::Same(b), true) = (&shown_blend, shown_blend != blend_before) {
app.run("transparency.set", json!({"blend": b.label()})).ok();
@@ -493,6 +498,16 @@ mod tests {
assert_eq!(values(&panel), whole);
}
#[test]
fn opacity_field_has_a_visible_label_before_it() {
let mut app = new_app();
run_cmd(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}));
let panel = Panel::new(app, show);
let field = panel.rect_role("Opacity", Role::SPIN_BUTTON);
let labels: Vec<_> = panel.texts().into_iter().filter(|(t, r)| t.trim_end_matches(':') == "Opacity" && r.right() <= field.left()).collect();
assert_eq!(labels.len(), 1, "one Opacity label painted before the field at {field:?}: {:?}", panel.texts());
}
#[test]
fn panel_in_mask_editing_mode_shows_and_edits_the_masked_object() {
let mut app = new_app();
+28 -1
View File
@@ -1134,6 +1134,12 @@ fn is_tool(def: &CommandDef) -> bool {
matches!(def.kind, CommandKind::Tool { .. })
}
/// A tool of the Tools panel: a tool in the app's scope. The tools of a workspace's own dialog
/// (Content-Aware Fill, Liquify, Select and Mask, Vanishing Point and others) are scoped to that dialog, and neither tab lists them.
fn is_app_tool(def: &CommandDef) -> bool {
is_tool(def) && def.scope.is_app()
}
/// The app's rule for the keys a command takes: a tool's shortcut is one key, alone or with Shift,
/// or the tool's own default (the Quick Pen's Alt+P).
fn accept(def: &CommandDef, binding: &Binding) -> Result<(), String> {
@@ -1153,7 +1159,7 @@ fn options() -> Options {
Options::default().with(|o| {
o.area_tabs = true;
o.own_areas = true;
o.areas = vec![Area::new("tools", "Tools", is_tool), Area::new("menu", MENU_COMMANDS, |def| !is_tool(def))];
o.areas = vec![Area::new("tools", "Tools", is_app_tool), Area::new("menu", MENU_COMMANDS, |def| !is_tool(def))];
o.summary = false;
o.accept = Some(Box::new(accept));
o.import_formats = vec![Format::new("kys", "Shortcut set", &["kys"]), Format::new("json", "VectorCraft shortcut set", &["json"])];
@@ -2287,6 +2293,27 @@ mod tests {
assert_eq!(labels, ["Tools", "Menu Commands"]);
}
/// The Tools tab lists the Tools panel's tools, each once, and none of the tools scoped to a workspace's dialog,
/// which the window's keymap also holds.
#[test]
fn the_tools_tab_lists_only_the_apps_tools() {
let (mut app, ctx) = app();
open(&mut app);
dialog_pass(&mut app, &ctx);
dialog_pass(&mut app, &ctx);
let keymap = app.shortcuts_dialog.as_ref().and_then(|d| d.keymap.as_ref()).expect("the dialog's keymap");
let options = options();
let tools = options.areas.iter().find(|a| a.id == "tools").expect("the Tools area");
assert!(
keymap.catalog().iter().any(|d| is_tool(d) && !d.scope.is_app()),
"the window's keymap holds tools of a dialog's scope, which the Tools tab must leave out"
);
let listed: Vec<String> = keymap.catalog().iter().filter(|d| (tools.rows)(d)).map(|d| d.command.key()).collect();
let want: Vec<String> = entries().iter().filter(|e| e.is_tool).map(|e| command_of(&e.key).key()).collect();
assert_eq!(listed.iter().collect::<HashSet<_>>(), want.iter().collect::<HashSet<_>>());
assert_eq!(listed.len(), want.len(), "each tool is listed once");
}
/// An open dialog lists a live-effect plug-in installed while it is open, with the shortcut its
/// set gives it, and drops the row while the plug-in is removed, keeping that shortcut in the
/// set.
+4 -2
View File
@@ -439,12 +439,14 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m
let located = locate::wanted(&app.ui, &home);
let holds = |tool: &str| model.slots.iter().any(|slot| slot.tools.iter().any(|t| t.id == tool));
let reveal = matches!(at, GroupAt::Show(_)).then(|| locate::take_reveal(&mut app.ui, &home, holds)).flatten();
// The current tool in production's pressed fill, with no accent edge.
// The current tool in production's pressed fill, with no accent edge. A rail too short for its tools shows its
// scroll bar with the pointer away too, so the hidden tools can be found.
let mut rail = ToolRail::new(tl!("Tools"), &model.slots, &current, &model.last_used)
.opens(opens)
.tips(&cards)
.active_look(ActiveLook::Pressed)
.density(rail_density(app, &owner));
.density(rail_density(app, &owner))
.bar_at_rest();
if let Some(tool) = &located {
rail = rail.mark(tool);
}
+34
View File
@@ -582,3 +582,37 @@ fn the_rail_builds_its_slots_only_when_its_tool_groups_change() {
let kept = app.dock_rt.rail_models.get(&Owner::Tools.panel()).map(|model| model.slots.len());
assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots");
}
/// A window too short for the tools shows the rail's scroll bar with the pointer away from the rail: a narrow bar,
/// several times taller than wide, inside the rail's end edge. A window tall enough for every tool shows none.
#[test]
fn a_short_tools_rail_shows_its_scroll_bar_at_rest() {
let mut app = app_with(200, 200);
let ctx = reader();
app.run("window.toolbarColumns", json!({ "double": false })).unwrap();
let bars = |app: &mut VectorcraftApp, t0: f64, height: f32| {
let nodes = settled(app, &ctx, t0, height);
let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn");
let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, height)));
let out = crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(t0 + 0.2), screen_rect, ..Default::default() });
let mut stack: Vec<egui::Shape> = out.shapes.into_iter().map(|clipped| clipped.shape).collect();
let mut found = 0;
while let Some(shape) = stack.pop() {
match shape {
egui::Shape::Vec(inner) => stack.extend(inner),
egui::Shape::Rect(r) => {
let b = r.rect;
let narrow = b.width() > 0.0 && b.width() <= rail.width() * 0.25 && b.height() >= b.width() * 3.0;
let at_end = rail.expand(0.5).contains_rect(b) && b.center().x > rail.center().x;
if narrow && at_end {
found += 1;
}
}
_ => {}
}
}
found
};
assert!(bars(&mut app, 0.0, 400.0) > 0, "a short rail shows its scroll bar with the pointer away");
assert_eq!(bars(&mut app, 10.0, 2000.0), 0, "a rail with room for every tool shows no scroll bar");
}