From 24a512793ca825a92a88d79c1fdcbea26a88a270 Mon Sep 17 00:00:00 2001 From: AganzeFelicite Date: Thu, 29 Oct 2026 11:16:33 +0200 Subject: [PATCH 1/7] M4: a drag anywhere in vector edit mode draws a marquee (#1508) A press more than a few pixels from the edited shape left edit mode at once, so a drag over another layer moved that layer. The press now starts a marquee; released without a drag it still leaves edit mode and replays the click to the normal tool. --- crates/engine/src/tools.rs | 2 +- crates/engine/src/vectoredit/pointer.rs | 25 +++++++++++++++---------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tools.rs b/crates/engine/src/tools.rs index 86feed4f1..763b60ec9 100644 --- a/crates/engine/src/tools.rs +++ b/crates/engine/src/tools.rs @@ -212,7 +212,7 @@ pub struct PointerEvent { } /// The pointer is still within [`DRAG_SLOP_PX`] of where it was pressed. -fn within_slop(ev: &PointerEvent, start: Point) -> bool { +pub(crate) fn within_slop(ev: &PointerEvent, start: Point) -> bool { (ev.p() - start).hypot() * ev.zoom.max(1e-6) < DRAG_SLOP_PX } diff --git a/crates/engine/src/vectoredit/pointer.rs b/crates/engine/src/vectoredit/pointer.rs index 4721d6bd5..f9cb05931 100644 --- a/crates/engine/src/vectoredit/pointer.rs +++ b/crates/engine/src/vectoredit/pointer.rs @@ -13,7 +13,7 @@ use super::regions::region_hit; use super::transform::{self, BoxHit, PointBox}; use super::{EditPart, VHit, VTool, VectorEdit, edit, editing, hit, hit_any, local_offset, network, ops, points_of, selected_points, set_state}; use crate::snap::Targets; -use crate::tools::{Cursor, Gesture, Handle, PenCursor, PointerEvent, PointerKind}; +use crate::tools::{Cursor, Gesture, Handle, PenCursor, PointerEvent, PointerKind, within_slop}; use crate::{Result, Session}; /// An in-progress edit-mode gesture (cheap to clone: snap targets are shared). @@ -67,10 +67,13 @@ pub(crate) enum VGesture { moved: bool, smooth: bool, }, - /// Marquee and lasso: `base` is each edited layer's selection to add to. + /// Marquee and lasso: `base` is each edited layer's selection to add to. `leave` is a press + /// away from every edited layer: released without a drag, it leaves edit mode and goes to the + /// normal tool. Marquee { start: Point, base: Vec, + leave: Option, }, Lasso { points: Vec, @@ -661,17 +664,14 @@ impl Session { } } None => { - // Outside every edited layer (and not shift): leave edit mode. + // Outside every edited layer (and not shift): a click leaves edit mode, a drag marquees. let inside = ve.parts().iter().any(|p| doc.world_render_bounds(p.id).is_some_and(|b| b.inflate(tol * 4.0, tol * 4.0).contains(ev.p()))); - if !inside && !ev.shift { - super::end(self)?; - return Ok(false); - } if !ev.shift { set_state(self, VectorEdit::clear_selection)?; } - self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift) }); + let leave = (!inside && !ev.shift).then(|| ev.clone()); + self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift), leave }); } }, VTool::Bend => match h { @@ -695,7 +695,7 @@ impl Session { self.begin_interaction("Bend")?; self.vgesture(VGesture::BendSegment { seg, t }); } - None => self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift) }), + None => self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift), leave: None }), }, VTool::Pen => { let at = if h.is_none() && !ev.shift { self.snap_pen(ev, Some(id), &[])?.0 } else { ev.p() }; @@ -908,7 +908,7 @@ impl Session { self.preview(|doc, _| edit(doc, id, |net| ops::make_smooth(net, v, d)))?; self.vgesture(VGesture::BendVertex { v, origin, moved: true, smooth }); } - VGesture::Marquee { start, base } => { + VGesture::Marquee { start, base, .. } => { let r = Rect::from_points(start, ev.p()); self.tool.overlay.marquee = Some([r.x0, r.y0, r.x1, r.y1]); self.select_parts(&base, |doc, id| super::vertices_in(doc, id, r), false)?; @@ -1025,6 +1025,11 @@ impl Session { VGesture::Handle { .. } | VGesture::BendSegment { .. } | VGesture::Pen { .. } | VGesture::BoxRotate { .. } => { self.commit_interaction()? } + VGesture::Marquee { start, leave: Some(press), .. } if within_slop(ev, start) => { + super::end(self)?; + self.pointer(&press)?; + return self.pointer(ev); + } // The active layer moves to one with points selected when it has none. VGesture::Marquee { .. } | VGesture::Lasso { .. } => set_state(self, |e| { if e.vertices.is_empty() From 3e0e00c3fd23c05649ce588d40252e04ac96d59d Mon Sep 17 00:00:00 2001 From: AganzeFelicite Date: Thu, 29 Oct 2026 11:16:33 +0200 Subject: [PATCH 2/7] test(vector): a marquee starts anywhere on the canvas (#1508) --- crates/engine/src/vector_behaviour_tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index fb734085b..1a3b9b427 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -270,6 +270,27 @@ fn selecting_points_and_segments() { assert_eq!(page_pos(&s, id, tl), Point::new(1.0, 0.0), "the drag is one undo step"); } +#[test] +fn a_marquee_starts_anywhere_on_the_canvas() { + // #1508: a drag far from the edited shape, over another layer, marquees its points; a click + // there still leaves edit mode and selects that layer. + let mut s = Session::new(); + let bg = id_of(&ex(&mut s, "shape.rectangle", json!({"x": -500, "y": -500, "width": 1000, "height": 1000}))["id"]).unwrap(); + let id = square(&mut s, true); + let (tl, tr) = (point_at(&s, id, (0.0, 0.0)), point_at(&s, id, (100.0, 0.0))); + let bg_x = |s: &Session| s.doc().unwrap().world_transform(bg).translation().x; + drag(&mut s, (-200.0, -200.0), (110.0, 10.0), NONE); + let mut got = editing(&s).expect("a drag away from the shape stays in edit mode").vertices; + got.sort_unstable(); + let mut want = vec![tl, tr]; + want.sort_unstable(); + assert_eq!(got, want, "the marquee selects the points inside it"); + assert_eq!(bg_x(&s), -500.0, "the layer under the drag stays put"); + click(&mut s, (-200.0, -200.0), NONE); + assert!(editing(&s).is_none(), "a click away from the shape leaves edit mode"); + assert_eq!(s.selection(), vec![bg], "the click selects the layer under it"); +} + #[test] fn deleting_points_vs_delete_and_heal() { // (key, Shift, points, segments, closed afterwards, derivation) From 374ebdb0b91df3989dbc953ad55d4fbcf15d10a3 Mon Sep 17 00:00:00 2001 From: AganzeFelicite Date: Thu, 29 Oct 2026 11:24:30 +0200 Subject: [PATCH 3/7] docs: record the vector edit marquee fix (#1508) --- ROADMAP.md | 1 + docs/roadmap.md | 1 + 2 files changed, 2 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 69d3bf731..3f709e548 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -329,6 +329,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | A marquee from anywhere in vector edit mode (#1508): a press more than a few pixels from the edited shape used to leave edit mode at once, so a drag over another layer moved that layer; it now draws a marquee that selects the points inside it. A click there still leaves edit mode and selects what it lands on. Numbers unchanged | | 2026-10-24 | minor | Dev Mode tail (M6, gap 16): Measurements kept on the canvas (gap 16): `devMode.addMeasurement {from?, to?, side?}` places one between two layers, along one side of a layer or (neither) to the layer around it, stored on the layer it starts from (saved in `.figcraft`, synced, undoable; old files open without them); Dev Mode draws them as labelled redlines that follow the layers, the Inspect tab lists them (those of the selected layer, or every one on the page), places and removes them; `devMode.removeMeasurement` and `devMode.measurements` remove and list them; a copy keeps those to layers copied with it. The layers panel is read-only in Dev Mode: rows select and expand, but don't rename, reorder, hide or lock. Dev Mode 97% → 98% breadth, 76% → 78% ready, 2–4 h → 1–2 h; headline numbers unchanged at this rounding | | 2026-10-24 | minor | Boards (M12): a file kind of its own (`file.newBoard`, saved in `.figcraft`, carried to live-session joiners) with sticky notes, shapes with text, connectors that re-route when what they join moves (an engine recompute, the same for local edits, undo and others' edits), marker, highlighter and eraser, stamps with the placer's name, a board toolbar and a contextual bar; prototyping and Dev Mode refuse on boards; design files and boards have their own marks on tabs and file rows. Boards row added outside the weighted numbers; headline numbers unchanged at this rounding | | 2026-10-15 | minor | Auto-save (#305, #296): Preferences ▸ Save files automatically (`pref.autoSave`, off by default; desktop only, the browser has no files to save to) saves each open file that has a path 3 s after its last change, so steady editing doesn't save every few seconds, and never during a gesture, a live text preview or while a version is shown. The file is encoded on a thread of its own and written as of that moment (edits made meanwhile stay unsaved); a failed save says why in a toast and is tried again a minute later, and version history checkpoints keep coming with it on. Numbers unchanged | diff --git a/docs/roadmap.md b/docs/roadmap.md index 8e093ac93..29608c3f6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -75,6 +75,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | A marquee from anywhere in vector edit mode (#1508): a press more than a few pixels from the edited shape used to leave edit mode at once, so a drag over another layer moved that layer; it now draws a marquee that selects the points inside it. A click there still leaves edit mode and selects what it lands on. Numbers unchanged | | 2026-10-24 | minor | Boards (M12): a file kind of its own (`file.newBoard`, saved in `.figcraft`, carried to live-session joiners) with sticky notes, shapes with text, connectors that re-route when what they join moves (an engine recompute, the same for local edits, undo and others' edits), marker, highlighter and eraser, stamps with the placer's name, a board toolbar and a contextual bar; prototyping and Dev Mode refuse on boards; design files and boards have their own marks on tabs and file rows. Milestone M12 Boards added; AI features move to M13 | | 2026-10-15 | minor | Auto-save (#305, #296): Preferences ▸ Save files automatically (`pref.autoSave`, off by default; desktop only, the browser has no files to save to) saves each open file that has a path 3 s after its last change, so steady editing doesn't save every few seconds, and never during a gesture, a live text preview or while a version is shown. The file is encoded on a thread of its own and written as of that moment (edits made meanwhile stay unsaved); a failed save says why in a toast and is tried again a minute later, and version history checkpoints keep coming with it on. Numbers unchanged | | 2026-10-15 | minor | A text box by dragging (#363, #360): a drag with the Text tool makes a fixed-size text box the size of the drag (at least one line tall); a click, or a drag shorter than the drag threshold, still makes auto-width text. Numbers unchanged | From 2d507d959dbf363e4b753736b3a99a6c73f3f277 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 14:44:18 +0000 Subject: [PATCH 4/7] M12: board grid settings: dots, lines, graph paper or none The board canvas's background grid is now a preference (`board.grid`): dots (the default), lines, graph paper (a strong line every 2-12 cells over fainter ones, like Japanese section paper) or none, with spacing (4-512), mark size and contrast. Preferences gets a Board grid section; right-clicking an empty board offers Board grid settings. Zoomed out the grid still thins out (by halves, or down to graph paper's strong lines), and dots no longer shrink to a single pixel, so the grid stays visible at low zoom. The renderer draws lines as well as dots, with a configurable strong-mark rhythm; a crossing of two lines is blended once, in the stronger colour. A hand-edited preferences file falls back to the default grid instead of losing the other preferences. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FEkCVd8n1eC6xTHebmHMDR --- crates/engine/src/board_grid_tests.rs | 45 ++++++++ crates/engine/src/boards.rs | 1 + crates/engine/src/boards/board_grid.rs | 138 +++++++++++++++++++++++++ crates/engine/src/cmd.rs | 1 + crates/engine/src/lib.rs | 3 + crates/engine/src/prefs.rs | 4 + crates/render/src/dots.rs | 118 ++++++++++++++++++--- crates/render/src/dots_tests.rs | 50 ++++++++- crates/ui-egui/locales/en.toml | 5 + crates/ui-egui/src/board_ui_tests.rs | 39 ++++++- crates/ui-egui/src/canvas/board_bar.rs | 118 +++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/menus.rs | 4 + docs/boards-parity.md | 5 +- 14 files changed, 492 insertions(+), 41 deletions(-) create mode 100644 crates/engine/src/board_grid_tests.rs create mode 100644 crates/engine/src/boards/board_grid.rs diff --git a/crates/engine/src/board_grid_tests.rs b/crates/engine/src/board_grid_tests.rs new file mode 100644 index 000000000..ead747d04 --- /dev/null +++ b/crates/engine/src/board_grid_tests.rs @@ -0,0 +1,45 @@ +//! The board grid's settings: kept with the preferences, every value held within its range, and a +//! settings file edited by hand never costing the other preferences. + +use serde_json::json; + +use crate::board_grid::{BoardGrid, GridStyle}; +use crate::{Prefs, Session}; + +#[test] +fn board_grid_sets_and_reads_back_the_preferences() { + let mut s = Session::new(); + let r = s.execute("board.grid", &json!({})).unwrap(); + assert_eq!(r, json!({"style": "dots", "spacing": 24.0, "major": 5, "size": 1.0, "contrast": 1.0})); + let r = s.execute("board.grid", &json!({"style": "graph", "spacing": 8, "major": 10, "contrast": 2.5})).unwrap(); + assert_eq!(r["style"], "graph"); + assert_eq!(s.prefs.board_grid, BoardGrid { style: GridStyle::Graph, spacing: 8.0, major: 10, size: 1.0, contrast: 2.5 }); + // Out of range: the nearest end. + let r = s.execute("board.grid", &json!({"spacing": 1e9, "major": 1, "size": 0, "contrast": 99})).unwrap(); + assert_eq!(r, json!({"style": "graph", "spacing": 512.0, "major": 2, "size": 0.5, "contrast": 4.0})); + // Refused, and nothing changes. + let before = s.prefs.board_grid.clone(); + for p in [json!({"style": "hexagons"}), json!({"style": 3}), json!({"spacing": "wide"}), json!({"contrast": [1]})] { + assert!(s.execute("board.grid", &p).is_err(), "{p}"); + } + assert_eq!(s.prefs.board_grid, before); + // Off, then back to the default. + assert_eq!(s.execute("board.grid", &json!({"style": "None"})).unwrap()["style"], "none"); + s.execute("board.grid", &json!({"reset": true})).unwrap(); + assert_eq!(s.prefs.board_grid, BoardGrid::default()); +} + +#[test] +fn a_saved_board_grid_survives_hand_edits() { + let p = Prefs { board_grid: BoardGrid { style: GridStyle::Lines, spacing: 32.0, major: 4, size: 2.0, contrast: 1.5 }, ..Prefs::default() }; + let back: Prefs = serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap(); + assert_eq!(back.board_grid, p.board_grid); + // Unreadable: the default grid, and the other preferences stay. + let back: Prefs = serde_json::from_value(json!({"nudge_small": 3.0, "board_grid": {"style": "zigzag"}})).unwrap(); + assert_eq!((back.nudge_small, back.board_grid), (3.0, BoardGrid::default())); + let back: Prefs = serde_json::from_value(json!({"board_grid": "dots"})).unwrap(); + assert_eq!(back.board_grid, BoardGrid::default()); + // Out of range: clamped; missing fields: their defaults. + let back: Prefs = serde_json::from_value(json!({"board_grid": {"style": "graph", "spacing": -5, "major": 400}})).unwrap(); + assert_eq!(back.board_grid, BoardGrid { style: GridStyle::Graph, spacing: 4.0, major: 12, ..BoardGrid::default() }); +} diff --git a/crates/engine/src/boards.rs b/crates/engine/src/boards.rs index 685c1d70b..9c95fb328 100644 --- a/crates/engine/src/boards.rs +++ b/crates/engine/src/boards.rs @@ -1,3 +1,4 @@ pub mod board; +pub mod board_grid; pub mod board_table; pub mod board_templates; diff --git a/crates/engine/src/boards/board_grid.rs b/crates/engine/src/boards/board_grid.rs new file mode 100644 index 000000000..4061e202f --- /dev/null +++ b/crates/engine/src/boards/board_grid.rs @@ -0,0 +1,138 @@ +//! The board canvas's background grid, kept with the preferences: dots (the default), lines, or +//! graph paper (a strong line every few cells over fainter ones, like Japanese 方眼紙 section +//! paper), how far apart, how large and how strong its marks are, or no grid at all. The canvas +//! thins it out as it zooms out, so it never turns into a wash of marks. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::cmd::CommandSpec; +use crate::params::{boolean, get, num}; +use crate::{Result, Session, bad, spec}; + +/// What the grid draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum GridStyle { + #[default] + Dots, + Lines, + /// Lines with every `major`th one strong (section paper). + Graph, + None, +} + +impl GridStyle { + pub const ALL: [GridStyle; 4] = [GridStyle::Dots, GridStyle::Lines, GridStyle::Graph, GridStyle::None]; + + pub fn id(self) -> &'static str { + match self { + GridStyle::Dots => "dots", + GridStyle::Lines => "lines", + GridStyle::Graph => "graph", + GridStyle::None => "none", + } + } + + pub fn from_id(id: &str) -> Option { + GridStyle::ALL.into_iter().find(|s| s.id().eq_ignore_ascii_case(id.trim())) + } +} + +/// The spacing's range (page units between neighbouring marks at 100 %). +pub const SPACING: (f64, f64) = (4.0, 512.0); +/// Graph paper's cells per strong line. +pub const MAJOR: (u32, u32) = (2, 12); +/// The marks' size and strength, relative to the usual (1). +pub const SIZE: (f64, f64) = (0.5, 4.0); +pub const CONTRAST: (f64, f64) = (0.25, 4.0); + +/// The board grid's settings. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BoardGrid { + pub style: GridStyle, + /// Page units between neighbouring marks at 100 % (zoomed out, every second, fourth… stays). + pub spacing: f64, + /// Graph paper: a strong line every `major` cells. + pub major: u32, + /// How large the marks are: 1 is about a point and a half across for dots, a point for lines. + pub size: f64, + /// How strong the marks are against the page: 1 is the usual, subtle grid. + pub contrast: f64, +} + +impl Default for BoardGrid { + fn default() -> Self { + Self { style: GridStyle::Dots, spacing: 24.0, major: 5, size: 1.0, contrast: 1.0 } + } +} + +/// `v` kept within `range`; `d` when it is not a finite number. +fn within(v: f64, (lo, hi): (f64, f64), d: f64) -> f64 { + if v.is_finite() { v.clamp(lo, hi) } else { d } +} + +impl BoardGrid { + /// Every value back within its range (a settings file edited by hand). + pub fn sanitized(mut self) -> Self { + let d = Self::default(); + self.spacing = within(self.spacing, SPACING, d.spacing); + self.major = self.major.clamp(MAJOR.0, MAJOR.1); + self.size = within(self.size, SIZE, d.size); + self.contrast = within(self.contrast, CONTRAST, d.contrast); + self + } + + pub fn to_json(&self) -> Value { + json!({"style": self.style.id(), "spacing": self.spacing, "major": self.major, "size": self.size, "contrast": self.contrast}) + } +} + +/// Reads the saved grid: anything unreadable is the default grid and values out of range are +/// clamped, so a settings file edited by hand never costs the other preferences. +pub(crate) fn read<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + Ok(serde_json::from_value::(Value::deserialize(d)?).unwrap_or_default().sanitized()) +} + +const CMD: &str = "board.grid"; + +/// A number param of `board.grid`: `None` when omitted, an error when not a finite number. +fn number(p: &Value, key: &str) -> Result> { + match get(p, key) { + None | Some(Value::Null) => Ok(None), + Some(_) => num(p, key).filter(|v| v.is_finite()).map(Some).ok_or_else(|| bad(CMD, format!("`{key}` must be a number"))), + } +} + +fn grid_cmd(s: &mut Session, p: &Value) -> Result { + let mut g = if boolean(p, "reset") == Some(true) { BoardGrid::default() } else { s.prefs.board_grid.clone() }; + if let Some(v) = get(p, "style").filter(|v| !v.is_null()) { + let id = v.as_str().unwrap_or_default(); + g.style = GridStyle::from_id(id).ok_or_else(|| bad(CMD, "`style` is dots, lines, graph or none"))?; + } + if let Some(v) = number(p, "spacing")? { + g.spacing = v; + } + if let Some(v) = number(p, "major")? { + g.major = v.round().clamp(f64::from(MAJOR.0), f64::from(MAJOR.1)) as u32; + } + if let Some(v) = number(p, "size")? { + g.size = v; + } + if let Some(v) = number(p, "contrast")? { + g.contrast = v; + } + s.prefs.board_grid = g.sanitized(); + Ok(s.prefs.board_grid.to_json()) +} + +pub fn specs() -> Vec { + vec![spec!( + "board.grid", + "Board grid", + "{style?: dots|lines|graph|none (graph: section paper, a strong line every `major` cells), spacing? (4–512 page units at 100 %), major? (2–12), size? (0.5–4, 1 the usual), contrast? (0.25–4, 1 the usual), reset? (back to the default first); omit all: just read it} → {style, spacing, major, size, contrast} the board canvas's background grid, kept with the preferences; zoomed out it thins out", + false, + grid_cmd + )] +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c046cd19f..f6584d9e7 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -117,6 +117,7 @@ fn registry() -> &'static Registry { list.extend(crate::textfit::specs()); list.extend(crate::board::specs()); list.extend(facilitate::specs()); + list.extend(crate::board_grid::specs()); list.extend(crate::board_table::specs()); list.extend(crate::board_templates::specs()); let mut index = HashMap::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 872f3cd3f..f6305cf83 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -39,6 +39,7 @@ pub use automation::file_access; pub use automation::inspect; pub use automation::params; pub use boards::board; +pub use boards::board_grid; pub use boards::board_table; pub use boards::board_templates; pub use canvas::al_keys; @@ -193,6 +194,8 @@ mod binding_lists_tests; #[cfg(test)] mod board_connector_tests; #[cfg(test)] +mod board_grid_tests; +#[cfg(test)] mod board_tables_tests; #[cfg(test)] mod board_tests; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 74913df65..89668a1a7 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -99,6 +99,9 @@ pub struct Prefs { /// files opened or made later start with them. Missing: the toggle's default. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub view: BTreeMap, + /// The board canvas's background grid (`board.grid`). + #[serde(deserialize_with = "crate::board_grid::read")] + pub board_grid: crate::board_grid::BoardGrid, /// Recently run actions (the Actions palette's Recents), newest first, at most /// [`MAX_RECENT_ACTIONS`]. Entries are `command:`, `plugin:/` or /// `widget:`. @@ -141,6 +144,7 @@ impl Default for Prefs { home_sort: "modified".into(), home_order: "desc".into(), view: BTreeMap::new(), + board_grid: Default::default(), recent_actions: Vec::new(), } } diff --git a/crates/render/src/dots.rs b/crates/render/src/dots.rs index 980ea85a5..b13cbdd57 100644 --- a/crates/render/src/dots.rs +++ b/crates/render/src/dots.rs @@ -1,22 +1,27 @@ -//! A dot grid on the page, under its layers (the board canvas): square dots on the device-pixel -//! grid, blended into the image right after the page colour so the layers cover them. Each dot's -//! pixels are computed from its page position alone, so bands and partial renders line up. Nothing -//! is allocated per dot. +//! A grid on the page, under its layers (the board canvas): square dots or lines on the +//! device-pixel grid, blended into the image right after the page colour so the layers cover them. +//! Each mark's pixels are computed from its page position alone, so bands and partial renders line +//! up. Nothing is allocated per mark. use figcraft_color::Color; use tiny_skia::Pixmap; use crate::View; -/// Dots every `step` page units from the page origin, `size` page units square (from one to 64 -/// device pixels): those on every second line both ways in `color`, the others (the ones a grid -/// twice as coarse leaves out) in `faded`. +/// Dots (or lines both ways) every `step` page units from the page origin, `size` page units +/// across (from one to 64 device pixels): those on every `major`th line both ways (every line of +/// the `major`th, for lines) in `color`, the others (the ones a grid `major` times as coarse leaves +/// out) in `faded`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Dots { pub step: f64, pub size: f64, pub color: Color, pub faded: Color, + /// Lines instead of dots. + pub lines: bool, + /// Every how many steps a mark is strong (2 or more; less reads as 2). + pub major: u32, } /// The most dots one render draws: a step far too small for the view draws none. @@ -43,31 +48,99 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { if !(count.is_finite() && count <= MAX_DOTS) { return; } - // Each dot on the device pixel nearest its point, from the view's top-left in device pixels. + // Each mark on the device pixel nearest its point, from the view's top-left in device pixels. let (ox, oy) = (x0 * s, y0 * s); let side = ((d.size * s).round() as i64).clamp(1, 64); let lead = side / 2; - let (strong, faded) = (premultiplied(d.color), premultiplied(d.faded)); + let colors = [premultiplied(d.faded), premultiplied(d.color)]; + let major = i64::from(d.major.max(2)); + let strong = |k: i64| k.rem_euclid(major) == 0; + // The device-pixel span of the mark on line `k` along an axis `len` pixels long from `o`. + let span = |k: i64, o: f64, len: i64| { + let a = ((k as f64 * d.step * s - o).round() as i64).saturating_sub(lead); + (a.max(0), a.saturating_add(side).min(len)) + }; let row = w as usize * 4; let data = pix.data_mut(); + if d.lines { + lines( + data, + row, + (w, h), + [(i0 as i64, i1 as i64), (j0 as i64, j1 as i64)], + &|k, vertical| { + let (o, len) = if vertical { (ox, w) } else { (oy, h) }; + (span(k, o, len), strong(k)) + }, + colors, + ); + return; + } for j in j0 as i64..=j1 as i64 { - let top = ((j as f64 * d.step * s - oy).round() as i64).saturating_sub(lead); - let (ya, yb) = (top.max(0), top.saturating_add(side).min(h)); + let (ya, yb) = span(j, oy, h); if ya >= yb { continue; } for i in i0 as i64..=i1 as i64 { - let left = ((i as f64 * d.step * s - ox).round() as i64).saturating_sub(lead); - let (xa, xb) = (left.max(0), left.saturating_add(side).min(w)); + let (xa, xb) = span(i, ox, w); if xa >= xb { continue; } - let rgba = if i % 2 == 0 && j % 2 == 0 { strong } else { faded }; + let rgba = colors[usize::from(strong(i) && strong(j))]; blend_square(data, row, (xa, xb), (ya, yb), rgba); } } } +/// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one. +type Cover = Vec; + +/// Draw lines both ways: the vertical ones `ks[0]`, the horizontal ones `ks[1]`, each line's span +/// and strength from `mark(k, vertical)`. A crossing is blended once, in the stronger colour. +fn lines( + data: &mut [u8], + row: usize, + (w, h): (i64, i64), + ks: [(i64, i64); 2], + mark: &dyn Fn(i64, bool) -> ((i64, i64), bool), + colors: [[u32; 4]; 2], +) { + let cover = |(k0, k1): (i64, i64), vertical: bool, len: i64| { + let mut c: Cover = vec![0; len.max(0) as usize]; + for k in k0..=k1 { + let ((a, b), strong) = mark(k, vertical); + for v in c.get_mut(a.max(0) as usize..b.max(a).max(0) as usize).into_iter().flatten() { + *v = (*v).max(1 + u8::from(strong)); + } + } + c + }; + let (cols, rows) = (cover(ks[0], true, w), cover(ks[1], false, h)); + // The columns' runs, so a row without a line only visits the vertical lines. + let mut runs: Vec<(usize, usize, u8)> = Vec::new(); + for (x, &c) in cols.iter().enumerate() { + match runs.last_mut() { + Some(r) if r.1 == x && r.2 == c => r.1 = x + 1, + _ if c > 0 => runs.push((x, x + 1, c)), + _ => {} + } + } + for (y, &rc) in rows.iter().enumerate() { + let start = y * row; + if rc == 0 { + for &(a, b, c) in &runs { + let rgba = colors[usize::from(c.saturating_sub(1).min(1))]; + blend_square(data, row, (a as i64, b as i64), (y as i64, y as i64 + 1), rgba); + } + continue; + } + let Some(line) = data.get_mut(start..start + w as usize * 4) else { continue }; + for (px, &cc) in line.chunks_exact_mut(4).zip(&cols) { + blend_px(px, colors[usize::from(rc.max(cc).saturating_sub(1).min(1))]); + } + } +} + /// Blend premultiplied `rgba` source-over into the pixels `xs` × `ys` of `data`, rows `row` bytes /// long. fn blend_square(data: &mut [u8], row: usize, (xa, xb): (i64, i64), (ya, yb): (i64, i64), rgba: [u32; 4]) { @@ -79,9 +152,20 @@ fn blend_square(data: &mut [u8], row: usize, (xa, xb): (i64, i64), (ya, yb): (i6 let start = y as usize * row; let Some(line) = data.get_mut(start + xa as usize * 4..start + xb as usize * 4) else { continue }; for px in line.chunks_exact_mut(4) { - for (dst, src) in px.iter_mut().zip(rgba) { - *dst = (src + u32::from(*dst) * keep / 255).min(255) as u8; - } + blend_with(px, rgba, keep); } } } + +/// Blend premultiplied `rgba` source-over into the pixel `px`. +fn blend_px(px: &mut [u8], rgba: [u32; 4]) { + if rgba[3] > 0 { + blend_with(px, rgba, 255 - rgba[3]); + } +} + +fn blend_with(px: &mut [u8], rgba: [u32; 4], keep: u32) { + for (dst, src) in px.iter_mut().zip(rgba) { + *dst = (src + u32::from(*dst) * keep / 255).min(255) as u8; + } +} diff --git a/crates/render/src/dots_tests.rs b/crates/render/src/dots_tests.rs index 3adcbeab8..53d052062 100644 --- a/crates/render/src/dots_tests.rs +++ b/crates/render/src/dots_tests.rs @@ -10,7 +10,7 @@ use figcraft_doc::{Document, NodeKind}; use crate::{Dots, Options, Retained, View, render_view, render_view_single}; fn dots() -> Dots { - Dots { step: 24.0, size: 2.0, color: Color::new(0.0, 0.0, 0.0, 0.5), faded: Color::new(0.0, 0.0, 0.0, 0.25) } + Dots { step: 24.0, size: 2.0, color: Color::new(0.0, 0.0, 0.0, 0.5), faded: Color::new(0.0, 0.0, 0.0, 0.25), lines: false, major: 2 } } fn page_with_square() -> (Document, figcraft_doc::NodeId) { @@ -85,4 +85,52 @@ fn dots_it_cant_draw_draw_nothing() { } let far = View { origin: (f64::MAX / 2.0, -f64::MAX / 2.0), scale: 1e10, width: 16, height: 16 }; let _ = render_view_single(&d, page, &far, &Options { dots: Some(dots()), ..Default::default() }); + for major in [0, 1, u32::MAX] { + for lines in [false, true] { + let opts = Options { dots: Some(Dots { major, lines, ..dots() }), ..Default::default() }; + let _ = render_view_single(&d, page, &view, &opts); + let _ = render_view_single(&d, page, &far, &opts); + } + } +} + +#[test] +fn lines_run_both_ways_with_crossings_blended_once() { + let (d, page) = page_with_square(); + let view = View { origin: (0.0, 0.0), scale: 1.0, width: 200, height: 200 }; + let lines = Dots { lines: true, size: 1.0, ..dots() }; + let pix = render_view_single(&d, page, &view, &Options { dots: Some(lines), ..Default::default() }).unwrap(); + let plain = render_view_single(&d, page, &view, &Options::default()).unwrap(); + // Line 0 is strong, line 1 (at 24) faded, line 2 (at 48) strong again; between them, the page. + let (strong, faded, empty) = (rgba(&pix, 0, 12), rgba(&pix, 24, 12), rgba(&pix, 12, 12)); + assert_eq!(empty, rgba(&plain, 12, 12)); + assert!(strong[0] < faded[0] && faded[0] < empty[0], "{strong:?} {faded:?} {empty:?}"); + assert_eq!(rgba(&pix, 12, 0), strong, "a horizontal line as strong as a vertical one"); + // A crossing is no darker than the stronger of its lines. + assert_eq!(rgba(&pix, 0, 0), strong); + assert_eq!(rgba(&pix, 24, 0), strong, "a faded line crossing a strong one"); + assert_eq!(rgba(&pix, 24, 24), faded); + // The square covers the lines under it. + assert_eq!(rgba(&pix, 72, 72), rgba(&plain, 72, 72)); + // Banded or not, the same pixels. + let wide = View { origin: (-212.0, -140.0), scale: 1.5, width: 900, height: 700 }; + let opts = Options { dots: Some(lines), ..Default::default() }; + assert_eq!(render_view_single(&d, page, &wide, &opts).unwrap().data(), render_view(&d, page, &wide, &opts).unwrap().data()); +} + +#[test] +fn graph_paper_is_strong_every_major_line() { + let (d, page) = page_with_square(); + let view = View { origin: (-200.0, -200.0), scale: 1.0, width: 160, height: 160 }; + let graph = Dots { lines: true, size: 1.0, major: 5, step: 10.0, ..dots() }; + let pix = render_view_single(&d, page, &view, &Options { dots: Some(graph), ..Default::default() }).unwrap(); + let at = |x: i32, y: i32| rgba(&pix, (x + 200) as u32, (y + 200) as u32); + let strong = at(-150, -195); + for x in [-190, -180, -170, -160, -140, -130, -120, -110] { + assert_ne!(at(x, -195), strong, "a faded line at {x}"); + assert_eq!(at(x, -195), at(-190, -195)); + } + for x in [-200, -100, -50] { + assert_eq!(at(x, -195), strong, "a strong line at {x}"); + } } diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 3450db8e8..2f22e76c8 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -183,6 +183,8 @@ name = "English" "Blend mode" = "Blend mode" "Blue" = "Blue" "Blur" = "Blur" +"Board grid" = "Board grid" +"Board grid settings…" = "Board grid settings…" "Boolean" = "Boolean" "Boolean groups" = "Boolean groups" "Both directions" = "Both directions" @@ -613,6 +615,7 @@ name = "English" "Go to {name}" = "Go to {name}" "Grab bag" = "Grab bag" "Gradient" = "Gradient" +"Graph paper" = "Graph paper" "Gray" = "Gray" "Green" = "Green" "Greyscale components and two example screens to sketch a flow with" = "Greyscale components and two example screens to sketch a flow with" @@ -1198,6 +1201,7 @@ name = "English" "Reset adjustments" = "Reset adjustments" "Reset all changes" = "Reset all changes" "Reset all overrides on this layer" = "Reset all overrides on this layer" +"Reset grid" = "Reset grid" "Reset overrides" = "Reset overrides" "Reset slot" = "Reset slot" "Reset this override" = "Reset this override" @@ -1425,6 +1429,7 @@ name = "English" "Stroke style" = "Stroke style" "Stroke weight" = "Stroke weight" "Strokes" = "Strokes" +"Strong line every" = "Strong line every" "Style" = "Style" "Styles" = "Styles" "Stylistic set 1" = "Stylistic set 1" diff --git a/crates/ui-egui/src/board_ui_tests.rs b/crates/ui-egui/src/board_ui_tests.rs index e4758ca79..f1216d77d 100644 --- a/crates/ui-egui/src/board_ui_tests.rs +++ b/crates/ui-egui/src/board_ui_tests.rs @@ -242,7 +242,7 @@ fn a_board_page_has_a_dot_grid_under_its_layers_thinned_out_zoomed_out() { let fill = u.app.session.doc().unwrap().node(sticky).unwrap().fills[0].solid_color().unwrap().to_rgba8(); assert_eq!(at(2.0 * step, 2.0 * step), [fill[0], fill[1], fill[2]], "the sticky covers the dot under it"); // Zoomed out, the dots space out: every second, fourth… stays, the next to go fading. - use crate::board_bar::dot_spacing; + let dot_spacing = |z: f64| crate::board_bar::grid_spacing(z, 24.0, 2, 14.0); assert_eq!(dot_spacing(1.0), Some((24.0, ((24.0 - 14.0) / 14.0) as f32))); assert_eq!(dot_spacing(0.25).map(|d| d.0), Some(96.0)); assert_eq!(dot_spacing(4.0), Some((24.0, 1.0))); @@ -271,3 +271,40 @@ fn a_selected_connector_shows_its_ends_as_handles() { assert!(ring, "a handle at {end:?}"); } } + +#[test] +fn the_board_grid_follows_its_settings() { + let mut u = board(); + u.app.session.execute("view.zoom100", &json!({})).unwrap(); + u.frame(vec![]); + let t = crate::theme::Tokens::get(&u.ctx); + let bg = egui::Color32::from_rgb(240, 240, 240); + let usual = crate::board_bar::dots(&u.app, bg, &t).unwrap(); + assert!(!usual.lines && usual.major == 2); + // Lines, as fine at any zoom. + u.app.run("board.grid", json!({"style": "lines"})); + let lines = crate::board_bar::dots(&u.app, bg, &t).unwrap(); + assert!(lines.lines && lines.major == 2 && lines.color.a < usual.color.a, "lines start fainter than dots"); + // Graph paper: a strong line every 5 cells of 8, the cells in between fainter even zoomed in. + u.app.run("board.grid", json!({"style": "graph", "spacing": 8, "major": 5})); + u.app.session.ds_mut().unwrap().view.zoom = 4.0; + let graph = crate::board_bar::dots(&u.app, bg, &t).unwrap(); + assert_eq!((graph.lines, graph.major, graph.step), (true, 5, 8.0)); + assert!(graph.faded.a < graph.color.a); + // Zoomed out, the fine cells go and the strong lines stay: the step grows by fives. + u.app.session.ds_mut().unwrap().view.zoom = 0.25; + let far = crate::board_bar::dots(&u.app, bg, &t).unwrap(); + assert_eq!(far.step, 8.0 * 5.0, "40 × 0.25 = 10 points apart, the closest lines come"); + assert_eq!(far.faded.a, 0.0, "the cells the next step drops have faded out"); + // More contrast: stronger marks; larger: larger. + u.app.run("board.grid", json!({"style": "dots", "contrast": 3, "size": 2})); + let strong = crate::board_bar::dots(&u.app, bg, &t).unwrap(); + assert!(strong.color.a > usual.color.a * 2.5 && strong.size > usual.size * 0.25 * 1.5, "{strong:?}"); + // None: no grid. + u.app.run("board.grid", json!({"style": "none"})); + assert!(crate::board_bar::dots(&u.app, bg, &t).is_none()); + use crate::board_bar::grid_spacing; + assert_eq!(grid_spacing(1.0, 24.0, 5, 0.0), None); + assert_eq!(grid_spacing(1e-320, 512.0, 2, 14.0), None, "no finite step that far out"); + assert!(grid_spacing(1e-300, 4.0, 12, 10.0).is_some_and(|(step, _)| step.is_finite())); +} diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index c1a76a4de..f7add740b 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use figcraft_doc::{BOARD_COLORS, BoardItem, BoardShape, NodeKind, Routing, Stamp, StrokeCap}; use figcraft_engine::board::{BoardTool, TEXT_SIZES}; +use figcraft_engine::board_grid::GridStyle; use serde_json::{Value, json}; use crate::FigApp; @@ -287,46 +288,123 @@ pub(crate) fn divider(ui: &Ui, t: &Tokens, x: f32, cy: f32) -> f32 { x + 8.0 } -/// The dot grid's spacing on the page at 100%, and the closest its dots come on screen (points): -/// zoomed out, every second, fourth… dot stays, the ones going fading out first. -const DOT_STEP: f64 = 24.0; +/// The closest the grid's marks come on screen (points): zoomed out, every second, fourth… mark +/// stays (graph paper: every strong line), the ones going fading out first. Lines read at a +/// smaller gap than dots. const DOT_MIN_GAP: f64 = 14.0; +const LINE_MIN_GAP: f64 = 10.0; -/// A board page's dot grid on its background `bg`, for the canvas render to draw under the -/// layers: dark dots on a light page, light ones on a dark page, in the theme's ink, about a point -/// and a half across on screen. `None` on design files. +/// A board page's grid on its background `bg` as the preferences set it (`board.grid`), for the +/// canvas render to draw under the layers: dark marks on a light page, light ones on a dark page, +/// in the theme's ink. `None` on design files and with the grid off. pub fn dots(app: &FigApp, bg: Color32, t: &Tokens) -> Option { let ds = app.session.ds().ok()?; if !figcraft_engine::board::is_board(&ds.doc) { return None; } + let g = app.session.prefs.board_grid.clone().sanitized(); + let lines = match g.style { + GridStyle::None => return None, + GridStyle::Dots => false, + GridStyle::Lines | GridStyle::Graph => true, + }; + // Dots and plain lines thin out by halves; graph paper keeps its strong lines. + let major = if g.style == GridStyle::Graph { g.major } else { 2 }; let zoom = ds.view.zoom; - let (step, fade) = dot_spacing(zoom)?; + let min_gap = if lines { LINE_MIN_GAP } else { DOT_MIN_GAP }; + let (step, fade) = grid_spacing(zoom, g.spacing, major, min_gap)?; let dark_page = 0.2126 * f32::from(bg.r()) + 0.7152 * f32::from(bg.g()) + 0.0722 * f32::from(bg.b()) < 128.0; let ink = if dark_page == t.dark { t.text } else { t.bg }; - let alpha = if dark_page { 0.22 } else { 0.18 }; + // Lines cover more of the page than dots, so they start fainter. + let base = if dark_page { 0.22 } else { 0.18 } * if lines { 0.6 } else { 1.0 }; + let alpha = (base * g.contrast as f32).clamp(0.0, 1.0); + // Graph paper's in-between lines stay fainter than its strong ones even zoomed in. + let faded = alpha * fade * if g.style == GridStyle::Graph { 0.5 } else { 1.0 }; let color = |a: f32| figcraft_color::Color::from_rgba8(ink.r(), ink.g(), ink.b(), (a * 255.0).round() as u8); - let size = (1.5 * zoom.sqrt()).clamp(1.0, 3.0) / zoom; - Some(figcraft_render::Dots { step, size, color: color(alpha), faded: color(alpha * fade) }) + // Dots grow a little zoomed in, and never shrink below their size at 100 % zoomed out (where + // a pixel-sized dot all but disappears). + let k = g.size; + let size = if lines { k.max(0.5) / zoom } else { (1.5 * k * zoom.max(1.0).sqrt()).min(3.0 * k.max(1.0)) / zoom }; + Some(figcraft_render::Dots { step, size, color: color(alpha), faded: color(faded), lines, major }) } -/// The dot grid's spacing on the page at `zoom` (doubled until the dots are far enough apart on -/// screen), and how strongly the dots the next doubling drops still show (0 to 1). -pub(crate) fn dot_spacing(zoom: f64) -> Option<(f64, f32)> { - if !(zoom.is_finite() && zoom > 0.0) { +/// The grid's spacing on the page at `zoom`, starting from `base` and multiplied by `major` until +/// the marks are at least `min_gap` apart on screen, and how strongly the marks the next step +/// drops still show (0 to 1). +pub(crate) fn grid_spacing(zoom: f64, base: f64, major: u32, min_gap: f64) -> Option<(f64, f32)> { + let ok = |v: f64| v.is_finite() && v > 0.0; + if !(ok(zoom) && ok(base) && ok(min_gap)) { return None; } - // Bounded: past about 1000 doublings the step is no longer finite, and there are no dots. - let mut step = DOT_STEP; + let factor = f64::from(major.max(2)); + // Bounded: past about 1000 multiplications the step is no longer finite, and there is no grid. + let mut step = base; for _ in 0..1100 { - if step * zoom >= DOT_MIN_GAP { + if step * zoom >= min_gap { break; } - step *= 2.0; + step *= factor; } let gap = step * zoom; - // From one to two minimum gaps apart, the in-between dots fade in. - (gap.is_finite() && gap >= DOT_MIN_GAP).then(|| (step, ((gap - DOT_MIN_GAP) / DOT_MIN_GAP).clamp(0.0, 1.0) as f32)) + // From one to two minimum gaps apart, the in-between marks fade in. + (gap.is_finite() && gap >= min_gap).then(|| (step, ((gap - min_gap) / min_gap).clamp(0.0, 1.0) as f32)) +} + +/// The Preferences dialog's board grid settings (`board.grid`): its style, then (with a grid) +/// how far apart, how large and how strong its marks are, and graph paper's cells per strong line. +pub(crate) fn grid_settings(app: &mut FigApp, ui: &mut Ui) { + let g = app.session.prefs.board_grid.clone().sanitized(); + let mut set = None; + ui.horizontal(|ui| { + ui.label(tr("Board grid")); + for style in GridStyle::ALL { + let label = match style { + GridStyle::Dots => tr("Dots"), + GridStyle::Lines => tr("Lines"), + GridStyle::Graph => tr("Graph paper"), + GridStyle::None => tr("None"), + }; + if ui.selectable_label(g.style == style, label).clicked() { + set = Some(json!({"style": style.id()})); + } + } + }); + if g.style != GridStyle::None { + ui.horizontal(|ui| { + let (mut spacing, mut major) = (g.spacing, g.major); + ui.label(tr("Spacing")); + let (lo, hi) = figcraft_engine::board_grid::SPACING; + if ui.add(egui::DragValue::new(&mut spacing).range(lo..=hi)).changed() { + set = Some(json!({"spacing": spacing})); + } + if g.style == GridStyle::Graph { + ui.label(tr("Strong line every")); + let (lo, hi) = figcraft_engine::board_grid::MAJOR; + if ui.add(egui::DragValue::new(&mut major).range(lo..=hi)).changed() { + set = Some(json!({"major": major})); + } + } + }); + ui.horizontal(|ui| { + let (mut size, mut contrast) = (g.size, g.contrast); + ui.label(tr("Size")); + let (lo, hi) = figcraft_engine::board_grid::SIZE; + if ui.add(egui::Slider::new(&mut size, lo..=hi).max_decimals(2)).changed() { + set = Some(json!({"size": size})); + } + ui.label(tr("Contrast")); + let (lo, hi) = figcraft_engine::board_grid::CONTRAST; + if ui.add(egui::Slider::new(&mut contrast, lo..=hi).max_decimals(2)).changed() { + set = Some(json!({"contrast": contrast})); + } + }); + if g != Default::default() && crate::widgets::button(ui, tr("Reset grid"), false, true).clicked() { + set = Some(json!({"reset": true})); + } + } + if let Some(p) = set { + app.run("board.grid", p); + } } /// The name of the person who placed the stamp under the pointer, beside it. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b3e1461ab..c6e5829f0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -300,6 +300,8 @@ pub fn show(app: &mut FigApp, ctx: &Context) { ui.add_space(8.0); interface_size(app, ui, prefs.ui_scale); ui.add_space(8.0); + crate::board_bar::grid_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.label(tr("Theme")); for (l, c) in [(tr_noop("Light"), "view.themeLight"), (tr_noop("Dark"), "view.themeDark"), (tr_noop("System"), "view.themeSystem")] { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 76f220f4f..f10283b3c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -554,6 +554,10 @@ pub fn popups(app: &mut FigApp, ctx: &egui::Context) { { entries[at] = (tr("Go to main component"), "component.goToMain"); } + // On a board, the background grid's settings (Preferences ▸ Board grid). + if !has_sel && app.session.doc().is_ok_and(figcraft_engine::board::is_board) { + entries.extend([("-", ""), (tr("Board grid settings…"), "app.preferences")]); + } // A right-clicked ruler guide (selected, with no layers) can be removed. if !has_sel && app.session.ds().is_ok_and(|d| d.selected_guide().is_some()) { entries.splice(0..0, [(tr("Remove guide"), "guide.remove"), ("-", "")]); diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 383a69337..82c32367a 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-29 · **Change:** minor (the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-29 · **Change:** minor (board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -56,13 +56,14 @@ all end with the same geometry. | Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | -| Dot grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it; 24 units apart, doubling when zoomed out until the dots are at least 14 points apart, the dots the next doubling drops fading out first; dark dots on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per dot; never in exports | +| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid, or right-click the board ▸ Board grid settings…). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots never shrink below their size at 100 %. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | | `.jam` import and export | missing | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | M12: board grid settings (`board.grid`): dots, lines, graph paper or none, with spacing, size and contrast, in Preferences and the board's right-click menu; zoomed-out dots no longer shrink to a pixel. Numbers unchanged (beyond the incumbent's behaviour) | | 2026-10-29 | minor | M12, #1387 (connector tool): while a connector is dragged out with the connector tool, the canvas shows the connector itself as it will be made (its straight, elbow or curved route, line, weight and arrowhead, built by the same code as `board.connector`), not a thin line; the object under the pointer is outlined with its four attach points (the middles of its sides), the one the end goes to ringed; within 10 px of one the end keeps that side (`fromSide`/`toSide`, and `side` when re-attaching). Hovering with the tool shows the attach points too. Escape drops the preview; releasing makes the connector in one undo step. Tests: `board_connector_tests`. Numbers unchanged | | 2026-10-24 | minor | M12: the dot grid on board pages (a render pass under the layers), dragging a selected connector's end onto another object or empty canvas (`board.reattach`), curved connectors, and elbows that go around the objects they join. Breadth ~35% → ~37%, ready ~20% → ~21%, ~30–60 h → ~28–56 h | | 2026-10-24 | minor | Facilitation (M12): a shared timer and voting sessions. Breadth ~35% → ~40%, ready ~20% → ~24%, ~30–60 h → ~26–54 h | From 59af2bc44a16b41b112f40a8831dc58e4185bdc6 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 30 Oct 2026 00:06:49 +0700 Subject: [PATCH 5/7] #1547: keep the default board dots' size, and test the Preferences grid section --- crates/ui-egui/src/board_ui_tests.rs | 29 ++++++++++++++++++++++++++ crates/ui-egui/src/canvas/board_bar.rs | 6 +++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/board_ui_tests.rs b/crates/ui-egui/src/board_ui_tests.rs index f1216d77d..7926dfd2d 100644 --- a/crates/ui-egui/src/board_ui_tests.rs +++ b/crates/ui-egui/src/board_ui_tests.rs @@ -308,3 +308,32 @@ fn the_board_grid_follows_its_settings() { assert_eq!(grid_spacing(1e-320, 512.0, 2, 14.0), None, "no finite step that far out"); assert!(grid_spacing(1e-300, 4.0, 12, 10.0).is_some_and(|(step, _)| step.is_finite())); } + +#[test] +fn preferences_set_the_board_grid_and_the_default_dots_keep_their_size() { + let mut u = board(); + let bg = egui::Color32::from_rgb(240, 240, 240); + // The default grid: dots a point and a half across at 100 %, one to three points on screen. + for (zoom, on_screen) in [(1.0, 1.5), (0.25, 1.0), (4.0, 3.0)] { + u.app.session.ds_mut().unwrap().view.zoom = zoom; + let t = crate::theme::Tokens::get(&u.ctx); + let size = crate::board_bar::dots(&u.app, bg, &t).unwrap().size; + assert!((size * zoom - on_screen).abs() < 1e-9, "at {zoom}: {size}"); + } + u.app.session.ds_mut().unwrap().view.zoom = 1.0; + u.app.ui.preferences = true; + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Board grid") && has_text(&shapes, "Spacing")); + assert!(!has_text(&shapes, "Strong line every") && !has_text(&shapes, "Reset grid"), "dots, as usual"); + click(&mut u, text_center(&shapes, "Graph paper")); + assert_eq!(u.app.session.prefs.board_grid.style, figcraft_engine::board_grid::GridStyle::Graph); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Strong line every"), "graph paper's cells per strong line"); + click(&mut u, text_center(&shapes, "Reset grid")); + assert_eq!(u.app.session.prefs.board_grid, Default::default()); + // No grid: nothing to set but the style. + u.app.run("board.grid", json!({"style": "none"})); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Board grid") && !has_text(&shapes, "Spacing")); +} diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index f7add740b..d7a03e0b5 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -321,10 +321,10 @@ pub fn dots(app: &FigApp, bg: Color32, t: &Tokens) -> Option Date: Fri, 30 Oct 2026 00:06:50 +0700 Subject: [PATCH 6/7] #1547: drop the board grid entry from the right-click menu --- crates/ui-egui/locales/en.toml | 1 - crates/ui-egui/src/menus.rs | 4 ---- docs/boards-parity.md | 4 ++-- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 2f22e76c8..cf5d0f97e 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -184,7 +184,6 @@ name = "English" "Blue" = "Blue" "Blur" = "Blur" "Board grid" = "Board grid" -"Board grid settings…" = "Board grid settings…" "Boolean" = "Boolean" "Boolean groups" = "Boolean groups" "Both directions" = "Both directions" diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index f10283b3c..76f220f4f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -554,10 +554,6 @@ pub fn popups(app: &mut FigApp, ctx: &egui::Context) { { entries[at] = (tr("Go to main component"), "component.goToMain"); } - // On a board, the background grid's settings (Preferences ▸ Board grid). - if !has_sel && app.session.doc().is_ok_and(figcraft_engine::board::is_board) { - entries.extend([("-", ""), (tr("Board grid settings…"), "app.preferences")]); - } // A right-clicked ruler guide (selected, with no layers) can be removed. if !has_sel && app.session.ds().is_ok_and(|d| d.selected_guide().is_some()) { entries.splice(0..0, [(tr("Remove guide"), "guide.remove"), ("-", "")]); diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 82c32367a..ff94b0a02 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -56,14 +56,14 @@ all end with the same geometry. | Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | -| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid, or right-click the board ▸ Board grid settings…). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots never shrink below their size at 100 %. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | +| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | | `.jam` import and export | missing | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history | Date | Change | Summary | |---|---|---| -| 2026-10-29 | minor | M12: board grid settings (`board.grid`): dots, lines, graph paper or none, with spacing, size and contrast, in Preferences and the board's right-click menu; zoomed-out dots no longer shrink to a pixel. Numbers unchanged (beyond the incumbent's behaviour) | +| 2026-10-29 | minor | M12: board grid settings (`board.grid`): dots, lines, graph paper or none, with spacing, size and contrast, in Preferences; the default grid looks as before. Numbers unchanged (beyond the incumbent's behaviour) | | 2026-10-29 | minor | M12, #1387 (connector tool): while a connector is dragged out with the connector tool, the canvas shows the connector itself as it will be made (its straight, elbow or curved route, line, weight and arrowhead, built by the same code as `board.connector`), not a thin line; the object under the pointer is outlined with its four attach points (the middles of its sides), the one the end goes to ringed; within 10 px of one the end keeps that side (`fromSide`/`toSide`, and `side` when re-attaching). Hovering with the tool shows the attach points too. Escape drops the preview; releasing makes the connector in one undo step. Tests: `board_connector_tests`. Numbers unchanged | | 2026-10-24 | minor | M12: the dot grid on board pages (a render pass under the layers), dragging a selected connector's end onto another object or empty canvas (`board.reattach`), curved connectors, and elbows that go around the objects they join. Breadth ~35% → ~37%, ready ~20% → ~21%, ~30–60 h → ~28–56 h | | 2026-10-24 | minor | Facilitation (M12): a shared timer and voting sessions. Breadth ~35% → ~40%, ready ~20% → ~24%, ~30–60 h → ~26–54 h | From b00cccb1144c958b2dad0825fa8f79d82cf8cba5 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 30 Oct 2026 00:13:46 +0700 Subject: [PATCH 7/7] #1547: name the grid styles in a table, keeping the Preferences section's complexity low --- crates/ui-egui/src/canvas/board_bar.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index d7a03e0b5..8a33538c3 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -357,14 +357,14 @@ pub(crate) fn grid_settings(app: &mut FigApp, ui: &mut Ui) { let mut set = None; ui.horizontal(|ui| { ui.label(tr("Board grid")); - for style in GridStyle::ALL { - let label = match style { - GridStyle::Dots => tr("Dots"), - GridStyle::Lines => tr("Lines"), - GridStyle::Graph => tr("Graph paper"), - GridStyle::None => tr("None"), - }; - if ui.selectable_label(g.style == style, label).clicked() { + let styles = [ + (GridStyle::Dots, tr_noop("Dots")), + (GridStyle::Lines, tr_noop("Lines")), + (GridStyle::Graph, tr_noop("Graph paper")), + (GridStyle::None, tr_noop("None")), + ]; + for (style, label) in styles { + if ui.selectable_label(g.style == style, tr(label)).clicked() { set = Some(json!({"style": style.id()})); } }