From db725dc73f3d99b598c12b3d2a8014059df9dd02 Mon Sep 17 00:00:00 2001 From: BFlat Date: Fri, 30 Oct 2026 21:58:41 +0700 Subject: [PATCH] M8: the Design panel and the selection overlays stop going over a large selection every frame (#1571) (#1660) --- ROADMAP.md | 3 +- crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/canvas/overlays.rs | 28 ++-- .../ui-egui/src/canvas/panel_nodes_tests.rs | 150 ++++++++++++++++++ .../src/canvas/selection_cache_tests.rs | 2 +- crates/ui-egui/src/panels/layout_panel.rs | 8 +- crates/ui-egui/src/panels/right.rs | 47 +++--- crates/ui-egui/src/panels/right/paints.rs | 12 +- crates/ui-egui/src/panels/right/stroke.rs | 2 +- crates/ui-egui/src/panels/section_panel.rs | 2 +- crates/ui-egui/src/selection_cache.rs | 53 ++++++- docs/roadmap.md | 3 +- 12 files changed, 267 insertions(+), 46 deletions(-) create mode 100644 crates/ui-egui/src/canvas/panel_nodes_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index fb4712746..8886f7aad 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-30 · **Change:** minor (plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); 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); 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-30 · **Change:** minor (with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); 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); 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 @@ -358,6 +358,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M8, #1571 (part 5, fixes it): with 648 layers selected, the right panel cost 0.55 ms on every frame against 0.19 ms with one layer, and the canvas overlays 0.27 ms against 0.16. Each Design panel section went over the whole selection several times a frame for mixed values and which kinds are selected (about 20 passes, each looking up 648 layers in the document). The overlays did the same for boolean operand outlines and constraint guides. Now the panel looks the selection up once per document snapshot and selection; while a drag only moves the layers, that is the document the drag started from. `common` and a new `every` read those layers. The overlays keep which layers have constraint guides and which boolean operands to outline, worked out once per document and selection; during such a drag, from the start document, since a move changes neither. Measured on the same synthetic file of about 1,900 layers: the drag-all UI mean went from 1.48 to 1.04–1.09 ms per frame, and hovering with all selected from 0.95–1.04 to 0.64–0.69 ms. The right panel went to 0.25 ms and the overlays to 0.18 ms. Screenshots of the panel and the overlays are byte-identical before and after. Tests cover the kept layers after edits, another selection, a deleted layer and another document, and the overlays after structure edits. | | 2026-10-30 | minor | M6, gap 6: plugin panels show pictures. An `image` control carries a PNG, JPEG, WebP, GIF, BMP or TIFF file as base64 (`data`, at most 256 KB; a panel spec may now be 1 MB) and is drawn at its size, at most a field wide and 240 pt tall, never scaled up; screen readers read its `label`. The app decodes it with the thumbnail decoder (its allocation limit), refuses pictures over 4,096 px on a side before decoding them, keeps the last 32 decoded, and shows the label instead of a picture it can't show. Images can't be clicked (`plugin.event` refuses them) and can't be command parameters. Also: a panel's or form's captions no longer wrap ("Palette" broke onto two lines when it was the widest). Numbers unchanged. Tests: `v2_tests`, `tests` (manifest), `plugin_panel_tests::panel_images_show_named_or_fall_back_to_their_label`. | | 2026-10-30 | minor | M6, gap 1: a `.fig` connector with a label but no saved snapshot of it lost the label. It now imports as a connector with a saved snapshot does: a frame holding its line (a vector with the connector's stroke and ends) and the label as text, centred on the middle of the line by length in a 200-wide box, in the connector's fill paints or black. The background the label sits on isn't known without the snapshot and is left out; the import report says so. Checked by rendering a synthetic file with figcraft-cli; not on real files. Numbers unchanged. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label`. | | 2026-10-30 | minor | M8, #1571 (part 4): every move of a drag copies the document from where the drag started and normalises it. The copy was already cheap, since layers are shared, not copied (about 0 ms). Normalising took 1.4 ms per move with 648 layers dragged, because each moved layer went through every step: variable bindings and style links, sizing coherence, text auto-size and the instance sync. Now `normalize` sends a layer whose transform is all that changed, and which is in no component or instance, only through the steps that follow what sits around it: groups refitting, auto layout, connectors, ready-for-dev marks and comment pins. Its bindings (never a position), style links, sizing and text have nothing to follow. This applies to any edit that only moves layers, not just drags. Normalising those 648 moves now takes 0.78 ms. Tests compare the result with a full normalisation for every layer, the top-level layers and every third layer of each example file moved at once, and for a drag of plain, bound, grouped, absolutely placed and component layers, while dragging and after the drop. | diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e63caaa3a..55a1ef33e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -376,6 +376,9 @@ mod builder_poly_tests; #[cfg(test)] mod outline_tests; +#[cfg(test)] +mod panel_nodes_tests; + #[cfg(test)] mod selection_cache_tests; diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index ad293cb6a..e2305769c 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -57,7 +57,12 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec } // Inside a boolean group (an operand selected or in vector edit mode): every operand's outline, // so the shapes making the live result stay visible while one of them changes. - let operands = figcraft_engine::booleans::outlined_operands(&doc, &sel, ds.vector_edit.as_ref().map(|ve| ve.id)); + let editing = ds.vector_edit.as_ref().map(|ve| ve.id); + let unmoved = crate::selection_cache::unmoved(ds, &doc); + let key: Vec = editing.map(|e| e.0).into_iter().collect(); + let operands = crate::selection_cache::cached(painter.ctx(), "operands", &unmoved, &sel, &key, || { + figcraft_engine::booleans::outlined_operands(&unmoved, &sel, editing) + }); for id in operands.iter().filter(|o| !sel.contains(o)) { draw_outline(app, painter, &doc, *id, stroke(outline_colour(&doc, *id, accent(painter)).gamma_multiply(0.6), 1.0)); } @@ -310,7 +315,7 @@ fn selection_overlay( // Constraint guides belong to the normal selection overlay: not while the Shape Builder // reshapes by regions, nor while measuring to another layer (Alt), whose lines take over. if app.session.tool.tool != ToolId::ShapeBuilder && app.session.tool.overlay.measure_box.is_none() { - constraint_lines(app, painter, doc, sel); + constraint_lines(app, painter, ds, doc, sel); } // The shape builder reshapes by regions: no transform box. if app.session.tool.tool != ToolId::ShapeBuilder @@ -494,7 +499,17 @@ fn transform_box( /// short bar through the layer's middle — a horizontal one, a vertical one, or both (a cross when /// the layer is centred on both axes). Auto-layout frames ignore constraints, so no guides are /// drawn there, except for a layer that ignores the auto layout (absolute position). -fn constraint_lines(app: &FigApp, painter: &egui::Painter, doc: &Document, sel: &[NodeId]) { +fn constraint_lines(app: &FigApp, painter: &egui::Painter, ds: &figcraft_engine::DocState, doc: &Arc, sel: &[NodeId]) { + // Constraints bind a layer only to a frame it sits inside: one without auto layout, or one + // whose auto layout the layer ignores (absolute position). A move changes neither. + let unmoved = crate::selection_cache::unmoved(ds, doc); + let bound = crate::selection_cache::cached(painter.ctx(), "constrained", &unmoved, sel, &[], || -> Vec { + let binds = |n: &figcraft_doc::Node, p: &figcraft_doc::Node| p.kind.is_frame_like() && (p.layout.is_none() || n.child_layout.absolute); + sel.iter() + .copied() + .filter(|i| unmoved.node(*i).is_some_and(|n| n.parent.and_then(|p| unmoved.node(p)).is_some_and(|p| binds(n, p)))) + .collect() + }); let s = stroke(accent(painter), 1.0); let line = |a: Pos2, b: Pos2| { painter.add(Shape::dashed_line(&[a, b], s, 4.0, 3.0)); @@ -508,15 +523,10 @@ fn constraint_lines(app: &FigApp, painter: &egui::Painter, doc: &Document, sel: painter.line_segment([pos2(c.x, c.y - half), pos2(c.x, c.y + half)], s); } }; - for &id in sel { + for &id in &bound { let Some(n) = doc.node(id) else { continue }; let Some(parent_id) = n.parent else { continue }; let Some(parent) = doc.node(parent_id) else { continue }; - // Constraints bind a layer only to a frame it sits inside: one without auto layout, or one - // whose auto layout the layer ignores (absolute position). - if !parent.kind.is_frame_like() || (parent.layout.is_some() && !n.child_layout.absolute) { - continue; - } let nw = doc.world_transform(id); let pw = doc.world_transform(parent_id); let (nw_w, nw_h) = (n.width, n.height); diff --git a/crates/ui-egui/src/canvas/panel_nodes_tests.rs b/crates/ui-egui/src/canvas/panel_nodes_tests.rs new file mode 100644 index 000000000..cd38e7560 --- /dev/null +++ b/crates/ui-egui/src/canvas/panel_nodes_tests.rs @@ -0,0 +1,150 @@ +//! What a large selection's frames keep (#1571): the Design panel looks the selected layers up once +//! per document snapshot and selection, and the canvas keeps which layers its constraint guides and +//! boolean operand outlines go with. Each answers as the document does, after edits, another +//! selection, a deleted layer, and for any other document. + +use std::sync::Arc; + +use egui::{Color32, Context, Rect, pos2, vec2}; +use figcraft_doc::{Document, NodeId, NodeKind}; +use figcraft_engine::Session; +use serde_json::{Value, json}; + +use super::selection_cache_tests::drawn; +use crate::right::common; +use crate::selection_cache::{every, show}; +use crate::theme::set_canvas_page; +use crate::{FigApp, NoServices}; + +fn id(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: i32, parent: Option) -> NodeId { + let mut p = json!({"x": x, "y": 10, "width": 40, "height": 40}); + if let Some(parent) = parent { + p["parent"] = json!(parent); + } + id(s.execute("shape.rectangle", &p).unwrap()) +} + +/// The panel's questions (the selection's common opacity, whether it is all rectangles), asked as +/// the panel asks them. +fn answers(doc: &Document, sel: &[NodeId]) -> (Option, bool) { + (common(doc, sel, |n| n.opacity.to_bits()), every(doc, sel, |n| matches!(n.kind, NodeKind::Rectangle))) +} + +/// The same questions asked of the document directly. +fn direct(doc: &Document, sel: &[NodeId]) -> (Option, bool) { + let opacities: Vec = sel.iter().filter_map(|i| doc.node(*i)).map(|n| n.opacity.to_bits()).collect(); + let common = opacities.first().copied().filter(|o| opacities.iter().all(|x| x == o)); + (common, sel.iter().all(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Rectangle)))) +} + +#[test] +fn the_panels_kept_layers_answer_as_the_document_does() { + let mut s = Session::new(); + let (a, b) = (rect(&mut s, 0, None), rect(&mut s, 80, None)); + s.execute("node.set", &json!({"ids": [a], "props": {"opacity": 0.5}})).unwrap(); + let sel = vec![a, b]; + let doc = s.ds().unwrap().doc.clone(); + show(&doc, &sel); + assert_eq!(answers(&doc, &sel), direct(&doc, &sel)); + assert_eq!(answers(&doc, &sel).0, None, "mixed"); + // An edit is a new snapshot: answered from itself, before it is shown and after. + s.execute("node.set", &json!({"ids": [a, b], "props": {"opacity": 0.25}})).unwrap(); + let edited = s.ds().unwrap().doc.clone(); + assert!(!Arc::ptr_eq(&doc, &edited)); + assert_eq!(answers(&edited, &sel), (Some(0.25f32.to_bits()), true)); + show(&edited, &sel); + assert_eq!(answers(&edited, &sel), (Some(0.25f32.to_bits()), true)); + assert_eq!(answers(&doc, &sel), direct(&doc, &sel), "the document shown before still answers for itself"); + // Another selection. + s.execute("node.set", &json!({"ids": [b], "props": {"opacity": 1.0}})).unwrap(); + let doc = s.ds().unwrap().doc.clone(); + show(&doc, &sel); + for ids in [vec![a], vec![b], vec![b, a]] { + assert_eq!(answers(&doc, &ids), direct(&doc, &ids), "{ids:?}"); + show(&doc, &ids); + assert_eq!(answers(&doc, &ids), direct(&doc, &ids), "{ids:?} shown"); + } + // A layer that isn't in the document: `every` says no, `common` goes by the others. + s.execute("edit.delete", &json!({"ids": [b]})).unwrap(); + let doc = s.ds().unwrap().doc.clone(); + show(&doc, &sel); + assert_eq!(answers(&doc, &sel), (Some(0.25f32.to_bits()), false)); +} + +#[test] +fn a_kept_selection_never_answers_for_another_document() { + let mut s = Session::new(); + let a = rect(&mut s, 0, None); + let sel = vec![a]; + let base = s.doc().unwrap().clone(); + let first = Arc::new(base.clone()); + let kept_at = Arc::as_ptr(&first); + show(&first, &sel); + drop(first); + let mut changed = base; + changed.node_mut(a).unwrap().opacity = 0.1; + let second = Arc::new(changed); + assert_ne!(Arc::as_ptr(&second), kept_at, "the kept document's place stays taken while it is kept"); + assert_eq!(answers(&second, &sel), (Some(0.1f32.to_bits()), true)); +} + +fn app_of(s: Session) -> (FigApp, Context) { + let mut app = FigApp::new(s, Box::new(NoServices)); + app.canvas.rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let ctx = Context::default(); + set_canvas_page(&ctx, Color32::WHITE); + (app, ctx) +} + +/// What one frame draws, and what it draws with nothing kept. +fn drawn_now(app: &FigApp, ctx: &Context) -> (usize, usize) { + let fresh = Context::default(); + set_canvas_page(&fresh, Color32::WHITE); + (drawn(app, ctx), drawn(app, &fresh)) +} + +#[test] +fn constraint_guides_follow_the_layers_frame() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap()); + let r = rect(&mut s, 40, Some(f)); + let page = s.page().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let (mut app, ctx) = app_of(s); + let (pinned, fresh) = drawn_now(&app, &ctx); + assert_eq!(pinned, fresh); + for (parent, what) in [(page, "on the page: no frame to pin it to"), (f, "back in its frame")] { + app.session.execute("node.reparent", &json!({"ids": [r], "parent": parent})).unwrap(); + app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); + let (now, fresh) = drawn_now(&app, &ctx); + assert_eq!(now, fresh, "{what}"); + assert_eq!(now < pinned, parent == page, "{what}"); + } + // In an auto layout flow its constraints don't apply; ignoring the layout, they do. + app.session.execute("layout.add", &json!({"ids": [f]})).unwrap(); + let (placed, fresh) = drawn_now(&app, &ctx); + assert_eq!(placed, fresh, "auto layout places the layer"); + app.set_props(&[r], json!({"absolute": true})); + let (absolute, fresh) = drawn_now(&app, &ctx); + assert_eq!(absolute, fresh, "ignoring the auto layout"); +} + +#[test] +fn operand_outlines_follow_the_boolean_group() { + let mut s = Session::new(); + let ops = [rect(&mut s, 0, None), rect(&mut s, 20, None), rect(&mut s, 40, None)]; + s.execute("bool.union", &json!({"ids": ops})).unwrap(); + s.execute("select.set", &json!({"ids": [ops[0]]})).unwrap(); + let (mut app, ctx) = app_of(s); + let (three, fresh) = drawn_now(&app, &ctx); + assert_eq!(three, fresh); + app.session.execute("edit.delete", &json!({"ids": [ops[2]]})).unwrap(); + app.session.execute("select.set", &json!({"ids": [ops[0]]})).unwrap(); + let (two, fresh) = drawn_now(&app, &ctx); + assert_eq!(two, fresh, "one operand fewer to outline"); + assert!(two < three); +} diff --git a/crates/ui-egui/src/canvas/selection_cache_tests.rs b/crates/ui-egui/src/canvas/selection_cache_tests.rs index 49427ce26..061fe5b59 100644 --- a/crates/ui-egui/src/canvas/selection_cache_tests.rs +++ b/crates/ui-egui/src/canvas/selection_cache_tests.rs @@ -112,7 +112,7 @@ fn every_input_the_geometry_shows_makes_it_again() { } /// How many shapes one frame of the canvas overlays draws. -fn drawn(app: &FigApp, ctx: &Context) -> usize { +pub(super) fn drawn(app: &FigApp, ctx: &Context) -> usize { let mut out = ctx.run_ui(Default::default(), |ui| { overlays(app, &ui.ctx().layer_painter(LayerId::background()), &Tokens::light()); }); diff --git a/crates/ui-egui/src/panels/layout_panel.rs b/crates/ui-egui/src/panels/layout_panel.rs index 117715d87..4762bdd08 100644 --- a/crates/ui-egui/src/panels/layout_panel.rs +++ b/crates/ui-egui/src/panels/layout_panel.rs @@ -29,9 +29,9 @@ fn parent_of(doc: &Document, id: NodeId) -> Option<&Node> { /// no auto layout and the selection is editable outside an instance. pub fn layout_section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[NodeId]) { let ids = sel.to_vec(); - let frames = sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like())); - let layout_containers = sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Group))); - let no_al = !sel.is_empty() && sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.layout.is_none())); + let frames = crate::selection_cache::every(doc, sel, |n| n.kind.is_frame_like()); + let layout_containers = crate::selection_cache::every(doc, sel, |n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Group)); + let no_al = !sel.is_empty() && crate::selection_cache::every(doc, sel, |n| n.layout.is_none()); let al = common(doc, sel, |n| n.layout.clone()); let has_al = matches!(al, Some(Some(_))); let title = if has_al { tr("Auto layout") } else { tr("Layout") }; @@ -187,7 +187,7 @@ fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has return; } // Min/max apply to auto layout frames and their children; absolute children neither fill nor limit. - let can_fill = parent_al && sel.iter().all(|i| doc.node(*i).is_some_and(|n| !n.child_layout.absolute)); + let can_fill = parent_al && crate::selection_cache::every(doc, sel, |n| !n.child_layout.absolute); let can_limit = has_al || can_fill; let first = sel.first().and_then(|i| doc.node(*i)); row(ui, 32.0, |ui| { diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 58a1a6e19..6dde13136 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -42,9 +42,11 @@ pub(crate) use stroke::{CAP_ART_W, cap_art, join_label}; /// Common value of `f` across `ids` (None when mixed or empty). pub(crate) fn common(doc: &Document, ids: &[NodeId], f: impl Fn(&Node) -> T) -> Option { - let mut it = ids.iter().filter_map(|i| doc.node(*i)); - let first = f(it.next()?); - if it.all(|n| f(n) == first) { Some(first) } else { None } + crate::selection_cache::with_nodes(doc, ids, |it| { + let mut it = it.flatten(); + let first = f(it.next()?); + if it.all(|n| f(n) == first) { Some(first) } else { None } + }) } impl FigApp { @@ -257,6 +259,7 @@ fn design(app: &mut FigApp, ui: &mut Ui) { page_section(app, ui, &doc); return; } + crate::selection_cache::show(&shown, &sel); header(app, ui, &shown, &sel); widgets::separator(ui); // Editing a vector with points selected, the points' fields stand in for the layer's position @@ -287,7 +290,7 @@ fn design(app: &mut FigApp, ui: &mut Ui) { if variable_modes(app, ui, &shown, &sel) { widgets::separator(ui); } - if sel.iter().any(|i| matches!(doc.node(*i).map(|n| &n.kind), Some(NodeKind::Text(_)))) { + if crate::selection_cache::with_nodes(&shown, &sel, |it| it.flatten().any(|n| matches!(n.kind, NodeKind::Text(_)))) { crate::typography::typography(app, ui, &shown, &sel); widgets::separator(ui); } @@ -298,7 +301,7 @@ fn design(app: &mut FigApp, ui: &mut Ui) { effects(app, ui, &shown, &sel); widgets::separator(ui); crate::selection_colors::section(app, ui, &shown, &sel); - if sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like())) { + if crate::selection_cache::every(&shown, &sel, |n| n.kind.is_frame_like()) { grids(app, ui, &shown, &sel); widgets::separator(ui); } @@ -376,7 +379,7 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) { }; let is_frame = sel.len() == 1 && sel.first().and_then(|i| doc.node(*i)).is_some_and(|n| matches!(n.kind, NodeKind::Frame)); // Frames and groups convert into each other from the type menu. - let is_group = !sel.is_empty() && sel.iter().all(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Group))); + let is_group = !sel.is_empty() && crate::selection_cache::every(doc, sel, |n| matches!(n.kind, NodeKind::Group)); let kind_items = |app: &mut FigApp, ui: &mut Ui, frame: bool| { for (to_frame, label, cmd) in [(true, tr("Frame"), "object.convertToFrame"), (false, tr("Group"), "object.convertToGroup")] { if menu_check(ui, to_frame == frame, label, "") { @@ -718,13 +721,14 @@ fn constraints_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], c: Option bool { - let arcs: Vec<(f64, f64, f64)> = sel - .iter() - .filter_map(|i| match doc.node(*i)?.kind { - NodeKind::Ellipse { start, sweep, inner } => Some((start, sweep, inner)), - _ => None, - }) - .collect(); + let arcs: Vec<(f64, f64, f64)> = crate::selection_cache::with_nodes(doc, sel, |it| { + it.flatten() + .filter_map(|n| match n.kind { + NodeKind::Ellipse { start, sweep, inner } => Some((start, sweep, inner)), + _ => None, + }) + .collect() + }); if arcs.is_empty() || arcs.len() != sel.len() { return false; } @@ -761,14 +765,15 @@ fn arc_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) -> /// inner radius as a share of the outer one), as `node.set`'s `pointCount` / `innerRadius`. /// Returns whether it showed. fn points_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) -> bool { - let shapes: Vec<(u32, Option)> = sel - .iter() - .filter_map(|i| match doc.node(*i)?.kind { - NodeKind::Polygon { count } => Some((count, None)), - NodeKind::Star { count, inner_ratio } => Some((count, Some(inner_ratio))), - _ => None, - }) - .collect(); + let shapes: Vec<(u32, Option)> = crate::selection_cache::with_nodes(doc, sel, |it| { + it.flatten() + .filter_map(|n| match n.kind { + NodeKind::Polygon { count } => Some((count, None)), + NodeKind::Star { count, inner_ratio } => Some((count, Some(inner_ratio))), + _ => None, + }) + .collect() + }); if shapes.is_empty() || shapes.len() != sel.len() { return false; } diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 11b368d1a..58423d252 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -33,7 +33,7 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N let col = widgets::col_width(ui.available_width()); crate::variable_ui::bound_row(app, ui, &ids, "visible", VariableType::Boolean, Lead::Icon(Icon::Eye, tr("Visible")), col * 2.0 + 8.0); // Masks: how they mask. - if sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.is_mask)) { + if crate::selection_cache::every(doc, sel, |n| n.is_mask) { let mt = common(doc, sel, |n| n.mask_type); widgets::sublabels(ui, tr("Mask"), None); row(ui, 32.0, |ui| { @@ -50,11 +50,11 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N } let op_of = |n: &Node| (f64::from(n.opacity) * 100.0).round(); let op = common(doc, sel, op_of); - let radius_ok = sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.has_corner_radius())); + let radius_ok = crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_radius()); // Only rectangles and frames round each corner on its own. - let indep_ok = radius_ok && sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.has_independent_corners())); + let indep_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_independent_corners()); // For polygons and stars the same panel holds only the Corner smoothing row. - let smooth_ok = radius_ok && sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.has_corner_smoothing())); + let smooth_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_smoothing()); let r = common(doc, sel, |n| n.corners.uniform().map(|r| (r * 100.0).round() / 100.0)); widgets::sublabels(ui, tr("Opacity"), radius_ok.then_some(tr("Corner radius"))); row(ui, 32.0, |ui| { @@ -147,7 +147,7 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N /// of its own (`variable.setMode`). Collections from enabled libraries follow under their /// library's name (`library.setVariableMode` copies the collection in). Returns whether it showed. pub(super) fn variable_modes(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) -> bool { - if !sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like())) { + if !crate::selection_cache::every(doc, sel, |n| n.kind.is_frame_like()) { return false; } let libs = crate::variable_ui::libraries(app, doc); @@ -351,7 +351,7 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI // The row is the panel's width: the two fields split what the buttons at its end leave, // so the align field and the weight field are the same column (76 at the default width // with two buttons, 88 with one). The buttons are 24 pt each, 4 apart on the icon grid. - let sided = sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle))); + let sided = crate::selection_cache::every(doc, sel, |n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle)); let group = if sided { 24.0 + 4.0 + 24.0 } else { 24.0 }; let field_w = ((ui.available_width() - widgets::GUTTER * 2.0 - group) / 2.0).max(40.0); let resp = widgets::dropdown( diff --git a/crates/ui-egui/src/panels/right/stroke.rs b/crates/ui-egui/src/panels/right/stroke.rs index e7ebbcd89..ef7a3648d 100644 --- a/crates/ui-egui/src/panels/right/stroke.rs +++ b/crates/ui-egui/src/panels/right/stroke.rs @@ -240,7 +240,7 @@ pub(super) fn stroke_settings(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel } }); // End points only mean something on open paths. - let open_paths = sel.iter().all(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Line | NodeKind::Vector { .. }))); + let open_paths = crate::selection_cache::every(doc, sel, |n| matches!(n.kind, NodeKind::Line | NodeKind::Vector { .. })); if open_paths { widgets::sublabels(ui, tr("Start point"), Some(tr("End point"))); row(ui, 32.0, |ui| { diff --git a/crates/ui-egui/src/panels/section_panel.rs b/crates/ui-egui/src/panels/section_panel.rs index daa793db8..4ea146924 100644 --- a/crates/ui-egui/src/panels/section_panel.rs +++ b/crates/ui-egui/src/panels/section_panel.rs @@ -107,7 +107,7 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) { } }); row(ui, 28.0, |ui| { - let hidden = sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.hides_contents())); + let hidden = crate::selection_cache::every(doc, sel, |n| n.hides_contents()); if widgets::checkbox(ui, hidden, tr("Hide contents")) { app.run("section.toggleContents", json!({"ids": ids, "hidden": !hidden})); } diff --git a/crates/ui-egui/src/selection_cache.rs b/crates/ui-egui/src/selection_cache.rs index e799c48b0..2bf0f8672 100644 --- a/crates/ui-egui/src/selection_cache.rs +++ b/crates/ui-egui/src/selection_cache.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Weak}; -use figcraft_doc::{Document, NodeId}; +use figcraft_doc::{Document, Node, NodeId}; /// One kept value and what it was made from. The document is held weakly, so a kept value never /// keeps an old snapshot alive; the weak reference keeps its address from being reused. @@ -52,6 +52,57 @@ pub(crate) fn moved(ds: &figcraft_engine::DocState) -> Option<(Arc, (f (it.selection == ds.selection).then(|| (it.doc.clone(), d)) } +/// The document to work out from what a move doesn't change (which layers, their kinds and +/// parents): the one a gesture that only moved the selection started from, kept for the whole +/// gesture ([`moved`]), else `doc`. +pub(crate) fn unmoved(ds: &figcraft_engine::DocState, doc: &Arc) -> Arc { + moved(ds).map_or_else(|| doc.clone(), |(base, _)| base) +} + +/// The selected layers of the document the Design panel shows, looked up once: its sections go +/// over the whole selection many times a frame (mixed values, which kinds are selected), and with +/// hundreds of layers selected the lookups cost more than the rest of the panel (#1571). +struct Shown { + doc: Weak, + sel: Vec, + nodes: Vec>>, +} + +thread_local! { + static SHOWN: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The panel is about to show `sel` of `doc`: [`with_nodes`] over exactly these reads the layers +/// looked up here, kept while the document snapshot and the selection stay the same. +pub(crate) fn show(doc: &Arc, sel: &[NodeId]) { + SHOWN.with(|s| { + let mut s = s.borrow_mut(); + if s.as_ref().is_some_and(|k| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(doc)) && k.sel == sel) { + return; + } + *s = Some(Shown { doc: Arc::downgrade(doc), sel: sel.to_vec(), nodes: sel.iter().map(|i| doc.node_arc(*i).cloned()).collect() }); + }); +} + +/// `f` over the layers of `ids` in `doc`, in order (`None` for one not in it): the ones [`show`] +/// kept when `doc` and `ids` are what it was given, else looked up. The kept document is held +/// weakly, so its address can't be another document's and its contents can't change. +pub(crate) fn with_nodes(doc: &Document, ids: &[NodeId], f: impl FnOnce(&mut dyn Iterator>) -> R) -> R { + SHOWN.with(|s| { + let s = s.borrow(); + match s.as_ref().filter(|k| std::ptr::eq(k.doc.as_ptr(), doc) && k.sel == ids) { + Some(k) => f(&mut k.nodes.iter().map(Option::as_deref)), + None => f(&mut ids.iter().map(|i| doc.node(*i))), + } + }) +} + +/// Whether every one of `ids` is in `doc` and passes `f`. +pub(crate) fn every(doc: &Document, ids: &[NodeId], f: impl Fn(&Node) -> bool) -> bool { + // `Iterator::all` on the `&mut dyn Iterator` itself (sized), not on the trait object. + with_nodes(doc, ids, |mut it| Iterator::all(&mut it, |n| n.is_some_and(&f))) +} + /// A screen point as key material. pub(crate) fn bits(p: egui::Pos2) -> [u64; 2] { [u64::from(p.x.to_bits()), u64::from(p.y.to_bits())] diff --git a/docs/roadmap.md b/docs/roadmap.md index 55553f9db..b2ee3980f 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-30 · **Change:** minor (plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); 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); 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-30 · **Change:** minor (with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); 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); 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 @@ -75,6 +75,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M8, #1571 (part 5, fixes it): with 648 layers selected, the right panel cost 0.55 ms on every frame against 0.19 ms with one layer, and the canvas overlays 0.27 ms against 0.16. Each Design panel section went over the whole selection several times a frame for mixed values and which kinds are selected (about 20 passes, each looking up 648 layers in the document). The overlays did the same for boolean operand outlines and constraint guides. Now the panel looks the selection up once per document snapshot and selection; while a drag only moves the layers, that is the document the drag started from. `common` and a new `every` read those layers. The overlays keep which layers have constraint guides and which boolean operands to outline, worked out once per document and selection; during such a drag, from the start document, since a move changes neither. Measured on the same synthetic file of about 1,900 layers: the drag-all UI mean went from 1.48 to 1.04–1.09 ms per frame, and hovering with all selected from 0.95–1.04 to 0.64–0.69 ms. The right panel went to 0.25 ms and the overlays to 0.18 ms. Screenshots of the panel and the overlays are byte-identical before and after. Tests cover the kept layers after edits, another selection, a deleted layer and another document, and the overlays after structure edits. | | 2026-10-30 | minor | M6, gap 6: `image` controls in plugin panels (base64, 256 KB, 4,096 px a side; specs up to 1 MB), named by their label. Tests: `v2_tests`, `plugin_panel_tests` | | 2026-10-30 | minor | M6, gap 1: `.fig` connector labels without a saved snapshot are kept, centred on the line, instead of skipped. Test: `fig::tests::tail` | | 2026-10-30 | minor | M8, #1571 (part 4): every move of a drag copies the document from where the drag started and normalises it. The copy was already cheap, since layers are shared, not copied (about 0 ms). Normalising took 1.4 ms per move with 648 layers dragged, because each moved layer went through every step: variable bindings and style links, sizing coherence, text auto-size and the instance sync. Now `normalize` sends a layer whose transform is all that changed, and which is in no component or instance, only through the steps that follow what sits around it: groups refitting, auto layout, connectors, ready-for-dev marks and comment pins. Its bindings (never a position), style links, sizing and text have nothing to follow. This applies to any edit that only moves layers, not just drags. Normalising those 648 moves now takes 0.78 ms. Tests compare the result with a full normalisation for every layer, the top-level layers and every third layer of each example file moved at once, and for a drag of plain, bound, grouped, absolutely placed and component layers, while dragging and after the drop. |