Merge branch 'fw/merge-c1' into fw/merge-c4

This commit is contained in:
aiongg
2026-11-16 12:44:54 +00:00
10 changed files with 636 additions and 93 deletions
+28 -2
View File
@@ -1,5 +1,5 @@
//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`] and
//! [`polygon_step`].
//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`],
//! [`polygon_step`] and [`axis_or_diagonal`].
use kurbo::{Point, Vec2};
@@ -7,6 +7,10 @@ use kurbo::{Point, Vec2};
/// before a locked direction switches, so it doesn't flicker near the diagonal.
pub const LOCK_HYSTERESIS_DEGREES: f64 = 8.0;
/// How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal
/// ([`axis_or_diagonal`]).
pub const AXIS_BAND_DEGREES: f64 = 30.0;
/// The directions ⇧ locks a move to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
@@ -56,6 +60,28 @@ pub fn polygon_step(from: Point, point: Point) -> Point {
from + Vec2::new(shorter.copysign(delta.x), shorter.copysign(delta.y))
}
/// Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the
/// axis through `from` and keeps its offset along it; otherwise onto the 45° diagonal, at the shorter of its two
/// offsets on both axes. `point` itself for a zero or non-finite offset.
pub fn axis_or_diagonal(from: Point, point: Point) -> Point {
// Photoshop flattens a 26.6° drag and keeps a 39.8° one diagonal (#13243); anchors stay on the axis at a 5:12
// slope (22.6°) and go diagonal at 45° (#13207).
let delta = point - from;
if !delta.x.is_finite() || !delta.y.is_finite() || delta == Vec2::ZERO {
return point;
}
let tan = AXIS_BAND_DEGREES.to_radians().tan();
let (ax, ay) = (delta.x.abs(), delta.y.abs());
if ay < ax * tan {
return Point::new(point.x, from.y);
}
if ax < ay * tan {
return Point::new(from.x, point.y);
}
let shorter = ax.min(ay);
from + Vec2::new(shorter.copysign(delta.x), shorter.copysign(delta.y))
}
/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle
/// or a segment drawn from a fixed point. A polygon's vertex takes [`polygon_step`] instead. `point` itself when it
/// is on `from` or not finite.
+3 -1
View File
@@ -18,7 +18,9 @@ pub mod snap;
pub use crop::{AspectHold, CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step, turn_grid};
pub use draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft};
pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, polygon_step, round_to_direction, turn_to_45};
pub use lock::{
AXIS_BAND_DEGREES, Directions, LOCK_HYSTERESIS_DEGREES, axis_or_diagonal, lock_direction, polygon_step, round_to_direction, turn_to_45,
};
pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels};
pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock};
pub use outside::outside_pieces;
+26 -2
View File
@@ -1,7 +1,7 @@
//! The ⇧ rules for a drag from a fixed point.
use craft_behavior::geometry::turn_to_45;
use kurbo::Point;
use craft_behavior::geometry::{axis_or_diagonal, turn_to_45};
use kurbo::{Point, Vec2};
#[test]
fn shift_turns_a_point_onto_the_nearest_45_degree_ray_keeping_its_distance() {
@@ -13,3 +13,27 @@ fn shift_turns_a_point_onto_the_nearest_45_degree_ray_keeping_its_distance() {
assert!(((turned - from).hypot() - 20.0).abs() < 1e-9, "the distance is kept");
assert_eq!(turn_to_45(from, from), from);
}
/// A drag of `(dx, dy)` from `from`, reflected into each octant: the rule must not depend on the direction.
fn octants(dx: f64, dy: f64) -> [Vec2; 8] {
[(dx, dy), (dy, dx), (-dx, dy), (-dy, dx), (dx, -dy), (dy, -dx), (-dx, -dy), (-dy, -dx)].map(|(x, y)| Vec2::new(x, y))
}
#[test]
fn shift_snaps_a_line_to_the_axis_within_30_degrees_and_to_the_diagonal_past_it() {
let from = Point::new(10.0, 10.0);
// 26.6° from the axis: onto the axis, keeping the offset along it.
for d in octants(40.0, 20.0) {
let snapped = axis_or_diagonal(from, from + d) - from;
let along = if d.x.abs() > d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) };
assert_eq!(snapped, along, "{d:?} lies within 30° of an axis");
}
// 39.8° from the axis: onto the diagonal at the shorter offset, both signs kept.
for d in octants(60.0, 50.0) {
let snapped = axis_or_diagonal(from, from + d) - from;
assert_eq!(snapped, Vec2::new(50f64.copysign(d.x), 50f64.copysign(d.y)), "{d:?} is past 30° from the axes");
}
// An anchor at a 5:12 slope, with the noise a stored path carries, stays on the axis.
assert_eq!(axis_or_diagonal(from, from + Vec2::new(60.0, -25.0 + 5e-5)), Point::new(70.0, 10.0));
assert_eq!(axis_or_diagonal(from, from), from, "no offset, no change");
}
+73 -20
View File
@@ -40,9 +40,14 @@ pub enum ShapeGeometry {
/// The bounds of the ellipse.
rect: Rect,
},
/// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Triangle and
/// Polygon). `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon.
/// The Triangle tool is 3 sides.
/// A triangle filling `rect`: the apex at the top centre, the base on the bottom edge (PhotoCraft's Triangle
/// tool and Create Triangle).
Triangle {
/// The triangle's bounds.
rect: Rect,
},
/// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Polygon).
/// `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon.
Polygon {
/// The box whose inscribed ellipse holds the polygon.
rect: Rect,
@@ -93,9 +98,10 @@ impl ShapeGeometry {
/// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain
/// rectangle.
/// - `Ellipse`: kurbo's `Ellipse::from_rect`.
/// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`.
/// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point
/// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine:
/// a triangle's base lies a quarter of the height below the centre, not on the bottom
/// a 3-sided polygon's base lies a quarter of the height below the centre, not on the bottom
/// edge); a star alternates outer and inner points, the inner ones on the ellipse
/// scaled by `star_ratio`.
/// - `RadialPolygon`: `sides` outer points on the circle of `radius`, the first at `rotation`
@@ -105,7 +111,7 @@ impl ShapeGeometry {
/// - `Custom`: the box itself (the app draws the preset).
pub fn to_path(&self, tolerance: f64) -> BezPath {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:73-79 (the kinds: `roundedRect` with four
// equal radii, ellipse, a polygon of 3 sides for the Triangle, `polygon_sides.max(3)`).
// equal radii, ellipse, `triangle` filling its rect, `polygon_sides.max(3)`).
// new: PhotoCraft's engine draws the outline; here it is kurbo's `RoundedRect`, `Ellipse`
// and a point list, so engines without one share it.
let tolerance = tolerance.max(f64::EPSILON);
@@ -119,6 +125,11 @@ impl ShapeGeometry {
}
}
Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance),
Self::Triangle { rect } => {
// pc: #13350 (the triangle fills its box, apex on top).
let rect = rect.abs();
closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)])
}
Self::Polygon { rect, sides, star_ratio } => {
let rect = rect.abs();
let (c, rx, ry) = (rect.center(), rect.width() / 2.0, rect.height() / 2.0);
@@ -145,34 +156,76 @@ impl ShapeGeometry {
pub fn bounds(&self) -> Rect {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box).
match *self {
Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => rect.abs(),
Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Triangle { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => {
rect.abs()
}
Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius),
Self::Line { from, to, .. } => Rect::from_points(from, to),
}
}
}
/// The box a drag from `start` to `end` draws, in whole pixels, or `None` when a side is under
/// How a box drag turns the press and the pointer into a box ([`box_drag`]). The default draws the dragged box.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct BoxRule {
/// Both sides take the drag's shorter extent, each keeping its direction (⇧).
pub square: bool,
/// The press is the centre: the box is twice the extent (⌥). With `fixed`, the release is the centre.
pub from_centre: bool,
/// A fixed width and height: the box has this size with its top left at the release, whatever the drag.
pub fixed: Option<(f64, f64)>,
/// A width to height ratio: the largest box of this ratio inside the dragged one, from the press.
pub ratio: Option<(f64, f64)>,
}
/// The box a drag from `start` to `end` draws under `rule`, in whole pixels, or `None` when a side is under
/// [`MIN_SIDE`].
///
/// - `square` (⇧): both sides take the larger absolute extent, each keeping its direction.
/// - `from_centre` (⌥): `start` is the centre; the box is twice the extent.
/// - `fixed` (both sides finite and above 0): that size at the release; `square` and `ratio` do not apply.
/// - `square`: both sides take the drag's shorter extent, each keeping its direction.
/// - `ratio` (both parts finite and above 0): the largest box of that ratio inside the (squared) drag.
/// - `from_centre`: `start` is the centre; the box is twice the extent.
/// - The top left and the size round to whole pixels, as PhotoCraft rounds `[x, y, w, h]`.
pub fn box_drag(start: Point, end: Point, square: bool, from_centre: bool) -> Option<Rect> {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:63-72 (⇧: `m = w.abs().max(h.abs())` with the
// signs kept; ⌥: origin `start - (w, h)`, size doubled; `[x0.min(x0 + w).round(), …,
// w.abs().round(), …]`; `rect[2] < 1.0 || rect[3] < 1.0` draws nothing).
let (mut w, mut h) = (end.x - start.x, end.y - start.y);
if square {
let m = w.abs().max(h.abs());
(w, h) = (m * sign(w), m * sign(h));
}
let (x0, y0) = if from_centre { (start.x - w, start.y - h) } else { (start.x, start.y) };
let (w, h) = if from_centre { (w * 2.0, h * 2.0) } else { (w, h) };
pub fn box_drag(start: Point, end: Point, rule: BoxRule) -> Option<Rect> {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs `drag_box` (⇧: `m = w.abs().min(h.abs())` with the
// signs kept, #13222; ⌥: origin `start - (w, h)`, size doubled; the Rectangle gear's Fixed Size and
// Proportional, #13343), `shape_geometry` (`[x0.min(x0 + w).round(), …, w.abs().round(), …]`;
// `rect[2] < 1.0 || rect[3] < 1.0` draws nothing).
let (x0, y0, w, h) = if let Some((fw, fh)) = rule.fixed.and_then(positive) {
// From Center with Fixed Size is not measured: the size is centred on the release.
if rule.from_centre { (end.x - fw / 2.0, end.y - fh / 2.0, fw, fh) } else { (end.x, end.y, fw, fh) }
} else {
let (mut w, mut h) = (end.x - start.x, end.y - start.y);
if rule.square {
let m = w.abs().min(h.abs());
(w, h) = (m * sign(w), m * sign(h));
}
if let Some((rw, rh)) = rule.ratio.and_then(positive) {
let s = (w.abs() / rw).min(h.abs() / rh);
(w, h) = (rw * s * sign(w), rh * s * sign(h));
}
if rule.from_centre { (start.x - w, start.y - h, w * 2.0, h * 2.0) } else { (start.x, start.y, w, h) }
};
let (x, y, w, h) = (x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round());
(w >= MIN_SIDE && h >= MIN_SIDE).then(|| Rect::new(x, y, x + w, y + h))
}
/// `pair` when both parts are finite and above 0 (a gear field that is not empty).
fn positive(pair: (f64, f64)) -> Option<(f64, f64)> {
(pair.0.is_finite() && pair.1.is_finite() && pair.0 > 0.0 && pair.1 > 0.0).then_some(pair)
}
/// The tight box of the equilateral triangle, apex up, inscribed in the circle of `square`: what ⇧ draws with the
/// Triangle tool (#13350). With the square centred on the press (⇧⌥), the triangle's centre is the press.
pub fn equilateral_in(square: Rect) -> Rect {
let square = square.abs();
let r = square.width() / 2.0;
let half_base = r * 3f64.sqrt() / 2.0;
let x = square.center().x - half_base;
Rect::new(x, square.y0, x + 2.0 * half_base, square.y0 + 1.5 * r)
}
/// The end of a line dragged from `from` to `to`, or `None` when it is shorter than
/// [`MIN_SIDE`].
pub fn line_drag(from: Point, to: Point) -> Option<Point> {
+1 -1
View File
@@ -293,6 +293,6 @@ impl Default for ShapeToolSettings {
impl ShapeToolSettings {
/// The drag options of `kind` with these values.
pub fn drag_options(&self, kind: ShapeKind) -> ShapeDragOptions {
ShapeDragOptions { kind, corner_radius: self.corner_radius, sides: self.sides, star_ratio: self.star_ratio, line_weight: self.line_weight }
ShapeDragOptions::new(kind).corner_radius(self.corner_radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight)
}
}
+60 -34
View File
@@ -9,7 +9,7 @@ use craft_behavior::Mixed;
use craft_theme::variant::Tone;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Entry, Props as _, Remember as _, Show as _, ShowContainer as _};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::dialog::{Alert, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::{FormDialog, GuideUnits};
@@ -17,7 +17,7 @@ use craft_ui::pickers::UnitSelect;
use craft_ui::runtime::env::{Env, Label, UnitKind, Units};
use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft_ui::sections::DialogRole;
use craft_ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField};
use craft_ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField, RangeAlert};
use egui::Ui;
use kurbo::{Point, Rect};
use serde::{Deserialize, Serialize};
@@ -151,9 +151,10 @@ struct Memory {
/// "Radius" label, with the "Link radii" toggle between the columns (`LinkMode::Equal`, on by
/// default). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon drag
/// keeps ratio 1. Then "From Center".
/// - A width or height outside [`CreateShapeOptions::SIZE`] shows [`CreateShapeWords::bad_size`] under
/// the fields and disables OK; so does a click farther than 300,000 px from the origin
/// ([`CreateShapeWords::bad_position`]).
/// - A width or height typed past [`CreateShapeOptions::SIZE`] keeps the nearest end and raises the range alert,
/// which the app opens from [`take_range_alert`](Self::take_range_alert) (#13358). A size set out of range
/// through automation shows [`CreateShapeWords::bad_size`] under the fields and disables OK; so does a click
/// farther than 300,000 px from the origin ([`CreateShapeWords::bad_position`]).
/// - OK answers [`CreatedShape`] at the click (centred on it with From Center, unrounded) and
/// remembers width, height, From Center and the star ratio per kind; Cancel answers nothing and
/// remembers nothing.
@@ -165,6 +166,10 @@ pub struct CreateShapeDialog {
units: [UnitKind; 2],
/// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it.
open: bool,
/// The title of the range alert; the dialog's own title when `None`.
alert_title: Option<Label>,
/// The last range alert a size field raised, with the env it showed in (which words it), until the app takes it.
range_alert: Option<(RangeAlert, Env)>,
}
/// The document a dialog without [`CreateShapeOptions::units`] measures in: pixels, with no percent.
@@ -209,7 +214,7 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re
ShapeGeometry::Rect { rect, radii }
}
ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect },
ShapeKind::Triangle => ShapeGeometry::Polygon { rect, sides: 3, star_ratio: 1.0 },
ShapeKind::Triangle => ShapeGeometry::Triangle { rect },
ShapeKind::Polygon | ShapeKind::Star => {
let ratio = if o.star_ratio.is_finite() { o.star_ratio.clamp(0.01, 1.0) } else { 1.0 };
ShapeGeometry::Polygon { rect, sides, star_ratio: ratio }
@@ -219,6 +224,19 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re
Ok(CreatedShape { kind: o.kind, geometry, from_center: o.from_center })
}
/// The dialog's title for `kind`.
fn title_of(kind: ShapeKind, words: &CreateShapeWords) -> Label {
let title = match kind {
ShapeKind::RoundedRectangle => &words.rounded_rectangle,
ShapeKind::Ellipse => &words.ellipse,
ShapeKind::Triangle => &words.triangle,
ShapeKind::Polygon => &words.polygon,
ShapeKind::Star => &words.star,
ShapeKind::Rectangle | ShapeKind::Line | ShapeKind::Custom => &words.rectangle,
};
Label::from(title.as_str().to_owned())
}
/// The save key of the kind: `craft_draw.shape.create.<kind>`.
fn save_key(kind: ShapeKind) -> SaveKey {
let kind = match kind {
@@ -272,7 +290,22 @@ impl CreateShapeDialog {
/// Create Shape with `options`.
pub fn new(options: CreateShapeOptions) -> Self {
let ruler = options.units.map_or(UnitKind::Pixels, |units| units.ruler);
CreateShapeDialog { id: dialog_id("shape.create"), options, units: [ruler; 2], open: true }
CreateShapeDialog { id: dialog_id("shape.create"), options, units: [ruler; 2], open: true, alert_title: None, range_alert: None }
}
/// The title of the range alert a size field raises (the app's name); the dialog's title by default.
#[must_use]
pub fn alert_title(mut self, title: impl Into<Label>) -> Self {
self.alert_title = Some(title.into());
self
}
/// The range alert of a width or height typed past [`CreateShapeOptions::SIZE`], worded once; `None` until a
/// size field raises one, and after it was taken.
pub fn take_range_alert(&mut self) -> Option<Alert<'static>> {
let (alert, env) = self.range_alert.take()?;
let title = self.alert_title.clone().unwrap_or_else(|| title_of(self.options.kind, &env.words::<CreateShapeWords>()));
Some(Alert::range(title, &alert, &env))
}
/// Puts the kind's remembered values over the opening ones, once, before the first show, OK or set reads them:
@@ -297,7 +330,8 @@ impl CreateShapeDialog {
}
}
/// One size field (`axis` 0 is Width, 1 Height) in its unit; sets `size` when the number changed.
/// One size field (`axis` 0 is Width, 1 Height) in its unit; sets `size` when the number changed. The range alert
/// of a typed number past [`CreateShapeOptions::SIZE`].
fn size_field(
ui: &mut Ui,
axis: usize,
@@ -306,7 +340,7 @@ fn size_field(
size: &mut (f64, f64),
document: &GuideUnits,
entries: &[Entry<UnitKind>],
) {
) -> Option<RangeAlert> {
let extent = extent_of(document, axis);
let shown = shown_size(document, axis, *unit, *size);
let (low, high) = (
@@ -326,6 +360,7 @@ fn size_field(
{
set_size(document, axis, *unit, size, value);
}
out.out_of_range
}
/// The pixels a percentage of size field `axis` is of: the document's width or height.
@@ -372,22 +407,20 @@ fn body(
words: &CreateShapeWords,
numbers: &Units,
latest: &RefCell<Option<Memory>>,
typed: &mut Option<RangeAlert>,
) -> bool {
let document = values.units.unwrap_or_else(pixels_only);
let entries: Vec<Entry<UnitKind>> = length_units(values).map(|kind| Entry::new(kind, Label::from(numbers.symbol(kind)))).collect();
let kind = values.kind;
let name = match kind {
ShapeKind::RoundedRectangle => &words.rounded_rectangle,
ShapeKind::Ellipse => &words.ellipse,
ShapeKind::Triangle => &words.triangle,
ShapeKind::Polygon => &words.polygon,
ShapeKind::Star => &words.star,
ShapeKind::Rectangle | ShapeKind::Line | ShapeKind::Custom => &words.rectangle,
};
FieldGroup::new(name.clone()).show(ui, |ui, _| {
FieldGroup::new(title_of(kind, words)).show(ui, |ui, _| {
let (width, height) = (Label::from(words.width.as_str().to_owned()), Label::from(words.height.as_str().to_owned()));
Field::new(width.clone()).show(ui, |ui, _| size_field(ui, 0, &width, &mut units[0], &mut values.size, &document, &entries));
Field::new(height.clone()).show(ui, |ui, _| size_field(ui, 1, &height, &mut units[1], &mut values.size, &document, &entries));
for (axis, caption) in [(0, &width), (1, &height)] {
Field::new(caption.clone()).show(ui, |ui, _| {
if let Some(alert) = size_field(ui, axis, caption, &mut units[axis], &mut values.size, &document, &entries) {
*typed = Some(alert);
}
});
}
if matches!(kind, ShapeKind::Rectangle | ShapeKind::RoundedRectangle) {
Field::new(Label::from(words.radius.as_str().to_owned())).show(ui, |ui, _| {
// The radii are top-left, top-right, bottom-right, bottom-left; the two columns read
@@ -541,23 +574,13 @@ impl StackDialog for CreateShapeDialog {
let env = Env::of(ui);
let words = env.words::<CreateShapeWords>();
let numbers = env.units();
let title = Label::from(
match self.options.kind {
ShapeKind::RoundedRectangle => &words.rounded_rectangle,
ShapeKind::Ellipse => &words.ellipse,
ShapeKind::Triangle => &words.triangle,
ShapeKind::Polygon => &words.polygon,
ShapeKind::Star => &words.star,
ShapeKind::Rectangle | ShapeKind::Line | ShapeKind::Custom => &words.rectangle,
}
.as_str()
.to_owned(),
);
let title = title_of(self.options.kind, &words);
self.recall(ui.ctx());
let write_key = save_key(self.options.kind);
let latest = Rc::new(RefCell::new(None::<Memory>));
let write = Rc::clone(&latest);
let CreateShapeDialog { options, units, open, .. } = self;
let mut typed = None::<RangeAlert>;
let CreateShapeDialog { options, units, open, range_alert, .. } = self;
let shown = FormDialog::new(title, Bind::bound(options))
.opened(Bind::bound(open))
.alt_resets(false)
@@ -570,7 +593,10 @@ impl StackDialog for CreateShapeDialog {
}
})
})
.show(ui, |ui, _, values| body(ui, values, units, &words, &numbers, &latest));
.show(ui, |ui, _, values| body(ui, values, units, &words, &numbers, &latest, &mut typed));
if let Some(alert) = typed {
*range_alert = Some((alert, env.clone()));
}
match (shown.accepted, shown.closed) {
(Some(values), _) => answer(&values, &words, &numbers).ok().map(DialogResult::Ok),
(None, Some(_)) => Some(DialogResult::Cancel),
+80 -2
View File
@@ -11,11 +11,15 @@ mod dialog;
mod tool;
mod words;
use std::ops::RangeInclusive;
use craft_behavior::EditEvent;
use craft_keymap::Mods;
use kurbo::Point;
use serde::{Deserialize, Serialize};
use crate::geometry::shape::ShapeGeometry;
use crate::ui::shape::VectorMode;
pub use dialog::{CreateShapeDialog, CreateShapeOptions, CreatedShape};
pub use tool::ShapeDragTool;
@@ -57,6 +61,52 @@ pub enum ShapeFrame {
Radial,
}
/// What the Rectangle tool's gear keeps a box drag to ([`BoxConstraints::constraint`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum BoxConstraint {
/// The dragged box.
#[default]
Unconstrained,
/// A square; ⇧ draws the dragged box instead.
Square,
/// The gear's width and height, with the top left at the release.
FixedSize,
/// The largest box of the gear's width to height ratio inside the drag, from the press.
Proportional,
}
/// The Rectangle tool's gear: a constraint, its sizes, and From Center. A Fixed Size or Proportional pair with an
/// empty field (`None`) or a 0 draws as Unconstrained.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct BoxConstraints {
/// The constraint chosen.
pub constraint: BoxConstraint,
/// Fixed Size's width and height in pixels, in [`FIXED`](Self::FIXED); empty to start.
pub fixed: (Option<f64>, Option<f64>),
/// Proportional's width and height, in [`RATIO`](Self::RATIO); 1 : 1 to start.
pub ratio: (Option<f64>, Option<f64>),
/// The press is the box's centre; ⌥ draws from the corner instead.
pub from_center: bool,
}
impl BoxConstraints {
/// The range of a Fixed Size field, in whole pixels.
pub const FIXED: RangeInclusive<f64> = 0.0..=300_000.0;
/// The range of a Proportional field.
pub const RATIO: RangeInclusive<f64> = 0.0..=99_999.0;
}
impl Default for BoxConstraints {
/// Unconstrained, Fixed Size empty, Proportional 1 : 1, From Center off.
fn default() -> Self {
BoxConstraints { constraint: BoxConstraint::Unconstrained, fixed: (None, None), ratio: (Some(1.0), Some(1.0)), from_center: false }
}
}
/// The tool options a drag reads each pass: the kind from the selected tool, the rest from the
/// options bar (PhotoCraft's `ToolOptions`). [`ShapeToolSettings::drag_options`](super::shape::ShapeToolSettings::drag_options)
/// builds it from the stored settings.
@@ -73,6 +123,11 @@ pub struct ShapeDragOptions {
pub star_ratio: f64,
/// The Line's weight, at least 1.
pub line_weight: f64,
/// The gear's constraints for a box drag; ⇧ and ⌥ turn its Square and From Center off.
pub constraints: BoxConstraints,
/// What the drag makes: a Rectangle in Shape mode ends a click within 1 screen point, every other drag within
/// the press slop.
pub mode: VectorMode,
}
impl ShapeDragOptions {
@@ -108,12 +163,35 @@ impl ShapeDragOptions {
self.line_weight = weight;
self
}
/// The gear's constraints for a box drag (Photoshop shows the gear for the Rectangle only).
#[must_use]
pub fn constraints(mut self, constraints: BoxConstraints) -> Self {
self.constraints = constraints;
self
}
/// What the drag makes (the options bar's mode).
#[must_use]
pub fn mode(mut self, mode: VectorMode) -> Self {
self.mode = mode;
self
}
}
impl Default for ShapeDragOptions {
/// Rectangle, square corners, 5 sides, a plain polygon, weight 3 (PhotoCraft's defaults).
/// Rectangle, square corners, 5 sides, a plain polygon, weight 3, unconstrained, Shape mode (PhotoCraft's
/// defaults).
fn default() -> Self {
ShapeDragOptions { kind: ShapeKind::Rectangle, corner_radius: 0.0, sides: 5, star_ratio: 1.0, line_weight: 3.0 }
ShapeDragOptions {
kind: ShapeKind::Rectangle,
corner_radius: 0.0,
sides: 5,
star_ratio: 1.0,
line_weight: 3.0,
constraints: BoxConstraints::default(),
mode: VectorMode::Shape,
}
}
}
+53 -22
View File
@@ -2,18 +2,19 @@
use std::sync::Arc;
use craft_behavior::geometry::turn_to_45;
use craft_behavior::geometry::axis_or_diagonal;
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed};
use craft_keymap::{Key, Mods};
use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas_controls::path_runs;
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth};
use craft_ui::runtime::env::Label;
use kurbo::Point;
use kurbo::{Point, Vec2};
use super::words::ShapeDragWords;
use super::{ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind};
use crate::geometry::shape::{RadialFrame, SIDES, ShapeGeometry, box_drag, line_drag};
use super::{BoxConstraint, ShapeDragEvent, ShapeDragOptions, ShapeDragRules, ShapeFrame, ShapeKind};
use crate::geometry::shape::{BoxRule, MIN_SIDE, RadialFrame, SIDES, ShapeGeometry, box_drag, equilateral_in, line_drag};
use crate::ui::shape::VectorMode;
/// The flattening tolerance of the outline being drawn, in screen points.
const OUTLINE_TOLERANCE: f32 = 0.25;
@@ -27,11 +28,16 @@ const OUTLINE_TOLERANCE: f32 = 0.25;
/// - The press starts at the snapped point; past the press slop the drag begins and each pass reports
/// the shape it would draw; release commits it.
/// - A side under 1 px makes nothing: the gesture is cancelled as `Dismissed`.
/// - A press and release inside the slop is a [`Click`](ShapeDragEvent::Click) at the press.
/// - ⇧ makes a square or circle (a Line: 45° steps keeping its length); ⌥ draws from the centre.
/// - A press and release inside the slop is a [`Click`](ShapeDragEvent::Click) at the press; a Rectangle in
/// Shape mode has a slop of 1 screen point, so a 2 × 1 point drag draws.
/// - ⇧ makes a square or circle from the drag's shorter side (a Line: onto the axis within 30° of it, keeping the
/// offset along it, else onto the diagonal at the shorter offset); ⌥ draws from the centre.
/// Both may go down or up mid-drag; the shape follows the modifiers held now.
/// - Space held moves the shape being drawn without resizing it: the press point moves with the
/// pointer while Space is down, and the box snaps as a whole.
/// - The options' [`BoxConstraints`](super::BoxConstraints) (the Rectangle tool's gear) keep a box drag square, at a
/// fixed size at the release, or at a ratio, and From Center draws from the press as the centre; with Square or
/// From Center on, ⇧ or ⌥ turns it off.
/// - Space held moves the shape being drawn without resizing it: every move while Space is down, the first one
/// included, moves the press point by the pointer's motion, and the box snaps as a whole.
/// - Esc cancels (the host calls [`cancel`](CanvasTool::cancel)); so does a tool switch: `Cancel`
/// goes out when a drag had begun.
///
@@ -78,6 +84,8 @@ struct Drag {
options: ShapeDragOptions,
/// The press on screen, for the press slop.
press: egui::Pos2,
/// How far the pointer may move from the press, in screen points, before the drag begins.
click_slop: f32,
/// The press as the pointer made it, snapped.
origin: Point,
/// The press, moved by Space.
@@ -86,8 +94,6 @@ struct Drag {
at: Point,
/// Past the press slop: `Begin` went out.
began: bool,
/// Whether Space was held in the last call.
space: bool,
/// A radial star's inner radius held by Ctrl/Cmd.
inner: Option<f64>,
/// Sides or points as changed by ↑ and ↓ during this drag.
@@ -141,10 +147,12 @@ impl ShapeDragTool {
}
/// The shape a drag from `start` to `at` with `mods` draws under the options and rules, or `None`
/// when a side is under 1 px: [`box_drag`] for the box kinds (Rectangle with four equal radii when
/// `corner_radius` > 0, Rounded Rectangle always with them, Triangle a 3-sided polygon, Polygon and
/// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧
/// toggling Square and ⌥ From Center (Rectangle with four equal radii when
/// `corner_radius` > 0, Rounded Rectangle always with them, Triangle filling the box (⇧: the equilateral
/// triangle in the square's circle), Polygon and
/// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧),
/// [`line_drag`] for a Line (weight at least 1, ⇧ turning the end to 45° steps), and
/// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and
/// [`RadialFrame::drag`] in the radial frame.
fn shape_of(&self, drag: &Drag, mods: Mods) -> Option<ShapeGeometry> {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:50-82 `shape_geometry`.
@@ -152,8 +160,9 @@ impl ShapeDragTool {
let o = &drag.options;
let radii = [o.corner_radius.max(0.0); 4];
if o.kind == ShapeKind::Line {
let end = if mods.shift { turn_to_45(drag.start, drag.at) } else { drag.at };
let to = line_drag(drag.start, end)?;
// The drag's own length decides whether a line is drawn, before ⇧ shortens a diagonal.
line_drag(drag.start, drag.at)?;
let to = if mods.shift { line_shift(drag.start, drag.at) } else { drag.at };
return Some(ShapeGeometry::Line { from: drag.start, to, weight: o.line_weight.max(1.0) });
}
if self.radial(o.kind) {
@@ -171,13 +180,21 @@ impl ShapeDragTool {
};
return Some(frame.geometry(drag.sides, star_ratio));
}
let rect = box_drag(drag.start, drag.at, mods.shift, mods.alt)?;
let c = &o.constraints;
let pair = |(w, h): (Option<f64>, Option<f64>)| w.zip(h);
let rule = BoxRule {
square: mods.shift != (c.constraint == BoxConstraint::Square),
from_centre: mods.alt != c.from_center,
fixed: (c.constraint == BoxConstraint::FixedSize).then(|| pair(c.fixed)).flatten(),
ratio: (c.constraint == BoxConstraint::Proportional).then(|| pair(c.ratio)).flatten(),
};
let rect = box_drag(drag.start, drag.at, rule)?;
Some(match o.kind {
ShapeKind::Rectangle if o.corner_radius > 0.0 => ShapeGeometry::Rect { rect, radii },
ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] },
ShapeKind::RoundedRectangle => ShapeGeometry::Rect { rect, radii },
ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect },
ShapeKind::Triangle => ShapeGeometry::Polygon { rect, sides: 3, star_ratio: 1.0 },
ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect } },
ShapeKind::Polygon => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: 1.0 },
ShapeKind::Star => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: o.star_ratio },
ShapeKind::Custom | ShapeKind::Line => ShapeGeometry::Custom { rect, keep_proportions: mods.shift },
@@ -197,14 +214,13 @@ impl ShapeDragTool {
self.drag = Some(drag);
return;
}
let space_held = cx.held(Key::Space);
if space_held && drag.space {
// pc: #13867 (the Frame tool: every move with Space held, the first included, moves the box by the motion).
if cx.held(Key::Space) {
drag.start += at - drag.at;
}
drag.space = space_held;
drag.at = at;
if !drag.began {
if pos.distance(drag.press) < cx.slop {
if pos.distance(drag.press) < drag.click_slop {
self.drag = Some(drag);
return;
}
@@ -239,6 +255,19 @@ impl ShapeDragTool {
}
}
/// The end of a ⇧ Line drag from `from` to `to`: [`axis_or_diagonal`], with a line on an axis at least
/// [`MIN_SIDE`] long (a drag of a pixel can keep less than that along its axis).
fn line_shift(from: Point, to: Point) -> Point {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs `shape_geometry` (#13243: `dx.abs().max(1.0).copysign(dx)` on
// an axis).
let d = axis_or_diagonal(from, to) - from;
if d.x != 0.0 && d.y != 0.0 {
return from + d;
}
let at_least = |v: f64| if v == 0.0 { 0.0 } else { v.abs().max(MIN_SIDE).copysign(v) };
from + Vec2::new(at_least(d.x), at_least(d.y))
}
impl CanvasTool for ShapeDragTool {
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
// pc: crates/ui-egui/src/canvas/gesture.rs:84 (a shape drag that stays inside
@@ -246,17 +275,19 @@ impl CanvasTool for ShapeDragTool {
let Some(space) = cx.space() else { return ToolAction::Ignored };
let options = self.options;
let origin = cx.snap(space.view.to_doc(pointer.pos));
// pc: crates/ui-egui/src/dialogs/shape_dialog.rs `is_tool_click` (#13340).
let click_slop = if options.kind == ShapeKind::Rectangle && options.mode == VectorMode::Shape { 1.0 } else { cx.slop };
self.next = self.next.next();
self.drag = Some(Drag {
id: self.next,
label: Arc::from(cx.words::<ShapeDragWords>().draw.as_str()),
options,
press: pointer.pos,
click_slop,
origin,
start: origin,
at: origin,
began: false,
space: cx.held(Key::Space),
inner: None,
sides: options.sides.clamp(*SIDES.start(), *SIDES.end()),
shape: None,
+290 -4
View File
@@ -1,12 +1,19 @@
//! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point.
use craft_behavior::CanvasView;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::kurbo::{Point, Rect, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::geometry::shape::ShapeGeometry;
use craft_draw::ui::shape_drag::{CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragOptions, ShapeDragTool, ShapeKind};
use craft_draw::ui::shape::VectorMode;
use craft_draw::ui::shape_drag::{
BoxConstraint, BoxConstraints, CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragEvent, ShapeDragOptions, ShapeDragTool, ShapeKind,
};
use craft_ui::contract::Role;
use craft_ui::dialog::{DialogHost, DialogId, DialogResult};
use craft_ui::testing::{ToolFixture, trial};
use craft_ui::testing::{Fixture, ToolFixture, trial};
use egui::{Event, Key, Modifiers, PointerButton, Pos2};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::rc::Rc;
/// The view of a canvas filling `room`, with its middle at the document's middle.
fn room_view(room: egui::Rect) -> CanvasView {
@@ -19,6 +26,249 @@ fn tool(kind: ShapeKind) -> ShapeDragTool {
tool
}
/// A Shape tool on a canvas, with the events it reported so far.
struct Shapes {
fixture: ToolFixture<ShapeDragTool>,
log: Vec<ShapeDragEvent>,
}
impl Shapes {
fn new(options: ShapeDragOptions) -> Self {
let mut tool = ShapeDragTool::new();
tool.options(options);
Shapes { fixture: ToolFixture::with_view("Shape", tool, room_view, |_, _| {}), log: Vec::new() }
}
fn sync(&mut self) {
let events = self.fixture.tool_mut().take_events();
self.log.extend(events);
}
/// The screen point of the document point `p`.
fn at(&self, p: Point) -> Pos2 {
room_view(self.fixture.canvas().rect).to_screen(p)
}
fn button(&mut self, p: Point, pressed: bool, modifiers: Modifiers) {
let pos = self.at(p);
self.fixture.fixture().frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }]);
self.sync();
}
fn press(&mut self, p: Point, modifiers: Modifiers) {
self.fixture.fixture().hold(modifiers);
let pos = self.at(p);
self.fixture.fixture().frame(vec![Event::PointerMoved(pos)]);
self.button(p, true, modifiers);
}
fn move_to(&mut self, p: Point, modifiers: Modifiers) {
self.fixture.fixture().hold(modifiers);
let pos = self.at(p);
self.fixture.fixture().frame(vec![Event::PointerMoved(pos)]);
self.sync();
}
fn release(&mut self, p: Point, modifiers: Modifiers) {
self.button(p, false, modifiers);
self.fixture.fixture().hold(Modifiers::NONE);
self.fixture.fixture().frame(Vec::new());
self.sync();
}
/// Space goes down or up.
fn space(&mut self, down: bool) {
let key = Event::Key { key: egui::Key::Space, physical_key: None, pressed: down, repeat: false, modifiers: Modifiers::NONE };
self.fixture.fixture().frame(vec![key]);
self.sync();
}
/// Press at `from`, move past the press slop, then to `to`, and release there, all with `modifiers`.
fn drag(&mut self, from: Point, to: Point, modifiers: Modifiers) {
self.press(from, modifiers);
self.move_to(from + Vec2::new(40.0, 30.0), modifiers);
self.move_to(to, modifiers);
self.release(to, modifiers);
}
/// The shape the last drag committed.
fn committed(&self) -> Option<ShapeGeometry> {
self.log.iter().rev().find_map(|event| match event {
ShapeDragEvent::Draw(EditEvent::Commit { after, .. }) => Some(after.clone()),
_ => None,
})
}
/// The shape of the last `Update`.
fn proposed(&self) -> Option<ShapeGeometry> {
self.log.iter().rev().find_map(|event| match event {
ShapeDragEvent::Draw(EditEvent::Update { value, .. }) => Some(value.clone()),
_ => None,
})
}
/// The box the last drag committed.
fn committed_box(&self) -> Option<Rect> {
self.committed().map(|shape| shape.bounds())
}
/// Whether the last gesture ended as a click.
fn clicked(&self) -> bool {
matches!(self.log.last(), Some(ShapeDragEvent::Click { .. }))
}
fn forget(&mut self) {
self.log.clear();
}
}
const PRESS: Point = Point::new(100.0, 100.0);
/// A ⇧ Line drag snaps onto the axis within 30° of it, keeping the offset along it and at least a pixel long, and
/// onto the diagonal at the shorter offset past that; the drag's last proposal is the line it commits.
#[trial]
fn a_shift_line_snaps_to_the_axis_or_the_diagonal_and_commits_what_it_proposed() {
let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Line));
let line_end = |shape: Option<ShapeGeometry>| match shape {
Some(ShapeGeometry::Line { from, to, .. }) => Some(to - from),
_ => None,
};
shapes.drag(PRESS, PRESS + Vec2::new(0.95, 0.4), Modifiers::SHIFT);
assert_eq!(line_end(shapes.committed()), Some(Vec2::new(1.0, 0.0)), "a short drag still draws a 1 px horizontal line");
assert_eq!(shapes.proposed(), shapes.committed(), "the last proposal is the committed line");
shapes.forget();
shapes.drag(PRESS, PRESS + Vec2::new(-60.0, 50.0), Modifiers::SHIFT);
assert_eq!(line_end(shapes.committed()), Some(Vec2::new(-50.0, 50.0)), "past 30° the line takes the diagonal");
assert_eq!(shapes.proposed(), shapes.committed());
}
/// ⇧ squares the box from the drag's shorter side, ⇧⌥ from the press as the centre; an Ellipse becomes a circle.
#[trial]
fn shift_squares_the_box_from_the_shorter_side() {
let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle));
shapes.drag(PRESS, PRESS + Vec2::new(60.0, 20.0), Modifiers::SHIFT);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 120.0, 120.0)), "the square takes the shorter side at the press");
shapes.forget();
shapes.drag(PRESS, PRESS + Vec2::new(-60.0, 20.0), Modifiers::SHIFT | Modifiers::ALT);
assert_eq!(shapes.committed_box(), Some(Rect::new(80.0, 80.0, 120.0, 120.0)), "⇧⌥ centres the square on the press");
let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Ellipse));
shapes.drag(PRESS, PRESS + Vec2::new(20.0, 60.0), Modifiers::SHIFT);
assert_eq!(shapes.committed(), Some(ShapeGeometry::Ellipse { rect: Rect::new(100.0, 100.0, 120.0, 120.0) }), "a circle of the shorter side");
}
/// A Rectangle drag under the gear `constraint` with `change` applied to the gear's values.
fn gear(constraint: BoxConstraint, change: impl FnOnce(&mut BoxConstraints)) -> Shapes {
let mut constraints = BoxConstraints::default();
constraints.constraint = constraint;
change(&mut constraints);
Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle).constraints(constraints))
}
/// The gear's Square and From Center hold without ⇧ or ⌥, which turn them off; Fixed Size puts its size at the
/// release; Proportional draws the largest box of its ratio inside the drag; an empty Fixed Size field draws the
/// dragged box.
#[trial]
fn the_rectangle_gear_constrains_the_drag_and_shift_and_alt_turn_it_off() {
let to = PRESS + Vec2::new(60.0, 20.0);
let mut shapes = gear(BoxConstraint::Square, |_| {});
shapes.drag(PRESS, to, Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 120.0, 120.0)), "Square holds without ⇧");
shapes.drag(PRESS, to, Modifiers::SHIFT);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "⇧ turns Square off");
let mut shapes = gear(BoxConstraint::Unconstrained, |c| c.from_center = true);
shapes.drag(PRESS, to, Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(40.0, 80.0, 160.0, 120.0)), "From Center draws about the press");
shapes.drag(PRESS, to, Modifiers::ALT);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "⌥ turns From Center off");
let mut shapes = gear(BoxConstraint::FixedSize, |c| c.fixed = (Some(30.0), Some(10.0)));
shapes.drag(PRESS, to, Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(160.0, 120.0, 190.0, 130.0)), "Fixed Size puts its top left at the release");
let mut shapes = gear(BoxConstraint::FixedSize, |c| c.fixed = (Some(30.0), None));
shapes.drag(PRESS, to, Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 120.0)), "an empty field draws the dragged box");
let mut shapes = gear(BoxConstraint::Proportional, |c| c.ratio = (Some(2.0), Some(1.0)));
shapes.drag(PRESS, PRESS + Vec2::new(60.0, 50.0), Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(100.0, 100.0, 160.0, 130.0)), "the largest 2 : 1 box inside the drag");
}
/// The corners of the triangle `shape` draws, from the apex clockwise.
fn corners(shape: Option<ShapeGeometry>) -> Vec<Point> {
let Some(shape @ ShapeGeometry::Triangle { .. }) = shape else { return Vec::new() };
shape.to_path(0.1).elements().iter().filter_map(|el| el.end_point()).collect()
}
/// A Triangle drag fills its box, apex on top; ⇧ draws the equilateral triangle in the circle of the shorter
/// side's square; ⇧⌥ centres it on the press.
#[trial]
fn a_triangle_fills_its_box_and_shift_makes_it_equilateral() {
let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Triangle));
let to = PRESS + Vec2::new(60.0, 40.0);
shapes.drag(PRESS, to, Modifiers::NONE);
let plain = corners(shapes.committed());
assert_eq!(plain.first(), Some(&Point::new(130.0, 100.0)), "the apex is the box's top centre: {plain:?}");
assert!(plain.len() >= 3 && plain[1..].iter().all(|p| p.y == 140.0), "the base lies on the bottom edge: {plain:?}");
shapes.drag(PRESS, to, Modifiers::SHIFT);
let equal = corners(shapes.committed());
assert!(equal.len() >= 3, "a triangle: {equal:?}");
let sides = [(equal[0] - equal[1]).hypot(), (equal[1] - equal[2]).hypot(), (equal[2] - equal[0]).hypot()];
assert!(sides.iter().all(|side| (side - 20.0 * 3f64.sqrt()).abs() < 1e-9), "three equal sides in the 40 px square's circle: {sides:?}");
assert_eq!(equal[0], Point::new(120.0, 100.0), "the apex is the top of the circle");
shapes.drag(PRESS, to, Modifiers::SHIFT | Modifiers::ALT);
let centred = corners(shapes.committed());
assert!(centred.len() >= 3, "a triangle: {centred:?}");
let centre = (centred[0].to_vec2() + centred[1].to_vec2() + centred[2].to_vec2()) / 3.0;
assert!((centre.to_point() - PRESS).hypot() < 1e-9, "⇧⌥ puts the centre on the press, got {centre:?}");
}
/// A press moved 2 × 1 points and released: a Rectangle in Shape mode draws it, in Path mode it is a click, and an
/// Ellipse in Shape mode keeps the press slop.
#[trial]
fn a_shape_mode_rectangle_ends_a_click_within_one_point() {
let nudge = |kind: ShapeKind, mode: VectorMode| {
let mut shapes = Shapes::new(ShapeDragOptions::new(kind).mode(mode));
let to = PRESS + Vec2::new(2.0, 1.0);
shapes.press(PRESS, Modifiers::NONE);
shapes.move_to(to, Modifiers::NONE);
shapes.release(to, Modifiers::NONE);
shapes
};
let drawn = nudge(ShapeKind::Rectangle, VectorMode::Shape);
assert!(!drawn.clicked(), "the Rectangle in Shape mode drew: {:?}", drawn.log);
assert_eq!(drawn.committed_box(), Some(Rect::new(100.0, 100.0, 102.0, 101.0)));
assert!(nudge(ShapeKind::Rectangle, VectorMode::Path).clicked(), "in Path mode the press slop holds");
assert!(nudge(ShapeKind::Ellipse, VectorMode::Shape).clicked(), "other kinds keep the press slop");
}
/// Space held moves the box by the pointer's whole motion, the first move after Space went down included; released,
/// the drag resizes again.
#[trial]
fn space_moves_the_box_by_the_full_motion() {
let mut shapes = Shapes::new(ShapeDragOptions::new(ShapeKind::Rectangle));
let corner = PRESS + Vec2::new(40.0, 30.0);
shapes.press(PRESS, Modifiers::NONE);
shapes.move_to(corner, Modifiers::NONE);
assert_eq!(shapes.proposed().map(|shape| shape.bounds()), Some(Rect::new(100.0, 100.0, 140.0, 130.0)));
shapes.space(true);
shapes.move_to(corner + Vec2::new(10.0, 5.0), Modifiers::NONE);
assert_eq!(shapes.proposed().map(|shape| shape.bounds()), Some(Rect::new(110.0, 105.0, 150.0, 135.0)), "the first move moves the box");
shapes.space(false);
let end = corner + Vec2::new(30.0, 25.0);
shapes.move_to(end, Modifiers::NONE);
shapes.release(end, Modifiers::NONE);
assert_eq!(shapes.committed_box(), Some(Rect::new(110.0, 105.0, 170.0, 155.0)), "without Space the drag resizes from the moved press");
}
#[trial]
fn the_shape_tool_owes_the_canvas_what_every_tool_owes() {
ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check();
@@ -88,3 +338,39 @@ fn create_shape_ok_remembers_the_size_and_cancel_and_a_picked_unit_do_not() {
let ellipse = confirm(&mut host, &ctx).expect("an ellipse answers");
assert_eq!(ellipse.geometry.bounds(), Rect::new(10.0, 20.0, 110.0, 120.0), "an ellipse keeps its own memory: the defaults");
}
/// A width typed past 1–300,000 px keeps 300,000 and raises the range alert once, for every kind; a width in range
/// raises none.
#[trial]
fn create_shape_alerts_once_for_a_size_typed_past_its_range() {
for kind in [ShapeKind::Rectangle, ShapeKind::Triangle] {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(egui::Vec2::new(1200.0, 900.0));
let options = CreateShapeOptions::initial(kind, Point::new(10.0, 20.0)).recalled();
host.borrow_mut().open(CreateShapeDialog::new(options).alert_title("PhotoCraft"));
fixture.settle();
let width = fixture
.by_role(Role::SPIN_BUTTON)
.into_iter()
.find(|field| fixture.tree().name_of(field.node) == Some("Width"))
.expect("the Width field");
let type_width = |fixture: &mut Fixture, text: &str| {
fixture.click(&width).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text(text);
fixture.key(Key::Tab, Modifiers::NONE).settle();
};
let width_now = |host: &Rc<RefCell<DialogHost>>| host.borrow().get::<CreateShapeDialog>().map(|dialog| dialog.options().size.0);
let take = |host: &Rc<RefCell<DialogHost>>| host.borrow_mut().get_mut::<CreateShapeDialog>().and_then(CreateShapeDialog::take_range_alert);
type_width(&mut fixture, "400000");
assert_eq!(width_now(&host), Some(300_000.0), "{kind:?}: the field keeps the end of the range");
assert!(take(&host).is_some(), "{kind:?}: the typed width raises the range alert");
assert!(take(&host).is_none(), "{kind:?}: the alert is taken once");
type_width(&mut fixture, "500");
assert_eq!(width_now(&host), Some(500.0));
assert!(take(&host).is_none(), "{kind:?}: a width in range raises no alert");
}
}
+22 -5
View File
@@ -6,7 +6,7 @@ use crate::contract::{
};
use crate::runtime::env::{Label, UnitKind};
use crate::style::{ComponentStyle, StyleCx};
use crate::text::NumberField;
use crate::text::{NumberField, RangeAlert};
use craft_behavior::{EditEvents, Flow, Metrics, Mixed, Proposal, Sense};
use egui::{Rect, Response, Vec2, pos2};
use std::ops::{Deref, RangeInclusive};
@@ -24,7 +24,8 @@ pub struct UnitSelectStyle {
number: f32,
}
/// The output of a unit select: the number's edit, and the unit's edit when a unit was picked.
/// The output of a unit select: the number's edit, the unit's edit when a unit was picked, and the number field's
/// range alert.
#[derive(Debug)]
#[non_exhaustive]
pub struct UnitSelectOutput {
@@ -32,6 +33,9 @@ pub struct UnitSelectOutput {
pub edit: EditResponse<Option<f64>>,
/// The unit the user picked this pass.
pub unit: EditEvents<UnitKind>,
/// A typed number the field clamped to its range, in the pass it committed (the number field's own
/// `out_of_range`): the app shows the range alert.
pub out_of_range: Option<RangeAlert>,
}
impl Deref for UnitSelectOutput {
@@ -77,13 +81,25 @@ pub struct UnitSelect<'a> {
number_enabled: Option<bool>,
/// The unit child's event of this pass, kept from `paint` to `finish`.
unit_event: EditEvents<UnitKind>,
/// The number child's range alert of this pass, kept from `paint` to `finish`.
out_of_range: Option<RangeAlert>,
}
impl<'a> UnitSelect<'a> {
/// A number field named `label` over `value`, with a select of `units` over `unit` after it.
pub fn new(label: impl Into<Label>, value: Bind<'a, Option<f64>>, unit: Bind<'a, UnitKind>, units: &'a [Entry<UnitKind>]) -> Self {
UnitSelect { common: Common::new(), value, unit, units, range: None, unit_label: None, number_enabled: None, unit_event: EditEvents::new() }
.label(label)
UnitSelect {
common: Common::new(),
value,
unit,
units,
range: None,
unit_label: None,
number_enabled: None,
unit_event: EditEvents::new(),
out_of_range: None,
}
.label(label)
}
fn number(&self, name: Label, value: Mixed<Option<f64>>, kind: Option<UnitKind>) -> NumberField<'static> {
@@ -158,12 +174,13 @@ impl Component for UnitSelect<'_> {
let start = cx.value().and_then(|value| *value);
let number = ui.child("number", place(number_rect), self.number(group.clone(), shown, kind));
cx.adopt(&number, &start, |value, mine| *mine = *value);
self.out_of_range = number.out_of_range;
let select = Select::new(self.select_name(&group), self.unit.reborrowed(), self.units);
self.unit_event = ui.child("unit", place(select_rect), select).events;
}
fn finish(self, cx: Cx<'_, Self>) -> UnitSelectOutput {
UnitSelectOutput { edit: cx.edit_response(), unit: self.unit_event }
UnitSelectOutput { edit: cx.edit_response(), unit: self.unit_event, out_of_range: self.out_of_range }
}
}