Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Rulers: drag the zero point from the ruler corner, double-click resets it (#2955) (#3505)

David Mannb41e34c20fcf
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 3850ba0cb..c4f7f523d 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -865,6 +865,10 @@ pub struct Document {
pub layers: Vec<Layer>,
pub channels: Vec<AlphaChannel>,
pub guides: Guides,
+ /// The rulers' zero point in document pixels (`[x, y]`), dragged from the ruler corner. The
+ /// rulers, the Info panel and other position readouts measure from it; `[0, 0]` (the
+ /// image's top-left) is the default.
+ pub ruler_origin: [f64; 2],
/// Active selection as a grayscale coverage surface (None = no selection).
pub selection: Option<Surface>,
pub metadata: Metadata,
@@ -952,6 +956,7 @@ impl Document {
layers: Vec::new(),
channels: Vec::new(),
guides: Guides::default(),
+ ruler_origin: [0.0, 0.0],
selection: None,
metadata: Metadata::default(),
global_light: GlobalLight::default(),
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index 6bf834ae1..f0541136a 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -881,6 +881,32 @@ fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result<Value> {
Ok(Value::Null)
}
+/// Farthest the ruler zero point may sit from the image, in document pixels.
+const MAX_RULER_ORIGIN: f64 = 1.0e7;
+
+/// Move the rulers' zero point (`view.setRulerOrigin`), or put it back at the image's top-left
+/// (`view.resetRulerOrigin`, `p` = None). Undoable like the guides.
+fn ruler_origin_cmd(s: &mut Session, p: Option<&Value>) -> Result<Value> {
+ let origin = match p {
+ None => [0.0, 0.0],
+ Some(p) => {
+ let axis = |k: &str| {
+ p.get(k)
+ .and_then(Value::as_f64)
+ .filter(|v| v.is_finite() && v.abs() <= MAX_RULER_ORIGIN)
+ .ok_or_else(|| EngineError::Other(format!("`{k}` must be a number of pixels within ±{MAX_RULER_ORIGIN}")))
+ };
+ [axis("x")?, axis("y")?]
+ }
+ };
+ let label = if p.is_some() { "Set Ruler Origin" } else { "Reset Ruler Origin" };
+ s.edit(label, |doc, _| {
+ doc.ruler_origin = origin;
+ Ok(())
+ })?;
+ Ok(json!({"x": origin[0], "y": origin[1]}))
+}
+
pub fn specs() -> Vec<CommandSpec> {
macro_rules! spec {
($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => {
@@ -987,6 +1013,18 @@ pub fn specs() -> Vec<CommandSpec> {
),
spec!("view.deleteGuide", "Delete Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n}"##, has_doc, |s, p| guide_cmd(s, p, "delete")),
spec!("view.clearGuides", "Clear Guides", &["View"], None, "{}", has_doc, |s, p| guide_cmd(s, p, "clear")),
+ spec!(
+ "view.setRulerOrigin",
+ "Set Ruler Origin",
+ &[],
+ None,
+ r##"{"x":px,"y":px} (the rulers' zero point in document pixels; the rulers and Info panel measure from it)"##,
+ has_doc,
+ |s, p| ruler_origin_cmd(s, Some(p))
+ ),
+ spec!("view.resetRulerOrigin", "Reset Ruler Origin", &[], None, "{} (zero point back at the image's top-left)", has_doc, |s, _| ruler_origin_cmd(
+ s, None
+ )),
]
}
@@ -1915,6 +1953,28 @@ mod tests {
assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err());
}
+ /// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are
+ /// refused without touching the document.
+ #[test]
+ fn ruler_origin_is_set_reset_and_undoable() {
+ let mut s = session();
+ assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]);
+ assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5}));
+ assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
+ s.execute("view.resetRulerOrigin", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]);
+ s.undo();
+ assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
+ for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])]
+ {
+ assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused");
+ }
+ assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
+ let mut empty = Session::new();
+ assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err());
+ assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err());
+ }
+
/// The last guide added in `orientation` for `position`.
fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 {
s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap();
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 8d71810dc..21e9e2caa 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -639,6 +639,7 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
layers: _,
channels,
guides: _,
+ ruler_origin: _,
selection: _,
metadata: _,
global_light,
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index a26219033..51d6183ba 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -230,6 +230,7 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
layers: d.layers.iter().map(|l| layer_m(l, sink)).collect(),
channels: d.channels.iter().map(|c| channel_m(c, sink)).collect(),
guides: d.guides.clone(),
+ ruler_origin: d.ruler_origin,
selection: d.selection.as_ref().map(|s| surface_m(s, sink)),
metadata: MetadataM {
xmp: d.metadata.xmp.clone(),
@@ -628,6 +629,7 @@ impl Loader<'_> {
layers,
channels,
guides: m.guides.clone(),
+ ruler_origin: m.ruler_origin,
selection: self.opt_surface(&m.selection)?,
metadata: md,
global_light: m.global_light,
diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs
index d76a496fb..82480e05c 100644
--- a/crates/format/src/manifest.rs
+++ b/crates/format/src/manifest.rs
@@ -46,6 +46,9 @@ pub struct DocM {
pub layers: Vec<LayerM>,
pub channels: Vec<ChannelM>,
pub guides: Guides,
+ /// The rulers' zero point in document pixels (absent in older files: the top-left).
+ #[serde(default)]
+ pub ruler_origin: [f64; 2],
pub selection: Option<SurfaceM>,
pub metadata: MetadataM,
pub global_light: GlobalLight,
diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rs
index ef840cfc8..8d5641d9c 100644
--- a/crates/format/tests/common/mod.rs
+++ b/crates/format/tests/common/mod.rs
@@ -230,6 +230,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
});
d.guides =
Guides { horizontal: vec![10.0, 20.5], vertical: vec![100.25], colors: vec![GuideColor { vertical: true, position: 100.25, rgb: [0x33, 0x66, 0xff] }] };
+ d.ruler_origin = [12.5, -4.25];
let mut sel = Surface::new(PixelFormat::GRAY8);
scribble(&mut sel, 14, false);
d.selection = Some(sel);
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index cff94a840..733f923c8 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1784,7 +1784,7 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
empty(ui, tl!("No document"));
return;
};
- let (rev, size) = (st.revision, st.doc.size);
+ let (rev, size, origin) = (st.revision, st.doc.size, st.doc.ruler_origin);
// Positions and sizes in the ruler unit (Preferences › Units & Rulers).
let units = app.session.prefs().units_and_rulers.clone();
let dpi = st.doc.resolution_dpi as f64;
@@ -1833,8 +1833,9 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
widgets::hairline(ui);
ui.columns(2, |cols| {
let dash = || "—".to_string();
- row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64)));
- row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64)));
+ // Measured from the rulers' zero point (#2955).
+ row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64 - origin[0])));
+ row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64 - origin[1])));
row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64)));
row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64)));
});
diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs
index cc427758f..ff5f106bd 100644
--- a/crates/ui-egui/src/rulers.rs
+++ b/crates/ui-egui/src/rulers.rs
@@ -237,34 +237,59 @@ pub fn finish_drag(app: &mut PhotocraftApp, d: GuideDrag) {
/// the document origin as the rotated view draws it, as in Photoshop. Tilted guides then meet the
/// rulers near their numbers. Measuring along the rotated axes instead squeezed the ticks into a
/// few pixels (or none at 90°) and left the rest of the ruler empty (#3233).
-fn ruler_xform(xf: &ViewXform) -> ViewXform {
+///
+/// The returned mapping measures from the rulers' zero point `zero` (document px, #2955): its
+/// document coordinates are distances from `zero`, and 0 sits where the canvas draws `zero`.
+fn ruler_xform(xf: &ViewXform, zero: [f64; 2]) -> ViewXform {
let level = ViewXform { rotation: 0.0, ..*xf };
- // The level view is an axis-aligned scale, so moving the origin by `shift` on screen moves
- // every point by it: re-centre on the document point that sat `shift` before the centre.
- let shift = xf.to_screen(0.0, 0.0) - level.to_screen(0.0, 0.0);
+ let (zx, zy) = (zero[0] as f32, zero[1] as f32);
+ // The level view is an axis-aligned scale, so moving the zero point by `shift` on screen moves
+ // every point by it: re-centre on the document point that sat `shift` before the centre, then
+ // count from the zero point.
+ let shift = xf.to_screen(zx, zy) - level.to_screen(zx, zy);
let center = level.to_doc(xf.rect.center() - shift);
+ let center = [center[0] as f32 - zx, center[1] as f32 - zy];
if !(center[0].is_finite() && center[1].is_finite()) {
return level;
}
- ViewXform { center: [center[0] as f32, center[1] as f32], ..level }
+ ViewXform { center, ..level }
}
/// Visible ruler range in ruler units, normalised to `(min, max)` so the tick loop runs for
-/// flipped views too (#1814). `xf` is the canvas mapping; rotation is ignored (see
-/// [`ruler_xform`]). Shared by the renderer and its tests.
-fn ruler_range(xf: &ViewXform, a: Pos2, b: Pos2, axis: usize, px_per_unit: f64) -> (f64, f64) {
- let rxf = ruler_xform(xf);
+/// flipped views too (#1814), measured from the zero point `zero`. `xf` is the canvas mapping;
+/// rotation is ignored (see [`ruler_xform`]). Shared by the renderer and its tests.
+fn ruler_range(xf: &ViewXform, a: Pos2, b: Pos2, axis: usize, px_per_unit: f64, zero: [f64; 2]) -> (f64, f64) {
+ let rxf = ruler_xform(xf, zero);
let d0 = rxf.to_doc(a)[axis];
let d1 = rxf.to_doc(b)[axis];
let (u0, u1) = (d0 / px_per_unit, d1 / px_per_unit);
(u0.min(u1), u0.max(u1))
}
+/// Snap a document position to the nearest ruler tick, measured from the zero point `origin`
+/// (`tick` px apart). Shift-dragging the zero point lands it on a tick, as in Photoshop.
+fn snap_px_to_tick(px: f64, origin: f64, tick: f64) -> f64 {
+ if !(tick.is_finite() && tick > 0.0) {
+ return px;
+ }
+ origin + ((px - origin) / tick).round() * tick
+}
+
+/// Where a zero-point drag from the ruler corner lands for the pointer at document `d`: on the
+/// nearest ruler tick (`ticks`, px per axis) with Shift, else View › Snap To targets.
+fn origin_drop(app: &mut PhotocraftApp, d: [f64; 2], shift: bool, origin: [f64; 2], ticks: [f64; 2]) -> [f64; 2] {
+ if shift {
+ [snap_px_to_tick(d[0], origin[0], ticks[0]), snap_px_to_tick(d[1], origin[1], ticks[1])]
+ } else {
+ [crate::snap_ui::snap_guide(app, true, d[0]), crate::snap_ui::snap_guide(app, false, d[1])]
+ }
+}
+
/// Screen coordinate along the ruler (x for the top ruler, y for the left one) of the value `u`
-/// in ruler units. The inverse of [`ruler_range`]'s mapping.
-fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64) -> f32 {
+/// in ruler units from the zero point `zero`. The inverse of [`ruler_range`]'s mapping.
+fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64, zero: [f64; 2]) -> f32 {
let px = (u * px_per_unit) as f32;
- let rxf = ruler_xform(xf);
+ let rxf = ruler_xform(xf, zero);
if vertical { rxf.to_screen(0.0, px).y } else { rxf.to_screen(px, 0.0).x }
}
@@ -282,13 +307,14 @@ fn ruler_scale(app: &PhotocraftApp, xf: &ViewXform, y_axis: bool) -> (f64, f64)
(px_per_unit, nice_step(60.0 / (zoom as f64 * px_per_unit).max(1e-6), unit == Unit::Pixels))
}
-/// `pos` (document px) moved to the nearest tick mark the ruler draws: where a guide lands when
+/// `pos` (document px) moved to the nearest tick mark the ruler draws (counted from the zero point): where a guide lands when
/// Shift is held while dragging it out of a ruler, as in Photoshop (#3770).
fn snap_to_tick(app: &PhotocraftApp, xf: &ViewXform, vertical: bool, pos: f64) -> f64 {
// A vertical guide sits at an x position, which the top ruler measures.
let (px_per_unit, step) = ruler_scale(app, xf, !vertical);
- let tick = step / 10.0 * px_per_unit;
- if tick.is_finite() && tick > 0.0 { (pos / tick).round() * tick } else { pos }
+ // Ticks count from the zero point (#2955), which a vertical guide measures along x.
+ let origin = app.session.active().map_or(0.0, |d| d.doc.ruler_origin[usize::from(!vertical)]);
+ snap_px_to_tick(pos, origin, step / 10.0 * px_per_unit)
}
/// The number a ruler prints at the tick `v` (in ruler units). Like Photoshop, rulers show the
@@ -317,17 +343,21 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
// Preferences › Units & Rulers: labels in the ruler unit (percent of the document's side).
let unit = app.session.prefs().units_and_rulers.rulers;
let whole = unit == Unit::Pixels;
+ // The zero point (#2955): rulers read 0 there and count the distance from it.
+ let origin = app.session.active().map_or([0.0, 0.0], |d| d.doc.ruler_origin);
+ let mut ticks = [1.0; 2];
for vertical in [false, true] {
let p = p.with_clip_rect(if vertical { left } else { top });
let (px_per_unit, step) = ruler_scale(app, xf, vertical);
+ ticks[usize::from(vertical)] = step * px_per_unit / 10.0;
let (u0, u1) = if vertical {
- ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit)
+ ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit, origin)
} else {
- ruler_range(xf, top.left_top(), top.right_top(), 0, px_per_unit)
+ ruler_range(xf, top.left_top(), top.right_top(), 0, px_per_unit, origin)
};
let mut v = (u0 / step).floor() * step;
while v <= u1 {
- let at = |u: f64| -> f32 { ruler_pos(xf, vertical, u, px_per_unit) };
+ let at = |u: f64| -> f32 { ruler_pos(xf, vertical, u, px_per_unit, origin) };
let c = at(v);
if vertical {
p.line_segment([pos2(left.right() - RULER, c), pos2(left.right(), c)], tick);
@@ -360,14 +390,15 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
// Drag a new guide out of a ruler; right-click to switch the ruler unit.
let mut chosen_unit: Option<&'static str> = None;
for (r, vertical, salt) in [(top, false, "ruler-top"), (left, true, "ruler-left"), (corner, false, "ruler-corner")] {
- // Guides drag out of the top/left rulers; all three sense clicks so the right-click unit
- // menu opens anywhere on the ruler (the corner only needs the menu).
- let sense = if salt == "ruler-corner" { Sense::click() } else { Sense::click_and_drag() };
- let resp = ui.interact(r, ui.id().with(salt), sense);
- if resp.hovered() && salt != "ruler-corner" {
+ // Guides drag out of the top/left rulers and the zero point out of the corner; all three
+ // sense clicks so the right-click unit menu opens anywhere on the ruler.
+ let resp = ui.interact(r, ui.id().with(salt), Sense::click_and_drag());
+ if salt == "ruler-corner" {
+ corner_origin(app, ui, &resp, &p, xf, origin, ticks);
+ } else if resp.hovered() {
ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
}
- if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) {
+ if let Some(pos) = resp.interact_pointer_pos().filter(|_| salt != "ruler-corner" && (resp.dragged() || resp.drag_started())) {
let d = xf.to_doc(pos);
let along = if vertical { d[0] } else { d[1] };
let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) };
@@ -390,6 +421,41 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
let _ = Pos2::ZERO;
}
+/// The ruler corner: drag the zero point out of it (cross hairs mark where it lands; Shift snaps
+/// to the ruler ticks), double-click it to put the zero point back at the image's top-left.
+fn corner_origin(app: &mut PhotocraftApp, ui: &egui::Ui, resp: &egui::Response, p: &egui::Painter, xf: &ViewXform, origin: [f64; 2], ticks: [f64; 2]) {
+ let id = resp.id.with("origin-drag");
+ if resp.hovered() || resp.dragged() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ }
+ if resp.double_clicked() {
+ let _ = app.run("view.resetRulerOrigin", json!({}));
+ return;
+ }
+ // Dropped back on the corner (or a slow click), the zero point stays where it was.
+ if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) {
+ if resp.rect.contains(pos) {
+ ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id));
+ return;
+ }
+ let shift = ui.input(|i| i.modifiers.shift);
+ let at = origin_drop(app, xf.to_doc(pos), shift, origin, ticks);
+ ui.data_mut(|d| d.insert_temp(id, at));
+ // Cross hairs along the document axes through the new zero point, drawn like guides so
+ // they turn with a rotated view.
+ let t = Tokens::get(ui.ctx());
+ for (vertical, pos) in [(true, at[0]), (false, at[1])] {
+ p.line_segment(guide_segment(xf, p.clip_rect(), vertical, pos), Stroke::new(1.0, t.text));
+ }
+ }
+ if resp.drag_stopped()
+ && let Some(at) = ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id))
+ {
+ let round = |v: f64| (v * 1000.0).round() / 1000.0;
+ let _ = app.run("view.setRulerOrigin", json!({"x": round(at[0]), "y": round(at[1])}));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -433,6 +499,140 @@ mod tests {
assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}");
}
+ #[test]
+ fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() {
+ assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0);
+ assert_eq!(snap_px_to_tick(44.9, 0.0, 10.0), 40.0);
+ // Ticks run from the current zero point, so they sit at 3 + 10k.
+ assert_eq!(snap_px_to_tick(47.0, 3.0, 10.0), 43.0);
+ assert_eq!(snap_px_to_tick(-8.0, 3.0, 10.0), -7.0);
+ // A degenerate tick never panics or moves the point.
+ for tick in [0.0, -1.0, f64::NAN, f64::INFINITY] {
+ assert_eq!(snap_px_to_tick(47.5, 3.0, tick), 47.5);
+ }
+ }
+
+ /// Rulers alone in a 400×300 frame at 100 %, centred on a 256×128 document.
+ fn ruler_harness(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, Rect, ViewXform) {
+ let full = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
+ let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max);
+ let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 };
+ let h = egui_kittest::Harness::builder()
+ .with_size(vec2(400.0, 300.0))
+ .with_step_dt(1.0 / 60.0)
+ .build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app);
+ (h, full, xf)
+ }
+
+ fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: egui::Modifiers) {
+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers });
+ h.run_steps(2);
+ }
+
+ fn drag_corner_to(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, full: Rect, to: Pos2, modifiers: egui::Modifiers) {
+ let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
+ h.event(egui::Event::ModifiersChanged(modifiers));
+ h.event(egui::Event::PointerMoved(corner));
+ h.run_steps(1);
+ press(h, corner, true, modifiers);
+ for p in [corner + vec2(10.0, 10.0), to] {
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(2);
+ }
+ press(h, to, false, modifiers);
+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ h.run_steps(1);
+ }
+
+ fn origin(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> [f64; 2] {
+ h.state().session.active().unwrap().doc.ruler_origin
+ }
+
+ /// #2955: dragging out of the ruler corner sets the zero point (cross hairs while dragging),
+ /// the rulers then read 0 there, Shift snaps it to a tick, and double-clicking the corner
+ /// resets it.
+ #[test]
+ fn dragging_the_ruler_corner_sets_the_zero_point_and_double_click_resets_it() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 256, "height": 128})).unwrap();
+ app.ui.extras.snap = false;
+ let (mut h, full, xf) = ruler_harness(app);
+ h.run_steps(2);
+ let target = xf.to_screen(100.0, 40.0);
+ drag_corner_to(&mut h, full, target, egui::Modifiers::NONE);
+ let o = origin(&h);
+ assert!((o[0] - 100.0).abs() < 0.01 && (o[1] - 40.0).abs() < 0.01, "zero point lands under the pointer: {o:?}");
+ // The top ruler's "0" now sits at the new zero point, "100" (a distance, unsigned as in
+ // Photoshop) at the image's left edge.
+ h.run_steps(2);
+ let labels: Vec<(String, f32)> = h
+ .output()
+ .shapes
+ .iter()
+ .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some((t.galley.text().to_string(), t.pos.x)) } else { None })
+ .collect();
+ let near = |text: &str, x: f32| labels.iter().any(|(t, lx)| t == text && (lx - (x + 2.0)).abs() < 1.0);
+ assert!(near("0", target.x), "a 0 label at the zero point: {labels:?}");
+ assert!(near("100", xf.to_screen(0.0, 0.0).x), "100 at the image's left edge: {labels:?}");
+
+ // Mid-drag, cross hairs run through the pointer across the canvas.
+ let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
+ let mid = xf.to_screen(150.0, 90.0);
+ press(&mut h, corner, true, egui::Modifiers::NONE);
+ for p in [corner + vec2(10.0, 10.0), mid] {
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(2);
+ }
+ let crosshair = h.output().shapes.iter().any(|s| {
+ matches!(s.shape, egui::Shape::LineSegment { points: [a, b], .. } if (a.x - mid.x).abs() < 0.5 && (b.x - mid.x).abs() < 0.5 && (b.y - a.y).abs() > 200.0)
+ });
+ assert!(crosshair, "a vertical cross-hair line through the pointer while dragging");
+ assert_eq!(origin(&h), o, "the zero point moves on release only");
+ press(&mut h, mid, false, egui::Modifiers::NONE);
+ assert_eq!(origin(&h), [150.0, 90.0]);
+ h.state_mut().run("edit.undo", json!({})).unwrap();
+ assert_eq!(origin(&h), o, "setting the zero point is undoable");
+
+ // A drag dropped back on the corner leaves it alone.
+ drag_corner_to(&mut h, full, full.min + vec2(4.0, 4.0), egui::Modifiers::NONE);
+ assert_eq!(origin(&h), o);
+
+ // Shift: ticks are 10 px apart at 100 %, measured from the current zero point (100, 40).
+ drag_corner_to(&mut h, full, xf.to_screen(123.0, 57.0), egui::Modifiers::SHIFT);
+ assert_eq!(origin(&h), [120.0, 60.0]);
+
+ for _ in 0..40 {
+ h.step();
+ }
+ let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
+ h.event(egui::Event::PointerMoved(corner));
+ h.step();
+ for _ in 0..2 {
+ for pressed in [true, false] {
+ h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
+ h.step();
+ }
+ }
+ h.run_steps(2);
+ assert_eq!(origin(&h), [0.0, 0.0], "double-clicking the corner resets the zero point");
+ }
+
+ /// #2955: the Info panel's X/Y are measured from the rulers' zero point.
+ #[test]
+ fn info_panel_position_reads_from_the_zero_point() {
+ use egui_kittest::kittest::Queryable;
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
+ app.run("view.setRulerOrigin", json!({"x": 20, "y": 5})).unwrap();
+ app.hover_doc = Some([50.5, 20.5]);
+ let mut h = egui_kittest::Harness::builder()
+ .with_size(vec2(260.0, 240.0))
+ .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app);
+ h.run_steps(2);
+ assert!(h.query_by_label("30").is_some() && h.query_by_label("15").is_some(), "X 30, Y 15 from the zero point at (20, 5)");
+ assert!(h.query_by_label("50").is_none(), "not the raw image x");
+ }
+
#[test]
fn percentage_grid_spacing_uses_both_canvas_dimensions() {
let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() };
@@ -615,23 +815,23 @@ mod tests {
for rotation in [0.0f32, 30.0, 45.0, 90.0, -119.0, 180.0] {
for flip in [false, true] {
let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 };
- let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0);
+ let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]);
assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}");
let (first, last) = if flip { (u1, u0) } else { (u0, u1) };
- assert!((ruler_pos(&xf, false, first, 1.0) - a.x).abs() < 1e-2, "rotation {rotation}: first tick");
- assert!((ruler_pos(&xf, false, last, 1.0) - b.x).abs() < 1e-2, "rotation {rotation}: last tick");
+ assert!((ruler_pos(&xf, false, first, 1.0, [0.0; 2]) - a.x).abs() < 1e-2, "rotation {rotation}: first tick");
+ assert!((ruler_pos(&xf, false, last, 1.0, [0.0; 2]) - b.x).abs() < 1e-2, "rotation {rotation}: last tick");
// 0 at the projected origin, 500 document px = 500 × zoom screen px further on.
let origin = xf.to_screen(0.0, 0.0);
- assert!((ruler_pos(&xf, false, 0.0, 1.0) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
- assert!((ruler_pos(&xf, true, 0.0, 1.0) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
+ assert!((ruler_pos(&xf, false, 0.0, 1.0, [0.0; 2]) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
+ assert!((ruler_pos(&xf, true, 0.0, 1.0, [0.0; 2]) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
let dir = if flip { -1.0 } else { 1.0 };
- assert!((ruler_pos(&xf, false, 500.0, 1.0) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
- assert!((ruler_pos(&xf, true, 500.0, 1.0) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale");
+ assert!((ruler_pos(&xf, false, 500.0, 1.0, [0.0; 2]) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
+ assert!((ruler_pos(&xf, true, 500.0, 1.0, [0.0; 2]) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale");
}
}
// Distances left of / above the origin read without a minus sign, as in Photoshop.
let xf = ViewXform { rect, zoom: 0.5, center: [0.0, 0.0], flip: false, rotation: 0.0, aspect: 1.0 };
- let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0);
+ let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]);
assert!(u0 < -500.0 && u1 > 500.0, "the view spans the origin: {u0}..{u1}");
for (step, whole) in [(100.0, true), (100.0, false), (0.25, false)] {
let mut v = (u0 / step).floor() * step;
@@ -645,6 +845,31 @@ mod tests {
assert_eq!(ruler_label(-0.25, 0.25, false), "0.25");
}
+ /// #2955 with #3233: a zero point moved off the image's top-left reads 0 where the canvas draws
+ /// it, also on a rotated or flipped view, and the ruler keeps its full length and scale.
+ #[test]
+ fn rulers_count_from_the_zero_point_on_a_rotated_view() {
+ let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
+ let (a, b) = (rect.left_top(), rect.right_top());
+ let zero = [300.0, 120.0];
+ for rotation in [0.0f32, 30.0, 90.0, -119.0] {
+ for flip in [false, true] {
+ let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 };
+ let at = xf.to_screen(zero[0] as f32, zero[1] as f32);
+ assert!((ruler_pos(&xf, false, 0.0, 1.0, zero) - at.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
+ assert!((ruler_pos(&xf, true, 0.0, 1.0, zero) - at.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
+ let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, zero);
+ assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}");
+ let dir = if flip { -1.0 } else { 1.0 };
+ assert!((ruler_pos(&xf, false, 500.0, 1.0, zero) - at.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
+ }
+ }
+ // Unrotated, ruler value u sits over document x = zero + u.
+ let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 };
+ assert!((ruler_pos(&xf, false, -300.0, 1.0, zero) - xf.to_screen(0.0, 0.0).x).abs() < 1e-2);
+ assert!((ruler_pos(&xf, true, 80.0, 1.0, zero) - xf.to_screen(0.0, 200.0).y).abs() < 1e-2);
+ }
+
/// #3277: guides belong to the document, so a rotated view draws them along the document
/// line; unrotated they still span the whole clip rect.
#[test]
@@ -674,7 +899,7 @@ mod tests {
let top = Rect::from_min_size(rect.min, vec2(rect.width(), RULER));
for flip in [false, true] {
let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip, rotation: 0.0, aspect: 1.0 };
- let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0);
+ let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0, [0.0; 2]);
assert!(u0 <= u1, "flip={flip}: u0 ({u0}) must be <= u1 ({u1})");
assert!(u1 - u0 > 0.0, "flip={flip}: range is empty");
}
@@ -717,5 +942,10 @@ mod tests {
app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap();
assert!((snap_to_tick(&app, &xf, true, 37.0) - 38.4).abs() < 1e-9);
assert!((snap_to_tick(&app, &xf, false, 37.0) - 38.4).abs() < 1e-9);
+ // Ticks count from the zero point (#2955): a vertical guide follows the x origin only.
+ let mut app = new_app();
+ app.run("view.setRulerOrigin", json!({"x": 3, "y": 0})).unwrap();
+ assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0);
+ assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0);
}
}