Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Rulers: a document zero point you can drag, reset and lock

aiongg209f758727a2
diff --git a/ROADMAP.md b/ROADMAP.md
index 86a435456..2e9bc3c4f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -32,6 +32,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus.
- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands.
- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands.
+- Ruler zero point: drag from the ruler corner to place it (crosshair lines while dragging), double-click the corner to reset, right-click it to lock; one per document at the same place on every spread, saved with the document and as IDML `ZeroPoint`; rulers and the X/Y fields (Control, Properties, Info, `transform.set`) measure from it; moving it is not an undo step; `view.zeroPoint` / `view.lockZeroPoint`.
- Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands.
- Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`.
- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts.
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs
index 3bb827135..9d3d3486d 100644
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@ -61,6 +61,37 @@ impl Document {
}
}
+ /// Where spread `r`'s rulers and X/Y fields measure from, in spread coordinates: the
+ /// top-left corner of its pages moved by the document's zero point.
+ pub fn ruler_origin(&self, r: SpreadRef) -> Option<Point> {
+ let b = self.spread(r)?.bounds();
+ let [x, y] = self.zero_point();
+ Some(Point::new(b.x0 + x, b.y0 + y))
+ }
+
+ /// The document's zero point, kept on the pasteboard (a file may hold any numbers).
+ pub fn zero_point(&self) -> [f64; 2] {
+ self.clamp_zero_point(self.settings.zero_point).unwrap_or([0.0, 0.0])
+ }
+
+ /// `p` (a zero point) kept on the pasteboard around the largest spread, the area the canvas
+ /// shows; `None` when it isn't a finite point.
+ pub fn clamp_zero_point(&self, [x, y]: [f64; 2]) -> Option<[f64; 2]> {
+ if !x.is_finite() || !y.is_finite() {
+ return None;
+ }
+ let (w, h) = self
+ .spreads
+ .iter()
+ .chain(&self.parents)
+ .map(|sp| sp.bounds())
+ .fold((0.0_f64, 0.0_f64), |(w, h), b| (w.max(b.width()), h.max(b.height())));
+ let finite = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 };
+ let (px, py) = (finite(self.settings.pasteboard.0), finite(self.settings.pasteboard.1));
+ let side = px.max(w);
+ Some([x.clamp(-side, w + side), y.clamp(-py, h + py)])
+ }
+
/// All spread refs: document spreads then parents.
pub fn spread_refs(&self) -> impl Iterator<Item = SpreadRef> {
(0..self.spreads.len()).map(SpreadRef::Doc).chain((0..self.parents.len()).map(SpreadRef::Parent))
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index c4b69e86d..886ef2ae6 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -351,6 +351,17 @@ pub struct DocSettings {
/// Documents saved before the setting existed read as on, the way they were drawn.
#[serde(default = "yes")]
pub glyph_fallback: bool,
+ /// The rulers' zero point: points right of and below the top-left corner of each spread's
+ /// pages. One per document, at the same place on every spread. X/Y fields measure from it.
+ #[serde(skip_serializing_if = "is_origin")]
+ pub zero_point: [f64; 2],
+ /// Lock Zero Point: dragging from the ruler corner leaves it where it is.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub zero_point_locked: bool,
+}
+
+fn is_origin(p: &[f64; 2]) -> bool {
+ p[0] == 0.0 && p[1] == 0.0
}
impl Default for DocSettings {
@@ -383,6 +394,8 @@ impl Default for DocSettings {
overprint_black: true,
track_changes: false,
glyph_fallback: false,
+ zero_point: [0.0, 0.0],
+ zero_point_locked: false,
}
}
}
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index e7190acb4..ecb04f001 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -107,7 +107,9 @@ pub fn specs() -> Vec<CommandSpec> {
let st = s.doc_mut()?;
let e = st.history.undo.pop().ok_or_else(|| super::bad("edit.undo", "nothing to undo"))?;
st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
- st.doc = e.doc;
+ let mut doc = e.doc;
+ super::rulers::keep_zero_point(&st.doc, &mut doc);
+ st.doc = doc;
st.selection = e.selection;
st.revision += 1;
Ok(json!({"undone": e.label}))
@@ -116,7 +118,9 @@ pub fn specs() -> Vec<CommandSpec> {
let st = s.doc_mut()?;
let e = st.history.redo.pop().ok_or_else(|| super::bad("edit.redo", "nothing to redo"))?;
st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
- st.doc = e.doc;
+ let mut doc = e.doc;
+ super::rulers::keep_zero_point(&st.doc, &mut doc);
+ st.doc = doc;
st.selection = e.selection;
st.revision += 1;
Ok(json!({"redone": e.label}))
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 68061af0a..b67b7ea6b 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -42,6 +42,7 @@ pub mod preflight;
mod prefs;
mod print;
mod qr;
+mod rulers;
mod scripts;
mod select;
pub mod spelling;
@@ -198,6 +199,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(index::specs());
v.extend(anchored::specs());
v.extend(guides::specs());
+ v.extend(rulers::specs());
v.extend(links::specs());
v.extend(fonts::specs());
v.extend(spelling::specs());
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index 17c44c27a..134c8190d 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform Panel",
[],
None,
- "{x?, y?, width?, height?, scaleX? (%), scaleY? (%), rotation? (°), shear? (°), ref?: 0..8, ids?} — reference-point based geometry; rotation and shear are absolute (Transformations are Totals decides whether nested objects measure them on the pasteboard)",
+ "{x?, y? (measured from the rulers' zero point, view.zeroPoint), width?, height?, scaleX? (%), scaleY? (%), rotation? (°), shear? (°), ref?: 0..8, ids?} — reference-point based geometry; rotation and shear are absolute (Transformations are Totals decides whether nested objects measure them on the pasteboard)",
has_selection,
transform_set
),
@@ -1242,22 +1242,13 @@ fn transform_set(s: &mut Session, p: &Value) -> Result<Value> {
let fx = [0.0, 0.5, 1.0][rf % 3];
let fy = [0.0, 0.5, 1.0][(rf / 3).min(2)];
let mut to = Rect::new(anchor.x - fx * w, anchor.y - fy * h, anchor.x - fx * w + w, anchor.y - fy * h + h);
- // x/y are the reference point position relative to the page origin of the first page in the spread.
- let page_x = ids
- .first()
- .and_then(|i| d.find(*i))
- .and_then(|l| {
- d.spread(l.spread).map(|sp| {
- let pi = sp.page_at_x(from.center().x).unwrap_or(0);
- sp.pages[pi].x
- })
- })
- .unwrap_or(0.0);
- if let Some(x) = p.get("x").and_then(Value::as_f64) {
- to = to + Vec2::new(x + page_x - anchor.x, 0.0);
+ // x/y are the reference point's position measured from the rulers' zero point.
+ let origin = ids.first().and_then(|i| d.find(*i)).and_then(|l| d.ruler_origin(l.spread)).unwrap_or(Point::ORIGIN);
+ if let Some(x) = p.get("x").and_then(Value::as_f64).filter(|v| v.is_finite()) {
+ to = to + Vec2::new(x + origin.x - anchor.x, 0.0);
}
- if let Some(y) = p.get("y").and_then(Value::as_f64) {
- to = to + Vec2::new(0.0, y - anchor.y);
+ if let Some(y) = p.get("y").and_then(Value::as_f64).filter(|v| v.is_finite()) {
+ to = to + Vec2::new(0.0, y + origin.y - anchor.y);
}
let to = Rect::new(to.x0 + pad.0, to.y0 + pad.1, (to.x1 - pad.2).max(to.x0 + pad.0 + 0.01), (to.y1 - pad.3).max(to.y0 + pad.1 + 0.01));
let m = Affine::translate((to.x0, to.y0))
diff --git a/crates/engine/src/cmd/rulers.rs b/crates/engine/src/cmd/rulers.rs
new file mode 100644
index 000000000..4e850e571
--- /dev/null
+++ b/crates/engine/src/cmd/rulers.rs
@@ -0,0 +1,179 @@
+//! The rulers' zero point: one per document, an offset from the top-left corner of each spread's
+//! pages, so every spread measures from the same relative place. Moving it is not an undo step,
+//! and undo and redo leave it where it is.
+
+use std::sync::Arc;
+
+use designcraft_doc::Document;
+use serde_json::{Value, json};
+
+use super::{CommandSpec, bad, cmd, has_doc, point_param};
+use crate::{Result, Session};
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(noundo
+ "view.zeroPoint",
+ "Ruler Zero Point",
+ [],
+ None,
+ "{at?: [x, y] (points right of and below the top-left corner of each spread's pages; kept on the pasteboard), reset?: bool} → {zeroPoint: [x, y], locked}; with neither, reports it. Not an undo step; refused while locked",
+ has_doc,
+ zero_point
+ ),
+ cmd!(noundo
+ "view.lockZeroPoint",
+ "Lock Zero Point",
+ [],
+ None,
+ "{on?: bool (default: toggle)} → {locked} — a locked zero point can't be dragged, moved or reset",
+ has_doc,
+ lock
+ ),
+ ]
+}
+
+fn state(d: &Document) -> Value {
+ json!({"zeroPoint": d.settings.zero_point, "locked": d.settings.zero_point_locked})
+}
+
+fn zero_point(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "view.zeroPoint";
+ let reset = p.get("reset").and_then(Value::as_bool).unwrap_or(false);
+ let at = match p.get("at") {
+ None => None,
+ Some(_) => Some(point_param(p, "at").ok_or_else(|| bad(ID, "at must be [x, y] in points"))?),
+ };
+ let st = s.doc()?;
+ let to = match (reset, at) {
+ (true, _) => [0.0, 0.0],
+ (false, Some(a)) => st.doc.clamp_zero_point([a.x, a.y]).ok_or_else(|| bad(ID, "at must be finite"))?,
+ (false, None) => return Ok(state(&st.doc)),
+ };
+ if st.doc.settings.zero_point_locked {
+ return Err(bad(ID, "the zero point is locked"));
+ }
+ if st.doc.settings.zero_point == to {
+ return Ok(state(&st.doc));
+ }
+ s.edit(|d, _| {
+ d.settings.zero_point = to;
+ Ok(state(d))
+ })
+}
+
+fn lock(s: &mut Session, p: &Value) -> Result<Value> {
+ let cur = s.doc()?.doc.settings.zero_point_locked;
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!cur);
+ if on == cur {
+ return Ok(json!({"locked": cur}));
+ }
+ s.edit(|d, _| {
+ d.settings.zero_point_locked = on;
+ Ok(json!({"locked": on}))
+ })
+}
+
+/// Undo and redo swap whole documents; the zero point stays as it is now.
+pub(crate) fn keep_zero_point(now: &Document, to: &mut Arc<Document>) {
+ let (zp, locked) = (now.settings.zero_point, now.settings.zero_point_locked);
+ if to.settings.zero_point != zp || to.settings.zero_point_locked != locked {
+ let d = Arc::make_mut(to);
+ d.settings.zero_point = zp;
+ d.settings.zero_point_locked = locked;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use designcraft_doc::{ItemId, SpreadRef};
+ use designcraft_geom::Point;
+ use serde_json::json;
+
+ use crate::Session;
+
+ fn zp(s: &Session) -> [f64; 2] {
+ s.doc().unwrap().doc.settings.zero_point
+ }
+
+ #[test]
+ fn the_zero_point_moves_resets_and_locks_without_undo_steps() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 3})).unwrap();
+ s.execute("frame.create", &json!({"rect": [36, 36, 136, 136]})).unwrap();
+ let undo_steps = s.doc().unwrap().history.undo.len();
+ let r = s.execute("view.zeroPoint", &json!({"at": [72, 36]})).unwrap();
+ assert_eq!(r["zeroPoint"], json!([72.0, 36.0]));
+ assert_eq!(zp(&s), [72.0, 36.0]);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo_steps, "not an undo step");
+ // Undo takes back the frame, not the zero point.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(zp(&s), [72.0, 36.0]);
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(zp(&s), [72.0, 36.0]);
+ // Locked: moving and resetting are refused.
+ assert_eq!(s.execute("view.lockZeroPoint", &json!({})).unwrap()["locked"], true);
+ assert!(s.execute("view.zeroPoint", &json!({"at": [0, 0]})).is_err());
+ assert!(s.execute("view.zeroPoint", &json!({"reset": true})).is_err());
+ assert_eq!(s.execute("view.zeroPoint", &json!({})).unwrap()["locked"], true);
+ s.execute("view.lockZeroPoint", &json!({"on": false})).unwrap();
+ s.execute("view.zeroPoint", &json!({"reset": true})).unwrap();
+ assert_eq!(zp(&s), [0.0, 0.0]);
+ // Hostile input: non-numbers are refused, far-off points stay on the pasteboard.
+ assert!(s.execute("view.zeroPoint", &json!({"at": "here"})).is_err());
+ assert!(s.execute("view.zeroPoint", &json!({"at": [1]})).is_err());
+ s.execute("view.zeroPoint", &json!({"at": [1e300, -1e300]})).unwrap();
+ let [x, y] = zp(&s);
+ assert!(x.is_finite() && y.is_finite() && x < 5000.0 && y > -5000.0, "{x} {y}");
+ }
+
+ #[test]
+ fn x_and_y_measure_from_the_zero_point_on_every_spread() {
+ let mut s = Session::new();
+ // Page 1 alone on spread 0; pages 2–3 on spread 1.
+ s.execute("file.new", &json!({"pages": 3})).unwrap();
+ s.execute("view.zeroPoint", &json!({"at": [100, 50]})).unwrap();
+ s.prefs.dimensions_include_stroke = false;
+ let d = s.doc().unwrap().doc.clone();
+ let o0 = d.ruler_origin(SpreadRef::Doc(0)).unwrap();
+ let o1 = d.ruler_origin(SpreadRef::Doc(1)).unwrap();
+ // The same place relative to each spread's top-left page corner.
+ let b0 = d.spreads[0].bounds();
+ let b1 = d.spreads[1].bounds();
+ assert_eq!(o0, Point::new(b0.x0 + 100.0, b0.y0 + 50.0));
+ assert_eq!(o1, Point::new(b1.x0 + 100.0, b1.y0 + 50.0));
+ // transform.set x/y places the frame's top-left at that distance from the zero point.
+ // Spread 1: a frame on its right-hand page measures from the left-hand page's corner too,
+ // as the ruler does.
+ for (spread, x0, o) in [(0, 10, o0), (1, 700, o1)] {
+ let r = s.execute("frame.create", &json!({"spread": spread, "rect": [x0, 10, x0 + 50, 60]})).unwrap();
+ let id = ItemId(r["id"].as_u64().unwrap());
+ s.execute("transform.set", &json!({"ids": [id.0], "x": 20, "y": 30, "ref": 0})).unwrap();
+ let b = s.doc().unwrap().doc.item(id).unwrap().bounds();
+ assert!((b.x0 - (o.x + 20.0)).abs() < 1e-6 && (b.y0 - (o.y + 30.0)).abs() < 1e-6, "spread {spread}: {b:?} from {o:?}");
+ }
+ }
+
+ #[test]
+ fn old_documents_read_with_the_zero_point_at_the_corner() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let json = serde_json::to_string(&*d).unwrap();
+ assert!(!json.contains("zeroPoint"), "the default isn't written");
+ let back: designcraft_doc::Document = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.settings.zero_point, [0.0, 0.0]);
+ assert!(!back.settings.zero_point_locked);
+ s.execute("view.zeroPoint", &json!({"at": [12, 34]})).unwrap();
+ s.execute("view.lockZeroPoint", &json!({"on": true})).unwrap();
+ let json = serde_json::to_string(&*s.doc().unwrap().doc).unwrap();
+ let back: designcraft_doc::Document = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.settings.zero_point, [12.0, 34.0]);
+ assert!(back.settings.zero_point_locked);
+ // A file can hold any numbers; rulers and X/Y read them kept on the pasteboard.
+ let far = json.replace("[12.0,34.0]", "[1e300,-1e300]");
+ let back: designcraft_doc::Document = serde_json::from_str(&far).unwrap();
+ let [x, y] = back.zero_point();
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ }
+}
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 9d73562b9..ca4527a82 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -250,7 +250,10 @@ impl<'a> Ex<'a> {
.attr("Self", "d")
.attr("StoryList", story_list.join(" "))
.attr("Name", format!("{}.indd", d.title))
- .attr("ZeroPoint", "0 0")
+ .attr("ZeroPoint", {
+ let [x, y] = d.zero_point();
+ format!("{} {}", num(x), num(y))
+ })
.attr("ActiveLayer", d.layers.first().map(|l| uid(l.id.0)).unwrap_or_else(|| "n".into()));
root.push(
El::new("Language")
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d85d9ee02..f28726307 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -2307,7 +2307,7 @@ impl<'r> Importer<'r> {
}
self.settings.lists = std::mem::take(&mut self.lists);
// Make sure built-in paragraph styles exist and are first.
- let d = Document {
+ let mut d = Document {
title,
settings: self.settings.clone(),
spreads: std::mem::take(&mut self.spreads).into_iter().map(Arc::new).collect(),
@@ -2341,6 +2341,11 @@ impl<'r> Importer<'r> {
next_id: self.next_id,
font_scope: 0,
};
+ if let [x, y] = root.get("ZeroPoint").map(nums).unwrap_or_default()[..]
+ && let Some(zp) = d.clamp_zero_point([x, y])
+ {
+ d.settings.zero_point = zp;
+ }
Ok(d)
}
}
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 7b747587a..9b21c4c33 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -1399,3 +1399,27 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {
check(&d);
check(&import_idml(&export_idml(&d)).unwrap());
}
+
+#[test]
+fn round_trips_the_zero_point() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ d.settings.zero_point = [36.0, 18.5];
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);
+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.
+ let fixture = |zp: &str| {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#
+ );
+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>
+ </idPkg:Spread>"#;
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()
+ };
+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);
+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 34dd61442..a972d69b8 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1227,13 +1227,19 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf,
painter.line_segment([pos2(rect.min.x, rect.min.y - 0.25), pos2(full.max.x, rect.min.y - 0.25)], Stroke::new(0.5, t.ruler_tick));
painter.line_segment([pos2(rect.min.x - 0.25, rect.min.y), pos2(rect.min.x - 0.25, full.max.y)], Stroke::new(0.5, t.ruler_tick));
// Zero-point crosshair box.
- let zc = Rect::from_min_max(full.min, rect.min).center();
+ let corner = Rect::from_min_max(full.min, rect.min);
+ let zc = corner.center();
painter.line_segment([zc - vec2(4.0, 0.0), zc + vec2(4.0, 0.0)], Stroke::new(1.0, t.ruler_tick));
painter.line_segment([zc - vec2(0.0, 4.0), zc + vec2(0.0, 4.0)], Stroke::new(1.0, t.ruler_tick));
- // Origin: top-left of the current spread's first page.
- let Some(i) = current_slot(app, layout) else { return };
- let slot = &layout.slots[i];
- let origin = Point::new(slot.bounds.x0, slot.bounds.y0);
+ // While the zero point is dragged out of the corner, the rulers measure from the pointer and
+ // crosshair lines show where it lands.
+ let dragged = ui.data(|d| d.get_temp::<Pos2>(egui::Id::new((ZERO_POINT_DRAG, app.pane)))).filter(|p| !corner.contains(*p));
+ if let Some(p) = dragged {
+ let m = Stroke::new(1.0, t.text_dim);
+ dashed(&painter, pos2(p.x, rect.min.y), pos2(p.x, full.max.y), m, 3.0, 3.0);
+ dashed(&painter, pos2(rect.min.x, p.y), pos2(full.max.x, p.y), m, 3.0, 3.0);
+ }
+ let Some(origin) = dragged.map(|p| xf.to_canvas(p)).or_else(|| ruler_zero(app, doc, layout)) else { return };
let font = egui::FontId::proportional(9.0);
let tick = Stroke::new(1.0, t.ruler_tick);
// Horizontal.
@@ -1299,6 +1305,13 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf,
}
}
+/// Where the rulers measure from (canvas coordinates): the document's zero point on the spread
+/// in view.
+fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option<Point> {
+ let slot = layout.slots.get(current_slot(app, layout)?)?;
+ Some(slot.to_canvas(doc.ruler_origin(slot.spread)?))
+}
+
/// The horizontal (top) and vertical (left) rulers around the view `rect` in `full`.
fn ruler_rects(full: Rect, rect: Rect) -> (Rect, Rect) {
(
@@ -1307,10 +1320,27 @@ fn ruler_rects(full: Rect, rect: Rect) -> (Rect, Rect) {
)
}
-/// Right-clicking a ruler opens a menu of units for that ruler.
+/// Right-clicking a ruler opens a menu of units for that ruler; right-clicking the corner, one
+/// to lock the zero point.
fn ruler_units_menus(app: &mut DesignApp, resp: &egui::Response, full: Rect, rect: Rect, doc: &Document) {
let (top, left) = ruler_rects(full, rect);
let at = resp.interact_pointer_pos();
+ let corner = Rect::from_min_max(full.min, rect.min);
+ let open = if resp.secondary_clicked() {
+ Some(egui::SetOpenCommand::Bool(at.is_some_and(|p| corner.contains(p))))
+ } else if resp.clicked() {
+ Some(egui::SetOpenCommand::Bool(false))
+ } else {
+ None
+ };
+ let locked = doc.settings.zero_point_locked;
+ egui::Popup::context_menu(resp).id(resp.id.with("ruler_corner")).open_memory(open).show(|ui| {
+ let label = crate::i18n::tr(&app.ui.language, if locked { "Unlock Zero Point" } else { "Lock Zero Point" });
+ if ui.button(crate::rtl::widget(ui, label)).clicked() {
+ let _ = app.run("view.lockZeroPoint", json!({"on": !locked}));
+ ui.close();
+ }
+ });
for (ruler, key, cur) in [(top, "horizontalUnits", doc.settings.horizontal_units), (left, "verticalUnits", doc.settings.vertical_units)] {
let open = if resp.secondary_clicked() {
Some(egui::SetOpenCommand::Bool(at.is_some_and(|p| ruler.contains(p))))
@@ -1373,7 +1403,10 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
}
return;
}
- // Ruler guides need the rulers (hidden while the view is rotated).
+ // The zero point and ruler guides need the rulers (hidden while the view is rotated).
+ if !space && xf.rot == 0 && zero_point_drag(app, ui, resp, rect, &xf) {
+ return;
+ }
if !space && xf.rot == 0 && guide_drag(app, ui, resp, rect, &xf) {
return;
}
@@ -1609,6 +1642,69 @@ fn hair(painter: &egui::Painter) -> f32 {
1.0 / painter.ctx().pixels_per_point()
}
+const ZERO_POINT_DRAG: &str = "canvas_zero_point_drag";
+
+/// The ruler corner: drag from it and the zero point lands where the pointer is released; a click
+/// that stays in the corner leaves it; a double-click resets it. Locked, the corner ignores both.
+/// Holds the pointer position while dragging; returns true while it owns the pointer.
+fn zero_point_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf) -> bool {
+ let id = egui::Id::new((ZERO_POINT_DRAG, app.pane));
+ let corner = Rect::from_min_max(resp.rect.min, rect.min);
+ let (pressed, released, down, origin, latest, dbl) = ui.input(|i| {
+ (
+ i.pointer.primary_pressed(),
+ i.pointer.primary_released(),
+ i.pointer.primary_down(),
+ i.pointer.press_origin(),
+ i.pointer.latest_pos(),
+ i.pointer.button_double_clicked(egui::PointerButton::Primary),
+ )
+ });
+ let mut at: Option<Pos2> = ui.data(|d| d.get_temp(id));
+ if at.is_none() {
+ let locked = app.session.active().is_none_or(|st| st.doc.settings.zero_point_locked);
+ if !pressed || !resp.hovered() || locked || corner.width() <= 0.0 || corner.height() <= 0.0 {
+ return false;
+ }
+ at = origin.filter(|o| corner.contains(*o));
+ }
+ let Some(mut p) = at else { return false };
+ if let Some(l) = latest.filter(|l| l.x.is_finite() && l.y.is_finite()) {
+ p = l;
+ }
+ if !released && down {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ ui.data_mut(|d| d.insert_temp(id, p));
+ return true;
+ }
+ ui.data_mut(|d| d.remove::<Pos2>(id));
+ if !released {
+ // The release happened where we couldn't see it (outside the window).
+ return false;
+ }
+ if dbl {
+ let _ = app.run("view.zeroPoint", json!({"reset": true}));
+ } else if !corner.contains(p)
+ && let Some(zp) = zero_point_at(app, xf, p)
+ {
+ let _ = app.run("view.zeroPoint", json!({ "at": zp }));
+ }
+ true
+}
+
+/// A screen point as a zero point: its offset from the top-left page corner of the spread in
+/// view, the spread the rulers measure.
+fn zero_point_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<[f64; 2]> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let slot = layout.slots.get(current_slot(app, &layout)?)?;
+ let corner = st.doc.spread(slot.spread)?.bounds();
+ let sp = slot.to_spread(xf.to_canvas(p));
+ let zp = [sp.x - corner.x0, sp.y - corner.y0];
+ // The engine keeps it on the pasteboard.
+ zp.iter().all(|v| v.is_finite()).then_some(zp)
+}
+
const GUIDE_DRAG: &str = "canvas_guide_drag";
/// A ruler guide being dragged: out of a ruler (`from` None) or an existing one.
@@ -1798,6 +1894,136 @@ mod tests {
}
}
+ /// A harness whose frames are 1 ms apart, so two clicks make a double-click.
+ fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> {
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(4);
+ h
+ }
+
+ fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) {
+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.run_steps(2);
+ }
+
+ fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) {
+ h.hover_at(from);
+ h.step();
+ primary(h, from, true);
+ h.event(egui::Event::PointerMoved(from + (to - from) / 2.0));
+ h.run_steps(2);
+ h.event(egui::Event::PointerMoved(to));
+ h.run_steps(2);
+ primary(h, to, false);
+ }
+
+ fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) {
+ h.hover_at(p);
+ h.step();
+ primary(h, p, true);
+ primary(h, p, false);
+ }
+
+ fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] {
+ h.state().session.doc().unwrap().doc.settings.zero_point
+ }
+
+ #[test]
+ fn the_ruler_corner_drags_resets_and_locks_the_zero_point() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ let mut h = fast_harness(app);
+ let rect = h.state().canvas_rect.unwrap();
+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);
+ // A click that stays in the corner leaves the zero point.
+ corner_click(&mut h, corner);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Dragged out, it lands where released, measured from the spread in view.
+ let dest = rect.min + vec2(80.0, 50.0);
+ let expected = {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let layout = CanvasLayout::new(&st.doc, false);
+ let slot = layout.slots[current_slot(app, &layout).unwrap()];
+ let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest));
+ let b = st.doc.spread(slot.spread).unwrap().bounds();
+ [sp.x - b.x0, sp.y - b.y0]
+ };
+ corner_drag(&mut h, corner, dest);
+ let zp = zero_point(&h);
+ assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}");
+ assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}");
+ // The rulers measure from the point it was dropped on.
+ {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let layout = CanvasLayout::new(&st.doc, false);
+ let o = ruler_zero(app, &st.doc, &layout).unwrap();
+ let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o);
+ assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}");
+ }
+ // A double-click resets it.
+ corner_click(&mut h, corner);
+ corner_click(&mut h, corner);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Locked from the corner's context menu, the corner ignores drags and double-clicks.
+ right_click(&mut h, corner);
+ h.get_by_label("Lock Zero Point").click();
+ h.run_steps(3);
+ assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked);
+ corner_drag(&mut h, corner, dest);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Unlocked again from the same menu.
+ right_click(&mut h, corner);
+ h.get_by_label("Unlock Zero Point").click();
+ h.run_steps(3);
+ corner_drag(&mut h, corner, dest);
+ assert_ne!(zero_point(&h), [0.0, 0.0]);
+ h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap();
+ corner_click(&mut h, corner);
+ corner_click(&mut h, corner);
+ assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset");
+ }
+
+ #[test]
+ fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ // Spread 0: page 1; spread 1: pages 2 and 3.
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();
+ app.session.prefs.dimensions_include_stroke = false;
+ let mut h = harness(app);
+ let rect = h.state().canvas_rect.unwrap();
+ for (spread, x0) in [(0usize, 136.0), (1, 736.0)] {
+ let app = h.state_mut();
+ let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone();
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ // X/Y (Control, Properties and Info panels).
+ let r = crate::panels::sel_info(app).unwrap().page_rect;
+ assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}");
+ // The rulers, with that spread in view.
+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);
+ let slot = layout.slots[spread];
+ let v = app.view_mut().unwrap();
+ let zoom = v.zoom;
+ let c = slot.bounds.center();
+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom);
+ h.run_steps(2);
+ let app = h.state();
+ let doc = app.session.active().unwrap().doc.clone();
+ assert_eq!(current_slot(app, &layout), Some(spread));
+ let o = ruler_zero(app, &doc, &layout).unwrap();
+ assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}");
+ }
+ }
+
#[test]
fn rulers_open_no_units_menu_without_a_document() {
let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 05a73395b..9a5f0e2ba 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -24,7 +24,7 @@ use crate::theme::Tokens;
/// Summary of the current object selection (for the Control panel and Properties).
#[derive(Clone, Debug)]
pub struct SelInfo {
- /// Bounds relative to the page the selection is on.
+ /// Bounds measured from the rulers' zero point (as the X/Y fields show them).
pub page_rect: Rect,
pub count: usize,
pub fill: String,
@@ -68,9 +68,7 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
let b = b?;
let first = d.item(st.selection.items[0])?;
let loc = d.find(first.id)?;
- let sp = d.spread(loc.spread)?;
- let pi = sp.page_at_x(b.center().x).unwrap_or(0);
- let px = sp.pages.get(pi).map(|p| p.x).unwrap_or(0.0);
+ let o = d.ruler_origin(loc.spread)?;
let wrap = match first.wrap.mode {
WrapMode::None => "none",
WrapMode::BoundingBox => "boundingBox",
@@ -79,7 +77,7 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
WrapMode::JumpToNextColumn => "jumpToNextColumn",
};
Some(SelInfo {
- page_rect: Rect::new(b.x0 - px, b.y0, b.x1 - px, b.y1),
+ page_rect: Rect::new(b.x0 - o.x, b.y0 - o.y, b.x1 - o.x, b.y1 - o.y),
count: st.selection.items.len(),
fill: first.fill.swatch.clone(),
stroke: first.stroke.swatch.clone(),