Merge upstream/main into feat/jam-native-board-items-1808

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Trevor BrownandClaude Opus 5.5 committed 2026-11-11 20:39:08 -05:00
commit 55e2b85fd0
72 files changed
+2326 -153

No files matched your search

+4
View File
@@ -29,6 +29,10 @@ jobs:
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+5
View File
@@ -1,6 +1,10 @@
name: Release
on:
# A nightly dry run on main: every release build except macOS, nothing signed or released
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
schedule:
- cron: "40 1 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -30,6 +34,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: figcraft
app-title: FigCraft
# Combined Latin presentation and core UI catalog. Required web builds enforce
Generated
+25 -23
View File
@@ -1134,7 +1134,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"chrono",
"dunce",
@@ -1144,6 +1144,7 @@ dependencies = [
"image",
"log",
"plist",
"rustix 1.1.5",
"semver",
"serde",
"serde_json",
@@ -1546,6 +1547,7 @@ dependencies = [
"raw-window-handle",
"smithay-clipboard",
"web-time",
"webbrowser",
"windows-sys 0.61.2",
"winit",
]
@@ -1783,7 +1785,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
[[package]]
name = "figcraft"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"arboard",
"craft-menu",
@@ -1815,7 +1817,7 @@ dependencies = [
[[package]]
name = "figcraft-cli"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"clap",
"clap_complete",
@@ -1833,7 +1835,7 @@ dependencies = [
[[package]]
name = "figcraft-collab"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -1851,7 +1853,7 @@ dependencies = [
[[package]]
name = "figcraft-collab-net"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"figcraft-collab",
@@ -1874,7 +1876,7 @@ dependencies = [
[[package]]
name = "figcraft-color"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"kurbo",
"serde",
@@ -1883,7 +1885,7 @@ dependencies = [
[[package]]
name = "figcraft-doc"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-color",
"figcraft-geom",
@@ -1896,7 +1898,7 @@ dependencies = [
[[package]]
name = "figcraft-engine"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"craft-docpath",
@@ -1930,7 +1932,7 @@ dependencies = [
[[package]]
name = "figcraft-format"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-doc",
"figcraft-layout",
@@ -1947,7 +1949,7 @@ dependencies = [
[[package]]
name = "figcraft-geom"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"kurbo",
"serde",
@@ -1955,7 +1957,7 @@ dependencies = [
[[package]]
name = "figcraft-layout"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-doc",
"figcraft-geom",
@@ -1963,7 +1965,7 @@ dependencies = [
[[package]]
name = "figcraft-mcp"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"figcraft-collab-net",
@@ -1979,7 +1981,7 @@ dependencies = [
[[package]]
name = "figcraft-pathops"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-doc",
"figcraft-geom",
@@ -1988,7 +1990,7 @@ dependencies = [
[[package]]
name = "figcraft-pdf"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-color",
"figcraft-doc",
@@ -2005,7 +2007,7 @@ dependencies = [
[[package]]
name = "figcraft-plugin"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-color",
"serde",
@@ -2018,7 +2020,7 @@ dependencies = [
[[package]]
name = "figcraft-render"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"crc32fast",
"figcraft-color",
@@ -2037,7 +2039,7 @@ dependencies = [
[[package]]
name = "figcraft-server"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"chrono",
"crc32fast",
@@ -2062,7 +2064,7 @@ dependencies = [
[[package]]
name = "figcraft-svg"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"figcraft-color",
@@ -2078,7 +2080,7 @@ dependencies = [
[[package]]
name = "figcraft-text"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"core-text",
"craft-font-catalog",
@@ -2096,7 +2098,7 @@ dependencies = [
[[package]]
name = "figcraft-ui-egui"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2124,7 +2126,7 @@ dependencies = [
[[package]]
name = "figcraft-vectordrawable"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-color",
"figcraft-doc",
@@ -2138,7 +2140,7 @@ dependencies = [
[[package]]
name = "figcraft-web"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"craft-web-api",
@@ -6761,7 +6763,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"figcraft-engine",
"serde_json",
+2 -2
View File
@@ -6,7 +6,7 @@ exclude = ["plugins"]
# default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"]
[workspace.package]
version = "0.15.0"
version = "0.18.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -43,7 +43,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
# pull a second egui family version).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
# The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto
# indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
+2 -1
View File
@@ -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-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library Line truncated
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
@@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged |
| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged |
| 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged |
+3 -1
View File
@@ -23,7 +23,9 @@ craft-window = { workspace = true }
# The suite's settings folder: `FIGCRAFT_CONFIG_DIR`, a portable marker, then the platform folder.
craft-settings = { workspace = true }
egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11"] }
# `links`: without it eframe drops every `ctx.open_url` and hyperlink click (the update prompt's
# What's new and Download, About, Credits) with only a log warning.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] }
serde_json = { workspace = true }
log = { workspace = true }
rfd = { workspace = true }
+10
View File
@@ -142,3 +142,13 @@ fn the_next_dialog_starts_in_the_folder_of_the_last_pick() {
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(start_folder(Some(dir)), None, "a folder deleted since: the system's own");
}
/// The update prompt's What's new and Download, and the About and Credits links, open through
/// `ctx.open_url`. eframe drops those with only a log warning unless it is built with `links`.
#[test]
fn links_in_the_interface_open_in_the_browser() {
let manifest = include_str!("../Cargo.toml");
let eframe: Vec<&str> = manifest.lines().filter(|l| l.trim_start().starts_with("eframe =")).collect();
assert!(!eframe.is_empty(), "the app depends on eframe");
assert!(eframe.iter().any(|l| l.contains("\"links\"")), "eframe is built with `links`: {eframe:?}");
}
+4
View File
@@ -220,6 +220,7 @@ impl LiveLink for NetLink {
let (server, query) = Endpoint::parse(&o.server)?;
// Without a key: as anyone may, when the server is open to the public (it says if not).
let key = requests::server_key(o.key, query);
requests::key_over_tls(&server, key.as_deref())?;
// Until the upload is done the invite names only the server.
let cfg = self.guest_config(Invite { server: server.clone(), file: String::new(), token: String::new() }, None, &o.me);
let inbox = self.sessions.inbox();
@@ -342,6 +343,7 @@ fn upload(o: PublishOptions, limits: &NetLimits) -> Result<Published, String> {
let (server, query) = Endpoint::parse(&o.server)?;
let key = requests::server_key(o.key, query)
.ok_or("the server address needs the server's key (ws://host:port/?key=…; `figcraft-server key` prints it)")?;
requests::key_over_tls(&server, Some(&key))?;
upload_file(&server, Some(&key), &o.name, &o.doc, limits, CONNECT).map(|(_, published, _)| published)
}
@@ -358,6 +360,7 @@ fn hosting(server: &str, file: &str, owner: &str, req: Option<Admin>, limits: &N
fn share(server: &str, file: &str, owner: &str, revoke: &[String], create: bool, limits: &NetLimits) -> Result<Option<Shared>, String> {
let (endpoint, query) = Endpoint::parse(server)?;
let key = requests::server_key(None, query);
requests::key_over_tls(&endpoint, key.as_deref())?;
manage::share(&endpoint, key.as_deref(), file, owner, revoke, create, limits, CONNECT)
}
@@ -365,6 +368,7 @@ fn share(server: &str, file: &str, owner: &str, revoke: &[String], create: bool,
fn plugins(server: &str, req: PluginReq, limits: &NetLimits) -> Result<PluginReply, String> {
let (server, query) = Endpoint::parse(server)?;
let key = query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v).unwrap_or_default();
requests::key_over_tls(&server, Some(&key))?;
manage::plugins(&server, key.trim(), req, limits, CONNECT)
}
+34 -4
View File
@@ -242,18 +242,30 @@ pub fn shutdown(s: &TcpStream) {
/// Connect to `server` (through TLS for `wss://`): the reader's and the writer's handles, and the
/// socket to shut it down with.
pub fn open(server: &Endpoint, timeout: Duration, limits: &NetLimits) -> Result<(Duplex, Duplex, TcpStream), String> {
let stream = dial(&server.host, timeout, limits)?;
// A plain `ws://localhost` is trusted as this machine (a key may go over it), so only loopback
// addresses are connected to: a resolver mapping the name elsewhere must not carry it off-machine.
let stream = dial(&server.host, !server.secure && server.loopback(), timeout, limits)?;
let tls = if server.secure { Some(tls::handshake(&stream, &server.host)?) } else { None };
Duplex::split(stream, tls).map_err(|e| e.to_string())
}
/// Connect to `host` (`name:port`), trying each of its addresses within `timeout`, with Nagle off
/// and reads and writes bounded by `limits`' hello and write timeouts.
fn dial(host: &str, timeout: Duration, limits: &NetLimits) -> Result<TcpStream, String> {
/// Whether `a` may be connected to: any address, or with `loopback_only` just this machine's.
fn dialable(a: &std::net::SocketAddr, loopback_only: bool) -> bool {
!loopback_only || a.ip().is_loopback()
}
/// Connect to `host` (`name:port`), trying each of its addresses within `timeout` (only loopback
/// ones with `loopback_only`), with Nagle off and reads and writes bounded by `limits`' hello and
/// write timeouts.
fn dial(host: &str, loopback_only: bool, timeout: Duration, limits: &NetLimits) -> Result<TcpStream, String> {
use std::net::ToSocketAddrs;
let addrs = host.to_socket_addrs().map_err(|e| format!("can't find {host}: {e}"))?;
let mut last = format!("can't find {host}");
for a in addrs {
if !dialable(&a, loopback_only) {
last = format!("{host} resolves to {a}, which is not this machine");
continue;
}
match TcpStream::connect_timeout(&a, timeout) {
Ok(s) => {
let _ = s.set_nodelay(true);
@@ -318,3 +330,21 @@ impl Bucket {
self.tokens = (self.tokens + n).min(self.burst);
}
}
#[cfg(test)]
mod dial_tests {
use super::dialable;
use std::net::SocketAddr;
#[test]
fn a_loopback_only_dial_skips_addresses_off_this_machine() {
let at = |s: &str| s.parse::<SocketAddr>().unwrap();
for a in ["127.0.0.1:9", "[::1]:9", "127.5.5.5:9"] {
assert!(dialable(&at(a), true), "{a}");
}
for a in ["10.0.0.5:9", "203.0.113.7:9", "[2001:db8::1]:9"] {
assert!(!dialable(&at(a), true), "{a}");
assert!(dialable(&at(a), false), "{a} when anywhere is allowed");
}
}
}
+27
View File
@@ -32,6 +32,15 @@ pub(crate) fn server_key(given: Option<String>, query: Vec<(String, String)>) ->
given.or_else(|| query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v)).filter(|k| !k.trim().is_empty())
}
/// Refuse to send the server's key (its whole administrative authority, reusable) in the clear:
/// `ws://` is only for a server on this machine; anywhere else needs `wss://`.
pub(crate) fn key_over_tls(server: &Endpoint, key: Option<&str>) -> Result<(), String> {
if key.is_some_and(|k| !k.trim().is_empty()) && !server.secure && !server.loopback() {
return Err("the server's key is only sent over wss:// (or ws:// to this machine): it would be readable on the network".into());
}
Ok(())
}
/// Why asking `server` about its hosting failed with `e`: a server older than open hosting can't
/// read the question.
pub(crate) fn hosting_error(server: &Endpoint, e: String) -> String {
@@ -145,3 +154,21 @@ pub(crate) fn hosted(server: &Endpoint, reply: Option<AdminReply>) -> Option<Adm
other => other,
})
}
#[cfg(test)]
mod key_tests {
use super::*;
#[test]
fn the_key_never_goes_over_plain_tcp_to_another_machine() {
let at = |url: &str| Endpoint::parse(url).unwrap().0;
assert!(key_over_tls(&at("ws://share.example:9000/"), Some("k")).is_err());
assert!(key_over_tls(&at("ws://10.0.0.5:9000/"), Some("k")).is_err());
assert!(key_over_tls(&at("wss://share.example/"), Some("k")).is_ok());
assert!(key_over_tls(&at("ws://127.0.0.1:9000/"), Some("k")).is_ok());
assert!(key_over_tls(&at("ws://localhost:9000/"), Some("k")).is_ok());
// Browsing or publishing as anyone sends no key, so plain is fine.
assert!(key_over_tls(&at("ws://share.example:9000/"), None).is_ok());
assert!(key_over_tls(&at("ws://share.example:9000/"), Some(" ")).is_ok());
}
}
+2
View File
@@ -29,6 +29,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() {
to: End::Point { x: 5.0, y: 5.0 },
routing: Routing::Elbow,
path: None,
branch: false,
}));
let mut r = host.clone();
r.apply(&diff(&host, &edited).unwrap().changes, Mode::Strict).unwrap();
@@ -38,6 +39,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() {
to: End::Point { x: 9.0, y: 1.0 },
routing: Routing::Straight,
path: None,
branch: false,
}));
let d = diff(&r, &moved).unwrap();
assert!(matches!(d.changes.as_slice(), [Change::Set { prop: Prop::Board, .. }]), "{:?}", d.changes);
+17 -2
View File
@@ -62,18 +62,29 @@ pub enum BoardItem {
/// A table: a frame of row frames holding cell frames with text (its column lines are thin
/// rectangles laid over it).
Table,
/// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the
/// branch (a connector with `branch`) arriving at it.
MindNode,
}
impl BoardItem {
/// Objects selected and moved as a whole: a click on their text or outline picks them, and
/// they never take other layers in.
pub fn is_atom(&self) -> bool {
matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table)
matches!(
self,
BoardItem::Sticky { .. }
| BoardItem::Shape { .. }
| BoardItem::Label { .. }
| BoardItem::Stamp { .. }
| BoardItem::Table
| BoardItem::MindNode
)
}
/// Objects whose first text layer is their text (a double-click or Enter edits it).
pub fn has_text(&self) -> bool {
matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. })
matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode)
}
/// Who made it (stickies and stamps; empty when unknown).
@@ -115,6 +126,7 @@ impl BoardItem {
BoardItem::Stamp { .. } => "stamp",
BoardItem::Ink => "ink",
BoardItem::Table => "table",
BoardItem::MindNode => "mindNode",
}
}
}
@@ -619,4 +631,7 @@ pub struct Connector {
/// Its path as reshaped by hand; `None`: routed by itself.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<ConnectorPath>,
/// A mind map's branch: `from` is the parent, `to` the child. The map's shape is read from these.
#[serde(default, skip_serializing_if = "crate::node::is_default")]
pub branch: bool,
}
+138
View File
@@ -0,0 +1,138 @@
//! Mind map layout: where the nodes of a map go, from their sizes and their tree. Pure geometry,
//! like `board_route`; the engine's normalize pass reads the tree from the branches and moves the
//! layers (#2226).
use figcraft_geom::{Point, Rect};
use crate::NodeId;
/// The room between a node's column and its children's column.
pub const MIND_GAP_X: f64 = 88.0;
/// The room between a node (with everything under it) and the next one below.
pub const MIND_GAP_Y: f64 = 48.0;
/// The most nodes one map is laid out with (a larger one is left as it is).
pub const MIND_MAX_NODES: usize = 2000;
/// The deepest level of a map that is laid out (the first node is level 0).
pub const MIND_MAX_DEPTH: usize = 64;
/// One node of a mind map as the layout sees it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MindBox {
pub id: NodeId,
/// Its box on the page now. The root's stays; of the others only the size counts, and the
/// centre's y, which orders siblings.
pub rect: Rect,
/// Its parent's index in the slice (`None`: the root, entry 0). Always a smaller index.
pub parent: Option<usize>,
/// Left of the root. Read on the root's children only: deeper nodes follow their parent.
pub left: bool,
}
fn finite(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())
}
/// Where every node but the root goes: its box's top-left on the page. Nodes whose parent isn't
/// an earlier entry, that are deeper than [`MIND_MAX_DEPTH`] or that would land off the finite
/// plane are left out; a slice that is empty, longer than [`MIND_MAX_NODES`], whose first entry
/// has a parent or that holds a box that is not finite is left alone altogether.
pub fn mind_layout(nodes: &[MindBox]) -> Vec<(NodeId, Point)> {
let n = nodes.len();
let Some(root) = nodes.first().filter(|r| r.parent.is_none()) else { return Vec::new() };
if n > MIND_MAX_NODES || !nodes.iter().all(|b| finite(b.rect)) {
return Vec::new();
}
// The tree: who is a child of whom, which side of the root it is on, how deep.
let (mut left, mut depth, mut valid) = (vec![false; n], vec![0_usize; n], vec![false; n]);
if let Some(v) = valid.first_mut() {
*v = true;
}
// Children by parent and side (0: right, 1: left; below the root only the parent's side is used).
let mut kids: Vec<[Vec<usize>; 2]> = vec![[Vec::new(), Vec::new()]; n];
for (i, b) in nodes.iter().enumerate().skip(1) {
let Some(p) = b.parent.filter(|p| *p < i && valid.get(*p).copied().unwrap_or(false)) else { continue };
let d = depth.get(p).copied().unwrap_or(0) + 1;
if d > MIND_MAX_DEPTH {
continue;
}
let side = if p == 0 { b.left } else { left.get(p).copied().unwrap_or(false) };
if let (Some(v), Some(l), Some(dp)) = (valid.get_mut(i), left.get_mut(i), depth.get_mut(i)) {
(*v, *l, *dp) = (true, side, d);
}
if let Some(k) = kids.get_mut(p) {
k[usize::from(side)].push(i);
}
}
// Siblings keep the order they are in: by their middles, then by id.
for k in kids.iter_mut().flatten() {
k.sort_by(|a, b| {
let (x, y) = (nodes.get(*a), nodes.get(*b));
match (x, y) {
(Some(x), Some(y)) => x.rect.center().y.total_cmp(&y.rect.center().y).then(x.id.cmp(&y.id)),
_ => std::cmp::Ordering::Equal,
}
});
}
let height = |i: usize| nodes.get(i).map_or(0.0, |b| b.rect.height());
let width = |i: usize| nodes.get(i).map_or(0.0, |b| b.rect.width());
// Span, backward: a node's room is its own height or its children's stack, whichever is more.
let stack = |span: &[f64], list: &[usize]| {
let total: f64 = list.iter().map(|c| span.get(*c).copied().unwrap_or(0.0)).sum();
total + MIND_GAP_Y * list.len().saturating_sub(1) as f64
};
let mut span = vec![0.0_f64; n];
for i in (1..n).rev() {
let own = kids.get(i).map_or(0.0, |k| stack(&span, &k[usize::from(left.get(i).copied().unwrap_or(false))]));
if let Some(s) = span.get_mut(i) {
*s = height(i).max(own);
}
}
// Place, forward. `column[i]`: where node i's children's column begins (its left edge on the
// right side, its right edge on the left side); `centre[i]`: its middle.
let mut column = vec![0.0_f64; n];
let mut centre = vec![0.0_f64; n];
let mut out = Vec::new();
let root_c = root.rect.center().y;
if let Some(c) = centre.first_mut() {
*c = root_c;
}
let mut ok = vec![false; n];
if let Some(o) = ok.first_mut() {
*o = true;
}
for i in 0..n {
if !ok.get(i).copied().unwrap_or(false) {
continue;
}
let Some(k) = kids.get(i) else { continue };
for side in [false, true] {
let list = k[usize::from(side)].as_slice();
if list.is_empty() {
continue;
}
// The column the group starts in: past the widest node of its parent's own group.
let x =
if i == 0 { if side { root.rect.x0 - MIND_GAP_X } else { root.rect.x1 + MIND_GAP_X } } else { column.get(i).copied().unwrap_or(0.0) };
let widest = list.iter().map(|c| width(*c)).fold(0.0, f64::max);
let mut top = centre.get(i).copied().unwrap_or(0.0) - stack(&span, list) / 2.0;
for &c in list {
let s = span.get(c).copied().unwrap_or(0.0);
let mid = top + s / 2.0;
let at = Point::new(if side { x - width(c) } else { x }, mid - height(c) / 2.0);
top += s + MIND_GAP_Y;
if !(at.x.is_finite() && at.y.is_finite() && mid.is_finite()) {
continue;
}
if let (Some(m), Some(col), Some(o)) = (centre.get_mut(c), column.get_mut(c), ok.get_mut(c)) {
*m = mid;
*col = if side { x - widest - MIND_GAP_X } else { x + widest + MIND_GAP_X };
*o = true;
}
if let Some(b) = nodes.get(c) {
out.push((b.id, at));
}
}
}
}
out
}
+99
View File
@@ -0,0 +1,99 @@
//! Mind map layout (`board_mindmap`): columns 88 apart, siblings 48 apart, stacks centred on their
//! parents (#2226).
use figcraft_geom::{Point, Rect};
use crate::NodeId;
use crate::board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_NODES, MindBox, mind_layout};
/// The first node, always at the origin, 200 x 36.
fn root() -> MindBox {
MindBox { id: NodeId(1), rect: Rect::new(0.0, 0.0, 200.0, 36.0), parent: None, left: false }
}
/// A node `w` x `h` whose current top is `y` (only its middle, which orders siblings, counts).
fn node(id: u64, parent: usize, (w, h): (f64, f64), y: f64) -> MindBox {
MindBox { id: NodeId(id), rect: Rect::new(0.0, y, w, y + h), parent: Some(parent), left: false }
}
fn at(placed: &[(NodeId, Point)], id: u64) -> (f64, f64) {
let p = placed.iter().find(|(n, _)| *n == NodeId(id)).map(|(_, p)| *p).unwrap_or_else(|| panic!("node {id} not placed in {placed:?}"));
(p.x, p.y)
}
/// The root and three children (100, 60 and 80 wide) whose middles are in that order; `middle` is
/// the second child's size.
fn three(middle: (f64, f64)) -> Vec<MindBox> {
vec![root(), node(2, 0, (100.0, 24.0), 0.0), node(3, 0, middle, 22.0 - middle.1 / 2.0), node(4, 0, (80.0, 24.0), 20.0)]
}
/// The root, two children (100 and 60 wide) under it, two more under the first and one under the second.
fn six() -> Vec<MindBox> {
vec![
root(),
node(2, 0, (100.0, 24.0), 0.0),
node(3, 0, (60.0, 24.0), 10.0),
node(4, 1, (40.0, 24.0), 0.0),
node(5, 1, (40.0, 24.0), 10.0),
node(6, 2, (40.0, 24.0), 0.0),
]
}
#[test]
fn three_children_stand_88_right_of_the_root_72_apart_centred_on_it() {
assert_eq!((MIND_GAP_X, MIND_GAP_Y), (88.0, 48.0));
let placed = mind_layout(&three((60.0, 24.0)));
assert_eq!([at(&placed, 2), at(&placed, 3), at(&placed, 4)], [(288.0, -66.0), (288.0, 6.0), (288.0, 78.0)]);
assert!(placed.iter().all(|(n, _)| *n != NodeId(1)), "the first node stays where it is");
}
#[test]
fn a_taller_node_pushes_its_neighbours_half_its_growth_each_way() {
let placed = mind_layout(&three((60.0, 72.0)));
assert_eq!([at(&placed, 2), at(&placed, 3), at(&placed, 4)], [(288.0, -90.0), (288.0, -18.0), (288.0, 102.0)]);
}
#[test]
fn grandchildren_share_a_column_past_the_widest_sibling_and_their_parents_make_room() {
let nodes = six();
let placed = mind_layout(&nodes);
// 476 = 288 + 100 + 88, although B is only 60 wide.
let got: Vec<(f64, f64)> = (2..=6).map(|i| at(&placed, i)).collect();
assert_eq!(got, [(288.0, -30.0), (288.0, 78.0), (476.0, -66.0), (476.0, 6.0), (476.0, 78.0)]);
}
#[test]
fn left_children_mirror_the_right_ones() {
let mut l = node(2, 0, (80.0, 24.0), 0.0);
l.left = true;
let placed = mind_layout(&[root(), l, node(3, 1, (50.0, 24.0), 0.0)]);
assert_eq!((at(&placed, 2), at(&placed, 3)), ((-168.0, 6.0), (-306.0, 6.0)));
}
#[test]
fn the_layout_is_a_fixed_point_ties_go_by_id_and_junk_is_skipped() {
let nodes = six();
let placed = mind_layout(&nodes);
let again: Vec<MindBox> = nodes
.iter()
.map(|b| {
let p = placed.iter().find(|(n, _)| *n == b.id).map_or(b.rect.origin(), |(_, p)| *p);
MindBox { rect: Rect::from_origin_size(p, b.rect.size()), ..*b }
})
.collect();
assert_eq!(mind_layout(&again), placed, "a laid out map is left as it is");
// The same height: the lower id goes first.
let tied = mind_layout(&[root(), node(9, 0, (10.0, 24.0), 5.0), node(7, 0, (10.0, 24.0), 5.0)]);
assert!(at(&tied, 7).1 < at(&tied, 9).1);
// Junk: nothing placed, nothing panics.
assert!(mind_layout(&[]).is_empty());
let mut nan = three((60.0, 24.0));
nan[2].rect = Rect::new(f64::NAN, 0.0, 1.0, 1.0);
assert!(mind_layout(&nan).is_empty());
let mut orphan = three((60.0, 24.0));
orphan.push(node(8, 9, (10.0, 24.0), 0.0));
assert!(!mind_layout(&orphan).iter().any(|(n, _)| *n == NodeId(8)), "a parent that doesn't come first");
let mut huge = vec![root()];
huge.extend((0..MIND_MAX_NODES as u64).map(|i| node(i + 2, 0, (10.0, 24.0), i as f64)));
assert!(mind_layout(&huge).is_empty());
}
+4
View File
@@ -9,6 +9,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod board;
mod board_mindmap;
mod board_route;
pub mod colors;
pub mod comments;
@@ -27,6 +28,7 @@ pub mod vector_faces;
pub mod vector_regions;
pub use board::*;
pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout};
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
pub use colors::*;
pub use comments::*;
@@ -1314,6 +1316,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap<NodeId, NodeId>) {
#[cfg(test)]
mod blur_tests;
#[cfg(test)]
mod board_mindmap_tests;
#[cfg(test)]
mod board_route_tests;
#[cfg(test)]
mod board_shape_tests;
+70 -7
View File
@@ -14,6 +14,40 @@ use crate::{Result, bad};
/// Deepest params nesting the resolver walks before giving up.
const MAX_DEPTH: usize = 64;
/// How much referenced data (values and string bytes) the params of one step may copy in.
const MAX_EXPANDED: usize = 8 << 20;
/// What copying `v` costs: its values and string bytes, counting stops past `limit`.
fn weight(v: &Value, limit: usize) -> usize {
let mut total = 0usize;
let mut stack = vec![v];
while let Some(v) = stack.pop() {
total += 1;
match v {
Value::String(s) => total += s.len(),
// Checked before they are queued, so a huge list can't grow the worklist past the limit.
Value::Array(a) => {
if total + a.len() > limit {
return total + a.len();
}
stack.extend(a);
}
Value::Object(o) => {
total += o.keys().map(String::len).sum::<usize>();
if total + o.len() > limit {
return total + o.len();
}
stack.extend(o.values());
}
_ => {}
}
if total > limit {
return total;
}
}
total
}
/// One step of a batch: a command, its params and the name later steps can call it by.
#[derive(Clone, Debug, PartialEq)]
pub struct BatchStep {
@@ -99,30 +133,32 @@ impl BatchScope {
/// `params` of the next step with every reference in it replaced.
pub(crate) fn resolve(&self, params: &Value) -> Result<Value> {
self.resolve_in(params, 0)
let mut left = MAX_EXPANDED;
self.resolve_in(params, 0, &mut left)
}
fn resolve_in(&self, v: &Value, depth: usize) -> Result<Value> {
/// `left`: how much referenced data one step's params may still copy in.
fn resolve_in(&self, v: &Value, depth: usize, left: &mut usize) -> Result<Value> {
let step = self.next_step();
if depth > MAX_DEPTH {
return Err(bad("command.batch", format!("step {step}: params nest deeper than {MAX_DEPTH} levels")));
}
match v {
Value::Object(o) if o.contains_key("$step") || o.contains_key("$ref") => self.reference(o),
Value::Object(o) if o.contains_key("$step") || o.contains_key("$ref") => self.reference(o, left),
Value::Object(o) => {
let mut out = Map::with_capacity(o.len());
for (k, x) in o {
out.insert(k.clone(), self.resolve_in(x, depth + 1)?);
out.insert(k.clone(), self.resolve_in(x, depth + 1, left)?);
}
Ok(Value::Object(out))
}
Value::Array(a) => a.iter().map(|x| self.resolve_in(x, depth + 1)).collect::<Result<Vec<_>>>().map(Value::Array),
Value::Array(a) => a.iter().map(|x| self.resolve_in(x, depth + 1, left)).collect::<Result<Vec<_>>>().map(Value::Array),
_ => Ok(v.clone()),
}
}
/// The value a `{"$step": n}` or `{"$ref": "name"}` object (with an optional `field`) stands for.
fn reference(&self, o: &Map<String, Value>) -> Result<Value> {
fn reference(&self, o: &Map<String, Value>, left: &mut usize) -> Result<Value> {
let step = self.next_step();
let fail = |msg: String| bad("command.batch", format!("step {step}: {msg}"));
let key = if o.contains_key("$step") { "$step" } else { "$ref" };
@@ -153,7 +189,10 @@ impl BatchScope {
Some(_) => return Err(fail("`field` must be a string".into())),
};
let result = self.results.get(n).ok_or_else(|| fail(format!("{who} has no result")))?;
lookup(result, path).cloned().map_err(|why| fail(format!("{who}'s result has no `{path}`{why}")))
let value = lookup(result, path).map_err(|why| fail(format!("{who}'s result has no `{path}`{why}")))?;
// Counted before copying: a few references to one big result can't multiply it.
*left = left.checked_sub(weight(value, *left)).ok_or_else(|| fail("the references copy more than the batch may expand".into()))?;
Ok(value.clone())
}
/// Most step names a missing-reference error lists.
@@ -218,3 +257,27 @@ fn kind(v: &Value) -> &'static str {
Value::Object(_) => "an object",
}
}
#[cfg(test)]
mod expansion_tests {
use super::*;
use serde_json::json;
#[test]
fn references_copy_a_bounded_amount_into_one_step() {
let steps = [BatchStep::new("a", json!({})), BatchStep::new("b", json!({}))];
let mut scope = BatchScope::new(&steps).unwrap();
// A result of about 1 MB.
scope.push(json!({"ids": vec!["x".repeat(1000); 1000]}));
let refs = |n: usize| json!({"all": vec![json!({"$step": 0, "field": "ids"}); n]});
assert!(scope.resolve(&refs(4)).is_ok());
let err = scope.resolve(&refs(200)).unwrap_err().to_string();
assert!(err.contains("more than the batch may expand"), "{err}");
}
#[test]
fn a_huge_list_is_refused_before_it_is_queued() {
assert!(weight(&json!(vec![0; 100_000]), 1000) > 1000);
assert!(weight(&json!(vec![0; 10]), 1000) <= 1000);
}
}
+19 -8
View File
@@ -165,6 +165,14 @@ pub fn node_json(doc: &Document, id: NodeId, depth: usize) -> Value {
/// A node's selected properties, applied at every level of its subtree.
pub fn node_json_with_options(doc: &Document, id: NodeId, depth: usize, options: &InspectOptions) -> Value {
node_json_in(doc, id, depth, options, &GridCells::default())
}
/// The cells of the grid frames met so far in one inspection, so a grid's geometry is worked out
/// once, not once per child.
type GridCells = std::cell::RefCell<std::collections::HashMap<NodeId, std::collections::HashMap<NodeId, figcraft_layout::GridCell>>>;
fn node_json_in(doc: &Document, id: NodeId, depth: usize, options: &InspectOptions, grids: &GridCells) -> Value {
let Some(n) = doc.node(id) else { return Value::Null };
let mut v = json!({"id": n.id});
let Some(o) = v.as_object_mut() else { return v };
@@ -176,7 +184,7 @@ pub fn node_json_with_options(doc: &Document, id: NodeId, depth: usize, options:
if !n.is_page() {
base_props(doc, n, id, o, options);
paint_props(n, o, options);
layout_props(doc, n, o, options);
layout_props(doc, n, o, options, grids);
dev_props(doc, n, o, options);
}
// Layer data written with `node.set {props: {pluginData}}` (pages too).
@@ -189,7 +197,7 @@ pub fn node_json_with_options(doc: &Document, id: NodeId, depth: usize, options:
}
if !n.children.is_empty() {
if depth > 0 {
o.insert("children".into(), Value::Array(n.children.iter().map(|c| node_json_with_options(doc, *c, depth - 1, options)).collect()));
o.insert("children".into(), Value::Array(n.children.iter().map(|c| node_json_in(doc, *c, depth - 1, options, grids)).collect()));
} else {
o.insert("childCount".into(), json!(n.children.len()));
}
@@ -286,7 +294,7 @@ fn paint_props(n: &Node, o: &mut serde_json::Map<String, Value>, options: &Inspe
}
}
fn layout_props(doc: &Document, n: &Node, o: &mut serde_json::Map<String, Value>, options: &InspectOptions) {
fn layout_props(doc: &Document, n: &Node, o: &mut serde_json::Map<String, Value>, options: &InspectOptions, grids: &GridCells) {
if let Some(l) = &n.layout {
insert_prop(o, options, "layout", || camel(serde_json::to_value(l).unwrap_or(Value::Null)));
}
@@ -303,11 +311,14 @@ fn layout_props(doc: &Document, n: &Node, o: &mut serde_json::Map<String, Value>
insert_prop(o, options, k, || json!(v));
}
}
if let Some(cell) = (parent_al && options.includes("gridCell"))
.then(|| n.parent.and_then(|p| figcraft_layout::grid_geometry(doc, p)))
.flatten()
.and_then(|g| g.cells.into_iter().find(|c| c.id == n.id))
{
let cell = (parent_al && options.includes("gridCell")).then_some(n.parent).flatten().and_then(|p| {
let mut grids = grids.borrow_mut();
let cells = grids
.entry(p)
.or_insert_with(|| figcraft_layout::grid_geometry(doc, p).map(|g| g.cells.into_iter().map(|c| (c.id, c)).collect()).unwrap_or_default());
cells.get(&n.id).copied()
});
if let Some(cell) = cell {
insert_prop(o, options, "gridCell", || {
json!({"column": cell.column, "row": cell.row, "columnSpan": cell.column_span, "rowSpan": cell.row_span,
"anchored": cl.grid_column.is_some() || cl.grid_row.is_some(), "alignH": cl.grid_align_h, "alignV": cl.grid_align_v})
+385
View File
@@ -0,0 +1,385 @@
//! Mind maps (#2226): `board.mindMap` and `board.mindMapAdd` make nodes and branches, and the
//! normalize pass lays a touched map out again from its first node after every edit.
use figcraft_color::{Color, Paint};
use figcraft_doc::{BoardItem, Connector, Document, END_GAP, End, LetterSpacing, LineHeight, NodeId, NodeKind, Routing, Side, StrokeCap};
use figcraft_geom::{Point, Rect};
use serde_json::{Value, json};
use crate::Session;
use crate::board::text_of;
use crate::board_tests::{board, connector, drawn, id, near, node};
use crate::collab_live_tests::Room;
fn bx(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().world_bounds(id).unwrap()
}
fn same(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
/// `board.mindMap` at (100, 200): the first node, its three children and their branches.
fn map(s: &mut Session) -> (NodeId, [NodeId; 3], [NodeId; 3]) {
let out = s.execute("board.mindMap", &json!({"x": 100, "y": 200})).unwrap();
let kids: Vec<Value> = out["children"].as_array().unwrap().clone();
let (c, k): (Vec<NodeId>, Vec<NodeId>) = kids.iter().map(|v| (id(v, "id"), id(v, "connector"))).unzip();
(id(&out, "id"), [c[0], c[1], c[2]], [k[0], k[1], k[2]])
}
fn text_data(s: &Session, n: NodeId) -> figcraft_doc::TextData {
let t = text_of(s.doc().unwrap(), n).unwrap();
match node(s, t).kind {
NodeKind::Text(td) => td,
other => panic!("not text: {other:?}"),
}
}
fn is_mind_node(s: &Session, n: NodeId) -> bool {
node(s, n).board == Some(BoardItem::MindNode)
}
/// The nodes hanging off `parent`, top to bottom, in `doc`.
fn kids(doc: &Document, parent: NodeId) -> Vec<NodeId> {
let mut v: Vec<(f64, NodeId)> = doc
.nodes()
.filter_map(|n| match &n.board {
Some(BoardItem::Connector(Connector { from: End::Node { node, .. }, to: End::Node { node: to, .. }, branch: true, .. }))
if *node == parent =>
{
doc.world_bounds(*to).map(|b| (b.center().y, *to))
}
_ => None,
})
.collect();
v.sort_by(|a, b| a.0.total_cmp(&b.0));
v.into_iter().map(|p| p.1).collect()
}
fn places(s: &Session, ids: &[NodeId]) -> Vec<Rect> {
ids.iter().map(|i| bx(s, *i)).collect()
}
fn branches(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().nodes().filter(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)).map(|n| n.id).collect()
}
/// Starter child `i` (`k`, on branch `line`) of the first node: its text, its place and its branch.
fn check_child(s: &Session, root: NodeId, (k, line): (NodeId, NodeId), i: usize) {
let r = bx(s, root);
let td = text_data(s, k);
assert_eq!(td.characters, ["Idea 1", "Idea 2", "Idea 3"][i]);
assert_eq!((td.style.font_size, td.style.font_style.as_str()), (16.0, "Medium"));
assert_eq!((td.style.line_height, td.style.letter_spacing), (LineHeight::Percent(150.0), LetterSpacing::Percent(-1.1)));
let b = bx(s, k);
assert!(same(b.x0, r.x1 + 88.0), "child {i}: 88 right of the root");
assert_eq!(b.height(), 24.0);
let t = bx(s, text_of(s.doc().unwrap(), k).unwrap());
assert!(same(b.width(), t.width()), "child {i}: the node is its text, no padding");
assert!(is_mind_node(s, k));
let want = Connector {
from: End::Node { node: root, side: Side::Right, at: None },
to: End::Node { node: k, side: Side::Left, at: None },
routing: Routing::Curved,
path: None,
branch: true,
};
assert_eq!(connector(s, line), want);
let l = node(s, line);
assert_eq!((l.stroke.cap_start, l.stroke.cap_end), (StrokeCap::Round, StrokeCap::Round));
assert_eq!((l.stroke.weight, l.strokes), (4.0, vec![Paint::solid(Color::from_rgb8_const(0x75, 0x75, 0x75))]));
let pts = drawn(s, line);
assert!(near(pts[0], Point::new(r.x1 + END_GAP, r.center().y)), "{pts:?}");
assert!(near(*pts.last().unwrap(), Point::new(b.x0 - END_GAP, b.center().y)), "{pts:?}");
}
#[test]
fn a_mind_map_is_a_first_node_with_three_children_on_branches() {
let mut s = board();
let before = s.doc().unwrap().ids().count();
let depth = s.undo_depth().0;
let (root, kids, lines) = map(&mut s);
assert_eq!(node(&s, root).board, Some(BoardItem::MindNode));
assert!(node(&s, root).is_board_atom());
let r = bx(&s, root);
assert_eq!((r.x0, r.y0), (100.0, 200.0));
let td = text_data(&s, root);
assert_eq!((td.characters.as_str(), td.style.font_size, td.style.font_style.as_str()), ("Topic", 24.0, "Bold"));
assert_eq!((td.style.line_height, td.style.letter_spacing), (LineHeight::Percent(150.0), LetterSpacing::Percent(-1.9)));
assert_eq!(r.height(), 36.0, "one line at 150%");
let text = text_of(s.doc().unwrap(), root).unwrap();
assert_eq!(node(&s, text).fills, vec![Paint::solid(Color::from_rgb8_const(0x1E, 0x1E, 0x1E))]);
for (i, pair) in kids.into_iter().zip(lines).enumerate() {
check_child(&s, root, pair, i);
}
let h = bx(&s, kids[0]).height();
assert!(same(bx(&s, kids[1]).center().y, r.center().y));
assert!(same(bx(&s, kids[0]).center().y, r.center().y - h - 48.0));
assert!(same(bx(&s, kids[2]).center().y, r.center().y + h + 48.0));
assert_eq!(s.selection(), vec![root]);
assert_eq!(s.undo_depth().0, depth + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().ids().count(), before);
}
#[test]
fn a_new_child_goes_below_its_siblings_and_the_stack_stays_centred() {
let mut s = board();
let (root, kids3, _) = map(&mut s);
let h = bx(&s, kids3[0]).height();
let was = places(&s, &kids3);
s.ui_requests.clear();
let out = s.execute("board.mindMapAdd", &json!({"id": root, "text": "Four", "edit": true})).unwrap();
let new = id(&out, "id");
assert!(is_mind_node(&s, new));
assert_eq!(text_data(&s, new).style.font_size, 16.0);
let order = kids(s.doc().unwrap(), root);
assert_eq!(order, [kids3[0], kids3[1], kids3[2], new]);
let cy: Vec<f64> = order.iter().map(|n| bx(&s, *n).center().y).collect();
assert!(cy.windows(2).all(|w| same(w[1] - w[0], h + 48.0)), "{cy:?}");
assert!(same((cy[0] + cy[3]) / 2.0, bx(&s, root).center().y));
assert!(same(bx(&s, kids3[0]).y0, was[0].y0 - (h + 48.0) / 2.0), "the first one moved up 36");
assert_eq!(s.selection(), vec![new]);
assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(new)));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(places(&s, &kids3), was, "the three are back exactly");
// Without an id the selected first node is the one.
s.execute("select.set", &json!({"ids": [root]})).unwrap();
s.execute("board.mindMapAdd", &json!({})).unwrap();
assert_eq!(kids(s.doc().unwrap(), root).len(), 4);
}
#[test]
fn a_childs_child_starts_the_next_column_and_a_sibling_goes_right_after() {
let mut s = board();
let (root, [c0, c1, c2], _) = map(&mut s);
let h = bx(&s, c0).height();
let g1 = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id");
let g2 = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id");
let column = [c0, c1, c2].iter().map(|n| bx(&s, *n).x1).fold(f64::MIN, f64::max) + 88.0;
assert!(same(bx(&s, g1).x0, column) && same(bx(&s, g2).x0, column), "past the widest of the three");
assert!(same(bx(&s, g2).center().y - bx(&s, g1).center().y, h + 48.0));
assert!(same((bx(&s, g1).center().y + bx(&s, g2).center().y) / 2.0, bx(&s, c0).center().y));
for g in [g1, g2] {
let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(g))).unwrap().id;
assert!(matches!(connector(&s, line).from, End::Node { node, side: Side::Right, .. } if node == c0));
}
assert!(same(bx(&s, c1).center().y - bx(&s, c0).center().y, (2.0 * h + 48.0) / 2.0 + 48.0 + h / 2.0), "108 below");
let new = id(&s.execute("board.mindMapAdd", &json!({"id": c1, "relation": "sibling"})).unwrap(), "id");
let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(new))).unwrap().id;
assert!(matches!(connector(&s, line).from, End::Node { node, .. } if node == root));
assert_eq!(kids(s.doc().unwrap(), root), [c0, c1, new, c2]);
}
#[test]
fn more_lines_push_the_siblings_apart() {
let mut s = board();
let (root, [c0, c1, c2], _) = map(&mut s);
let (h, was) = (bx(&s, c1).height(), places(&s, &[c0, c1, c2]));
let t = text_of(s.doc().unwrap(), c1).unwrap();
s.execute("node.set", &json!({"id": t, "props": {"characters": "one\ntwo\nthree"}})).unwrap();
let h3 = bx(&s, c1).height();
assert_eq!((h, h3), (24.0, 72.0));
assert!(same(bx(&s, c1).center().y, bx(&s, root).center().y));
for k in [c0, c2] {
assert!(same((bx(&s, k).center().y - bx(&s, c1).center().y).abs(), (h + h3) / 2.0 + 48.0));
}
assert!(same(bx(&s, c0).y0, was[0].y0 - (h3 - h) / 2.0), "24 up");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(places(&s, &[c0, c1, c2]), was);
}
#[test]
fn the_first_node_carries_the_map_and_a_child_moved_by_hand_goes_back_or_swaps() {
let mut s = board();
let (root, kids3, lines) = map(&mut s);
let was = places(&s, &kids3);
s.execute("transform.move", &json!({"ids": [root], "dx": 50, "dy": 30})).unwrap();
for (k, w) in kids3.iter().zip(&was) {
let b = bx(&s, *k);
assert!(same(b.x0, w.x0 + 50.0) && same(b.y0, w.y0 + 30.0), "{b:?} from {w:?}");
}
for l in lines {
assert!(near(drawn(&s, l)[0], Point::new(bx(&s, root).x1 + END_GAP, bx(&s, root).center().y)));
}
let now = places(&s, &kids3);
s.execute("transform.move", &json!({"ids": [kids3[2]], "dx": 300, "dy": 5})).unwrap();
assert_eq!(places(&s, &kids3), now, "it goes back");
s.execute("transform.move", &json!({"ids": [kids3[0]], "dx": 0, "dy": 100})).unwrap();
assert_eq!(kids(s.doc().unwrap(), root), [kids3[1], kids3[0], kids3[2]], "past the middle one's middle: they swap");
assert!(same(bx(&s, kids3[1]).center().y, bx(&s, root).center().y - 72.0));
}
#[test]
fn a_deleted_node_leaves_its_children_in_place_and_takes_its_branches() {
let mut s = board();
let (root, [c0, c1, c2], _) = map(&mut s);
let h = bx(&s, c0).height();
let g = id(&s.execute("board.mindMapAdd", &json!({"id": c1})).unwrap(), "id");
let at = bx(&s, g);
let (undo, _) = s.undo_depth();
s.execute("edit.delete", &json!({"ids": [c1]})).unwrap();
let left = branches(&s);
assert_eq!(left.len(), 2, "the root's two others");
for l in &left {
assert!(!matches!(connector(&s, *l).to, End::Node { node, .. } if node == c1 || node == g), "none to the gone node or its child");
}
assert_eq!(bx(&s, g), at, "the child stays where it was");
assert!(is_mind_node(&s, g));
let r = bx(&s, root).center().y;
assert!(same(bx(&s, c0).center().y, r - (h + 48.0) / 2.0) && same(bx(&s, c2).center().y, r + (h + 48.0) / 2.0));
let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(c2))).unwrap().id;
let spot = bx(&s, c2);
s.execute("edit.delete", &json!({"ids": [line]})).unwrap();
assert_eq!(bx(&s, c2), spot, "a detached node stays");
assert!(same(bx(&s, c0).center().y, r));
assert_eq!(branches(&s).len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth().0, undo);
assert_eq!(branches(&s).len(), 4);
assert!(s.doc().unwrap().contains(c1));
}
#[test]
fn two_people_adding_at_once_end_with_one_layout() {
let mut s = board();
let (root, [c0, ..], _) = map(&mut s);
let h = bx(&s, c0).height();
let mut room = Room::new(s.doc().unwrap().clone(), 2, 7);
for i in 0..2 {
room.s(i).execute("board.mindMapAdd", &json!({"id": root})).unwrap();
}
room.settle();
room.check();
let doc = room.server.document();
let order = kids(doc, root);
assert_eq!(order.len(), 5);
let centres = |doc: &Document, order: &[NodeId]| order.iter().map(|n| doc.world_bounds(*n).unwrap().center().y).collect::<Vec<f64>>();
let cy = centres(doc, &order);
assert!(cy.windows(2).all(|w| w[1] > w[0] && same(w[1] - w[0], h + 48.0)), "{cy:?}");
assert!(same((cy[0] + cy[4]) / 2.0, doc.world_bounds(root).unwrap().center().y));
// One makes a child three lines tall while the other adds one.
let t = text_of(doc, order[1]).unwrap();
room.s(0).execute("node.set", &json!({"id": t, "props": {"characters": "one\ntwo\nthree"}})).unwrap();
room.s(1).execute("board.mindMapAdd", &json!({"id": root})).unwrap();
room.settle();
room.check();
let doc = room.server.document();
let order = kids(doc, root);
assert_eq!(order.len(), 6);
let (boxes, mut gap_ok) = (order.iter().map(|n| doc.world_bounds(*n).unwrap()).collect::<Vec<Rect>>(), true);
for w in boxes.windows(2) {
gap_ok &= same(w[1].y0 - w[0].y1, 48.0);
}
assert!(gap_ok, "48 between every pair: {boxes:?}");
assert!(boxes.iter().any(|b| same(b.height(), 3.0 * h)));
let (top, bottom) = (boxes[0].y0, boxes[5].y1);
assert!(same((top + bottom) / 2.0, doc.world_bounds(root).unwrap().center().y));
}
#[test]
fn refusals_saved_files_and_a_second_pass_changes_nothing() {
let mut d = Session::new();
d.execute("file.new", &json!({})).unwrap();
for cmd in ["board.mindMap", "board.mindMapAdd"] {
assert!(matches!(d.execute(cmd, &json!({})), Err(crate::EngineError::Disabled(..))), "{cmd} on a design file");
}
let mut s = board();
let (root, ..) = map(&mut s);
let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id");
for p in [json!({"id": sticky}), json!({"id": root, "relation": "cousin"}), json!({"id": root, "relation": "sibling"})] {
assert!(s.execute("board.mindMapAdd", &p).is_err(), "{p}");
}
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("board.mindMapAdd", &json!({})).is_err(), "nothing selected");
let twenty_one: Vec<String> = (0..21).map(|i| format!("n{i}")).collect();
assert!(s.execute("board.mindMap", &json!({"children": twenty_one})).is_err());
assert!(s.execute("board.mindMap", &json!({"children": "x"})).is_err());
let doc = s.doc().unwrap();
let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap();
assert_eq!(back.nodes().filter(|n| n.board == Some(BoardItem::MindNode)).count(), 4);
assert_eq!(back.nodes().filter(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)).count(), 3);
// An ordinary connector writes no `branch`; a file without it reads `false`.
let mut plain = board();
let a = id(&plain.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap(), "id");
let b = id(&plain.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id");
plain.execute("board.connector", &json!({"from": a, "to": b})).unwrap();
assert!(!figcraft_format::to_json(plain.doc().unwrap()).unwrap().to_string().contains("\"branch\""));
let item: BoardItem = serde_json::from_value(json!({"type": "connector", "from": {"x": 0, "y": 0}, "to": {"x": 1, "y": 1}})).unwrap();
assert!(matches!(item, BoardItem::Connector(c) if !c.branch));
// Every layer touched again: a laid out map is not an edit.
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, doc);
assert!(again == *doc, "a second pass changes nothing");
}
/// Every layer touched again on a copy of `s`'s document: a map in place is left as it is.
fn second_pass_is_a_no_op(s: &Session) {
let doc = s.doc().unwrap();
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, doc);
assert!(again == *doc, "a second pass changes nothing");
}
#[test]
fn a_map_around_its_own_container_stays_put() {
let mut s = board();
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 800, "height": 600})).unwrap(), "id");
let out = s.execute("board.mindMap", &json!({"parent": sec, "x": 40, "y": 40})).unwrap();
let line = id(&out["children"][1], "connector");
s.execute("board.reattach", &json!({"id": line, "end": "to", "target": sec})).unwrap();
let was = bx(&s, sec);
second_pass_is_a_no_op(&s);
s.execute("node.set", &json!({"id": id(&out, "id"), "props": {"name": "again"}})).unwrap();
assert_eq!(bx(&s, sec), was, "the section stays where it is");
second_pass_is_a_no_op(&s);
}
#[test]
fn a_branch_moved_by_its_start_leaves_no_gap_and_odd_structures_settle() {
let mut s = board();
let (root, [c0, c1, c2], lines) = map(&mut s);
let (h, at) = (bx(&s, c1).height(), bx(&s, c1));
s.execute("board.reattach", &json!({"id": lines[1], "end": "from", "target": {"x": 900, "y": 900}})).unwrap();
assert_eq!(branches(&s).len(), 2, "one branch fewer");
assert_eq!(bx(&s, c1), at, "that child stays where it was");
let r = bx(&s, root).center().y;
assert!(same(bx(&s, c0).center().y, r - (h + 48.0) / 2.0), "{:?}", bx(&s, c0));
assert!(same(bx(&s, c2).center().y, r + (h + 48.0) / 2.0), "{:?}", bx(&s, c2));
second_pass_is_a_no_op(&s);
// Two branches arrive at one node: the lower connector id stays its parent.
let mut s = board();
let (root, [c0, c1, _], lines) = map(&mut s);
let g = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id");
let gl = branches(&s).into_iter().find(|b| !lines.contains(b)).unwrap();
s.execute("board.reattach", &json!({"id": gl, "end": "to", "target": c1})).unwrap();
assert_eq!(kids(s.doc().unwrap(), root).len(), 3);
assert!(same(bx(&s, c1).x0, bx(&s, root).x1 + 88.0), "c1 stays in the root's column");
assert!(is_mind_node(&s, g));
second_pass_is_a_no_op(&s);
// A cycle: nothing in it moves, and nothing changes after.
let mut s = board();
let (_, [c0, ..], lines) = map(&mut s);
let g = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id");
let gg = id(&s.execute("board.mindMapAdd", &json!({"id": g})).unwrap(), "id");
s.execute("board.reattach", &json!({"id": lines[0], "end": "from", "target": gg})).unwrap();
let ring = places(&s, &[c0, g, gg]);
second_pass_is_a_no_op(&s);
assert_eq!(places(&s, &[c0, g, gg]), ring);
}
#[test]
fn the_caps_refuse_what_is_too_far_and_cut_what_is_too_long() {
let mut s = board();
assert!(s.execute("board.mindMap", &json!({"x": 2.0e9})).is_err());
assert!(s.execute("board.mindMap", &json!({"y": -2.0e9})).is_err());
let long = "x".repeat(600);
let out = s.execute("board.mindMap", &json!({"text": long, "children": [long]})).unwrap();
assert_eq!(text_data(&s, id(&out, "id")).characters.chars().count(), 500);
assert_eq!(text_data(&s, id(&out["children"][0], "id")).characters.chars().count(), 500);
}
+3
View File
@@ -182,6 +182,9 @@ fn table_edits_add_and_remove_rows_and_columns_keeping_text() {
#[test]
fn a_double_click_types_in_the_cell_and_its_row_grows_with_the_text() {
// Measure with system fonts when the optional craft-fonts checkout is absent,
// without depending on another test having scanned them first.
figcraft_text::scan_system_fonts();
let mut s = board();
let r = s.execute("board.table", &json!({"x": 0, "y": 0})).unwrap();
let t = id(&r, "id");
+2
View File
@@ -206,6 +206,7 @@ fn routes_are_the_same_for_the_same_document() {
to: End::Point { x: 300.0, y: 500.0 },
routing: Routing::Elbow,
path: None,
branch: false,
};
let doc = s.doc().unwrap();
let r = route(doc, &c).unwrap();
@@ -357,6 +358,7 @@ fn board_commands_survive_junk() {
json!({"path": "M0 0 L 1e308 1e308", "points": [[0, 0], [1e308, 1]]}),
json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}),
json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}),
json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}),
];
let ids: Vec<&str> = crate::cmd::all_commands()
.iter()
+12 -3
View File
@@ -96,7 +96,8 @@ fn routes_take_named_sides_and_free_points() {
let a = id(&s.execute("board.shape", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(), "id");
let b = id(&s.execute("board.shape", &json!({"x": 300, "y": 300, "width": 100, "height": 100})).unwrap(), "id");
let doc = s.doc().unwrap();
let elbow = |from, to| route(doc, &figcraft_doc::Connector { from, to, routing: figcraft_doc::Routing::Elbow, path: None }).unwrap();
let elbow =
|from, to| route(doc, &figcraft_doc::Connector { from, to, routing: figcraft_doc::Routing::Elbow, path: None, branch: false }).unwrap();
let side = |n, side| End::Node { node: n, side, at: None };
let p = |x, y| End::Point { x, y };
let pt = Point::new;
@@ -109,8 +110,16 @@ fn routes_take_named_sides_and_free_points() {
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 40.0)), vec![pt(0.0, 0.0), pt(50.0, 0.0), pt(50.0, 40.0), pt(100.0, 40.0)]);
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 0.0)), vec![pt(0.0, 0.0), pt(100.0, 0.0)]);
// An automatic side faces the other end.
let straight =
route(doc, &figcraft_doc::Connector { from: side(a, Side::Auto), to: p(50.0, 500.0), routing: figcraft_doc::Routing::Straight, path: None });
let straight = route(
doc,
&figcraft_doc::Connector {
from: side(a, Side::Auto),
to: p(50.0, 500.0),
routing: figcraft_doc::Routing::Straight,
path: None,
branch: false,
},
);
assert_eq!(straight.unwrap(), vec![pt(50.0, 104.0), pt(50.0, 500.0)]);
assert_eq!(Side::from_id("TOP"), Some(Side::Top));
assert_eq!(Side::from_id("inside"), None);
+16
View File
@@ -25,6 +25,7 @@ mod connectors;
mod derived;
mod edit;
mod items;
mod mindmap;
mod reshape;
mod tools;
@@ -70,6 +71,7 @@ pub(crate) use items::add_text;
pub use items::{CONNECTED_GAP, connected_place};
use items::{add_connected, ink_cmd, next_sticky, shape_cmd, stamp_cmd, sticky_cmd};
pub use items::{edit_text, owner_of_text, sticky_font_size, text_of};
pub(crate) use mindmap::settle_mind_maps;
pub(crate) use reshape::path_handle_at;
pub use reshape::selected_connector_handles;
@@ -176,6 +178,20 @@ pub fn specs() -> Vec<CommandSpec> {
true,
reshape::reshape
),
spec!(
"board.mindMap",
"Mind map",
"{x?, y? (the first node's top-left in the parent; default the middle of the view), text? (default Topic), children? (their texts, at most 20; default Idea 1, Idea 2, Idea 3), parent?, edit? (start typing in the first node; default false)} → {id, text, children: [{id, text, connector}...]} a first node with children on its right, joined by branches; the map lays itself out",
true,
mindmap::mind_map_cmd
),
spec!(
"board.mindMapAdd",
"Add mind map node",
"{id? (a mind map node; default the selected or edited one), relation?: child|sibling (default child), text?, edit? (start typing in it; default false)} → {id, text, connector} a child below the node's other children, or a sibling right after it; the map lays itself out again",
true,
mindmap::mind_map_add
),
spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd),
spec!(
"board.stamp",
+1 -1
View File
@@ -65,7 +65,7 @@ pub(super) fn connector_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let end = cap_of(cmd, p, "endCap")?.unwrap_or(CAPS.1);
let page = s.page()?;
let doc = s.doc_mut()?;
let id = make(doc, page, Connector { from, to, routing, path: None }, (start, end))?;
let id = make(doc, page, Connector { from, to, routing, path: None, branch: false }, (start, end))?;
let mut out = json!({"id": id});
if let Some(text) = string(p, "label").filter(|t| !t.trim().is_empty()) {
out["label"] = json!(set_label(doc, id, &text)?);
+2 -2
View File
@@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
n.strokes = vec![Paint::solid(line_shade(color))];
}
BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))],
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table => continue,
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue,
}
changed.push(id);
}
@@ -132,7 +132,7 @@ impl Restyle {
};
// Text sizes: shapes' and labels' text (stickies size theirs to fit).
let sized = match (self.size, &item) {
(Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. }) => resize_text(doc, id, size),
(Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => resize_text(doc, id, size),
_ => false,
};
Ok(changed || sized)
+1
View File
@@ -250,6 +250,7 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
to: End::Node { node: id, side: to_side, at: None },
routing,
path: None,
branch: false,
};
let line = make(doc, page, connector, CAPS)?;
s.set_selection(vec![id]);
+380
View File
@@ -0,0 +1,380 @@
//! Mind maps (#2226): a node is a frame hugging one text ([`BoardItem::MindNode`]) and a branch is
//! a connector with `branch` set, from the parent to the child. The tree is read from the branches
//! and from nothing else; [`settle_mind_maps`] lays a touched map out again in the normalize pass,
//! so the commands only make nodes and branches.
use std::collections::{BTreeMap, BTreeSet};
use figcraft_color::{Color, Paint};
use figcraft_doc::{
AutoLayout, BoardItem, Connector, Document, End, LetterSpacing, LineHeight, MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox,
NodeId, NodeKind, Routing, Side, Sizing, StrokeCap, TextAlignH, TextAutoResize, mind_layout,
};
use figcraft_geom::{Affine, Point, Rect};
use serde_json::{Value, json};
use super::connectors::make;
use super::items::{add, add_text, owner_of_text};
use super::{INK, Result, Session, bad, boolean, get, id, is_board, num_or, parent_of, require, string, textedit};
use crate::EngineError;
/// The first node's text size and the other nodes'.
const MIND_ROOT_SIZE: f64 = 24.0;
const MIND_NODE_SIZE: f64 = 16.0;
/// The line height of every node's text, in percent, and the letter spacing of the first node's
/// and the others' (percent of the size).
const MIND_LINE_HEIGHT: f64 = 150.0;
const MIND_ROOT_TRACKING: f64 = -1.9;
const MIND_NODE_TRACKING: f64 = -1.1;
/// A node's least width: an emptied one stays clickable.
const MIND_MIN_W: f64 = 8.0;
/// What `board.mindMap` puts in the first node and its children when it isn't told.
const MIND_ROOT_TEXT: &str = "Topic";
const MIND_STARTERS: [&str; 3] = ["Idea 1", "Idea 2", "Idea 3"];
/// The most children `board.mindMap` makes, and the longest text it puts in a node.
const MIND_MAX_STARTERS: usize = 20;
const MIND_MAX_TEXT: usize = 500;
/// How far from the page's middle a first node may be put.
const MIND_MAX_COORD: f64 = 1.0e9;
/// Branches' look.
const BRANCH: Color = Color::from_rgb8_const(0x75, 0x75, 0x75);
const BRANCH_WEIGHT: f64 = 4.0;
/// A node's frame and its text, `text` at `size`: the frame hugs the text with no padding, and the
/// text grows on one line.
fn make_node(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, root: bool) -> Result<(NodeId, NodeId)> {
let size = if root { MIND_ROOT_SIZE } else { MIND_NODE_SIZE };
let line = size * MIND_LINE_HEIGHT / 100.0;
let frame = add(doc, parent, NodeKind::Frame, "Mind map node", at, (MIND_MIN_W, line), |n| {
n.fills.clear();
n.clip = false;
n.layout = Some(AutoLayout { padding: [0.0; 4], ..AutoLayout::default() });
n.child_layout.sizing_h = Sizing::Hug;
n.child_layout.sizing_v = Sizing::Hug;
n.child_layout.min_w = Some(MIND_MIN_W);
n.child_layout.min_h = Some(line);
n.board = Some(BoardItem::MindNode);
})?;
let label = add_text(doc, frame, text, size, INK, TextAlignH::Left, 1.0)?;
if let Some(n) = doc.node_mut(label) {
n.child_layout.sizing_h = Sizing::Hug;
if let NodeKind::Text(td) = &mut n.kind {
td.auto_resize = TextAutoResize::WidthAndHeight;
td.style.line_height = LineHeight::Percent(MIND_LINE_HEIGHT);
td.style.letter_spacing = LetterSpacing::Percent(if root { MIND_ROOT_TRACKING } else { MIND_NODE_TRACKING });
if root {
td.style.font_style = "Bold".into();
} else {
td.style.font_style = "Medium".into();
}
}
}
Ok((frame, label))
}
/// The branch from `parent` to `child` (on its left side when `left`), on `page`.
fn branch(doc: &mut Document, page: NodeId, parent: NodeId, child: NodeId, left: bool) -> Result<NodeId> {
let (out, back) = if left { (Side::Left, Side::Right) } else { (Side::Right, Side::Left) };
let c = Connector {
from: End::Node { node: parent, side: out, at: None },
to: End::Node { node: child, side: back, at: None },
routing: Routing::Curved,
path: None,
branch: true,
};
let line = make(doc, page, c, (StrokeCap::Round, StrokeCap::Round))?;
let n = doc.get_mut(line)?;
n.strokes = vec![Paint::solid(BRANCH)];
n.stroke.weight = BRANCH_WEIGHT;
Ok(line)
}
/// A branch of a map as the tree reads it.
#[derive(Clone, Copy)]
struct Branch {
line: NodeId,
parent: NodeId,
child: NodeId,
left: bool,
}
/// The branches of `doc` that join two different layers of their own page, by id. (Others are
/// the normalize pass's to remove.)
fn branches(doc: &Document) -> Vec<Branch> {
let mut v: Vec<Branch> = doc
.nodes()
.filter_map(|n| match &n.board {
Some(BoardItem::Connector(Connector { from: End::Node { node: a, side, .. }, to: End::Node { node: b, .. }, branch: true, .. }))
if a != b && doc.contains(*a) && doc.contains(*b) && doc.page_of(*a) == doc.page_of(n.id) && doc.page_of(*b) == doc.page_of(n.id) =>
{
Some(Branch { line: n.id, parent: *a, child: *b, left: *side == Side::Left })
}
_ => None,
})
.collect();
v.sort_by_key(|b| b.line);
v
}
/// The branch arriving at `node`: the one with the lowest connector id, when it has several.
fn arriving(bs: &[Branch], node: NodeId) -> Option<Branch> {
bs.iter().find(|b| b.child == node).copied()
}
/// The children of `node` on one side, in layout order (by their middles, then id).
fn map_children(doc: &Document, bs: &[Branch], node: NodeId, left: bool) -> Vec<NodeId> {
let mut v: Vec<(f64, NodeId)> = bs
.iter()
.filter(|b| b.parent == node && b.left == left && arriving(bs, b.child).is_some_and(|a| a.line == b.line))
.filter_map(|b| doc.world_bounds(b.child).map(|r| (r.center().y, b.child)))
.collect();
v.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
v.into_iter().map(|p| p.1).collect()
}
/// Whether `node` is on the left of its map (a first node: no).
fn map_side(bs: &[Branch], node: NodeId) -> bool {
let (mut at, mut left) = (node, false);
for _ in 0..MIND_MAX_DEPTH {
let Some(b) = arriving(bs, at) else { break };
(at, left) = (b.parent, b.left);
}
left
}
/// The text `p` gives for `key`, a node's at most [`MIND_MAX_TEXT`] characters.
fn text_param(p: &Value, key: &str) -> String {
string(p, key).unwrap_or_default().chars().take(MIND_MAX_TEXT).collect()
}
/// A coordinate from the params, finite and within [`MIND_MAX_COORD`] of the origin.
fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result<f64> {
let v = num_or(p, key, default);
if v.is_finite() && v.abs() <= MIND_MAX_COORD { Ok(v) } else { Err(bad(cmd, format!("`{key}` is a position within a billion of the origin"))) }
}
/// `children?` of `board.mindMap`: the starter texts.
fn starters(cmd: &str, p: &Value) -> Result<Vec<String>> {
match get(p, "children") {
None => Ok(MIND_STARTERS.iter().map(|t| (*t).to_string()).collect()),
Some(Value::Array(a)) if a.len() <= MIND_MAX_STARTERS => {
a.iter().map(|v| v.as_str().map(|t| t.chars().take(MIND_MAX_TEXT).collect()).ok_or_else(|| bad(cmd, "`children` holds texts"))).collect()
}
_ => Err(bad(cmd, format!("`children` is a list of at most {MIND_MAX_STARTERS} texts"))),
}
}
pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.mindMap";
require(s, cmd)?;
let parent = parent_of(cmd, s, p)?;
let (vx, vy) = {
let v = &s.ds()?.view;
(v.cx, v.cy)
};
let (x, y) = (coord(cmd, p, "x", vx)?, coord(cmd, p, "y", vy)?);
let texts = starters(cmd, p)?;
let root_text = string(p, "text").map_or_else(|| MIND_ROOT_TEXT.to_string(), |_| text_param(p, "text"));
let page = s.page()?;
let doc = s.doc_mut()?;
let (root, label) = make_node(doc, parent, (x, y), &root_text, true)?;
let mut made = Vec::new();
// Anywhere below one another will do: the normalize pass puts them right, in this order.
let line = MIND_NODE_SIZE * MIND_LINE_HEIGHT / 100.0 + MIND_GAP_Y;
for (i, t) in texts.iter().enumerate() {
let (k, text) = make_node(doc, parent, (x + MIND_MIN_W + MIND_GAP_X, y + i as f64 * line), t, false)?;
let b = branch(doc, page, root, k, false)?;
made.push(json!({"id": k, "text": text, "connector": b}));
}
s.set_selection(vec![root]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": root}));
}
Ok(json!({"id": root, "text": label, "children": made}))
}
pub(super) fn mind_map_add(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.mindMapAdd";
require(s, cmd)?;
let editing = s.ds()?.text_edit.as_ref().map(|t| t.id);
let doc = s.doc()?;
let from = id(p, "id")
.or_else(|| editing.and_then(|t| owner_of_text(doc, t)))
.or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i)))
.ok_or_else(|| EngineError::Disabled(cmd.into(), "select a mind map node first".into()))?;
let n = doc.get(from)?;
if n.board != Some(BoardItem::MindNode) {
return Err(bad(cmd, "that isn't a mind map node"));
}
let sibling = match string(p, "relation").as_deref() {
None | Some("child") => false,
Some("sibling") => true,
Some(other) => return Err(bad(cmd, format!("`relation` is child or sibling, not `{other}`"))),
};
let (page, container) = (s.page()?, n.parent.ok_or_else(|| bad(cmd, "that node has no parent"))?);
if doc.page_of(from) != Some(page) {
return Err(bad(cmd, "that node is on another page"));
}
let bs = branches(doc);
let at = doc.world_bounds(from).ok_or_else(|| bad(cmd, "that node has no place"))?;
let new_h = MIND_NODE_SIZE * MIND_LINE_HEIGHT / 100.0;
// The parent, the side, and where the new node's top-left goes on the page.
let (parent, left, top_left) = if sibling {
let a = arriving(&bs, from).ok_or_else(|| bad(cmd, "the first node has no siblings: add a child"))?;
// Its middle lands between this node and the next sibling, so the order puts it right after.
(a.parent, a.left, Point::new(at.x0, at.y1 + MIND_GAP_Y / 2.0 - new_h / 2.0))
} else {
let left = map_side(&bs, from);
let last = map_children(doc, &bs, from, left).last().and_then(|l| doc.world_bounds(*l));
let top = last.map_or(at.center().y - new_h / 2.0, |l| l.y1 + MIND_GAP_Y);
(from, left, Point::new(if left { at.x0 - MIND_GAP_X - MIND_MIN_W } else { at.x1 + MIND_GAP_X }, top))
};
let local = doc.world_transform(container).inverse() * top_left;
if !(local.x.is_finite() && local.y.is_finite()) {
return Err(bad(cmd, "the new node can't be placed there"));
}
let text = text_param(p, "text");
if editing.is_some() {
textedit::end(s)?;
}
let doc = s.doc_mut()?;
let (node, label) = make_node(doc, container, (local.x, local.y), &text, false)?;
let line = branch(doc, page, parent, node, left)?;
s.set_selection(vec![node]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": node}));
}
Ok(json!({"id": node, "text": label, "connector": line}))
}
/// The tree of a document's branches: for each layer its arriving branch (the lowest connector
/// id), and each parent's children by it.
type Children = BTreeMap<NodeId, Vec<Branch>>;
fn children_of(bs: &[Branch]) -> (BTreeSet<NodeId>, Children) {
let mut arrived = BTreeSet::new();
let mut kids: Children = BTreeMap::new();
for b in bs {
if arrived.insert(b.child) {
kids.entry(b.parent).or_default().push(*b);
}
}
(arrived, kids)
}
/// Every branch that no longer joins two layers of its own page is removed, and the layers it
/// joined that are still there count as stirred (so do the old ends of a touched branch: one that
/// is gone, or that was moved to join something else).
fn prune_branches(doc: &mut Document, before: &Document, touched: &BTreeSet<NodeId>) -> BTreeSet<NodeId> {
let mut stirred = BTreeSet::new();
let ends = |c: &Connector| [c.from.node(), c.to.node()].into_iter().flatten().collect::<Vec<NodeId>>();
for id in touched {
if let Some(BoardItem::Connector(c)) = before.node(*id).and_then(|n| n.board.as_ref())
&& c.branch
{
stirred.extend(ends(c));
}
}
let mut gone = Vec::new();
for n in doc.nodes() {
let Some(BoardItem::Connector(c)) = &n.board else { continue };
let page = doc.page_of(n.id);
let joins = |e: &End| matches!(e, End::Node { node, .. } if doc.contains(*node) && page.is_some() && doc.page_of(*node) == page);
if c.branch && !(joins(&c.from) && joins(&c.to) && c.from.node() != c.to.node()) {
gone.push((n.id, ends(c)));
}
}
for (line, joined) in gone {
stirred.extend(joined);
let _ = doc.remove(line);
}
stirred.retain(|i| doc.contains(*i));
stirred
}
/// The boxes of the map under `root`, breadth first (so a parent always comes before its
/// children), and the connectors that hold it together. `None`: a box is missing, or the map has
/// more than [`MIND_MAX_NODES`] nodes (it is left as it is).
fn map_boxes(doc: &Document, root: NodeId, kids: &Children) -> Option<(Vec<MindBox>, Vec<NodeId>)> {
let first = doc.world_bounds(root)?;
let mut boxes = vec![MindBox { id: root, rect: first, parent: None, left: false }];
let (mut lines, mut seen) = (Vec::new(), BTreeSet::from([root]));
let (mut at, mut depths) = (0, vec![0_usize]);
while let Some(b) = boxes.get(at).copied() {
let depth = depths.get(at).copied().unwrap_or(MIND_MAX_DEPTH);
for k in kids.get(&b.id).filter(|_| depth < MIND_MAX_DEPTH).into_iter().flatten() {
if !seen.insert(k.child) {
continue;
}
if boxes.len() >= MIND_MAX_NODES {
return None;
}
boxes.push(MindBox { id: k.child, rect: doc.world_bounds(k.child)?, parent: Some(at), left: k.left });
depths.push(depth + 1);
lines.push(k.line);
}
at += 1;
}
Some((boxes, lines))
}
/// Move layer `id` by `d` on the page.
fn shift(doc: &mut Document, id: NodeId, d: Point) {
let parent = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p));
let inverse = parent.inverse();
if !inverse.as_coeffs().iter().all(|v| v.is_finite()) {
return;
}
if let Some(n) = doc.node_mut(id) {
let moved = inverse * Affine::translate((d.x, d.y)) * parent * n.transform;
if moved.as_coeffs().iter().all(|v| v.is_finite()) {
n.transform = moved;
}
}
}
/// After layout and before connectors follow: the maps an edit touched are laid out again from
/// their first nodes (a map that is already in place is not written to, so the pass is idempotent).
/// A branch that no longer joins two layers of its page is removed first: the only structural
/// write, and what makes a deleted node's children float free and a detached node stay detached.
pub(crate) fn settle_mind_maps(doc: &mut Document, before: &Document, touched: &BTreeSet<NodeId>) {
if !is_board(doc) || touched.is_empty() {
return;
}
// One look at every layer: a board without a branch (nearly all) goes no further.
if !doc.nodes().any(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)) {
return;
}
let stirred = prune_branches(doc, before, touched);
let bs = branches(doc);
if bs.is_empty() {
return;
}
let hit = |doc: &Document, id: NodeId| touched.contains(&id) || doc.ancestors(id).iter().any(|a| touched.contains(a));
let (arrived, kids) = children_of(&bs);
let roots: Vec<NodeId> = kids.keys().copied().filter(|p| !arrived.contains(p)).collect();
for root in roots {
let Some((boxes, lines)) = map_boxes(doc, root, &kids) else { continue };
if boxes.iter().any(|b| !(b.rect.x0.is_finite() && b.rect.y0.is_finite() && b.rect.x1.is_finite() && b.rect.y1.is_finite())) {
continue;
}
// A map holding a layer and something inside it would move that layer with its own
// children: leave it as it is.
let ids: BTreeSet<NodeId> = boxes.iter().map(|b| b.id).collect();
if boxes.iter().any(|b| doc.ancestors(b.id).iter().any(|a| ids.contains(a))) {
continue;
}
let stale = boxes.iter().any(|b| stirred.contains(&b.id) || hit(doc, b.id)) || lines.iter().any(|l| hit(doc, *l));
if !stale {
continue;
}
let now: BTreeMap<NodeId, Rect> = boxes.iter().map(|b| (b.id, b.rect)).collect();
for (id, to) in mind_layout(&boxes) {
let Some(was) = now.get(&id) else { continue };
let d = to - was.origin();
if d.x.is_finite() && d.y.is_finite() && d.hypot() > 1e-6 {
shift(doc, id, Point::new(d.x, d.y));
}
}
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ fn moved(doc: &Document, c: &Connector, portion: usize, p: Point) -> Option<Conn
let (from, to) = route_ends(doc, c)?;
let path = reshaped(from, to, c.routing, c.path.as_ref(), portion, p)?;
let (s0, s1) = attached_sides(from, to);
Some(Connector { from: pinned(c.from, s0), to: pinned(c.to, s1), routing: c.routing, path: Some(path) })
Some(Connector { from: pinned(c.from, s0), to: pinned(c.to, s1), routing: c.routing, path: Some(path), branch: c.branch })
}
/// Write `c` into connector `id` and run it along its new route.
+1 -1
View File
@@ -171,7 +171,7 @@ impl Session {
/// or free point under the pointer.
pub(crate) fn connect_drag(&mut self, ev: &PointerEvent, from: End, start: Point) {
self.tool.gesture = Gesture::Connect { from, start };
let c = self.drag_end(ev, from, start).map(|to| Connector { from, to, routing: self.tool.board.routing, path: None });
let c = self.drag_end(ev, from, start).map(|to| Connector { from, to, routing: self.tool.board.routing, path: None, branch: false });
if let Ok(page) = self.page() {
// One that can't be placed shows nothing, as none would be made.
let _ = self.preview(|d, _| {
+14 -3
View File
@@ -174,7 +174,8 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
// no undo step.
let mut work = s.doc()?.clone();
let doc = &mut work;
let ids = roots(doc, &ids);
// A locked layer (or one in a locked layer) ignores the arrow keys.
let ids: Vec<NodeId> = roots(doc, &ids).into_iter().filter(|i| !crate::tools::locked_in(doc, *i)).collect();
let mut changed = false;
// Children in an auto layout flow move one place instead (see `al_keys`).
for i in &ids {
@@ -209,6 +210,9 @@ pub(super) fn nudge_size(s: &mut Session, p: &Value) -> Result<Value> {
let ids = req_targets("transform.nudgeSize", s, p)?;
let ids = roots(s.doc()?, &ids);
for i in ids {
if crate::tools::locked_in(s.doc()?, i) {
continue;
}
let Some((w, h)) = s.doc()?.node(i).map(|n| (n.width, n.height)) else { continue };
let mut q = serde_json::Map::new();
q.insert("ids".into(), json!([i]));
@@ -231,9 +235,16 @@ pub(super) fn toggle(s: &mut Session, p: &Value, what: &str) -> Result<Value> {
// Figma: if any is visible, hide all (and vice versa).
let value = explicit.unwrap_or_else(|| match what {
"visible" => !ids.iter().all(|i| doc.node(*i).is_some_and(|n| n.visible)),
_ => !ids.iter().all(|i| doc.node(*i).is_some_and(|n| n.locked)),
// A child of a locked layer counts as locked: its own flag can't be toggled while the
// parent is locked.
_ => !ids.iter().all(|i| crate::tools::locked_in(doc, *i)),
});
for i in &ids {
// Lock/Unlock leaves a child of a locked layer alone, as its padlock does: its own flag must
// still hold once the parent is unlocked. An explicit `locked` (scripts) sets it anyway.
let under_lock = |i: NodeId| doc.ancestors(i).into_iter().any(|a| doc.node(a).is_some_and(|n| n.locked));
let skip: Vec<NodeId> =
if what == "locked" && explicit.is_none() { ids.iter().copied().filter(|i| under_lock(*i)).collect() } else { Vec::new() };
for i in ids.iter().filter(|i| !skip.contains(i)) {
let n = doc.get_mut(*i)?;
if what == "visible" {
n.visible = value;
+7
View File
@@ -270,6 +270,13 @@ mod tests {
assert_eq!(info["gridCell"]["column"], json!(2));
assert_eq!(info["gridCell"]["row"], json!(1));
assert_eq!(info["gridCell"]["anchored"], json!(true));
// Inspected together with the frame, each child still gets its own cell.
let all = crate::inspect::node_json(s.doc().unwrap(), f, 1);
let cells: Vec<(Value, Value)> =
all["children"].as_array().unwrap().iter().map(|c| (c["gridCell"]["column"].clone(), c["gridCell"]["row"].clone())).collect();
assert_eq!(cells[3], (json!(2), json!(1)));
assert_eq!(cells[0].0, json!(0));
assert!(cells.iter().all(|(c, r)| c.is_number() && r.is_number()), "{cells:?}");
ex(&mut s, "node.set", json!({"id": kids[3], "props": {"gridColumn": "auto", "gridRow": null}}));
assert_eq!(node(&s, kids[3]).child_layout.grid_column, None);
// Fewer columns drop the extra tracks.
+13
View File
@@ -285,3 +285,16 @@ fn vue_layer_trees_import_connected_components_in_script_setup() {
assert!(code.starts_with(want), "{code}");
assert_eq!(code.matches("import Card").count(), 1, "{code}");
}
#[test]
fn many_entries_for_one_component_each_link() {
let mut s = Session::new();
let (_, hover) = button(&mut s);
let links: Vec<Value> = (0..crate::code_connect::MAX_FILE_LINKS)
.map(|i| json!({"component": "Button", "language": if i % 2 == 0 { "react" } else { "vue" }, "name": "Button", "template": "<Button />"}))
.collect();
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
assert_eq!(r["linked"], crate::code_connect::MAX_FILE_LINKS, "{r}");
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500})));
assert_eq!(code(&mut s, i, "react"), "<Button />\n");
}
+4 -1
View File
@@ -164,7 +164,10 @@ pub fn normalize(doc: &mut Document, before: &Document) {
}
}
touched.extend(doc.take_dirty());
// 4b. Board connectors follow the layers they join; their labels sit at their middles.
// 4b. Mind maps re-flow from their first nodes; then board connectors follow the layers they
// join and their labels sit at their middles.
board::settle_mind_maps(doc, before, &touched);
touched.extend(doc.take_dirty());
board::settle_routes(doc, before, &touched);
board::settle_stamps(doc, before, &touched);
touched.extend(doc.take_dirty());
+9 -4
View File
@@ -669,7 +669,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
}
let doc = s.doc()?;
// Components and sets by name (variants are linked through their set).
let owners: Vec<(String, NodeId)> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| (n.name.clone(), n.id)).collect();
let mut owners: std::collections::HashMap<&str, Vec<NodeId>> = std::collections::HashMap::new();
for n in doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)) {
owners.entry(n.name.as_str()).or_default().push(n.id);
}
// What each component looks like, worked out once however many entries name it.
let mut described: std::collections::HashMap<NodeId, Option<Component>> = std::collections::HashMap::new();
let mut warnings: Vec<String> = Vec::new();
let mut apply: Vec<(NodeId, CodeLink)> = Vec::new();
for (i, e) in entries.iter().enumerate() {
@@ -689,13 +694,13 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
name: name.into(),
template: template.into(),
};
let matches: Vec<NodeId> = owners.iter().filter(|(n, _)| n == component).map(|(_, id)| *id).collect();
let matches = owners.get(component).cloned().unwrap_or_default();
if matches.is_empty() {
warnings.push(format!("link {}: no component named {component:?}", i + 1));
}
for id in matches {
let Some(c) = main_of(doc, id).and_then(|m| describe(doc, m)) else { continue };
match check(&c, &link, lang) {
let Some(c) = described.entry(id).or_insert_with(|| main_of(doc, id).and_then(|m| describe(doc, m))).as_ref() else { continue };
match check(c, &link, lang) {
Ok(_) => apply.push((id, link.clone())),
Err(err) => warnings.push(format!("link {} ({component}): {err}", i + 1)),
}
+4
View File
@@ -213,6 +213,8 @@ mod board_connector_tests;
#[cfg(test)]
mod board_grid_tests;
#[cfg(test)]
mod board_mindmap_tests;
#[cfg(test)]
mod board_reshape_tests;
#[cfg(test)]
mod board_table_paste_tests;
@@ -419,6 +421,8 @@ mod live_signal_tests;
#[cfg(test)]
mod live_tests;
#[cfg(test)]
mod lock_behaviour_tests;
#[cfg(test)]
mod mask_tests;
#[cfg(test)]
mod masks_behaviour_tests;
+141
View File
@@ -0,0 +1,141 @@
//! Locked layers, as measured in Figma's web app (2026-11-10) and described in the help-center
//! article "Lock and unlock layers": the canvas never selects a locked layer or a child of a locked
//! frame; a locked layer selected in the layers panel has no handles and ignores the arrow keys, but
//! its properties still edit; a child of a locked frame can't be locked or unlocked on its own.
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind, handle_at};
use figcraft_doc::NodeId;
use figcraft_geom::Point;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn rect(s: &mut Session, x: f64, y: f64, parent: Option<NodeId>) -> NodeId {
let mut p = json!({"x": x, "y": y, "width": 40, "height": 40});
if let Some(parent) = parent {
p["parent"] = json!(parent);
}
id_of(&ex(s, "shape.rectangle", p)["id"]).unwrap()
}
/// A frame `f` (0,0 300x200) holding rectangle `d` (20,20 40x40); a locked rectangle `lk`
/// (400,0 40x40) and an unlocked one `r` (400,100 40x40) on the page.
fn scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
let f = id_of(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 200}))["id"]).unwrap();
let d = rect(s, 20.0, 20.0, Some(f));
let lk = rect(s, 400.0, 0.0, None);
let r = rect(s, 400.0, 100.0, None);
ex(s, "object.toggleLock", json!({"ids": [lk], "locked": true}));
(f, d, lk, r)
}
fn ev(kind: PointerKind, x: f64, y: f64, cmd: bool) -> PointerEvent {
let mut e = PointerEvent::at(kind, x, y, 1.0);
e.cmd = cmd;
e
}
fn click(s: &mut Session, x: f64, y: f64, cmd: bool) {
s.pointer(&ev(PointerKind::Down, x, y, cmd)).unwrap();
s.pointer(&ev(PointerKind::Up, x, y, cmd)).unwrap();
}
fn origin(s: &Session, id: NodeId) -> (f64, f64) {
let b = s.doc().unwrap().world_bounds(id).unwrap();
(b.x0, b.y0)
}
fn size(s: &Session, id: NodeId) -> (f64, f64) {
let b = s.doc().unwrap().world_bounds(id).unwrap();
(b.width(), b.height())
}
fn locked(s: &Session, id: NodeId) -> bool {
s.doc().unwrap().node(id).unwrap().locked
}
#[test]
fn canvas_never_selects_a_locked_layer_or_a_locked_frames_child() {
let mut s = Session::new();
let (f, d, _lk, _r) = scene(&mut s);
click(&mut s, 420.0, 20.0, false);
assert!(s.selection().is_empty(), "a click on a locked layer selects nothing");
click(&mut s, 420.0, 20.0, true);
assert!(s.selection().is_empty(), "Cmd/Ctrl-click on a locked layer selects nothing");
s.pointer(&ev(PointerKind::Down, 390.0, -10.0, false)).unwrap();
s.pointer(&ev(PointerKind::Move, 450.0, 50.0, false)).unwrap();
s.pointer(&ev(PointerKind::Up, 450.0, 50.0, false)).unwrap();
assert!(s.selection().is_empty(), "a marquee over a locked layer selects nothing");
ex(&mut s, "object.toggleLock", json!({"ids": [f], "locked": true}));
click(&mut s, 30.0, 30.0, false);
assert!(!s.selection().contains(&d), "a click on a child of a locked frame doesn't select it");
click(&mut s, 30.0, 30.0, true);
assert!(s.selection().is_empty(), "Cmd/Ctrl-click on a child of a locked frame selects nothing");
}
#[test]
fn a_panel_selected_locked_layer_has_no_handles_ignores_arrows_and_takes_property_edits() {
let mut s = Session::new();
let (_f, _d, lk, _r) = scene(&mut s);
ex(&mut s, "select.set", json!({"ids": [lk]}));
assert_eq!(handle_at(s.doc().unwrap(), &[lk], Point::new(400.0, 0.0), 1.0), None, "no handles on a locked layer");
let steps = s.undo_depth();
for _ in 0..3 {
ex(&mut s, "transform.nudge", json!({"dx": 1}));
}
assert_eq!(origin(&s, lk), (400.0, 0.0), "the arrow keys don't move a locked layer");
ex(&mut s, "transform.nudgeSize", json!({"dw": 1}));
assert_eq!(size(&s, lk), (40.0, 40.0), "the resize arrows don't resize a locked layer");
assert_eq!(s.undo_depth(), steps, "an arrow that changes nothing adds no undo step");
ex(&mut s, "node.set", json!({"id": lk, "props": {"x": 300}}));
assert_eq!(origin(&s, lk).0, 300.0, "the X field still moves a locked layer");
let before = format!("{:?}", s.doc().unwrap().node(lk).unwrap().fills);
ex(&mut s, "fill.set", json!({"ids": [lk], "color": "#ff0000"}));
assert_ne!(format!("{:?}", s.doc().unwrap().node(lk).unwrap().fills), before, "a fill still edits");
assert_eq!(s.selection(), vec![lk], "the selection stays the locked layer");
}
#[test]
fn a_child_of_a_locked_frame_cannot_be_locked_or_unlocked_on_its_own() {
let mut s = Session::new();
let (f, d, _lk, _r) = scene(&mut s);
ex(&mut s, "object.toggleLock", json!({"ids": [f], "locked": true}));
ex(&mut s, "object.toggleLock", json!({"ids": [d]}));
assert!(!locked(&s, d), "toggling a child of a locked frame doesn't lock the child");
ex(&mut s, "select.set", json!({"ids": [d]}));
ex(&mut s, "object.toggleLock", json!({}));
assert!(!locked(&s, d), "Lock/Unlock on a panel-selected child of a locked frame does nothing");
ex(&mut s, "object.toggleLock", json!({"ids": [f], "locked": false}));
click(&mut s, 30.0, 30.0, false);
assert_eq!(s.selection(), vec![d], "after unlocking the frame a click selects the child");
assert!(!locked(&s, d));
}
#[test]
fn lock_unlock_on_a_mixed_selection_leaves_a_locked_frames_child_alone() {
let mut s = Session::new();
let (f, d, _lk, r) = scene(&mut s);
ex(&mut s, "object.toggleLock", json!({"ids": [f], "locked": true}));
ex(&mut s, "select.set", json!({"ids": [d, r]}));
ex(&mut s, "object.toggleLock", json!({}));
assert!(locked(&s, r), "the unlocked layer in the selection is locked");
assert!(!locked(&s, d), "the locked frame's child keeps its own flag");
ex(&mut s, "object.toggleLock", json!({"ids": [f], "locked": false}));
click(&mut s, 30.0, 30.0, false);
assert_eq!(s.selection(), vec![d], "so unlocking the frame frees the child");
}
#[test]
fn ctrl_shift_l_on_a_panel_selected_locked_layer_unlocks_it() {
let mut s = Session::new();
let (_f, _d, lk, _r) = scene(&mut s);
ex(&mut s, "select.set", json!({"ids": [lk]}));
ex(&mut s, "object.toggleLock", json!({}));
assert!(!locked(&s, lk), "Lock/Unlock unlocks a locked layer");
assert!(handle_at(s.doc().unwrap(), &[lk], Point::new(400.0, 0.0), 1.0).is_some(), "handles return");
}
+26
View File
@@ -99,3 +99,29 @@ fn overlapping_rectangle_bounds_count_self_and_cross_pairs() {
let shapes = rects([Rect::new(0.0, 0.0, 2.0, 2.0), Rect::new(1.0, 1.0, 3.0, 3.0), Rect::new(4.0, 4.0, 5.0, 5.0)]);
assert_eq!(complexity([&shapes]), Some(Complexity { segments: 12, crossings: 14 }));
}
/// Open L shapes whose segments never overlap but whose implicit closing edges all do.
#[test]
fn faces_checks_the_closed_inputs_before_normalising() {
let mut p = BezPath::new();
for i in 0..2200 {
let (x, y) = (-(i as f64), 10_000.0 + i as f64);
p.move_to((x, 0.0));
p.line_to((x, y));
p.line_to((10_000.0, y));
}
assert!(complexity([&p]).is_some_and(|c| c.crossings <= MAX_CROSSINGS), "open input passes");
assert!(matches!(faces(&[(p, false)]), Err(PathOpsError::TooComplex)));
}
#[test]
fn closing_drops_move_only_subpaths() {
let mut p = BezPath::new();
for i in 0..1000 {
p.move_to((i as f64, 0.0));
}
assert!(crate::closed(&p).elements().is_empty());
p.line_to((5.0, 5.0));
let c = crate::closed(&p);
assert_eq!(c.elements().len(), 3, "the last move, the line and the close: {:?}", c.elements());
}
+14 -4
View File
@@ -57,20 +57,27 @@ impl std::fmt::Display for PathOpsError {
}
}
/// Close every open subpath (a filled open path paints as if closed).
/// Close every open subpath (a filled open path paints as if closed). A subpath of a lone move
/// fills nothing and is left out.
pub fn closed(path: &BezPath) -> BezPath {
let mut out = BezPath::new();
let mut open = false;
let mut pending: Option<PathEl> = None;
for el in path.elements() {
match el {
PathEl::MoveTo(_) => {
if open {
out.close_path();
}
open = true;
open = false;
pending = Some(*el);
continue;
}
PathEl::ClosePath => open = false,
_ => {}
_ => open = true,
}
if let Some(m) = pending.take() {
out.push(m);
}
out.push(*el);
}
@@ -240,7 +247,10 @@ pub fn faces(paths: &[(BezPath, bool)]) -> Result<Vec<ArrangementFace>, PathOpsE
// corner folds over itself and touches the shape's fill) leave the winding on each side of a
// segment ambiguous where they touch, which made the sweep report overlapping faces. Reducing
// every input to the simple contours of the area it fills first keeps the faces disjoint.
let closed_paths: Vec<BezPath> = paths.iter().map(|(p, even_odd)| plain(&closed(p), *even_odd)).collect();
// Closing adds edges, so what `plain` sweeps is checked first.
let closed_inputs: Vec<BezPath> = paths.iter().map(|(p, _)| closed(p)).collect();
budget::check(&closed_inputs)?;
let closed_paths: Vec<BezPath> = closed_inputs.iter().zip(paths).map(|(p, (_, even_odd))| plain(p, *even_odd)).collect();
if closed_paths.iter().all(|p| p.elements().is_empty()) {
return Ok(Vec::new());
}
+15 -2
View File
@@ -66,10 +66,23 @@ impl Styled {
}
// Each point's own join: a short corner along its two segments stroked with that join.
let reach = (width * 0.05).max(0.2);
// Segments per point, built once (a scan of every segment per point is quadratic); like `incident`, a loop segment counts at its `a` end only.
// Only points that draw a join of their own get a list.
let mut incident: std::collections::HashMap<usize, Vec<(usize, bool)>> =
(0..self.net.vertices.len()).filter(|v| self.breaks(*v)).map(|v| (v, Vec::new())).collect();
for (i, s) in self.net.segments.iter().enumerate() {
if let Some(list) = incident.get_mut(&s.a) {
list.push((i, true));
}
if s.b != s.a
&& let Some(list) = incident.get_mut(&s.b)
{
list.push((i, false));
}
}
for (v, x) in self.net.vertices.iter().enumerate() {
let Some(join) = x.join.filter(|_| self.breaks(v)) else { continue };
let inc = self.net.incident(v);
let [(s1, a1), (s2, a2)] = inc.as_slice() else { continue };
let Some([(s1, a1), (s2, a2)]) = incident.get(&v).map(Vec::as_slice) else { continue };
let (Some(d1), Some(d2)) = (self.net.tangent_out(*s1, *a1), self.net.tangent_out(*s2, *a2)) else { continue };
let p = x.point();
let mut corner = BezPath::new();
+14 -4
View File
@@ -262,7 +262,12 @@ const DASH_ACCURACY: f64 = 0.05;
/// Whether `pattern` (from [`dash_pattern`]) makes at most [`MAX_DASHES`] dashes along `len`;
/// past that a stroke draws solid instead of one outline per dash (#1060).
pub(crate) fn dashes_fit(len: f64, pattern: &[f64]) -> bool {
len / pattern.iter().sum::<f64>() * (pattern.len() as f64) < MAX_DASHES as f64
dash_count(len, pattern) < MAX_DASHES as f64
}
/// About how many dashes `pattern` makes along `len`.
fn dash_count(len: f64, pattern: &[f64]) -> f64 {
len / pattern.iter().sum::<f64>() * (pattern.len() as f64)
}
/// Resample a polyline so no step is longer than `max_step`; returns the points and the length at
@@ -303,6 +308,8 @@ pub fn variable_outline(path: &BezPath, width: f64, props: &StrokeProps, profile
let style = Style { join: props.join, miter_limit: props.miter_limit.clamp(1.0, 100.0), cap_start, cap_end };
let pattern = dash_pattern(props);
let mut budget = MAX_WIDTH_SAMPLES;
// The dashes of all subpaths together stay within MAX_DASHES; the rest draw solid.
let mut dash_budget = MAX_DASHES as f64;
let mut out = BezPath::new();
for line in &lines {
let len = line.length();
@@ -317,9 +324,12 @@ pub fn variable_outline(path: &BezPath, width: f64, props: &StrokeProps, profile
[0.5 * width * right, 0.5 * width * left]
})
.collect();
match &pattern {
Some(pat) if dashes_fit(len, pat) => {
let (pat, offset) = line_dashes(len, line.closed, pat);
// Budgeted by the pattern as fitted to this line (a short line still takes a whole pattern).
let fit = pattern.as_ref().map(|pat| line_dashes(len, line.closed, pat));
let used = fit.as_ref().map_or(0.0, |(pat, _)| dash_count(len, pat).max(pat.len() as f64));
match fit {
Some((pat, offset)) if used < dash_budget && dashes_fit(len, &pat) => {
dash_budget -= used;
for (p, h) in dashes(&pts, &hw, &pat, offset) {
outline_piece(&mut out, &p, &h, false, style);
}
+28
View File
@@ -145,3 +145,31 @@ fn hostile_and_huge_input_is_bounded() {
let s = stroke_outline(&line(1e6), &tiny, false);
assert!(s.elements().len() < 1_000_000);
}
#[test]
fn dashes_of_all_subpaths_share_one_allowance() {
let tiny = StrokeProps { dashes: vec![1.0, 1.0], ..props(1.0, Some(WidthProfile::uniform())) };
let many = |n: usize| {
let mut p = BezPath::new();
for i in 0..n {
p.move_to((0.0, i as f64 * 4.0));
p.line_to((15_000.0, i as f64 * 4.0));
}
variable_outline(&p, 1.0, &tiny, &WidthProfile::uniform()).unwrap().elements().len()
};
// The later subpaths draw solid once the first has used most of the allowance.
assert!(many(10) < 3 * many(1), "{} vs {}", many(10), many(1));
}
#[test]
fn a_short_subpath_is_budgeted_by_the_whole_pattern_it_takes() {
// 100 one-unit lines, each fitted to a 4,000-entry pattern: ~400,000 dashes if not budgeted.
let long = StrokeProps { dashes: vec![1.0; 4000], ..props(1.0, Some(WidthProfile::uniform())) };
let mut p = BezPath::new();
for i in 0..100 {
p.move_to((0.0, i as f64 * 4.0));
p.line_to((1.0, i as f64 * 4.0));
}
let n = variable_outline(&p, 1.0, &long, &WidthProfile::uniform()).unwrap().elements().len();
assert!(n < 20_000 * 12, "{n}");
}
+8
View File
@@ -91,3 +91,11 @@ fn kept_splat_answers_are_the_answers_worked_out_afresh() {
}
}
}
#[test]
fn ids_chosen_to_differ_only_in_high_bits_still_spread_over_buckets() {
use std::hash::BuildHasher;
let state = crate::draw::IdState::default();
let buckets: std::collections::HashSet<u64> = (0..4096u64).map(|k| state.hash_one(NodeId(k << 40)) & 0xfff).collect();
assert!(buckets.len() > 2000, "{}", buckets.len());
}
+25 -4
View File
@@ -69,16 +69,37 @@ impl<'a> Bounds<'a> {
}
/// A hash map keyed by node ids, which need no SipHash: they are counters (or a peer's range of
/// them), and SipHash took a good part of a render.
type IdMap<K, V> = HashMap<K, V, std::hash::BuildHasherDefault<IdHash>>;
/// them), and SipHash took a good part of a render. A file can choose its ids, so each map is
/// seeded at random and the hash mixes its high bits down (ids differing only up high would
/// otherwise share a bucket).
type IdMap<K, V> = HashMap<K, V, IdState>;
/// Builds [`IdHash`]es from a per-map random seed.
#[derive(Clone)]
pub(crate) struct IdState(u64);
impl Default for IdState {
fn default() -> Self {
use std::hash::BuildHasher;
IdState(std::collections::hash_map::RandomState::new().hash_one(0u8))
}
}
impl std::hash::BuildHasher for IdState {
type Hasher = IdHash;
fn build_hasher(&self) -> IdHash {
IdHash(self.0)
}
}
/// Mixes each word in with a multiply (Fibonacci hashing), so ids that differ in low bits spread.
#[derive(Default)]
pub(crate) struct IdHash(u64);
impl Hasher for IdHash {
fn finish(&self) -> u64 {
self.0
// The multiply's low bits depend only on the input's low bits: mix the high ones down.
let h = (self.0 ^ (self.0 >> 32)).wrapping_mul(0xFF51_AFD7_ED55_8CCD);
h ^ (h >> 29)
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
+4
View File
@@ -39,6 +39,10 @@ pub fn nested<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
/// the pixmap, the cell and the pixmap's pixels per unit on each axis (whole pixels per cell, so
/// the repeat lines up exactly).
pub fn cell_pixmap(doc: &Document, pt: &PatternPaint, w: f64, h: f64, scale: f64, time: f64) -> Option<(Pixmap, PatternCell, (f64, f64))> {
// Past the nesting limit nothing is drawn, so don't allocate a cell first.
if DEPTH.with(Cell::get) >= MAX_DEPTH {
return None;
}
let src = doc.node(NodeId(pt.source)).filter(|n| !n.is_page())?;
let cell = pt.cell(src.width, src.height, w, h)?;
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
+10
View File
@@ -57,3 +57,13 @@ fn a_transparent_images_inner_shadow_is_an_embedded_render() {
let svg = export(&d, n);
assert!(svg.contains("<pattern") && svg.contains("<mask"), "an opaque picture stays vector, shaded from its box: {svg}");
}
#[test]
fn paints_of_one_image_embed_its_bytes_once() {
let (mut d, n) = scene(false, EffectKind::DropShadow(shadow()));
let node = d.get_mut(n).unwrap();
node.fills = vec![Paint::image("svg-image-shadow-opaque", ImageScaleMode::Fill); 3];
let svg = export(&d, n);
assert_eq!(svg.matches("<image id=").count(), 1, "{svg}");
assert_eq!(svg.matches("<pattern").count(), 3);
}
+13 -5
View File
@@ -70,10 +70,15 @@ impl Img {
}
}
fn stack(bottom: Img, top: Img) -> Img {
/// The most layers a stack may hold. Results that name earlier results can double a stack at each
/// of up to 64 primitives; real shadow chains hold a handful of layers, and a longer stack isn't
/// an effect list anyone wrote.
const MAX_STACK: usize = 64;
fn stack(bottom: Img, top: Img) -> Option<Img> {
let mut v = bottom.into_layers();
v.extend(top.into_layers());
Img::Stack(v)
(v.len() <= MAX_STACK).then_some(Img::Stack(v))
}
/// The effects `filters` amount to on a layer whose user space maps to the page by `world`; `None`
@@ -148,13 +153,16 @@ fn primitive(k: &Kind, get: &dyn Fn(&Input) -> Option<Img>) -> Option<Img> {
let mut v = Vec::new();
for i in m.inputs() {
v.extend(get(i)?.into_layers());
if v.len() > MAX_STACK {
return None;
}
}
Img::Stack(v)
}
Kind::Blend(b) => {
let (top, bottom) = (get(b.input1())?, get(b.input2())?);
match b.mode() {
usvg::BlendMode::Normal => stack(bottom, top),
usvg::BlendMode::Normal => stack(bottom, top)?,
_ => return None,
}
}
@@ -162,7 +170,7 @@ fn primitive(k: &Kind, get: &dyn Fn(&Input) -> Option<Img>) -> Option<Img> {
let sigma = (f64::from(d.std_dev_x().get()) + f64::from(d.std_dev_y().get())) / 2.0;
let s = Sh { dx: f64::from(d.dx()), dy: f64::from(d.dy()), sigma, color: color(d.color(), d.opacity().get()), ..Sh::alpha() };
match get(d.input())? {
Img::Layer(b) => stack(Img::Shadow(s), Img::Layer(b)),
Img::Layer(b) => stack(Img::Shadow(s), Img::Layer(b))?,
_ => return None,
}
}
@@ -190,7 +198,7 @@ fn tint(v: &[f32], s: Sh) -> Option<Img> {
fn composite(a: Img, b: Img, op: CompositeOperator) -> Option<Img> {
let tinted = |s: Sh, c: Color| Sh { color: Color::new(c.r, c.g, c.b, (c.a * s.color.a).clamp(0.0, 1.0)), ..s };
Some(match (op, a, b) {
(CompositeOperator::Over, a, b) => stack(b, a),
(CompositeOperator::Over, a, b) => stack(b, a)?,
(CompositeOperator::In, Img::Flood(c), Img::Shadow(s)) | (CompositeOperator::In, Img::Shadow(s), Img::Flood(c)) => Img::Shadow(tinted(s, c)),
// A flood cut to everything but a shadow, then cut to the layer: an inner shadow.
(CompositeOperator::Out, Img::Flood(c), Img::Shadow(s)) if !s.inner && !s.inverted => Img::Shadow(Sh { inverted: true, ..tinted(s, c) }),
+12
View File
@@ -228,3 +228,15 @@ fn coloured_copies_of_a_blurred_layer_arent_shadows() {
assert!(!notes.is_empty(), "{filter}: reported");
}
}
#[test]
fn a_doubling_chain_of_merges_is_refused_not_expanded() {
// Each merge holds the previous result twice: 2^40 layers if expanded.
let mut f = String::from(r##"<feMerge result="r0"><feMergeNode in="SourceGraphic"/><feMergeNode in="SourceGraphic"/></feMerge>"##);
for i in 1..40 {
f.push_str(&format!(r##"<feMerge result="r{i}"><feMergeNode in="r{}"/><feMergeNode in="r{}"/></feMerge>"##, i - 1, i - 1));
}
let (fx, notes) = effects(&f, "");
assert!(fx.is_empty(), "{fx:?}");
assert!(!notes.is_empty());
}
+26 -13
View File
@@ -93,6 +93,8 @@ struct W<'a> {
used_ids: std::collections::BTreeSet<String>,
/// The next `_k` suffix to try per base id, so repeated names don't rescan from `_2`.
next_suffix: std::collections::HashMap<String, usize>,
/// The `<image>` written to `defs` per image key, so paints of one image share its bytes.
images: std::collections::HashMap<String, String>,
}
/// ` clip-path="url(#…)"` for a clip path id (else nothing).
@@ -269,17 +271,29 @@ impl W<'_> {
PaintKind::Image(img) => {
let data = self.doc.images.get(&img.image)?;
let pid = self.id("pattern");
let iid = self.id("image");
// Formats SVG viewers don't show (TIFF, BMP) go in as PNG.
let png;
let (mime, bytes) = match sniff_mime(&data.bytes) {
"application/octet-stream" => {
png = figcraft_render::images::decode(&data.bytes).and_then(|p| figcraft_render::encode_png(&p).ok())?;
("image/png", png.as_slice())
let iid = match self.images.get(&img.image) {
Some(iid) => iid.clone(),
None => {
let iid = self.id("image");
// Formats SVG viewers don't show (TIFF, BMP) go in as PNG.
let png;
let (mime, bytes) = match sniff_mime(&data.bytes) {
"application/octet-stream" => {
png = figcraft_render::images::decode(&data.bytes).and_then(|p| figcraft_render::encode_png(&p).ok())?;
("image/png", png.as_slice())
}
m => (m, data.bytes.as_slice()),
};
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
let _ = write!(
self.defs,
"<image id=\"{iid}\" width=\"{}\" height=\"{}\" href=\"data:{mime};base64,{b64}\"/>",
data.width, data.height
);
self.images.insert(img.image.clone(), iid.clone());
iid
}
m => (m, data.bytes.as_slice()),
};
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
let t = figcraft_render::paint::image_transform(img, f64::from(data.width), f64::from(data.height), w, h);
let m = Affine::new([f64::from(t.sx), f64::from(t.ky), f64::from(t.kx), f64::from(t.sy), f64::from(t.tx), f64::from(t.ty)]);
let (pw, ph) = if img.scale_mode == figcraft_color::ImageScaleMode::Tile {
@@ -289,12 +303,10 @@ impl W<'_> {
};
let _ = write!(
self.defs,
"<pattern id=\"{pid}\" patternUnits=\"userSpaceOnUse\" width=\"{}\" height=\"{}\" patternTransform=\"{}\"><image id=\"{iid}\" width=\"{}\" height=\"{}\" href=\"data:{mime};base64,{b64}\"/></pattern>",
"<pattern id=\"{pid}\" patternUnits=\"userSpaceOnUse\" width=\"{}\" height=\"{}\" patternTransform=\"{}\"><use href=\"#{iid}\"/></pattern>",
num(pw),
num(ph),
matrix(m),
data.width,
data.height
matrix(m)
);
let op = if p.opacity < 0.999 { format!(" fill-opacity=\"{}\"", num(f64::from(p.opacity))) } else { String::new() };
Some(format!("fill=\"url(#{pid})\"{op}{blend}"))
@@ -1148,6 +1160,7 @@ pub fn try_export_svg(doc: &Document, ids: &[NodeId], opts: &SvgOptions) -> Resu
clip: None,
used_ids: Default::default(),
next_suffix: Default::default(),
images: Default::default(),
};
for id in ids {
let parent_xf = doc.node(*id).and_then(|n| n.parent).map(|p| doc.world_transform(p)).unwrap_or(Affine::IDENTITY);
+1
View File
@@ -294,6 +294,7 @@ fn unique_id_is_linear_for_repeated_names() {
clip: None,
used_ids: Default::default(),
next_suffix: Default::default(),
images: Default::default(),
};
assert_eq!(w.unique_id("a"), "a");
assert_eq!(w.unique_id("a_3"), "a_3");
+6
View File
@@ -268,10 +268,16 @@ impl FigApp {
return;
}
if !self.has_files() || self.ui.home {
let docs = &self.session.docs;
self.canvas.drop_closed(|uid| docs.iter().any(|d| d.uid == uid));
home::show(self, ui);
// The shortcuts panel belongs to the canvas; it doesn't hang over the home screen
// (cleared after the home widgets, which may have just asked for it).
self.ui.shortcuts_panel = false;
// The keymap runs with the canvas; here the one shortcut that still applies is read directly.
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Comma)) {
self.run("app.preferences", serde_json::json!({}));
}
dialogs::keys(self, &ctx);
dialogs::show(self, &ctx);
updates_ui::show(self, &ctx);
+49
View File
@@ -57,6 +57,10 @@ pub struct CanvasState {
pub tex_coarse: bool,
/// The request the texture answers ([`crate::render_worker::Done::seq`]).
tex_seq: u64,
/// Refined images of the files and pages shown before, newest first: switching back to one
/// shows its image at once while it renders again, instead of a blank canvas (and, where
/// renders are slow, a coarse preview).
kept: Vec<Kept>,
submitted: Option<JobKey>,
/// The view of the last render asked for.
want_view: Option<figcraft_render::View>,
@@ -98,6 +102,7 @@ impl Default for CanvasState {
tex_of: None,
tex_coarse: false,
tex_seq: 0,
kept: Vec::new(),
submitted: None,
want_view: None,
render_work: None,
@@ -119,6 +124,45 @@ impl Default for CanvasState {
}
}
/// At most this many images of files and pages not shown are kept (each is a canvas-sized texture).
const KEPT: usize = 4;
/// A refined canvas image of a file and page not shown now ([`CanvasState::kept`]).
struct Kept {
texture: egui::TextureHandle,
view: figcraft_render::View,
of: (u64, NodeId),
seq: u64,
}
impl CanvasState {
/// When the file or page shown is no longer the one the texture is of, set the texture aside
/// (if refined) and bring back the image kept for `shown`, if any. Images of files that are no
/// longer open (`open` says which are) are dropped every frame, not only on a switch: a
/// background tab can close while the file shown stays the same.
fn switch_texture(&mut self, shown: Option<(u64, NodeId)>, open: impl Fn(u64) -> bool) {
if shown.is_some() && self.tex_of != shown {
let back = self.kept.iter().position(|k| Some(k.of) == shown).map(|i| self.kept.remove(i));
let (texture, view, of) = (self.texture.take(), self.tex_view.take(), self.tex_of.take());
if let (Some(texture), Some(view), Some(of), false) = (texture, view, of, self.tex_coarse) {
self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq });
}
self.tex_coarse = false;
if let Some(k) = back {
(self.texture, self.tex_view, self.tex_of, self.tex_seq) = (Some(k.texture), Some(k.view), Some(k.of), k.seq);
}
}
self.drop_closed(open);
self.kept.truncate(KEPT);
}
/// Drop the kept images of files that are no longer open (`open` says which are). Home calls
/// this too: the canvas isn't shown there, and closing the last file leads to it.
pub(crate) fn drop_closed(&mut self, open: impl Fn(u64) -> bool) {
self.kept.retain(|k| open(k.of.0));
}
}
/// What the canvas shows while an IME composition is in progress: the document with the
/// composition inserted at the caret (the real document only gets it on commit).
pub struct PreeditView {
@@ -264,6 +308,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
// Every finished render is shown, even when a newer one is already on its way: renders finish
// in order, and an edit every frame (a drag) would otherwise never show until it stopped.
let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok();
let docs = &app.session.docs;
app.canvas.switch_texture(shown, |uid| docs.iter().any(|d| d.uid == uid));
if let Some(done) = worker.poll()
&& shows(&app.canvas, &done, shown)
{
@@ -408,3 +454,6 @@ mod wheel_zoom_tests;
#[cfg(test)]
mod zoom_preview_tests;
#[cfg(test)]
mod tab_switch_tests;
+1 -1
View File
@@ -140,7 +140,7 @@ fn has(app: &FigApp) -> Option<Has> {
});
line.ids.push(n.id);
}
Some(BoardItem::Label { .. }) => h.text = true,
Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true,
Some(BoardItem::Table) => h.table = true,
Some(BoardItem::Stamp { .. }) | None => {}
}
@@ -0,0 +1,159 @@
//! Switching tabs: the canvas shows the image a file had when it was last on screen from the first
//! frame back, instead of a blank page (and, where renders are slow, a coarse preview) while the
//! file renders again.
use egui::{Pos2, RawInput, Rect, vec2};
use figcraft_engine::Session;
use serde_json::json;
use crate::idle_tests::wait_for_render;
use crate::{FigApp, NoServices};
/// The whole UI, driven headless, with files of their own names open.
struct Harness {
ctx: egui::Context,
app: FigApp,
time: f64,
}
impl Harness {
/// The UI with a file named after each of `names` (each with a rectangle); the last is shown.
fn new(names: &[&str]) -> Self {
figcraft_text::scan_system_fonts();
let mut s = Session::empty();
for n in names {
s.execute("file.new", &json!({"name": n})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 120})).unwrap();
}
Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0 }
}
/// One frame with no input, 1/60 s after the last.
fn frame(&mut self) {
self.time += 1.0 / 60.0;
self.app.clock.set_test_now(Some(self.time));
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), ..Default::default() };
let app = &mut self.app;
let mut out = self.ctx.run_ui(input, |ui| app.ui(ui));
out.textures_delta.clear();
}
/// Frames until the canvas shows a refined image of the file and page on screen.
fn settle(&mut self) {
for _ in 0..200 {
self.frame();
wait_for_render(&self.app);
let ds = self.app.session.ds().unwrap();
let c = &self.app.canvas;
if c.tex_of == Some((ds.uid, ds.page)) && !c.tex_coarse && c.texture.is_some() {
return;
}
}
panic!("the canvas never showed a refined image");
}
/// Show the file named `name`, as clicking its tab does.
fn switch(&mut self, name: &str) {
let i = self.app.session.docs.iter().position(|d| d.doc.name == name).unwrap();
self.app.run("doc.switch", json!({"index": i}));
}
/// The file and page on screen.
fn shown(&self) -> (u64, figcraft_doc::NodeId) {
let ds = self.app.session.ds().unwrap();
(ds.uid, ds.page)
}
}
#[test]
fn switching_back_to_a_tab_shows_its_image_on_the_first_frame() {
let mut h = Harness::new(&["A", "B"]);
h.switch("A");
h.settle();
let a = (h.shown(), h.app.canvas.tex_seq, h.app.canvas.texture.as_ref().map(egui::TextureHandle::id));
h.switch("B");
h.settle();
let b = (h.shown(), h.app.canvas.tex_seq);
assert_ne!(h.app.canvas.tex_of, Some(a.0));
// The image brought back is the one A had when it was last shown. Looked at without a frame:
// in one, a render of A asked for in it could already have come back and replaced it.
let c = &mut h.app.canvas;
c.switch_texture(Some(a.0), |_| true);
assert_eq!((c.tex_of, c.tex_seq, c.texture.as_ref().map(egui::TextureHandle::id)), (Some(a.0), a.1, a.2));
c.switch_texture(Some(b.0), |_| true);
assert_eq!((c.tex_of, c.tex_seq), (Some(b.0), b.1), "B's image was kept in turn");
h.switch("A");
h.frame();
let c = &h.app.canvas;
assert_eq!(c.tex_of, Some(a.0), "A's image is on screen at once");
assert!(!c.tex_coarse, "and it is the refined one, not a preview");
assert!(c.kept.iter().any(|k| k.of == b.0), "B's image is kept in turn");
h.settle();
}
#[test]
fn switching_back_to_a_page_shows_its_image_on_the_first_frame() {
let mut h = Harness::new(&["A"]);
h.settle();
let first = (h.shown(), h.app.canvas.tex_seq, h.app.canvas.texture.as_ref().map(egui::TextureHandle::id));
h.app.run("page.add", json!({}));
h.app.run("shape.ellipse", json!({"x": 40, "y": 40, "width": 120, "height": 120}));
h.settle();
let second = (h.shown(), h.app.canvas.tex_seq);
assert_ne!(first.0, second.0);
// Looked at without a frame, as for tabs: a render asked for in one could replace the image.
let c = &mut h.app.canvas;
c.switch_texture(Some(first.0), |_| true);
assert_eq!((c.tex_of, c.tex_seq, c.texture.as_ref().map(egui::TextureHandle::id)), (Some(first.0), first.1, first.2));
c.switch_texture(Some(second.0), |_| true);
assert_eq!((c.tex_of, c.tex_seq), (Some(second.0), second.1), "the second page's image was kept in turn");
h.app.run("page.select", json!({"index": 0}));
h.frame();
let c = &h.app.canvas;
assert_eq!(c.tex_of, Some(first.0), "the first page's image is on screen at once");
assert!(!c.tex_coarse);
assert!(c.kept.iter().any(|k| k.of == second.0), "the second page's image is kept in turn");
h.settle();
}
#[test]
fn kept_images_are_bounded_and_dropped_with_their_files() {
let names = ["A", "B", "C", "D", "E", "F", "G"];
let mut h = Harness::new(&names);
for n in names {
h.switch(n);
h.settle();
}
assert_eq!(h.app.canvas.kept.len(), super::KEPT);
let f = h.app.session.docs.iter().position(|d| d.doc.name == "F").unwrap();
let f_uid = h.app.session.docs[f].uid;
assert!(h.app.canvas.kept.iter().any(|k| k.of.0 == f_uid));
// A tab closed in the background: the file shown stays the same.
let before = h.shown();
h.app.run("file.close", json!({"index": f, "force": true}));
h.frame();
assert_eq!(h.shown(), before);
assert!(h.app.canvas.kept.iter().all(|k| k.of.0 != f_uid), "a closed file's image goes");
}
#[test]
fn closing_the_last_file_drops_its_kept_images() {
let mut h = Harness::new(&["A", "B"]);
h.switch("A");
h.settle();
h.switch("B");
h.settle();
assert_eq!(h.app.canvas.kept.len(), 1, "A's image is kept");
// Both close before the next frame, which then shows Home, not the canvas.
let a = h.app.session.docs.iter().position(|d| d.doc.name == "A").unwrap();
h.app.run("file.close", json!({"index": a, "force": true}));
h.app.run("file.close", json!({"index": 0, "force": true}));
assert!(h.app.session.docs.is_empty());
h.frame();
assert!(h.app.canvas.kept.is_empty(), "no closed file's image stays behind Home");
}
@@ -23,8 +23,12 @@ use crate::render_worker::{
Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now,
};
/// A page of ellipses with a rectangle on top; the session and the rectangle.
/// A page of ellipses with a rectangle on top; the session and the rectangle. The system fonts are
/// scanned first (once per process, and a concurrent caller waits for it): the scan another test
/// starts bumps the global font generation, and a render kept from before it is stale, so a pan
/// or an edit meanwhile would redraw in full instead of patching.
fn document() -> (Session, NodeId) {
figcraft_text::scan_system_fonts();
let mut s = Session::new();
for k in 0..12 {
let k = f64::from(k);
+22 -2
View File
@@ -190,8 +190,8 @@ fn dropped(app: &mut FigApp, ctx: &egui::Context) {
}
}
/// Draw the Home sidebar: app icon and wordmark, file/template search (Escape clears it)
/// and section tabs; choosing a section clears the file query.
/// Draw the Home sidebar: app icon and wordmark, file/template search (Escape clears it), section
/// tabs (choosing one clears the file query) and Preferences at the bottom.
fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
let mut y = left.min.y + 20.0;
crate::theme::paint_app_icon(ui, Rect::from_min_size(pos2(left.min.x + 12.0, y - 4.0), vec2(32.0, 32.0)));
@@ -229,6 +229,26 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
}
y += 34.0;
}
let pref_y = (left.max.y - 44.0).max(y + 12.0);
if pref_y > y + 12.0 {
ui.painter().line_segment([pos2(left.min.x + 12.0, pref_y - 6.0), pos2(left.max.x - 12.0, pref_y - 6.0)], Stroke::new(1.0, t.border));
}
let r = Rect::from_min_size(pos2(left.min.x + 8.0, pref_y), vec2(SIDEBAR - 16.0, 32.0));
let mut resp = ui.interact(r, ui.scope_id().with("home_preferences"), Sense::click());
let current = app.ui.preferences;
a11y::button(&resp, tr("Preferences"));
if current || resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
}
focus_ring(ui, t, r, &resp, 5);
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
let key_label = figcraft_engine::keymap::display("Cmd+,", crate::shortcuts::platform());
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
resp = resp.on_hover_text(format!("{} ({})", tr("Preferences"), key_label));
if resp.clicked() {
app.ui.preferences = !app.ui.preferences;
}
}
fn file_matches(name: &str, location: &str, query: &str) -> bool {
+31
View File
@@ -917,3 +917,34 @@ fn a_jam_file_is_a_document_open_and_drops_take() {
assert!(crate::open::opens(path) && crate::open::is_document(path), "{name}");
}
}
/// The Preferences dialog can be opened and toggled from the home screen via
/// the `Cmd/Ctrl + ,` shortcut as well as by clicking Preferences in the sidebar.
#[test]
fn home_screen_preferences_shortcut_and_sidebar_access() {
let mut u = first_run();
u.app.ui.home = true;
u.frame(vec![]);
assert!(!u.app.ui.preferences);
// Ctrl/Cmd + Comma opens Preferences on the Home screen.
u.frame(vec![
Event::Key { key: Key::Comma, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND },
Event::Key { key: Key::Comma, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::COMMAND },
]);
assert!(u.app.ui.preferences, "Ctrl/Cmd+, should open Preferences from the Home screen");
// Escape closes Preferences.
press(&mut u, Key::Escape);
assert!(!u.app.ui.preferences, "Escape should close Preferences");
// Clicking Preferences in the sidebar opens Preferences.
let s = shapes(&mut u);
click(&mut u, text_center(&s, "Preferences"));
assert!(u.app.ui.preferences, "Clicking Preferences in sidebar should open Preferences");
// Clicking it again toggles it closed.
let s = shapes(&mut u);
click(&mut u, text_center(&s, "Preferences"));
assert!(!u.app.ui.preferences, "Clicking Preferences in sidebar again should close it");
}
@@ -252,6 +252,54 @@ fn sweeping_across_eyes_and_padlocks_sets_several_layers() {
assert!(!u.app.session.doc().unwrap().node(a).unwrap().visible, "a click on the eye hides that layer");
}
#[test]
fn the_padlock_of_a_layer_in_a_locked_frame_is_inert() {
let mut s = Session::new();
let frame = id(s.execute("frame.create", &json!({"name": "Locked frame"})).unwrap());
let child = rect(&mut s, "child", 0.0, Some(frame));
s.execute("select.none", &json!({})).unwrap();
s.execute("object.toggleLock", &json!({"ids": [frame], "locked": true})).unwrap();
let mut u = Ui::new(s);
// Selecting the child reveals its row; then the selection goes away.
u.app.run("select.set", json!({"ids": [child]}));
u.frame(vec![]);
u.app.run("select.none", json!({}));
u.frame(vec![]);
let steps = u.app.session.undo_depth();
let r = u.row_at(child);
// The padlock column (see the sweep test above).
click(&mut u, Pos2::new(250.0, r.y), Modifiers::NONE);
assert!(!u.app.session.doc().unwrap().node(child).unwrap().locked, "the child's padlock doesn't lock it");
assert_eq!(u.app.session.undo_depth(), steps, "and adds no undo step");
}
#[test]
fn a_padlock_sweep_skips_the_children_of_a_locked_frame() {
let mut s = Session::new();
let frame = id(s.execute("frame.create", &json!({"name": "Locked frame"})).unwrap());
let c1 = rect(&mut s, "child 1", 0.0, Some(frame));
let c2 = rect(&mut s, "child 2", 20.0, Some(frame));
let sibling = rect(&mut s, "sibling", 40.0, None);
s.execute("select.none", &json!({})).unwrap();
s.execute("object.toggleLock", &json!({"ids": [frame], "locked": true})).unwrap();
let mut u = Ui::new(s);
// Selecting a child reveals the frame's rows; then the selection goes away.
u.app.run("select.set", json!({"ids": [c1]}));
u.frame(vec![]);
u.app.run("select.none", json!({}));
u.frame(vec![]);
let padlock = 250.0;
let (rs, rc) = (u.row_at(sibling), u.row_at(c1));
let from = Pos2::new(padlock, rs.y);
u.frame(vec![Event::PointerMoved(from)]);
u.drag_to(from, Pos2::new(padlock, rc.y));
u.button(Pos2::new(padlock, rc.y), false);
let doc = u.app.session.doc().unwrap();
assert!(doc.node(sibling).unwrap().locked, "the sibling is locked by the sweep");
assert!(!doc.node(c1).unwrap().locked, "a child of a locked frame keeps its own flag");
assert!(!doc.node(c2).unwrap().locked, "so does the other child");
}
#[test]
fn renaming_several_layers_opens_the_rename_dialog() {
let (mut u, [a, b, c, _d]) = four();
+2
View File
@@ -180,6 +180,8 @@ mod menu_contrast_tests;
#[cfg(test)]
mod menu_input_tests;
#[cfg(test)]
mod menu_overflow_tests;
#[cfg(test)]
mod mirror_tests;
#[cfg(test)]
mod missing_fonts_tests;
+107
View File
@@ -0,0 +1,107 @@
//! The main menu and its submenus stay inside the window (#2217): a submenu that would run past
//! the bottom moves up to fit, and one taller than the window scrolls.
use egui::{Event, Id, MouseWheelUnit, Rect, TouchPhase, pos2, vec2};
use figcraft_engine::Session;
use serde_json::json;
use crate::layers_drag_tests::Ui;
use crate::live_tests::{flat, text_center};
use crate::menus::{HOVER_DELAY, main_menu_id};
use crate::present_tests::id;
/// A window `h` tall with the main menu open and the Object submenu showing.
fn object_menu_open(s: Session, h: f32) -> Ui {
let mut u = Ui::new(s);
u.screen = vec2(1280.0, h);
u.app.ui.main_menu = true;
u.frame(vec![Event::PointerMoved(pos2(1000.0, 10.0))]);
u.frame(vec![]);
let m = u.ctx.memory(|m| m.area_rect(main_menu_id())).expect("main menu drawn");
// Frame margin, the Actions row and the space under it, then three rows down to Object.
let y = m.min.y + 8.0 + 30.0 + 6.0 + 28.0 * 3.0 + 14.0;
u.frame(vec![Event::PointerMoved(pos2(m.min.x + 60.0, y))]);
for _ in 0..((HOVER_DELAY + 0.3) * 60.0) as usize {
u.frame(vec![]);
}
u
}
fn object_panel(u: &Ui) -> Rect {
u.ctx.memory(|m| m.area_rect(Id::unique(("menu", "Object")))).expect("the Object submenu is drawn")
}
#[test]
fn the_object_submenu_stays_inside_a_short_window() {
let u = object_menu_open(Session::new(), 600.0);
let panel = object_panel(&u);
let window = Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 600.0));
assert!(window.contains_rect(panel), "the Object submenu {panel:?} runs outside the window {window:?}");
}
#[test]
fn a_menu_taller_than_the_window_scrolls_to_its_last_command() {
let mut s = Session::new();
let a = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap());
let b = id(&s.execute("shape.rectangle", &json!({"x": 100, "y": 30, "width": 20, "height": 20})).unwrap());
s.execute("select.set", &json!({"ids": [b]})).unwrap();
let mut u = object_menu_open(s, 420.0);
let panel = object_panel(&u);
assert!(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 420.0)).contains_rect(panel), "{panel:?} outside the window");
// Turn the wheel over the panel until the end of the list is in view.
for _ in 0..4 {
let wheel = Event::MouseWheel {
unit: MouseWheelUnit::Point,
source: egui::MouseWheelSource::Unknown,
delta: vec2(0.0, -1500.0),
phase: TouchPhase::Move,
modifiers: Default::default(),
};
u.frame(vec![Event::PointerMoved(panel.center()), wheel]);
for _ in 0..20 {
u.frame(vec![]);
}
}
let shapes = flat(&u.frame_output(vec![]).shapes);
let at = text_center(&shapes, "Move to page");
assert!(panel.contains(at), "the last commands are out of reach: at {at:?} outside {panel:?}");
// And a command above it, reached by scrolling back up, runs on click.
let wheel = Event::MouseWheel {
unit: MouseWheelUnit::Point,
source: egui::MouseWheelSource::Unknown,
delta: vec2(0.0, 1.0e5),
phase: TouchPhase::Move,
modifiers: Default::default(),
};
u.frame(vec![Event::PointerMoved(panel.center()), wheel]);
for _ in 0..20 {
u.frame(vec![]);
}
// Scroll down in small steps until "Send to back" shows inside the panel, then click it.
let mut hit = None;
for _ in 0..40 {
let shapes = flat(&u.frame_output(vec![]).shapes);
let at = text_center(&shapes, "Send to back");
if panel.contains(at) {
hit = Some(at);
break;
}
let wheel = Event::MouseWheel {
unit: MouseWheelUnit::Point,
source: egui::MouseWheelSource::Unknown,
delta: vec2(0.0, -120.0),
phase: TouchPhase::Move,
modifiers: Default::default(),
};
u.frame(vec![Event::PointerMoved(panel.center()), wheel]);
for _ in 0..10 {
u.frame(vec![]);
}
}
let at = hit.expect("Send to back scrolls into view");
crate::component_swap_default_tests::click(&mut u, at);
let doc = u.app.session.doc().unwrap();
let page = u.app.session.page().unwrap();
let kids = &doc.node(page).unwrap().children;
assert_eq!((kids.first().copied(), kids.last().copied()), (Some(b), Some(a)), "Send to back ran");
}
+40 -31
View File
@@ -382,40 +382,49 @@ pub fn popups(app: &mut FigApp, ctx: &egui::Context) {
// Main menu.
if app.ui.main_menu {
let mut close = false;
let area = egui::Area::new(main_menu_id()).fixed_pos(pos2(8.0, crate::tabs::HEIGHT + 48.0)).order(egui::Order::Foreground).show(ctx, |ui| {
menu_frame(ui, &t, At { root: main_menu_id(), path: String::new() }, |ui| {
// Quick actions search row.
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());
plain_row_hover(ui, &resp);
a11y::menu_item(&resp, tr("Actions…"), crate::shortcuts::shortcut("app.actions").unwrap_or(""), None);
ui.painter().rect_filled(r.shrink(2.0), CornerRadius::same(5), Color32::from_white_alpha(18));
icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 16.0, r.center().y), vec2(14.0, 14.0)), Icon::Search, t.menu_dim);
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, tr("Actions…"), regular(12.0), t.menu_dim);
ui.painter().text(
pos2(r.max.x - 10.0, r.center().y),
Align2::RIGHT_CENTER,
pretty_shortcut(crate::shortcuts::shortcut("app.actions").unwrap_or("")),
regular(12.0),
t.menu_dim,
);
if resp.clicked() {
set_palette(&mut app.ui, true);
close = true;
}
ui.add_space(6.0);
for top in TOP_MENUS {
if submenu_at(
ui,
SubmenuOptions { area: Id::unique(("menu", *top)), key: top, label: tr(top), gap: 12.0, constrain: false, tokens: &t },
|ui| menu_level(app, ui, top).then_some(()),
)
.is_some()
{
let area = egui::Area::new(main_menu_id())
.fixed_pos(pos2(8.0, crate::tabs::HEIGHT + 48.0))
.order(egui::Order::Foreground)
.constrain_to(tree::vertical_bounds(ctx))
.show(ctx, |ui| {
menu_frame(ui, &t, At { root: main_menu_id(), path: String::new() }, |ui| {
// Quick actions search row.
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());
plain_row_hover(ui, &resp);
a11y::menu_item(&resp, tr("Actions…"), crate::shortcuts::shortcut("app.actions").unwrap_or(""), None);
ui.painter().rect_filled(r.shrink(2.0), CornerRadius::same(5), Color32::from_white_alpha(18));
icons::paint(
ui.painter(),
Rect::from_center_size(pos2(r.min.x + 16.0, r.center().y), vec2(14.0, 14.0)),
Icon::Search,
t.menu_dim,
);
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, tr("Actions…"), regular(12.0), t.menu_dim);
ui.painter().text(
pos2(r.max.x - 10.0, r.center().y),
Align2::RIGHT_CENTER,
pretty_shortcut(crate::shortcuts::shortcut("app.actions").unwrap_or("")),
regular(12.0),
t.menu_dim,
);
if resp.clicked() {
set_palette(&mut app.ui, true);
close = true;
}
}
ui.add_space(6.0);
for top in TOP_MENUS {
if submenu_at(
ui,
SubmenuOptions { area: Id::unique(("menu", *top)), key: top, label: tr(top), gap: 12.0, constrain: false, tokens: &t },
|ui| menu_level(app, ui, top).then_some(()),
)
.is_some()
{
close = true;
}
}
});
});
});
let clicked_outside = ctx.input(|i| i.pointer.any_pressed()) && !over_menu(ctx) || ctx.input(|i| i.key_pressed(egui::Key::Escape));
if close || (clicked_outside && !area.response.hovered()) {
app.ui.main_menu = false;
+11 -3
View File
@@ -7,8 +7,8 @@ use crate::i18n::trf;
/// Paste: the system clipboard wins when it holds something newer than our own copy (layers copied
/// from another design app, an image, SVG or text from another app); otherwise our copied layers.
/// `event_text` is the text the platform handed over with the paste event (the browser has no
/// other way to read it). `at`: the page point to paste at (Paste here); `None` pastes in the
/// middle of the view.
/// other way to read it; the desktop's clipboard bridge has already read it). `at`: the page
/// point to paste at (Paste here); `None` pastes in the middle of the view.
/// In Dev Mode only a comment's link pastes (it opens the thread); everything else would edit.
pub fn paste(app: &mut FigApp, event_text: Option<&str>, at: Option<(f64, f64)>) {
// A gesture injected through the control channel pastes only our own copied layers: it must not
@@ -47,7 +47,15 @@ pub fn paste(app: &mut FigApp, event_text: Option<&str>, at: Option<(f64, f64)>)
}
return;
}
let sys_text = app.services.clipboard_get_text().or_else(|| event_text.map(str::to_string)).filter(|t| !t.is_empty());
// The text the platform handed over with the paste event is the system clipboard's text: the
// browser delivers it, and the desktop's async clipboard bridge read it while the window
// thread was free to serve the transfer. Never re-read the clipboard synchronously for it —
// on the desktop that read blocks the window thread for the read timeout, and when this app
// itself owns the clipboard (a self-paste) its own source can only be served by that very
// thread, so the read waits the full timeout and the window freezes for seconds (#2021).
// A paste the platform didn't hand text over (a chord, an image, the menu) reads it, as before.
let sys_text =
if let Some(t) = event_text { (!t.is_empty()).then(|| t.to_string()) } else { app.services.clipboard_get_text().filter(|t| !t.is_empty()) };
// The text matching `last_copy` means the system clipboard still holds what we mirrored only
// while the engine clipboard is the one we mirrored. A control-channel copy changes the engine
// clipboard without writing the system clipboard, so its generation no longer matches and the
+55 -2
View File
@@ -289,6 +289,7 @@ pub(super) fn submenu_at<R>(ui: &mut Ui, options: SubmenuOptions<'_>, add: impl
.fixed_pos(pos)
.order(egui::Order::Foreground)
.constrain(constrain || cramped)
.constrain_to(if constrain || cramped { screen } else { vertical_bounds(ui.ctx()) })
.show(ui.ctx(), |ui| menu_frame(ui, t, child, add));
let panel = shown.response.rect;
with_level(ui.ctx(), &at, |l| l.panel = Some(panel));
@@ -316,12 +317,64 @@ pub(super) fn menu_frame<R>(ui: &mut Ui, t: &Tokens, at: At, add: impl FnOnce(&m
ui.set_width(w);
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
let key = at_key(ui);
ui.data_mut(|d| d.insert_temp(key, at));
add(ui)
ui.data_mut(|d| d.insert_temp(key, at.clone()));
// Taller than the window (as measured last frame): its rows scroll. Otherwise they
// draw straight into the panel, so a menu that fits behaves as it always did.
let max_h = (ui.ctx().content_rect().height() - 2.0 * EDGE_MARGIN - 16.0).max(MENU_ROW_H);
let height_key = at_key(ui).with("content_h");
let last_h = ui.data(|d| d.get_temp::<f32>(height_key)).unwrap_or(0.0);
if last_h <= max_h {
let top = ui.cursor().min.y;
let r = add(ui);
let h = ui.min_rect().max.y - top;
ui.data_mut(|d| d.insert_temp(height_key, h));
if h > max_h {
ui.ctx().request_repaint();
}
return r;
}
// The scroll area's ui has its own scope, so it gets the level and width state of this
// one, and hands back the width its rows asked for.
let outer_w = width_key(ui);
let asked = ui.data(|d| d.get_temp::<f32>(outer_w));
let shown = egui::ScrollArea::vertical()
.max_height(max_h)
.auto_shrink([false, true])
.scroll_source(egui::scroll_area::ScrollSource::MOUSE_WHEEL | egui::scroll_area::ScrollSource::SCROLL_BAR)
.show(ui, |ui| {
let (inner_at, inner_w) = (at_key(ui), width_key(ui));
ui.data_mut(|d| {
d.insert_temp(inner_at, at);
if let Some(a) = asked {
d.insert_temp(inner_w, a);
}
});
let r = add(ui);
(r, ui.data(|d| d.get_temp::<f32>(inner_w)))
});
ui.data_mut(|d| d.insert_temp(height_key, shown.content_size.y));
let (r, wanted) = shown.inner;
if let Some(wanted) = wanted.filter(|w| asked.is_none_or(|a| *w > a)) {
ui.data_mut(|d| d.insert_temp(outer_w, wanted));
}
r
})
.inner
}
/// The gap a menu keeps from the window's top and bottom edges.
pub(super) const EDGE_MARGIN: f32 = 8.0;
/// A menu row's height.
const MENU_ROW_H: f32 = 28.0;
/// Where a menu may sit: anywhere across, within the window's height less the margins. A menu that
/// would run past the bottom moves up (never above the top); one taller than that scrolls.
pub(super) fn vertical_bounds(ctx: &egui::Context) -> Rect {
let s = ctx.content_rect();
Rect::from_min_max(pos2(-1.0e5, s.min.y + EDGE_MARGIN), pos2(1.0e5, s.max.y - EDGE_MARGIN))
}
/// A menu's narrowest width.
const MENU_W: f32 = 240.0;
+15 -6
View File
@@ -972,6 +972,8 @@ fn eye_lock(
// A sweep across the eyes or padlocks takes in the rows the pointer passes.
if let Some(sw) = sweep.as_mut()
&& !sw.ids.contains(&row.id)
// A padlock sweep leaves the children of a locked layer alone (their padlock is inert).
&& !(sw.lock && row.locked_above)
&& ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| r.y_range().contains(p.y))
{
sw.ids.push(row.id);
@@ -1003,13 +1005,20 @@ fn eye_lock(
icons::paint(ui.painter(), lr.shrink(3.0), if locked || row.locked_above { Icon::Lock } else { Icon::Unlock }, col);
}
if show_lock && !dev {
let lresp = ui.interact(lr, ui.scope_id().with(("lock", row.id)), Sense::click_and_drag());
// A child of a locked layer can't be locked or unlocked on its own while the parent is
// locked (Lock and unlock layers): its padlock is inert.
let sense = if row.locked_above { Sense::hover() } else { Sense::click_and_drag() };
let lresp = ui.interact(lr, ui.scope_id().with(("lock", row.id)), sense);
a11y::toggle(&lresp, tr("Locked"), locked || row.locked_above);
if lresp.clicked() {
lock = Some(row.id);
}
if lresp.drag_started() {
*sweep = Some(Sweep { lock: true, on: !n.locked, ids: vec![row.id] });
if row.locked_above {
a11y::disabled(&lresp);
} else {
if lresp.clicked() {
lock = Some(row.id);
}
if lresp.drag_started() {
*sweep = Some(Sweep { lock: true, on: !n.locked, ids: vec![row.id] });
}
}
}
(vis, lock)
+49
View File
@@ -3,6 +3,9 @@
//! whatever the system clipboard has. A copy that never reached the clipboard pasted the text that
//! was there before as a text layer instead of the copied layers.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use egui::{Event, Key, Modifiers, OutputCommand, Pos2, RawInput, Rect, vec2};
use figcraft_doc::NodeKind;
use figcraft_engine::Session;
@@ -223,3 +226,49 @@ fn a_mismatched_image_buffer_is_dropped() {
assert!(out.platform_output.commands.is_empty(), "{w}x{h}");
}
}
/// The system clipboard's text read, counted so a test can assert when it ran. The desktop's
/// arboard read blocks the window thread up to `CLIPBOARD_TIMEOUT`; against the app's own Wayland
/// source (a self-paste) it waits the full timeout — the whole UI freezes for seconds (#2021) —
/// and its result is discarded in favour of the paste event's text. A paste whose platform event
/// already carries the clipboard text must never perform that synchronous re-read.
struct CountingReads {
/// How often the synchronous text read was asked for.
reads: Arc<AtomicUsize>,
}
impl Services for CountingReads {
fn clipboard_get_text(&mut self) -> Option<String> {
self.reads.fetch_add(1, Ordering::Relaxed);
None
}
}
#[test]
fn a_paste_event_its_own_text_never_triggers_the_synchronous_text_read() {
// The platform (the desktop's async clipboard bridge, or the browser) already read the
// clipboard and handed the text with the paste event.
let reads = Arc::new(AtomicUsize::new(0));
let mut s = Session::new();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let mut p = Page {
ctx: egui::Context::default(),
app: FigApp::new(s, Box::new(CountingReads { reads: reads.clone() })),
time: 0.0,
clipboard: String::new(),
};
for _ in 0..3 {
p.frame(vec![]);
}
// The desktop delivers the copied layers' SVG as the paste event's text.
let text = "<svg width=\"100\" height=\"50\"><rect/></svg>";
p.frame(vec![Page::key(Key::V, true), Event::Paste(text.to_string())]);
p.frame(vec![Page::key(Key::V, false)]);
assert_eq!(reads.load(Ordering::Relaxed), 0, "the text came with the paste event: no blocking re-read of the system clipboard");
// Even a second paste must not re-read: the clipboard still holds the pasted text.
p.frame(vec![Page::key(Key::V, true), Event::Paste(text.to_string())]);
p.frame(vec![Page::key(Key::V, false)]);
assert_eq!(reads.load(Ordering::Relaxed), 0, "still the event's text: no blocking re-read");
}
+27
View File
@@ -0,0 +1,27 @@
//! Release and source Flatpaks must allow release checks and host update helpers.
fn finish_args(manifest: &str) -> Vec<&str> {
manifest
.split("finish-args:")
.nth(1)
.unwrap_or_default()
.lines()
.take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#'))
.filter_map(|line| line.trim().strip_prefix("- "))
.map(|arg| arg.trim_matches(['\'', '"']))
.collect()
}
#[test]
fn flatpak_update_permissions() {
let manifests = [
include_str!("../../../packaging/linux/flatpak/ai.storyteller.figcraft.bundle.yml"),
include_str!("../../../packaging/linux/flatpak/ai.storyteller.figcraft.yml"),
];
let args = manifests.map(finish_args);
assert_eq!(args[0], args[1], "source and release permissions must agree");
for permissions in args {
for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] {
assert!(permissions.contains(&required), "missing update permission: {required}");
}
}
}
+4 -3
View File
@@ -1,13 +1,13 @@
# Boards parity
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); 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)
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); 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
follow what they join (straight, elbow or curved, their ends dragged onto other objects), marker,
highlighter and eraser, stamps, text and sections, five built-in templates and tables, edited
together in the existing live sessions, with a shared countdown and voting sessions to run a
workshop. Music, board widgets, mind maps and the rest of the tail are missing. Remaining:
workshop. Music, board widgets, the mind maps' toolbar entry and gestures, and the rest of the tail are missing. Remaining:
~20–44 h. Tracked as area 22 of
[`target-app-parity.md`](target-app-parity.md) (not in its weighted sum: the target there is the
design product). The work item is gap 24 in [`gaps.md`](gaps.md).
@@ -61,7 +61,7 @@ all end with the same geometry.
| Board widgets | missing | design-file widgets exist (`crates/engine/src/extensions/widgets.rs`), not wired to boards |
| Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own |
| Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text |
| Mind maps | missing | |
| Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet |
| 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 | |
@@ -72,6 +72,7 @@ all end with the same geometry.
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). |
| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. |
| 2026-11-10 | minor | M9, #1808: a `.jam` sticky imports as a native board sticky (`BoardItem::Sticky`): its frame keeps the saved size (240 pt, not FigCraft's 200), place, opacity and shadows, the saved colour is kept as it is (not snapped to the board colours), the note and the author line are its text layers, and it lays out like one made here (vertical, space between, hugging the height down to the saved size, the saved inset as padding). The importer reads a `board` field on the REST JSON (a FigCraft extension) for this; a sticky whose generated records are damaged, or the same sticky in a `.fig`, keeps the generated layers as before. Shapes, connectors, stamps and tables are unchanged; the note's text keeps the file's size until it is edited. Tests: `board_import_tests.rs` (native sticky, no author, damaged records, `.fig` unchanged), `import_regression_tests.rs` (the `board` field and junk values). Numbers unchanged. |
| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. |
+3 -2
View File
@@ -1,6 +1,6 @@
# Where FigCraft falls short of Figma
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from
doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The
@@ -582,7 +582,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
connector's ends drag onto another object or empty canvas (`board.reattach`); curved connectors;
elbows that go around the objects they join.
- **Missing:** timer music, board widgets, saving your own templates, table column resizing and
cell colours, mind maps, washi tape, code blocks, audio and huddles, quick-create handles,
cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles,
the stamp wheel, emotes and stickers, `.jam` files
([`boards-parity.md`](boards-parity.md)).
- **User impact:** boards cover a brainstorm, a retrospective, a flow sketch and a timed, voted
@@ -593,6 +593,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged |
| 2026-10-31 | minor | Gap 10: library analytics list the layers and files using each style and variable; their insertions, detachments and modes stay on the missing list. |
| 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. |
+17 -1
View File
@@ -470,7 +470,8 @@ Returns `{fitted: [{id, fontSize, lines, fits, orphan}]}`. Use case: a carousel
A board is a file of its own kind for thinking together: `file.newBoard {name?}` opens one (its
page is light; `inspect_document` says `kind: "board"`). Board objects are ordinary layers with a
`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink, …}`), so the usual
`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode, …}`; a connector may say
`branch: true`), so the usual
commands move, resize, recolour, copy, delete and undo them. On a design file the board commands
refuse; on a board `proto.*`, `dev.*`, `view.prototype` and `view.devMode` refuse. Each of these is
one undo step and returns the ids it made:
@@ -488,6 +489,21 @@ one undo step and returns the ids it made:
one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo
step. With `edit: true` the app goes on typing in it (the "+" beside a selected sticky or shape
in the app does both).
- `board.mindMap {x?, y?, text?, children?, parent?, edit?}` → `{id, text, children: [{id, text, connector}]}`:
a mind map: a first node (`mindNode`, bold 24, no box; `text` defaults to `Topic`, `x`/`y` to the
middle of the view) with up to 20 `children` (texts; default `Idea 1`, `Idea 2`, `Idea 3`)
on its right, each joined to it by a curved branch (a connector with `branch: true`: stroke 4,
`#757575`, round caps). The map lays itself out: children stand in one column 88 units right of
the widest node of their parent's column, 48 apart, centred on their parent; a node is its text,
sized to it. One undo step. A map's shape is read from its branches alone: the parent of a node
is the layer a branch arrives from. After every edit (a command, typing, a gesture, undo, a live
session's change) a touched map is laid out again from its first node, so moving the first node
moves the map, a child moved by hand goes back (or swaps with the sibling whose middle it
passed), and a deleted node's children stay where they are, without their branch.
- `board.mindMapAdd {id?, relation?: child|sibling, text?, edit?}` → `{id, text, connector}`: a node
of the map that the given (or selected, or edited) one belongs to: a child below its other
children, or a sibling right after it (the first node has none); the map lays itself out again.
One undo step. With `edit: true` the app goes on typing in it.
- `board.shape {shape, x, y, width?, height?, text?, color?, parent?}` → `{id, text}`: a shape with centred,
wrapping text: `rectangle roundedRectangle ellipse diamond triangle triangleDown parallelogramRight parallelogramLeft trapezoid pentagon hexagon octagon star plus arrowLeft arrowRight chevron speechBubble database document predefinedProcess manualInput internalStorage`.
- `board.connector {from, to, fromSide?, toSide?, fromAt?, toAt?, style?: straight|elbow|curved, startCap?, endCap?, label?}`
+2 -1
View File
@@ -1,6 +1,6 @@
# FigCraft roadmap: milestones and what's next
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); 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 oLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); 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 whLine truncated
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-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged |
| 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged |
| 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged |
+6 -4
View File
@@ -1,6 +1,6 @@
# UI and interaction parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; 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); 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); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged;Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; 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); 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); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for tLine truncated
Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys,
drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status:
@@ -25,7 +25,7 @@ interaction feel not yet compared.
| Actions palette (Cmd+K, Cmd+/) | done | tabs: All (every command, grouped by menu, or Other; a command that needs parameters only through its menu item, and none twice under one label, #1574), Assets (components and styles) and Plugins & widgets; results ranked prefix first, then shortest, at most 60 rows; Up/Down move a highlight and Enter runs it; Recents list what was run from the palette (matching translated labels); one open/toggle path from every entry point (`palette_tests`). Ranking and the Assets results not compared with Figma's |
| Context menus | done | canvas and layers; submenus as in the main menu below, and a right-click in a new spot starts a fresh menu (Select layer closed); Shift+F10 or the keyboard's Menu key opens them from the keyboard (at the focused layer row or below the canvas selection) and the menu takes the keyboard (`layers_keyboard_tests`) |
| Home screen: Recents, Online and Templates | done (ours) | The sidebar switches between the three (`ui.set {homeSection}`). Online: your online files (see the collaboration checklist). Recents: new file, open, join with a code, open files, recent files (cards with the picture each file carries on its page colour, the file's icon, name and "Edited ... ago" or "File not found", full path on hover; or a Name, Last modified and Created table with sortable headers; sorted by name, creation or last change either way; grid or list and the sort kept in the preferences, `ui.set {homeRecentsView, homeRecentsSort, homeRecentsOrder}`; a click selects, a double-click or Enter opens, arrow keys move the selection; Open, Show in folder and Remove from recents on right-click), a Getting started card (six tips with their shortcuts from the keymap; its close button is remembered in the preferences and Help ▸ Getting started brings it back) and, while there are no recent files, four templates to start from. Templates: the eight starter templates as cards (thumbnail rendered from the document, cached per theme; name, description, kind and size), a search field and a kind filter, an empty state; Tab reaches every card and Enter opens it; cards and tabs are named for screen readers. A first run opens here. No Community files or drafts folder |
| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open after 0.15 s on their row (a click or the keyboard opens one at once) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; timings tuned by feel, not measured against Figma). Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place |
| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open after 0.15 s on their row (a click or the keyboard opens one at once) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; timings tuned by feel, not measured against Figma). A menu or submenu that would run past the window's bottom moves up to fit (never above the top), and one taller than the window scrolls with the wheel, the keyboard's focus kept in view; the context menu's submenus share this (#2217, `menu_overflow_tests`). Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place |
| Keyboard shortcuts panel | done | closes when the home screen shows (#548); docked, tabbed by group like the documentation, searchable, per-platform keycaps; held keys, gestures and presentation keys listed beside the bindings; a label too long for its column ends with "…" and shows in full on hover |
| Several windows | partial | File ▸ New window, Open in new window on a tab, a tab dragged off the strip; screen-reader tree in the main window only; positions not restored |
| Multiplayer avatars, Share button | missing | waits for multiplayer |
@@ -45,7 +45,7 @@ interaction feel not yet compared.
| Rows: click, Shift-click range, Cmd/Ctrl-click toggle; the selection follows on the canvas and a canvas selection is revealed | done | `layers_behaviour_tests`; selected hierarchies share a continuous background with rounded outer corners, including nested selections |
| Expand and collapse: Alt-click opens or closes everything inside; Collapse layers (Alt+L) keeps the way to the selection open | done | Alt-click pinned (the documentation is silent) |
| Drag to reorder and into frames, groups and auto layout: insertion line, spring-loaded open, several layers together, Escape cancels | done | several layers dropped together land together (they split apart before); instances and a layer's own children refuse drops |
| Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) |
| Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) |
| Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned |
| Find layers (filter by name) | done | not covered by the documentation |
| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`) |
@@ -56,7 +56,7 @@ interaction feel not yet compared.
| Item | Status | Notes |
|---|---|---|
| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to one axis (#498); a marquee selects what it touches; from a top-level frame's background, the layers inside it; locked and hidden layers are skipped (`selection_behaviour_tests`) |
| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to one axis (#498); a marquee selects what it touches; from a top-level frame's background, the layers inside it; locked and hidden layers are skipped (`selection_behaviour_tests`) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) |
| Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | |
| Select layer menu (every layer under the click) | done | |
| Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming |
@@ -187,6 +187,8 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | patch | M5, #1560: locked layers follow Figma's rules (Lock and unlock layers; measured in Figma's web app): a locked layer selected in the Layers panel ignores the arrow keys and the nudge commands while its properties still edit, and a child of a locked layer keeps its padlock inert (the Layers panel padlock, Lock/Unlock and `object.toggleLock` without a value no longer lock the child on its own) |
| 2026-11-10 | patch | #2217: the main menu's submenus (Object, say) ran past the window's bottom, behind the taskbar, with the lowest commands out of reach, because submenus were not constrained to the window (to keep them beside their row). Every menu panel now scrolls when taller than the window less 8 pt margins, and a submenu is held within the window's height (moved up, never above the top) while keeping its place beside its row, so menu-aim is unchanged. Tests: `menu_overflow_tests.rs`. Numbers unchanged. |
| 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` |
| 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged |
| 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. |
@@ -17,6 +17,8 @@ runtime-version: '26.08'
sdk: org.freedesktop.Sdk
command: figcraft
finish-args:
# The shared updater inspects and updates this installation via flatpak-spawn --host.
- --talk-name=org.freedesktop.Flatpak
- --filesystem=xdg-data/ArtCraft/versions:ro
# Display: Wayland first; X11 only when no Wayland compositor is running.
- --socket=wayland
@@ -22,6 +22,8 @@ sdk-extensions:
- org.freedesktop.Sdk.Extension.rust-stable
command: figcraft
finish-args:
# The shared updater inspects and updates this installation via flatpak-spawn --host.
- --talk-name=org.freedesktop.Flatpak
- --filesystem=xdg-data/ArtCraft/versions:ro
# Display: Wayland first; X11 only when no Wayland compositor is running.
- --socket=wayland
+6
View File
@@ -1,2 +1,8 @@
sonar.projectKey=storytold_figcraft
sonar.organization=storytold
# S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only
# length readers accept). It is an identifier the format fixes, not a security choice.
sonar.issue.ignore.multicriteria=fig_image_sha1
sonar.issue.ignore.multicriteria.fig_image_sha1.ruleKey=rust:S4790
sonar.issue.ignore.multicriteria.fig_image_sha1.resourceKey=crates/format/src/fig/export.rs