diff --git a/ROADMAP.md b/ROADMAP.md index 31b724596..1ec74b1bc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -356,6 +356,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| | 2026-10-29 | minor | M4, #1219: Thai, Lao, Khmer and Burmese text, written without spaces between words, wraps between words instead of where a line overflows (`พัฒนาซอ|ฟต์แวร์` → `พัฒนา|ซอฟต์แวร์`). `figcraft_text::breaks::word_breaks` finds the word starts inside each run of these scripts with ICU4X's line segmenter (`icu_segmenter` 2.3): its dictionaries on desktop, its LSTM models in the browser (about 0.39 MB of wasm instead of 1.86 MB, which the 24 MiB gate can't take; they split a few compounds the dictionaries keep whole). Where a run meets spaces, Latin or CJK the UAX #14 rules decide as before, and a word wider than its box still takes #1400's emergency break. Text without these scripts does no extra work. Grade unchanged. Evidence: `breaks::tests::thai_lines_break_between_words`, `lao_khmer_and_burmese_lines_break_between_words`, `word_breaks_survive_junk`, `behaviour_tests::thai_lines_break_between_words` (fails on main). | +| 2026-10-29 | minor | A marquee from anywhere in vector edit mode (#1508): a press on another layer used to leave edit mode at once, so a drag there 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-29 | minor | M9, #1381: joining a live session shows its progress. From the click on Join (the Share popover, the home screen or the Join dialog, which an invite link opens) the Join dialog says "Joining live session…" with a spinner and Cancel until the shared file is in its own tab and ready, then the file shows; while it is on its way the join fields don't start a second one. A join that fails or times out says why in the dialog, with Try again (a new join with the same code or link) and Cancel; Escape and the close button cancel too. `collab.leave` takes `session` to end a session by its id, whichever tab is in front. Tests: `live_joining_tests`. Numbers unchanged | | 2026-10-29 | minor | M9, #1075: `figcraft-server` gives requests that change its files (join codes, links, renames, removals, blocks, publishing with the key) a budget of 60 a minute per address, with the server key and owner tokens alike (100 renames in a row from one address: 100 served before, 60 now; another address is unaffected), and finds join codes through an index of their hashes instead of opening every link's code. Same results, same protocol. Tests: `admin_budget_tests`. Numbers unchanged | | 2026-10-29 | minor | M8, #1080: SVG import draws a pattern's tile once per pattern and scale and reuses it for every other layer it fills (1,000 rectangles filled with one pattern: 1,000 tile drawings before, 1 now, same image fill), and the layers inside a tile count in the import's 100,000-layer budget instead of each tile starting a fresh one, so patterns nested in patterns stop at the budget. Tests: `tile_tests` (svg). Numbers unchanged | 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/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index b7c185721..86f129c9a 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -236,7 +236,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/canvas/vectoredit/pointer.rs b/crates/engine/src/canvas/vectoredit/pointer.rs index ebd8e2e33..0d8bdfba1 100644 --- a/crates/engine/src/canvas/vectoredit/pointer.rs +++ b/crates/engine/src/canvas/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 + /// on another 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, @@ -700,21 +703,18 @@ impl Session { } } None => { - // A press on another layer (and not shift) leaves edit mode, so the normal tool - // takes it; empty canvas only clears the points and starts a marquee (a - // double-click or Escape leaves edit mode). + // Every drag here marquees (#1508). A click on another layer (and not shift) + // leaves edit mode, so the normal tool takes it; a click on empty canvas only + // clears the points (a double-click or Escape leaves edit mode). 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()))); let page = self.ds()?.page; let other = !inside && self.hit(&doc, page, ev.p(), tol * 2.0).is_some(); - if other && !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 = (other && !ev.shift).then(|| ev.clone()); + self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift), leave }); } }, VTool::Bend => match h { @@ -738,7 +738,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() }; @@ -951,7 +951,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)?; @@ -1068,6 +1068,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() 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 efc552c54..7d3164f15 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/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 9d24bc39f..83e585ea0 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -542,6 +542,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) 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 14167386e..1922669ce 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -183,6 +183,7 @@ name = "English" "Blend mode" = "Blend mode" "Blue" = "Blue" "Blur" = "Blur" +"Board grid" = "Board grid" "Boolean" = "Boolean" "Boolean groups" = "Boolean groups" "Both directions" = "Both directions" @@ -613,6 +614,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" @@ -1199,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" @@ -1426,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..7926dfd2d 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,69 @@ 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())); +} + +#[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 c1a76a4de..8a33538c3 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 are about a point and a half across on screen, growing a little zoomed in, scaled by + // the size setting (1, the default, keeps the usual dots). + let k = g.size; + let size = if lines { k.max(0.5) / zoom } else { (1.5 * zoom.sqrt()).clamp(1.0, 3.0) * k / 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")); + 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()})); + } + } + }); + 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/docs/boards-parity.md b/docs/boards-parity.md index 383a69337..ff94b0a02 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). 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; 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 | diff --git a/docs/roadmap.md b/docs/roadmap.md index de1860773..68754639b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| | 2026-10-29 | minor | M4, #1219: Thai, Lao, Khmer and Burmese text, written without spaces between words, wraps between words instead of where a line overflows (`พัฒนาซอ|ฟต์แวร์` → `พัฒนา|ซอฟต์แวร์`). `figcraft_text::breaks::word_breaks` finds the word starts inside each run of these scripts with ICU4X's line segmenter (`icu_segmenter` 2.3): its dictionaries on desktop, its LSTM models in the browser (about 0.39 MB of wasm instead of 1.86 MB, which the 24 MiB gate can't take; they split a few compounds the dictionaries keep whole). Where a run meets spaces, Latin or CJK the UAX #14 rules decide as before, and a word wider than its box still takes #1400's emergency break. Text without these scripts does no extra work. Grade unchanged. Evidence: `breaks::tests::thai_lines_break_between_words`, `lao_khmer_and_burmese_lines_break_between_words`, `word_breaks_survive_junk`, `behaviour_tests::thai_lines_break_between_words` (fails on main). | +| 2026-10-29 | minor | A marquee from anywhere in vector edit mode (#1508): a press on another layer used to leave edit mode at once, so a drag there 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-29 | minor | M9, #1381: joining a live session shows its progress. From the click on Join (the Share popover, the home screen or the Join dialog, which an invite link opens) the Join dialog says "Joining live session…" with a spinner and Cancel until the shared file is in its own tab and ready, then the file shows; while it is on its way the join fields don't start a second one. A join that fails or times out says why in the dialog, with Try again (a new join with the same code or link) and Cancel; Escape and the close button cancel too. `collab.leave` takes `session` to end a session by its id, whichever tab is in front. Tests: `live_joining_tests`. Numbers unchanged | | 2026-10-29 | minor | M9, #1075: `figcraft-server` gives requests that change its files a budget of 60 a minute per address, with the server key and owner tokens alike, and finds join codes through an index of their hashes. Tests: `admin_budget_tests` | | 2026-10-29 | minor | M8, #1080: SVG import draws a pattern's tile once per pattern and scale and reuses it for every other layer it fills, and the layers inside a tile count in the import's 100,000-layer budget instead of each tile starting a fresh one. Tests: `tile_tests` (svg) |