DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Rulers: Spread, Page or Spine origin; Cmd-drag the corner for guides
aionggade9eb6e6944
diff --git a/ROADMAP.md b/ROADMAP.mdindex 2e9bc3c4f..5f0316985 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -32,7 +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`.+- Ruler origin and zero point: Preferences › Units & Increments › Origin (Spread, Page or Spine; `document.preferences {rulerOrigin}`, IDML `RulerOrigin`); drag from the ruler corner to place the zero point (crosshair lines while dragging), double-click the corner to reset, right-click it to lock, Cmd-drag (Ctrl) to make a horizontal and a vertical guide; one zero point per document at the same place on every spread (and page, for a page origin), saved with the document and as IDML `ZeroPoint`; rulers and the X/Y fields (Control, Properties, Info, `transform.set`) measure from the origin plus the zero point; 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.rsindex 9d3d3486d..08c8588ea 100644--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@ -61,12 +61,48 @@ 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))+ /// Where the rulers of spread `r` start before the zero point moves them, for something at+ /// spread x `x` (a page origin is the page there, or the nearest page): spread coordinates.+ pub fn ruler_base(&self, r: SpreadRef, x: f64) -> Option<Point> {+ let sp = self.spread(r)?;+ let b = sp.bounds();+ Some(match self.settings.ruler_origin {+ crate::RulerOrigin::Spread => Point::new(b.x0, b.y0),+ crate::RulerOrigin::Spine => Point::new(sp.spine_x(), b.y0),+ crate::RulerOrigin::Page => {+ let pg = sp.pages.get(sp.page_at_x(x)?)?;+ Point::new(pg.x, b.y0)+ }+ })+ }++ /// Where the rulers and X/Y fields of spread `r` measure from, for something at spread x+ /// `x`: the ruler origin moved by the document's zero point.+ pub fn ruler_origin(&self, r: SpreadRef, x: f64) -> Option<Point> {+ let o = self.ruler_base(r, x)?;+ let [zx, zy] = self.zero_point();+ Some(Point::new(o.x + zx, o.y + zy))+ }++ /// The horizontal ruler of spread `r` in pieces `(from x, to x, base)`, spread coordinates,+ /// covering every x: one piece, or one per page for a page origin.+ pub fn ruler_pieces(&self, r: SpreadRef) -> Vec<(f64, f64, Point)> {+ let Some(sp) = self.spread(r) else { return Vec::new() };+ if self.settings.ruler_origin != crate::RulerOrigin::Page || sp.pages.len() < 2 {+ return self.ruler_base(r, 0.0).map(|o| (f64::NEG_INFINITY, f64::INFINITY, o)).into_iter().collect();+ }+ let mut pages: Vec<&crate::Page> = sp.pages.iter().collect();+ pages.sort_by(|a, b| a.x.total_cmp(&b.x));+ let y = sp.bounds().y0;+ pages+ .iter()+ .enumerate()+ .map(|(i, pg)| {+ let from = if i == 0 { f64::NEG_INFINITY } else { pg.x };+ let to = pages.get(i + 1).map_or(f64::INFINITY, |next| next.x);+ (from, to, Point::new(pg.x, y))+ })+ .collect()}/// The document's zero point, kept on the pasteboard (a file may hold any numbers).@@ -88,8 +124,9 @@ impl Document {.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));+ // From any ruler origin (a spine or a page can be at the spread's right edge).let side = px.max(w);- Some([x.clamp(-side, w + side), y.clamp(-py, h + py)])+ Some([x.clamp(-(w + side), w + side), y.clamp(-py, h + py)])}/// All spread refs: document spreads then parents.diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 886ef2ae6..74d46c58c 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -90,6 +90,20 @@ pub enum BlendSpace {Rgb,}+/// Preferences › Units & Increments › Origin: what the rulers and X/Y fields measure from+/// (before the zero point moves it).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum RulerOrigin {+ /// The top-left corner of the spread's pages.+ #[default]+ Spread,+ /// The top-left corner of each page.+ Page,+ /// The spine, at the top of the spread.+ Spine,+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub enum Intent {@@ -351,8 +365,11 @@ 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.+ /// What the rulers measure from before the zero point moves it.+ pub ruler_origin: RulerOrigin,+ /// The rulers' zero point: points right of and below the ruler origin (`ruler_origin`).+ /// One per document, at the same place on every spread (and page, for a page origin). 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.@@ -394,6 +411,7 @@ impl Default for DocSettings {overprint_black: true,track_changes: false,glyph_fallback: false,+ ruler_origin: RulerOrigin::Spread,zero_point: [0.0, 0.0],zero_point_locked: false,}diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rsindex 134c8190d..639c9d612 100644--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@ -1243,7 +1243,7 @@ fn transform_set(s: &mut Session, p: &Value) -> Result<Value> {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'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);+ let origin = ids.first().and_then(|i| d.find(*i)).and_then(|l| d.ruler_origin(l.spread, from.center().x)).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);}diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rsindex 68a5cf152..a64434652 100644--- a/crates/engine/src/cmd/prefs.rs+++ b/crates/engine/src/cmd/prefs.rs@@ -21,6 +21,7 @@ const DOC_KEYS: &[&str] = &["advancedType","overprintBlack","glyphFallback",+ "rulerOrigin",];pub fn specs() -> Vec<CommandSpec> {@@ -62,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {"Document Preferences",[],None,- "{horizontalUnits?, verticalUnits?: points|picas|inches|millimeters|…, keyboardIncrement? (pt), baselineGrid?: {start, increment, relativeTo, color, viewThreshold}, grid?: {horizontal, vertical, subdivisions, color, inBack}, pasteboard?: [h, v], marginColor?, columnColor?, bleedColor?, slugColor?: [r, g, b], advancedType?: {superscriptSize, superscriptPosition, subscriptSize, subscriptPosition} (%), overprintBlack?, glyphFallback? (draw characters the font lacks from fallback fonts; off: as the font's missing-glyph box)} → those settings",+ "{horizontalUnits?, verticalUnits?: points|picas|inches|millimeters|…, keyboardIncrement? (pt), baselineGrid?: {start, increment, relativeTo, color, viewThreshold}, grid?: {horizontal, vertical, subdivisions, color, inBack}, pasteboard?: [h, v], marginColor?, columnColor?, bleedColor?, slugColor?: [r, g, b], advancedType?: {superscriptSize, superscriptPosition, subscriptSize, subscriptPosition} (%), overprintBlack?, glyphFallback? (draw characters the font lacks from fallback fonts; off: as the font's missing-glyph box), rulerOrigin?: spread|page|spine (what rulers and X/Y measure from, with the zero point)} → those settings",has_doc,|s, p| {let cur = serde_json::to_value(&s.doc()?.doc.settings).map_err(|e| bad("document.preferences", e.to_string()))?;diff --git a/crates/engine/src/cmd/rulers.rs b/crates/engine/src/cmd/rulers.rsindex 4e850e571..a17afff79 100644--- a/crates/engine/src/cmd/rulers.rs+++ b/crates/engine/src/cmd/rulers.rs@@ -1,6 +1,6 @@-//! 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.+//! The rulers' zero point: one per document, an offset from the ruler origin (the spread's or+//! each page's top-left corner, or the spine), 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;@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {"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",+ "{at?: [x, y] (points right of and below the ruler origin — document.preferences rulerOrigin: spread|page|spine; 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),@@ -135,8 +135,8 @@ mod tests {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();+ let o0 = d.ruler_origin(SpreadRef::Doc(0), 0.0).unwrap();+ let o1 = d.ruler_origin(SpreadRef::Doc(1), 0.0).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();@@ -154,6 +154,37 @@ mod tests {}}+ #[test]+ fn x_measures_from_the_chosen_ruler_origin() {+ let mut s = Session::new();+ // Spread 1: page 2 (x 0–612) on the left, page 3 (612–1224) on the right.+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.prefs.dimensions_include_stroke = false;+ s.execute("view.zeroPoint", &json!({"at": [10, 0]})).unwrap();+ let left = s.execute("frame.create", &json!({"spread": 1, "rect": [100, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap();+ let right = s.execute("frame.create", &json!({"spread": 1, "rect": [700, 10, 750, 60]})).unwrap()["id"].as_u64().unwrap();+ let x_of = |s: &Session, id: u64| {+ let d = &s.doc().unwrap().doc;+ let b = d.item(ItemId(id)).unwrap().bounds();+ b.x0 - d.ruler_origin(SpreadRef::Doc(1), b.center().x).unwrap().x+ };+ assert_eq!(s.doc().unwrap().doc.settings.ruler_origin, designcraft_doc::RulerOrigin::Spread, "the default");+ for (origin, l, r) in [("spread", 90.0, 690.0), ("page", 90.0, 78.0), ("spine", -522.0, 78.0)] {+ s.execute("document.preferences", &json!({"rulerOrigin": origin})).unwrap();+ assert_eq!((x_of(&s, left), x_of(&s, right)), (l, r), "{origin}");+ // The X field sets what it shows.+ s.execute("transform.set", &json!({"ids": [right], "x": 5, "ref": 0})).unwrap();+ assert!((x_of(&s, right) - 5.0).abs() < 1e-6, "{origin}");+ s.execute("transform.set", &json!({"ids": [right], "x": r, "ref": 0})).unwrap();+ }+ // A page origin restarts the horizontal ruler on each page.+ let pieces = s.doc().unwrap().doc.ruler_pieces(SpreadRef::Doc(1));+ let starts: Vec<f64> = pieces.iter().map(|p| p.2.x).collect();+ assert_eq!(starts, [0.0, 612.0]);+ assert!(pieces[0].0.is_infinite() && pieces[0].1 == 612.0 && pieces[1].1.is_infinite());+ assert!(s.execute("document.preferences", &json!({"rulerOrigin": "elsewhere"})).is_err());+ }+#[test]fn old_documents_read_with_the_zero_point_at_the_corner() {let mut s = Session::new();diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex ca4527a82..d0a759c0c 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -768,7 +768,14 @@ impl<'a> Ex<'a> {El::new("ViewPreference").attr("HorizontalMeasurementUnits", names::unit_out(s.horizontal_units)).attr("VerticalMeasurementUnits", names::unit_out(s.vertical_units))- .attr("RulerOrigin", "SpreadOrigin")+ .attr(+ "RulerOrigin",+ match s.ruler_origin {+ designcraft_doc::RulerOrigin::Spread => "SpreadOrigin",+ designcraft_doc::RulerOrigin::Page => "PageOrigin",+ designcraft_doc::RulerOrigin::Spine => "SpineOrigin",+ },+ ).attr("CursorKeyIncrement", num(s.keyboard_increment)).attr("PointsPerInch", "72"),);diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex f28726307..bc153cffc 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -271,6 +271,12 @@ impl<'r> Importer<'r> {if let Some(v) = e.num("CursorKeyIncrement") {self.settings.keyboard_increment = v;}+ match e.get("RulerOrigin") {+ Some("PageOrigin") => self.settings.ruler_origin = designcraft_doc::RulerOrigin::Page,+ Some("SpineOrigin") => self.settings.ruler_origin = designcraft_doc::RulerOrigin::Spine,+ Some("SpreadOrigin") => self.settings.ruler_origin = designcraft_doc::RulerOrigin::Spread,+ _ => {}+ }}"GridPreference" => self.grid_prefs(e),"PasteboardPreference" => {diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 9b21c4c33..9e8c9c66c 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -1401,11 +1401,15 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {}#[test]-fn round_trips_the_zero_point() {+fn round_trips_the_zero_point_and_ruler_origin() {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]);+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {+ d.settings.ruler_origin = origin;+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);+ }// A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.let fixture = |zp: &str| {let designmap = format!(diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex a972d69b8..c38caba3a 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1231,42 +1231,58 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf,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));- // While the zero point is dragged out of the corner, the rulers measure from the pointer and- // crosshair lines show where it lands.+ // While the zero point is dragged out of the corner, the rulers measure from where it would+ // land (kept on the pasteboard, as the engine keeps it) and crosshair lines show the spot.+ // Cmd-dragged, the lines are the two guides it makes; locked, a plain drag does nothing.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 guides = ui.input(|i| i.modifiers.command);+ let moving = dragged.filter(|_| !guides && !doc.settings.zero_point_locked).and_then(|p| zero_point_at(app, xf, p));+ let cross = if guides { dragged } else { moving.map(|(_, c)| xf.to_screen(c)) };+ if let Some(p) = cross {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 zp = moving.map_or_else(|| doc.zero_point(), |(zp, _)| zp);+ let pieces = ruler_pieces(app, doc, layout, zp);+ let Some(&(_, _, origin)) = pieces.first() else { return };let font = egui::FontId::proportional(9.0);let tick = Stroke::new(1.0, t.ruler_tick);- // Horizontal.+ // Horizontal: one run of ticks per piece (a page origin restarts at every page).let unit = doc.settings.horizontal_units;let (major, sub) = unit.ruler_ticks(xf.zoom);- let c0 = xf.to_canvas(top.min).x - origin.x;- let c1 = xf.to_canvas(pos2(top.max.x, 0.0)).x - origin.x;- let mut k = (c0 / major).floor() as i64;- while (k as f64) * major <= c1 {- let x0 = k as f64 * major;- for s in 0..sub {- let x = x0 + major * s as f64 / sub as f64;- let sx = xf.to_screen(Point::new(origin.x + x, 0.0)).x;- let len = if s == 0 {- RULER- } else if sub % 2 == 0 && s == sub / 2 {- 7.0- } else {- 4.0- };- painter.line_segment([pos2(sx, top.max.y - len), pos2(sx, top.max.y)], tick);- if s == 0 {- let v = unit.from_pt(x);- painter.text(pos2(sx + 2.0, top.min.y + 1.0), egui::Align2::LEFT_TOP, fmt_tick(v), font.clone(), t.ruler_text);+ let (v0, v1) = (xf.to_canvas(top.min).x, xf.to_canvas(pos2(top.max.x, 0.0)).x);+ for &(from, to, o) in &pieces {+ // The piece and the visible ruler, measured from the piece's origin.+ let (s0, s1) = (from - o.x, to - o.x);+ let (c0, c1) = ((v0 - o.x).max(s0), (v1 - o.x).min(s1));+ if !(c0.is_finite() && c1.is_finite() && c0 <= c1) {+ continue;+ }+ let mut k = (c0 / major).floor() as i64;+ while (k as f64) * major <= c1 {+ let x0 = k as f64 * major;+ for s in 0..sub {+ let x = x0 + major * s as f64 / sub as f64;+ if x < s0 || x >= s1 {+ continue;+ }+ let sx = xf.to_screen(Point::new(o.x + x, 0.0)).x;+ let len = if s == 0 {+ RULER+ } else if sub % 2 == 0 && s == sub / 2 {+ 7.0+ } else {+ 4.0+ };+ painter.line_segment([pos2(sx, top.max.y - len), pos2(sx, top.max.y)], tick);+ if s == 0 {+ let v = unit.from_pt(x);+ painter.text(pos2(sx + 2.0, top.min.y + 1.0), egui::Align2::LEFT_TOP, fmt_tick(v), font.clone(), t.ruler_text);+ }}+ k += 1;}- k += 1;}// Vertical.let unit = doc.settings.vertical_units;@@ -1305,11 +1321,15 @@ 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 ruler of the spread in view in pieces `(from x, to x, origin)`, canvas+/// coordinates: the ruler origin (one per page for a page origin) moved by zero point `zp`.+fn ruler_pieces(app: &DesignApp, doc: &Document, layout: &CanvasLayout, zp: [f64; 2]) -> Vec<(f64, f64, Point)> {+ let Some(slot) = current_slot(app, layout).and_then(|i| layout.slots.get(i)) else { return Vec::new() };+ let x = |v: f64, y: f64| if v.is_finite() { slot.to_canvas(Point::new(v, y)).x } else { v };+ doc.ruler_pieces(slot.spread)+ .into_iter()+ .map(|(from, to, b)| (x(from, b.y), x(to, b.y), slot.to_canvas(Point::new(b.x + zp[0], b.y + zp[1]))))+ .collect()}/// The horizontal (top) and vertical (left) rulers around the view `rect` in `full`.@@ -1646,11 +1666,12 @@ 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.+/// Cmd-dragged (Ctrl elsewhere), it makes a horizontal and a vertical guide instead./// 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| {+ let (pressed, released, down, origin, latest, dbl, command) = ui.input(|i| {(i.pointer.primary_pressed(),i.pointer.primary_released(),@@ -1658,12 +1679,12 @@ fn zero_point_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Responsei.pointer.press_origin(),i.pointer.latest_pos(),i.pointer.button_double_clicked(egui::PointerButton::Primary),+ i.modifiers.command,)});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 {+ if !pressed || !resp.hovered() || app.session.active().is_none() || corner.width() <= 0.0 || corner.height() <= 0.0 {return false;}at = origin.filter(|o| corner.contains(*o));@@ -1682,27 +1703,50 @@ fn zero_point_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response// 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 }));+ let locked = app.session.active().is_none_or(|st| st.doc.settings.zero_point_locked);+ if command {+ if !corner.contains(p) && rect.contains(p) {+ corner_guides(app, xf, p);+ }+ } else if !locked {+ 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]> {+/// A screen point as a zero point (its offset from the ruler origin of the spread in view, kept+/// on the pasteboard as the engine keeps it), and where that zero point is on the canvas.+fn zero_point_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<([f64; 2], Point)> {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)+ let base = st.doc.ruler_base(slot.spread, sp.x)?;+ let zp = st.doc.clamp_zero_point([sp.x - base.x, sp.y - base.y])?;+ Some((zp, slot.to_canvas(Point::new(base.x + zp[0], base.y + zp[1]))))+}++/// Cmd-drag from the ruler corner: a horizontal and a vertical spread guide through the drop+/// point, on the spread under it.+fn corner_guides(app: &mut DesignApp, xf: &Xf, p: Pos2) {+ if !app.ui.guides || app.ui.guides_locked {+ return;+ }+ let Some((r, sp)) = app.session.active().and_then(|st| CanvasLayout::new(&st.doc, st.editing_parents).spread_at(xf.to_canvas(p))) else {+ return;+ };+ if !(sp.x.is_finite() && sp.y.is_finite()) {+ return;+ }+ for (orientation, position, at) in [("horizontal", sp.y, sp.x), ("vertical", sp.x, sp.y)] {+ let _ = app.run("guide.add", json!({"spread": r, "orientation": orientation, "position": position, "at": at, "spreadGuide": true}));+ }}const GUIDE_DRAG: &str = "canvas_guide_drag";@@ -1931,6 +1975,12 @@ mod tests {primary(h, p, false);}+ /// Where the rulers measure from (canvas coordinates): the document's zero point on the+ /// spread in view (its first page, for a page origin).+ fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option<Point> {+ ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2)+ }+fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] {h.state().session.doc().unwrap().doc.settings.zero_point}@@ -1992,6 +2042,34 @@ mod tests {assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset");}+ #[test]+ fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ let dest = rect.min + vec2(120.0, 90.0);+ let (r, at) = {+ let app = h.state();+ let st = app.session.active().unwrap();+ CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap()+ };+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));+ h.step();+ corner_drag(&mut h, corner, dest);+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ h.step();+ let doc = h.state().session.doc().unwrap().doc.clone();+ let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect();+ assert_eq!(guides.len(), 2, "{guides:?}");+ let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap();+ assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5);+ assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5);+ assert!(guides.iter().all(|g| g.spread));+ assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays");+ }+#[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());diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 2ab7a3bad..a7f77df1f 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -1053,6 +1053,21 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog, max_he"units" => {crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Ruler Units")).font(semibold(12.0)));egui::Grid::new("pref_units").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Origin:"));+ let cur = d.fields.get("rulerOrigin").and_then(Value::as_str).unwrap_or("spread").to_string();+ const ORIGINS: [(&str, &str); 3] = [("spread", "Spread"), ("page", "Page"), ("spine", "Spine")];+ let shown = ORIGINS.iter().find(|o| o.0 == cur).map_or("Spread", |o| o.1);+ egui::ComboBox::from_id_salt("rulerOrigin")+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, shown)))+ .width(140.0)+ .show_ui(ui, |ui| {+ for (v, l) in ORIGINS {+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() {+ d.fields.insert("rulerOrigin".into(), json!(v));+ }+ }+ });+ ui.end_row();for (key, label) in [("horizontalUnits", "Horizontal:"), ("verticalUnits", "Vertical:")] {crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));let cur: Unit = d.fields.get(key).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();@@ -2031,6 +2046,9 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {return Ok(Value::Null);}let mut doc = json!({"horizontalUnits": d.fields["horizontalUnits"], "verticalUnits": d.fields["verticalUnits"]});+ if let Some(o) = d.fields.get("rulerOrigin").filter(|o| o.is_string()) {+ doc["rulerOrigin"] = o.clone();+ }let mut bg = json!({"relativeTo": d.s("bg.relativeTo"), "color": d.fields.get("bg.color").cloned().unwrap_or(json!([140, 205, 230]))});if let Some(v) = d.m("bg.start") {bg["start"] = json!(v.max(0.0));diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rsindex e5e8a8d08..5ca36f896 100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@ -1734,6 +1734,10 @@ const TABLE: &[(&str, [&str; 5])] = &[],),("Ruler Units", ["Ruler Units", "Ruler Units", "Ruler Units", "Ruler Units", "标尺单位"]),+ ("Origin:", ["Ursprung:", "Origine :", "Origen:", "原点:", "原点:"]),+ ("Spine", ["Bund", "Dos", "Lomo", "ノド", "书脊"]),+ ("Lock Zero Point", ["Nullpunkt fixieren", "Verrouiller le point zéro", "Bloquear punto cero", "ゼロ点をロック", "锁定零点"]),+ ("Unlock Zero Point", ["Nullpunkt lösen", "Déverrouiller le point zéro", "Desbloquear punto cero", "ゼロ点のロックを解除", "解锁零点"]),("Saves which bars show and where the panels are.",[diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rsindex 10e393cd2..72a1701e8 100644--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@ -958,6 +958,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Right-click: stroke, groups", "نقرة يمنى: الحد والمجموعات"),("Rotate 90° Clockwise", "تدوير 90° مع عقارب الساعة"),("Ruler Units", "وحدات المسطرة"),+ ("Origin:", "نقطة الأصل:"),+ ("Spine", "الكعب"),+ ("Lock Zero Point", "قفل نقطة الصفر"),+ ("Unlock Zero Point", "إلغاء قفل نقطة الصفر"),("Save Swatches for Exchange…", "حفظ عينات الألوان للتبادل…"),("Save recovery data every:", "حفظ بيانات الاسترداد كل:"),("Saves which bars show and where the panels are.", "يحفظ الأشرطة الظاهرة ومواضع اللوحات."),diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rsindex c91afd6ba..a5945ba1b 100644--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@ -895,6 +895,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Replace With", "Sostituisci con"),("Right-click: stroke, groups", "Clic destro: traccia, gruppi"),("Ruler Units", "Unità righello"),+ ("Origin:", "Origine:"),+ ("Spine", "Dorso"),+ ("Lock Zero Point", "Blocca punto zero"),+ ("Unlock Zero Point", "Sblocca punto zero"),("Saves which bars show and where the panels are.", "Salva quali barre sono visibili e dove si trovano i pannelli."),("Select a placed video or sound (File › Place a .mp4, .mov, .mp3, .wav …).",diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rsindex be6e2c4da..0fbd29f45 100644--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@ -894,6 +894,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Replace With", "置換後"),("Right-click: stroke, groups", "右クリック: 線・グループ"),("Ruler Units", "定規の単位"),+ ("Origin:", "原点:"),+ ("Spine", "ノド"),+ ("Lock Zero Point", "ゼロ点をロック"),+ ("Unlock Zero Point", "ゼロ点のロックを解除"),("Saves which bars show and where the panels are.", "バーの表示状態とパネルの位置を保存します。"),("Select a placed video or sound (File › Place a .mp4, .mov, .mp3, .wav …).",diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex d25717dc6..f6d78bd04 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -966,6 +966,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Right-click: stroke, groups", "Clique direito: traçado, grupos"),("Rotate 90° Clockwise", "Girar 90° no sentido horário"),("Ruler Units", "Unidades da régua"),+ ("Origin:", "Origem:"),+ ("Spine", "Lombada"),+ ("Lock Zero Point", "Bloquear ponto zero"),+ ("Unlock Zero Point", "Desbloquear ponto zero"),("Save Swatches for Exchange…", "Salvar amostras para intercâmbio…"),("Save recovery data every:", "Salvar dados de recuperação a cada:"),("Saves which bars show and where the panels are.", "Salva quais barras são exibidas e onde ficam os painéis."),diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rsindex 9a9fb89ba..bd07ce785 100644--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@ -892,6 +892,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Replace With", "Замінити на"),("Right-click: stroke, groups", "Права кнопка миші: обведення, групи"),("Ruler Units", "Одиниці лінійки"),+ ("Origin:", "Початок координат:"),+ ("Spine", "Корінець"),+ ("Lock Zero Point", "Заблокувати нульову точку"),+ ("Unlock Zero Point", "Розблокувати нульову точку"),("Saves which bars show and where the panels are.", "Зберігає видимість панелей і їхнє розташування."),("Select a placed video or sound (File › Place a .mp4, .mov, .mp3, .wav …).",diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 94e5c0971..8af12fe5f 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -990,6 +990,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,if app.session.active().is_some() {let doc = app.session.execute("document.preferences", &json!({})).unwrap_or_default();f["horizontalUnits"] = doc["horizontalUnits"].clone();+ f["rulerOrigin"] = doc["rulerOrigin"].clone();f["overprintBlack"] = doc["overprintBlack"].clone();f["glyphFallback"] = doc["glyphFallback"].clone();for k in ["superscriptSize", "superscriptPosition", "subscriptSize", "subscriptPosition"] {diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 9a5f0e2ba..ae2a0732b 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -68,7 +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 o = d.ruler_origin(loc.spread)?;+ let o = d.ruler_origin(loc.spread, b.center().x)?;let wrap = match first.wrap.mode {WrapMode::None => "none",WrapMode::BoundingBox => "boundingBox",