behavior, ui-canvas: RulerUnits::with_labels(TickLabels::Signed) writes ruler ticks signed with only the decimals they need (-2.5, 0.3, 1), VectorCraft's form; TickLabels::Distance stays the default

This commit is contained in:
bflatastic
2026-11-23 19:35:36 +07:00
parent 0c633a83cd
commit 95e4ec879e
6 changed files with 122 additions and 29 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ mod view;
pub mod zoom;
pub use history::{ViewHistory, ViewPlace};
pub use units::{RulerUnits, Ticks};
pub use units::{RulerUnits, TickLabels, Ticks};
pub use view::{CanvasView, resize_cursor};
pub use zoom::{ZoomFloor, ZoomScheme};
+45 -13
View File
@@ -2,6 +2,8 @@
//! lives here; the text of a distance or a tick is written by craft-ui over `Env::units`, so no second number
//! formatter exists.
use std::ops::RangeInclusive;
/// How a ruler divides its unit at a zoom.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
@@ -19,8 +21,20 @@ pub enum Ticks {
Custom(fn(f64) -> (f64, u32)),
}
/// The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for
/// the readout of a drag, their AccessKit values and Shift's snap to the ticks.
/// How a ruler writes the number at a labelled tick.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TickLabels {
/// PhotoCraft's: the distance from the zero point with no minus sign, a step under 1 with at least two decimals
/// (`2.50`, `0.30`, `1.0000` on a sixteenth-inch ruler).
#[default]
Distance,
/// VectorCraft's: the signed position, with only the decimals the tick needs (`-2.5`, `0.3`, `1`).
Signed,
}
/// The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it;
/// guides use it for the readout of a drag, their AccessKit values and Shift's snap to the ticks.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct RulerUnits {
@@ -28,6 +42,8 @@ pub struct RulerUnits {
pub per_doc: f64,
/// How the ticks are spaced.
pub ticks: Ticks,
/// How the labelled ticks are written.
pub labels: TickLabels,
}
impl Ticks {
@@ -38,9 +54,16 @@ impl Ticks {
}
impl RulerUnits {
/// Ruler units of `per_doc` per document unit, spaced by `ticks`.
/// Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`].
pub const fn new(per_doc: f64, ticks: Ticks) -> Self {
Self { per_doc, ticks }
Self { per_doc, ticks, labels: TickLabels::Distance }
}
/// The units with their ticks written as `labels`.
#[must_use]
pub const fn with_labels(mut self, labels: TickLabels) -> Self {
self.labels = labels;
self
}
/// Whole document pixels.
@@ -78,22 +101,31 @@ impl RulerUnits {
(position - zero) * self.per_doc
}
/// The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at
/// least 1 takes the decimals it has (none for 5, one for 2.5), a smaller one at least two (PhotoCraft's
/// `0.50`), more when it has them (0.025).
pub fn label_decimals(&self, step: f64) -> usize {
match self.ticks {
/// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers;
/// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a
/// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them
/// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler).
pub fn label_decimals(&self, step: f64) -> RangeInclusive<usize> {
let most = match self.ticks {
Ticks::Decimal { whole: true } => 0,
_ if step.abs() < 1.0 => step_decimals(step).max(2),
_ if step.abs() < 1.0 && self.labels == TickLabels::Distance => step_decimals(step).max(2),
_ => step_decimals(step),
};
match self.labels {
TickLabels::Distance => most..=most,
TickLabels::Signed => 0..=most,
}
}
/// The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`:
/// the distance without a minus sign left of or above the zero point (PhotoCraft's `ruler_label`), rounded when
/// the ticks are whole.
/// under [`TickLabels::Distance`] the distance without a minus sign left of or above the zero point (PhotoCraft's
/// `ruler_label`), under [`TickLabels::Signed`] the value itself; rounded when the ticks are whole.
pub fn label_value(&self, value: f64, step: f64) -> f64 {
if self.label_decimals(step) == 0 { value.abs().round() } else { value.abs() }
let value = match self.labels {
TickLabels::Distance => value.abs(),
TickLabels::Signed => value,
};
if *self.label_decimals(step).end() == 0 { value.round() } else { value }
}
}
+1 -1
View File
@@ -65,7 +65,7 @@ pub use anchor::Anchor9;
pub use arrangement::Arrangement;
pub use canvas::CanvasTransform;
pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomScheme, resize_cursor};
pub use canvas::{CanvasView, RulerUnits, TickLabels, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomScheme, resize_cursor};
/// The f64 geometry crate the canvas view and its callers share.
pub use kurbo;
+22 -9
View File
@@ -9,7 +9,7 @@ use crate::runtime::env::{Message, UnitKind};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use crate::testing::{pointer, stage};
use craft_behavior::kurbo::Point;
use craft_behavior::{Mixed, RulerUnits};
use craft_behavior::{Mixed, RulerUnits, TickLabels, Ticks};
use egui::{Rect, Ui, Vec2};
/// How far the corner is dragged, in drag thresholds: out of the corner and onto the document.
@@ -74,9 +74,8 @@ fn configured<'a>(rulers: Rulers<'a>, settings: Settings) -> Rulers<'a> {
rulers.interactive(settings.interactive).origin_locked(settings.locked)
}
/// A canvas that shows `rulers` and whose view lies inside the strips, counting from their zero in pixels.
fn rulers_canvas<'a>(room: Rect, pixels_per_point: f32, settings: Settings, rulers: Rulers<'a>) -> Canvas<'a> {
let text = pixels();
/// A canvas that shows `rulers` and whose view lies inside the strips, counting from their zero in `text`.
fn rulers_canvas<'a>(room: Rect, pixels_per_point: f32, settings: Settings, text: RulerText, rulers: Rulers<'a>) -> Canvas<'a> {
let view =
StoryDocument::STANDARD.view(room, pixels_per_point, settings.zoom).rotation(settings.rotation).flip_x(settings.flip).aspect(settings.aspect);
Canvas::new("Document").view(view).with_rulers(Some(configured(rulers, settings))).rulers(text, text)
@@ -87,7 +86,7 @@ fn zero_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = settings(data);
let (zero, zero_at) = data.value_at("zero", Point::ZERO);
let room = stage(ui);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero)));
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, pixels(), Rulers::new("Rulers", zero_at.bind(&mut *zero)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
@@ -96,7 +95,7 @@ fn units_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = settings(data);
let (zero, zero_at) = data.value_at("zero", Point::ZERO);
let room = stage(ui);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero)).units(&UNITS));
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, pixels(), Rulers::new("Rulers", zero_at.bind(&mut *zero)).units(&UNITS));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
@@ -105,7 +104,7 @@ fn zero_points_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = settings(data);
let (zero, zero_at) = data.value_at("zero", Mixed::<Point>::Mixed);
let room = stage(ui);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind_mixed(&mut *zero)));
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, pixels(), Rulers::new("Rulers", zero_at.bind_mixed(&mut *zero)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
@@ -116,7 +115,7 @@ fn zero_point_left_of_the_document(ui: &mut Ui, data: &mut StoryData) -> StoryOu
let room = stage(ui);
let inside =
|zero: &Point| if zero.x < LEAST_X { Validity::Refuse(Message::new("The zero point is left of the document")) } else { Validity::Ok };
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero).check(inside)));
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, pixels(), Rulers::new("Rulers", zero_at.bind(&mut *zero).check(inside)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
@@ -129,7 +128,7 @@ fn in_face(ui: &mut Ui, data: &mut StoryData, face: RulerFace) -> StoryOutput {
let (width, height) = (f64::from(size.width), f64::from(size.height));
let margins = RulerMargins::new([0.0..MARGIN, width - MARGIN..width], [0.0..MARGIN, height - MARGIN..height]);
let rulers = Rulers::new("Rulers", zero_at.bind(&mut *zero)).margins(margins).face(face);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, rulers);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, pixels(), rulers);
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
@@ -146,3 +145,17 @@ fn edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
in_face(ui, data, RulerFace::Centred)
}
/// Signed labels (VectorCraft's) on an inch ruler counting from the document's centre: ticks left of and above the zero
/// point carry a minus sign, and a tick writes only the decimals it needs (`-0.5`, `1`).
#[story(Rulers<'static>, covers = [], drive = Drive::Never)]
fn signed_labels(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = settings(data);
let size = StoryDocument::STANDARD.size();
let centre = Point::new(f64::from(size.width) / 2.0, f64::from(size.height) / 2.0);
let (zero, zero_at) = data.value_at("zero", centre);
let room = stage(ui);
let inches = RulerText::new(RulerUnits::new(1.0 / 72.0, Ticks::decimal(false)).with_labels(TickLabels::Signed), UnitKind::Inches);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, inches, Rulers::new("Rulers", zero_at.bind(&mut *zero)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
+3 -4
View File
@@ -445,7 +445,7 @@ impl PartialEq for RulerText {
(Ticks::Custom(a), Ticks::Custom(b)) => std::ptr::fn_addr_eq(a, b),
_ => false,
};
self.kind == other.kind && self.units.per_doc == other.units.per_doc && same_ticks
self.kind == other.kind && self.units.per_doc == other.units.per_doc && same_ticks && self.units.labels == other.units.labels
}
}
@@ -469,10 +469,9 @@ impl RulerText {
}
/// The number a ruler prints at the tick `value` (ruler units from the zero point) of labelled step `step`, with
/// no unit.
/// no unit, as the units' [`TickLabels`](craft_behavior::TickLabels) write it.
pub fn tick_label(&self, numbers: &Units, value: f64, step: f64) -> String {
let digits = self.units.label_decimals(step);
numbers.number_ungrouped(self.units.label_value(value, step), digits..=digits)
numbers.number_ungrouped(self.units.label_value(value, step), self.units.label_decimals(step))
}
/// The unit's short name: `px`.
+50 -1
View File
@@ -2,7 +2,7 @@
use craft_behavior::geometry::{SnapOptions, SnapTargets};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::{CancelReason, CanvasView, RulerUnits, Ticks};
use craft_behavior::{CancelReason, CanvasView, RulerUnits, TickLabels, Ticks};
use craft_ui::canvas::{
Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, StepLadder, TickRule,
ToolAction, ToolContext, ToolPath, ToolPointer,
@@ -106,6 +106,55 @@ fn ticks_stay_level_and_the_zero_label_sits_at_the_zero_point_in_a_turned_view()
assert!(turned.is_subset(&level), "tick marks keep the lengths and cross coordinates of the level view: {turned:?} against {level:?}");
}
/// The labels of the top strip, left to right, over an inch ruler written as `labels` whose zero point is the middle of
/// a view at 4 points per document point (72 to the inch), so the step is a fraction of an inch.
fn top_inch_labels(labels: TickLabels) -> Vec<String> {
let room = Vec2::new(800.0, 600.0);
let middle = Point::new(400.0, 300.0);
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, room), middle, 4.0);
let text = RulerText::new(RulerUnits::new(1.0 / 72.0, Ticks::decimal(false)).with_labels(labels), UnitKind::Inches);
let content = Rc::new(Cell::new(Rect::NOTHING));
let seen = Rc::clone(&content);
let mut zero = middle;
let mut fixture = Fixture::new(move |ui| {
let strips = Rulers::new("Rulers", Bind::bound(&mut zero));
let shown = Canvas::new("Document").view(view).with_rulers(Some(strips)).rulers(text, text).show(ui, |_, _| {});
if let Some(rulers) = shown.output.rulers {
seen.set(rulers.content_rect());
}
});
fixture.room(room);
fixture.settle();
let content = content.get();
let mut runs: Vec<(f32, String)> = fixture
.texts()
.iter()
.filter(|run| run.rect.max.y <= content.min.y + 0.5 && run.rect.min.x >= content.min.x - 0.5)
.map(|run| (run.rect.min.x, run.text.clone()))
.collect();
runs.sort_by(|a, b| a.0.total_cmp(&b.0));
runs.into_iter().map(|(_, text)| text).collect()
}
/// VectorCraft's signed labels write the same ticks as the default distance labels, with a minus sign left of the zero
/// point and only the decimals each tick needs; the default keeps PhotoCraft's unsigned, padded form.
#[trial]
fn signed_tick_labels_carry_the_sign_and_drop_trailing_zeros() {
let distance = top_inch_labels(TickLabels::Distance);
let signed = top_inch_labels(TickLabels::Signed);
assert_eq!(distance.len(), signed.len(), "both styles label the same ticks: {distance:?} against {signed:?}");
let fractional = |labels: &[String]| labels.iter().any(|label| label.contains('.'));
assert!(fractional(&distance) && fractional(&signed), "the step is a fraction of an inch: {signed:?}");
assert!(!distance.iter().any(|label| label.starts_with('-')), "distance labels carry no sign: {distance:?}");
assert!(distance.iter().any(|label| label.contains('.') && label.ends_with('0')), "distance labels pad the decimals: {distance:?}");
assert!(signed.iter().any(|label| label.starts_with('-')), "labels left of the zero point are negative: {signed:?}");
assert!(!signed.iter().any(|label| label.contains('.') && label.ends_with('0')), "signed labels drop trailing zeros: {signed:?}");
for (padded, plain) in distance.iter().zip(&signed) {
let (padded, plain) = (padded.parse::<f64>(), plain.parse::<f64>().map(f64::abs));
assert_eq!(padded, plain, "each tick is the same distance from the zero point in both styles");
}
}
/// How far past the canvas the tool's fill and the marquee reach.
const PAST: f32 = 60.0;