Merge remote-tracking branch 'origin/main' into HEAD

# Conflicts:
#	ROADMAP.md
#	contributors/people.toml
This commit is contained in:
bflatastic committed 2026-11-27 16:25:37 +07:00
commit 4b99b1930e
86 files changed
+5015 -247

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ workflows:
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+9
View File
@@ -185,6 +185,15 @@ debug = false
strip = true
panic = "abort"
# The rasteriser's loops run for every pixel of the canvas on the page's one thread: built for
# speed. (The rest stays "z": the whole build at speed is megabytes over the gate.)
[profile.web-release.package.tiny-skia]
opt-level = 3
[profile.web-release.package.tiny-skia-path]
opt-level = 3
[profile.web-release.package.figcraft-render]
opt-level = 3
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
+8 -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-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); 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 earlieLine 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
@@ -368,6 +368,8 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|---|---|---|
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
| 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. |
| 2026-11-15 | patch | Removed the obsolete duplicate live-session bullet from the browser crate docs; the existing server publishing and remote wss guidance remains authoritative. Runtime behavior unchanged. |
| 2026-11-19 | minor | M8: screen sizes for agents. A frame can be marked as the mobile, tablet or desktop version of a design, and given rules for other sizes as notes in the Responsive annotation category, in the Inspect tab's Screen sizes section, `responsive.set` and `responsive.rule`. `responsive.list` returns only what the designer stated: nothing is inferred from names or sizes. Marks are layer data and rules are annotations, so the file format doesn't change. Numbers unchanged. Tests: `responsive_tests`. |
| 2026-11-15 | patch | M5: prototype arrow aliases match platform key names; explicit document selection survives addressed calls and nested batches; failed commands and groups discard their queued UI effects. Readiness numbers unchanged. |
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged |
@@ -378,6 +380,11 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| 2026-11-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). |
| 2026-11-15 | patch | Document HTTP(S) links without a host are refused before opening; regressions retain valid query, fragment, IPv6 and mail links. |
| 2026-11-15 | patch | The browser ignores a page server meta tag with an invalid host, port or path, using the same endpoint parser as sharing; valid local, IPv6 and reverse-proxy addresses keep their spelling. |
| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. |
| 2026-11-15 | patch | CLI export and render reject repeated scale suffixes such as `2xx` as usage errors (exit 2); numeric values and one optional `x` suffix retain the existing limits. |
| 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. |
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
| 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-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
+12 -3
View File
@@ -102,7 +102,7 @@ pub struct ExportArgs {
pub format: Option<String>,
#[command(flatten)]
pub scale: ScaleArg,
/// The page to export (default the first)
/// The page to export (default the first non-divider page)
#[arg(long, value_name = "NAME")]
pub page: Option<String>,
/// The layer to export, by id (12 or 0:12) or name
@@ -171,7 +171,7 @@ pub struct RenderArgs {
pub out: String,
#[command(flatten)]
pub scale: ScaleArg,
/// The page to render (default the first)
/// The page to render (default the first non-divider page)
#[arg(long, value_name = "NAME")]
pub page: Option<String>,
#[command(flatten)]
@@ -306,7 +306,7 @@ enum ValueError {
}
fn scale(s: &str) -> Result<f64, ValueError> {
s.trim_end_matches('x').parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0 && *v <= 64.0).ok_or(ValueError::Scale)
s.strip_suffix('x').unwrap_or(s).parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0 && *v <= 64.0).ok_or(ValueError::Scale)
}
/// `FIGCRAFT_NO_SYSTEM_FONTS`: the usual boolean spellings; an empty value is unset (RFC-0018 rule 1.7).
@@ -525,6 +525,13 @@ mod tests {
assert!(try_parse(&["commands"]).is_ok_and(|cli| !cli.no_system_fonts));
}
#[test]
fn scale_accepts_numbers_and_one_optional_suffix() {
for (value, want) in [("0.5", 0.5), ("0.5x", 0.5), ("2", 2.0), ("2x", 2.0), ("64", 64.0), ("64x", 64.0)] {
assert_eq!(super::scale(value).ok(), Some(want), "{value}");
}
}
#[test]
fn bad_arguments_are_usage_errors() {
use ErrorKind::{
@@ -543,6 +550,8 @@ mod tests {
(&["export", "a", "-o", "b", "--scale", "0"], ValueValidation),
(&["export", "a", "-o", "b", "--scale", "-3"], ValueValidation),
(&["export", "a", "-o", "b", "--scale", "65"], ValueValidation),
(&["export", "a", "-o", "b", "--scale", "2xx"], ValueValidation),
(&["render", "a", "-o", "b", "--scale", "2xxx"], ValueValidation),
(&["export", "a", "-o", "b", "--bleed", "lots"], ValueValidation),
(&["export", "a", "-o", "b", "--bleed", "3in"], ValueValidation),
(&["export", "a", "-o", "b", "--vd-compat", "sloppy"], ValueValidation),
+80 -1
View File
@@ -153,6 +153,20 @@ fn u64_at(b: &[u8], at: usize) -> Option<u64> {
b.get(at..at + 8).and_then(|s| s.try_into().ok()).map(u64::from_le_bytes)
}
/// Snapshot state before shared branches (fallback decoder for existing snapshots on disk).
#[derive(serde::Deserialize)]
struct SessionStateV1 {
session: u64,
snapshot: Vec<figcraft_collab::Change>,
seq: u64,
next_client: u32,
issued: std::collections::BTreeMap<u32, figcraft_collab::Processed>,
deleted: std::collections::BTreeSet<figcraft_collab::NodeId>,
#[serde(default)]
removed: std::collections::BTreeSet<figcraft_collab::Entry>,
log: Vec<figcraft_collab::Accepted>,
}
/// A snapshot file's bytes.
pub fn encode_snapshot(generation: u64, state: &SessionState) -> Result<Vec<u8>, String> {
let mut out = Vec::with_capacity(SNAP_HEADER);
@@ -191,7 +205,23 @@ pub fn check_snapshot(bytes: &[u8]) -> Result<u64, String> {
/// A snapshot's generation and session state.
pub fn decode_snapshot(bytes: &[u8]) -> Result<(u64, SessionState), String> {
let (generation, body) = snapshot_body(bytes)?;
let state = message::decode::<SessionState>(body, body.len()).map_err(|e| format!("the snapshot can't be read: {e}"))?;
let state = match message::decode::<SessionState>(body, body.len()) {
Ok(state) => state,
Err(err) => match message::decode::<SessionStateV1>(body, body.len()) {
Ok(v1) => SessionState {
session: v1.session,
snapshot: v1.snapshot,
seq: v1.seq,
next_client: v1.next_client,
issued: v1.issued,
deleted: v1.deleted,
removed: v1.removed,
log: v1.log,
branches: Vec::new(),
},
Err(_) => return Err(format!("the snapshot can't be read: {err}")),
},
};
Ok((generation, state))
}
@@ -262,3 +292,52 @@ pub fn read_log(bytes: &[u8]) -> Result<LogRead, String> {
}
Ok(LogRead { generation, entries, damaged })
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
use figcraft_collab::message;
use super::*;
#[derive(serde::Serialize)]
struct LegacySessionStateV1 {
session: u64,
snapshot: Vec<figcraft_collab::Change>,
seq: u64,
next_client: u32,
issued: BTreeMap<u32, figcraft_collab::Processed>,
deleted: BTreeSet<figcraft_collab::NodeId>,
removed: BTreeSet<figcraft_collab::Entry>,
log: Vec<figcraft_collab::Accepted>,
}
#[test]
fn decode_snapshot_reads_pre_branch_v1_snapshots() {
let v1 = LegacySessionStateV1 {
session: 42,
snapshot: Vec::new(),
seq: 7,
next_client: 3,
issued: BTreeMap::new(),
deleted: BTreeSet::new(),
removed: BTreeSet::new(),
log: Vec::new(),
};
let mut out = Vec::with_capacity(SNAP_HEADER);
out.extend_from_slice(SNAP_MAGIC);
out.push(FORMAT);
out.extend_from_slice(&9u64.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
let mut out = message::encode_into(&v1, out).unwrap();
let sum = crc(&out[SNAP_HEADER..]);
out[SNAP_HEADER - 4..SNAP_HEADER].copy_from_slice(&sum.to_le_bytes());
let (generation, state) = decode_snapshot(&out).unwrap();
assert_eq!(generation, 9);
assert_eq!(state.session, 42);
assert_eq!(state.seq, 7);
assert_eq!(state.next_client, 3);
assert!(state.branches.is_empty());
}
}
+50
View File
@@ -271,3 +271,53 @@ fn fuzzed_frames_dont_hurt_the_server() {
assert!(same(a.doc().unwrap(), b.doc().unwrap()));
server.stop();
}
#[test]
fn shared_branches_sync_and_survive_a_server_restart() {
let dir = TempDir::new("branches");
let mut cfg = config(dir.path());
let mut server = crate::start(&cfg).unwrap();
let addr = server.addr();
let mut a = session("Ada");
let base_rect = id_of(&a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 80, "height": 80})).unwrap());
let p = publish(&mut a, dir.path(), addr);
let mut b = join(&p.edit, "Bo");
pump(&mut [&mut a, &mut b], "both live with shared branches", |s| {
live(s[0]) && live(s[1]) && s[0].live().shared_branches && s[1].live().shared_branches
});
let b_main = b.active;
// Bo creates a branch, adds a new shape and renames the existing one.
let branch_id = b.execute("branch.create", &json!({"name": "New Card"})).unwrap()["id"].as_str().unwrap().to_string();
let card = id_of(&b.execute("shape.rectangle", &json!({"x": 120, "y": 20, "width": 100, "height": 60})).unwrap());
b.execute("node.set", &json!({"ids": [base_rect.0], "props": {"name": "Base From Branch"}})).unwrap();
pump(&mut [&mut a, &mut b], "Ada receives Bo's branch and edits", |s| {
s[0].docs[0]
.branches
.iter()
.any(|br| br.id == branch_id && br.head.contains(card) && br.head.node(base_rect).is_some_and(|n| n.name == "Base From Branch"))
});
assert!(!a.doc().unwrap().contains(card), "main stays clean until merged");
// Switch Bo back to main before checking reconnect status on main.
b.execute("doc.switch", &json!({"index": b_main})).unwrap();
// Restart the server: the branch and its edits must survive on disk.
server.stop();
pump(&mut [&mut a, &mut b], "reconnecting", |s| s.iter().all(|x| matches!(x.live().status, Status::Reconnecting { .. })));
cfg.listen = addr.to_string();
let mut server = start_again(&cfg);
pump(&mut [&mut a, &mut b], "back after restart", |s| s.iter().all(|x| live(x) && x.live().shared_branches));
// A brand-new participant Cy joins after the restart and gets the branch too.
let mut c = join(&p.edit, "Cy");
pump(&mut [&mut a, &mut b, &mut c], "Cy receives branch after restart", |s| {
live(s[2]) && s[2].ds().is_ok_and(|d| d.branches.iter().any(|br| br.id == branch_id && br.head.contains(card)))
});
// Ada reviews and merges Bo's branch into main.
assert_eq!(a.execute("branch.merge", &json!({"id": branch_id})).unwrap()["merged"], true);
pump(&mut [&mut a, &mut b, &mut c], "everyone converges after merge", |s| {
s.iter().all(|x| x.doc().unwrap().contains(card))
&& s[1].ds().is_ok_and(|d| d.branches.iter().any(|br| br.id == branch_id && br.state == figcraft_engine::branches::BranchState::Merged))
&& s[2].ds().is_ok_and(|d| d.branches.iter().any(|br| br.id == branch_id && br.state == figcraft_engine::branches::BranchState::Merged))
});
assert_eq!(c.doc().unwrap().node(base_rect).unwrap().name, "Base From Branch");
assert!(same(a.doc().unwrap(), b.doc().unwrap()) && same(a.doc().unwrap(), c.doc().unwrap()));
server.stop();
}
+12
View File
@@ -258,6 +258,18 @@ struct Log {
bytes: u64,
/// Changed since the last compaction.
dirty: bool,
/// Shared branch state changed since the last compaction.
branch_dirty: bool,
}
fn is_branch_journal(j: &figcraft_collab::Journal) -> bool {
matches!(
j,
figcraft_collab::Journal::BranchCreate(_)
| figcraft_collab::Journal::BranchEdit { .. }
| figcraft_collab::Journal::BranchUpdateFromMain { .. }
| figcraft_collab::Journal::BranchState { .. }
)
}
struct Entry {
+6 -3
View File
@@ -71,6 +71,9 @@ impl Backend for Store {
// A refusal changes nothing in the document: it counts toward the log's size (bytes), but
// not toward the entries that make a snapshot rewrite worthwhile.
log.entries += journal.iter().filter(|j| !matches!(j, figcraft_collab::Journal::Refused { .. })).count();
if journal.iter().any(super::is_branch_journal) {
log.branch_dirty = true;
}
log.dirty = true;
e.meta.updated = now();
if log.entries >= after || log.bytes + log.pending.len() as u64 >= max_bytes {
@@ -92,10 +95,10 @@ impl Backend for Store {
let compact = self.files.get_mut(file).is_some_and(|entry| {
let snapshot_seq = entry.meta.seq;
entry.log.as_mut().is_some_and(|log| {
// Issued client ids and refusals are durable in the log; only edits need a
// new image-bearing snapshot. Still try a snapshot if syncing the log failed.
// Issued client ids and refusals are durable in the log; edits (on main or
// shared branches) need a new snapshot. Still try a snapshot if syncing failed.
synced = flush_log(file, log).is_ok();
!synced || (log.dirty && server.seq() > snapshot_seq)
!synced || (log.dirty && (server.seq() > snapshot_seq || log.branch_dirty))
})
});
if compact {
+5 -2
View File
@@ -57,6 +57,7 @@ impl Store {
let mut issues = Vec::new();
let mut fresh_log = true;
let mut kept = 0;
let mut branch_dirty = false;
let log_path = dir.join(LOG);
// A log that's there but can't be read (an IO error, or over a lowered cap) may hold
// confirmed edits: the file isn't opened, and the log is left as it is for another try.
@@ -78,12 +79,14 @@ impl Store {
Ok(log) if log.generation == generation => {
fresh_log = false;
for entry in log.entries {
let is_branch = super::is_branch_journal(&entry);
if let Err(e) = server.replay(entry) {
issues.push(format!("file {file}: its log stops making sense after {kept} entries ({e}); the rest was dropped"));
fresh_log = true;
break;
}
kept += 1;
branch_dirty |= is_branch;
}
if let Some(why) = log.damaged {
issues.push(format!("file {file}: its log ended with {why}; that part was dropped"));
@@ -128,7 +131,7 @@ impl Store {
(false, Ok(f)) => {
let bytes = f.metadata().map_or(LOG_HEADER as u64, |m| m.len());
// Replayed entries make it worth compacting once everyone has left.
Log { generation, file: f, pending: Vec::new(), entries: kept, bytes, dirty: kept > 0 }
Log { generation, file: f, pending: Vec::new(), entries: kept, bytes, dirty: kept > 0, branch_dirty }
}
// A new snapshot and log of the next generation, so appends start clean.
_ => {
@@ -173,7 +176,7 @@ impl Store {
log::warn!("file {file}: couldn't update {META}: {err}");
}
}
Ok(Log { generation, file: f, pending: Vec::new(), entries: 0, bytes: LOG_HEADER as u64, dirty: false })
Ok(Log { generation, file: f, pending: Vec::new(), entries: 0, bytes: LOG_HEADER as u64, dirty: false, branch_dirty: false })
}
/// Compactions so far.
-2
View File
@@ -22,8 +22,6 @@
//! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `<iframe>`) or
//! `data-host="page"` on the canvas (the page's own document) hands the page the app's files
//! instead of downloading them and reports unsaved changes (`host`);
//! - live sessions: it joins sessions a desktop app hosts (File ▸ Join live session…) but can't
//! host one. A page served over `https://` can only reach sessions on the same computer
//!
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?control` installs
//! `window.figcraft`, the page's control channel (`api.rs`), which is off without it; `?host=parent`
+8 -1
View File
@@ -22,7 +22,14 @@ pub fn join_link(fragment: &str) -> Option<&str> {
pub fn page_server(content: &str) -> Option<String> {
let c = content.trim();
let scheme = c.starts_with("wss://") || c.starts_with("ws://");
(scheme && c.len() <= 512 && !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#')).then(|| c.to_string())
// Invalid metadata must not replace a usable default with an endpoint sharing cannot reach.
(scheme
&& c.len() <= 512
&& !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#')
// Endpoint parsing strips pasted-link delimiters; metadata must retain its spelling.
&& !c.ends_with(['<', '>', '"', '\''])
&& figcraft_collab_net::Endpoint::parse(c).is_ok())
.then(|| c.to_string())
}
/// Whether `search` (`location.search`, with or without its `?`) has a `control` entry (`?control`,
+33
View File
@@ -49,3 +49,36 @@ fn a_page_names_its_own_server_without_a_key() {
assert_eq!(page_server(bad), None, "{bad:?} is ignored");
}
}
#[test]
fn a_page_ignores_invalid_server_endpoints() {
for bad in [
"ws://",
"wss://",
"wss:///figcraft/",
"wss://:443/",
"wss://figcraft.example:0/",
"wss://figcraft.example:65536/",
"wss://figcraft.example:port/",
"wss://[::1/",
"wss://figcraft.example/a@b/",
] {
assert_eq!(page_server(bad), None, "{bad:?} must not replace the default server");
}
}
#[test]
fn a_page_preserves_valid_server_endpoint_spelling() {
for server in ["ws://localhost:47900/", "wss://figcraft.example/figcraft/", "wss://[::1]:47900/figcraft/"] {
assert_eq!(page_server(server).as_deref(), Some(server), "{server}");
}
}
#[test]
fn a_page_rejects_server_delimiters_that_endpoint_parsing_would_strip() {
for suffix in ["'", "\"", "<", ">", "\"'>"] {
let server = format!("wss://figcraft.example/{suffix}");
assert!(figcraft_collab_net::Endpoint::parse(&server).is_ok(), "the parser cleans {server:?}");
assert_eq!(page_server(&server), None, "{server:?} must not replace the default server");
}
}
+3
View File
@@ -14,6 +14,9 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.52Rain]
display_name = "Aether Sylvan"
[people.varvbudi-netizen]
sync_github_name = true
+1 -1
View File
@@ -235,7 +235,7 @@ impl<S: Socket> Driver<S> {
if bytes.len() > self.cfg.limits.max_server_message {
return self.end(too_large(&self.cfg.limits), now);
}
let taken = match message::decode::<ServerMsg>(bytes, self.cfg.limits.max_server_message) {
let taken = match message::decode_server(bytes, self.cfg.limits.max_server_message) {
// The join code's answer (or the team list's): join the file, on a new connection.
Ok(ServerMsg::Resolved { file, token }) if self.cfg.lookup.is_some() => {
return match resolved(&mut self.cfg, file, token) {
+29
View File
@@ -126,6 +126,35 @@ fn hello_then_the_welcome_releases_presence() {
assert!(!d.done());
}
#[test]
fn legacy_welcome_is_view_only_and_reconnects_with_a_fresh_hello() {
let mut w: ServerMsg = message::decode(&welcome(), usize::MAX).unwrap();
let ServerMsg::Welcome { access, secret, .. } = &mut w else { panic!("no welcome") };
*access = figcraft_collab::Access::View;
*secret = 0;
let mut legacy = encode(&w);
assert_eq!(legacy.pop(), Some(0));
let t0 = Instant::now();
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
inbox.drain();
d.message(&legacy, t0);
assert!(!d.done());
assert!(inbox.drain().iter().any(|e| matches!(e, Event::Welcome { info, .. } if info.access == figcraft_collab::Access::View)));
d.closed(1006, "connection dropped", t0);
let again = d.deadline().unwrap();
d.tick(again);
d.opened(again);
let Some(ClientMsg::Hello(h)) = d.sock.sent.last() else { panic!("no hello") };
assert_eq!(h.resume, None, "old hosts must re-authenticate the link, not resume without a secret");
assert_eq!(h.token, TOKEN);
d.message(&legacy, again);
assert!(!d.done());
assert!(inbox.drain().iter().any(|e| matches!(e, Event::Welcome { info, .. } if info.access == figcraft_collab::Access::View)));
}
#[test]
fn presence_is_throttled_and_quiet_connections_ping() {
let t0 = Instant::now();
+2 -2
View File
@@ -16,7 +16,7 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError, channel}
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use figcraft_collab::message::{self, ClientMsg, HostInfo, Presence, ServerMsg};
use figcraft_collab::message::{self, ClientMsg, HostInfo, Presence};
use figcraft_doc::Document;
use figcraft_engine::live::{Event, Published, Status};
use tungstenite::protocol::frame::coding::CloseCode;
@@ -378,7 +378,7 @@ fn read_loop(mut ws: WebSocket<Duplex>, ctx: &ReaderCtx) {
let mut seen = Seen::default();
let outcome = loop {
match ws.read() {
Ok(Message::Binary(b)) => match message::decode::<ServerMsg>(&b, ctx.cfg.limits.max_server_message) {
Ok(Message::Binary(b)) => match message::decode_server(&b, ctx.cfg.limits.max_server_message) {
Ok(m) => {
let welcomed = || {
let _ = ctx.tx.send(Cmd::Welcomed(ctx.epoch));
+1
View File
@@ -119,6 +119,7 @@ impl Host {
for o in outs {
match o {
Outgoing::To(id, w @ ServerMsg::Welcome { .. }) if id == me => inbox.push(Event::Sync(w)),
Outgoing::To(id, b @ ServerMsg::Branches(_)) if id == me => inbox.push(Event::Sync(b)),
Outgoing::To(id, ref m @ ServerMsg::Signal { .. }) if id == me => to_local(&inbox, me, m),
_ => {}
}
+8 -1
View File
@@ -354,6 +354,13 @@ impl<B: Backend> Hub<B> {
let reject = ServerMsg::Reject { batch_id: *batch_id, reason, fixes: Vec::new() };
return self.queue(file, vec![Outgoing::To(id, reject)]);
}
if let (ClientMsg::Branch(req), Some(n)) = (&msg, bytes)
&& let Some(room) = self.rooms.get(file)
&& let Err(reason) = self.backend.room(file, &room.server, n)
{
let reject = ServerMsg::Branch(Box::new(figcraft_collab::BranchEvent::Rejected { id: req.id().to_string(), reason }));
return self.queue(file, vec![Outgoing::To(id, reject)]);
}
let Some(room) = self.rooms.get_mut(file) else { return };
let outs = room.server.receive(id, msg);
self.backend.changed(file, &mut room.server);
@@ -800,7 +807,7 @@ pub(crate) fn to_local(inbox: &Inbox, local: u32, msg: &ServerMsg) {
ServerMsg::PeerJoined(p) if p.client_id != local => inbox.push(Event::PeerJoined(p.clone())),
ServerMsg::PeerLeft { client_id } => inbox.push(Event::PeerLeft(*client_id)),
ServerMsg::Presence { client_id, presence } => inbox.presence(*client_id, presence.clone()),
ServerMsg::Changes { .. } | ServerMsg::Reject { .. } => inbox.push(Event::Sync(msg.clone())),
ServerMsg::Changes { .. } | ServerMsg::Reject { .. } | ServerMsg::Branches(_) | ServerMsg::Branch(_) => inbox.push(Event::Sync(msg.clone())),
ServerMsg::Signal { client_id, signal } => inbox.push(Event::Signal(*client_id, signal.clone())),
_ => {}
}
+4 -2
View File
@@ -213,7 +213,9 @@ pub(crate) type Resuming = Mutex<Option<Resume>>;
/// was.
pub(crate) fn hello(cfg: &GuestConfig, resume: &Resuming) -> ClientMsg {
let mut hello = Client::hello(&cfg.invite.file, &cfg.invite.token, &cfg.name, "");
if let (ClientMsg::Hello(h), Some(r)) = (&mut hello, resume.lock().ok().and_then(|r| *r)) {
// A legacy host supplied no reconnect credential and cannot read the new Resume field.
// Re-authenticate with the share link instead of claiming an unauthenticated client id.
if let (ClientMsg::Hello(h), Some(r)) = (&mut hello, resume.lock().ok().and_then(|r| *r).filter(|r| r.secret != 0)) {
h.resume = Some(r);
}
hello
@@ -331,7 +333,7 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
}
inbox.push(Event::Sync(m));
}
ServerMsg::Reject { .. } => inbox.push(Event::Sync(m)),
ServerMsg::Reject { .. } | ServerMsg::Branches(_) | ServerMsg::Branch(_) => inbox.push(Event::Sync(m)),
// Checked again by the engine (the host is as untrusted as any peer).
ServerMsg::Signal { client_id, signal } => inbox.push(Event::Signal(client_id, signal)),
ServerMsg::Hosting(info) => inbox.push(Event::Hosting(*info)),
+370
View File
@@ -0,0 +1,370 @@
//! Server-side shared branch sync: capability gating, access control, hostile input and id-space
//! validation, undo of deleted peer layers, aggregate wire-size caps, journal replay, state
//! restore, and concurrent edits.
use figcraft_doc::ids::STYLE_ID_PREFIX;
use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind};
use crate::change::{Change, Entry, Json, Prop};
use crate::message::{Access, BranchEvent, BranchReq, BranchStatus, ClientMsg, Hello, MAX_SHARED_BRANCHES, ServerMsg, SharedBranch};
use crate::{Client, Journal, Limits, Outgoing, Server};
fn doc() -> (Document, NodeId, NodeId, NodeId) {
let mut d = Document::new("Shared");
let page = d.first_page().unwrap();
let frame = d.create(page, NodeKind::Frame, "Frame", 0.0, 0.0, 200.0, 200.0).unwrap();
let rect = d.create(frame, NodeKind::Rectangle, "Rect", 10.0, 10.0, 40.0, 40.0).unwrap();
(d, page, frame, rect)
}
fn hello(name: &str) -> Hello {
let ClientMsg::Hello(h) = Client::hello("f", "tok", name, "#3366FF") else { panic!("not a hello") };
h
}
fn join_as(server: &mut Server, h: Hello, access: Access) -> (u32, Vec<Outgoing>) {
server.join_as(h, access).unwrap()
}
fn join_editor(server: &mut Server, name: &str) -> u32 {
join_as(server, hello(name), Access::Edit).0
}
fn create_req(id: &str, name: &str, base_seq: u64, base_diff: Vec<Change>, head_diff: Vec<Change>) -> ClientMsg {
ClientMsg::Branch(Box::new(BranchReq::Create { id: id.into(), name: name.into(), time: 1_700_000_000, base_seq, base_diff, head_diff }))
}
fn make_rect_change(id: NodeId, parent: NodeId, name: &str) -> Change {
Change::Create {
id,
kind: Json::of(&NodeKind::Rectangle).unwrap(),
parent: Some(parent),
position: "a0".into(),
props: vec![(Prop::Name, Json::of(name).unwrap()), (Prop::Width, Json::of(&50.0f64).unwrap()), (Prop::Height, Json::of(&50.0f64).unwrap())],
}
}
fn put_style(id: String) -> Change {
let style = Style {
id: id.clone(),
name: "Forged".into(),
description: String::new(),
kind: StyleKind::Paint { paints: Vec::new() },
bound: Default::default(),
};
Change::Put { entry: Entry::Style(id), value: Json::of(&style).unwrap() }
}
fn is_rejected(outs: &[Outgoing], sender: u32) -> bool {
matches!(
outs,
[Outgoing::To(to, ServerMsg::Branch(ev))] if *to == sender && matches!(ev.as_ref(), BranchEvent::Rejected { .. })
)
}
#[test]
fn shared_branches_capability_gates_older_clients() {
let (d, _, _, _) = doc();
let mut server = Server::new(d, "tok", Limits::default());
// Older client does not announce the `branches` capability.
let (old_id, old_out) = join_as(&mut server, Hello { client_version: "0.15.0 signals".into(), ..hello("Old") }, Access::Edit);
assert!(!old_out.iter().any(|o| matches!(o, Outgoing::To(_, ServerMsg::Branches(_)))));
// Modern clients receive the initial branch list after Welcome.
let (a_id, a_out) = join_as(&mut server, hello("Ada"), Access::Edit);
assert!(a_out.iter().any(|o| matches!(o, Outgoing::To(to, ServerMsg::Branches(list)) if *to == a_id && list.is_empty())));
let (b_id, _) = join_as(&mut server, hello("Bo"), Access::Edit);
// Creating a branch broadcasts to branch-capable peers (including sender confirmation) and
// never to older clients; `client` is stamped from `from`.
let outs = server.receive(a_id, create_req("b1", "Header", server.seq(), Vec::new(), Vec::new()));
assert!(!outs.iter().any(|o| matches!(o, Outgoing::To(to, _) if *to == old_id)));
assert!(outs.iter().any(|o| matches!(
o,
Outgoing::To(to, ServerMsg::Branch(ev))
if *to == a_id && matches!(ev.as_ref(), BranchEvent::Created { author, branch } if *author == a_id && branch.client == a_id)
)));
assert!(outs.iter().any(|o| matches!(
o,
Outgoing::To(to, ServerMsg::Branch(ev))
if *to == b_id && matches!(ev.as_ref(), BranchEvent::Created { author, branch } if *author == a_id && branch.client == a_id)
)));
}
#[test]
fn view_and_comment_clients_cannot_mutate_shared_branches() {
let (d, _, _, rect) = doc();
let mut server = Server::new(d, "tok", Limits::default());
let editor = join_editor(&mut server, "Ada");
let (viewer, _) = join_as(&mut server, hello("Val"), Access::View);
let (commenter, _) = join_as(&mut server, hello("Cam"), Access::Comment);
server.receive(editor, create_req("b1", "Feature", server.seq(), Vec::new(), Vec::new()));
let before = server.state().unwrap();
for limited in [viewer, commenter] {
assert!(is_rejected(&server.receive(limited, create_req("b2", "Sneaky", server.seq(), Vec::new(), Vec::new())), limited));
assert!(is_rejected(
&server.receive(
limited,
ClientMsg::Branch(Box::new(BranchReq::Edit {
id: "b1".into(),
changes: vec![Change::Set { id: rect, prop: Prop::Name, value: Json::of("Hacked").unwrap() }],
}))
),
limited
));
assert!(is_rejected(
&server.receive(
limited,
ClientMsg::Branch(Box::new(BranchReq::UpdateFromMain {
id: "b1".into(),
base_changes: Vec::new(),
head_changes: vec![Change::Set { id: rect, prop: Prop::Name, value: Json::of("Hacked").unwrap() }],
}))
),
limited
));
assert!(is_rejected(
&server.receive(limited, ClientMsg::Branch(Box::new(BranchReq::SetState { id: "b1".into(), status: BranchStatus::Archived }))),
limited
));
}
assert_eq!(server.state().unwrap(), before);
}
#[test]
fn shared_branch_rejects_hostile_ids_names_limits_images_and_foreign_spaces() {
let (d, _, frame, rect) = doc();
let mut server = Server::new(d, "tok", Limits::default());
let a = join_editor(&mut server, "Ada");
let b = join_editor(&mut server, "Bo");
// Bad ids and empty/control-only names are rejected with an explicit Rejected event.
for bad_id in ["", "../escape", "has space", &"x".repeat(65)] {
assert!(is_rejected(&server.receive(a, create_req(bad_id, "Valid", server.seq(), Vec::new(), Vec::new())), a));
}
assert!(is_rejected(&server.receive(a, create_req("ok-id", " \n\t ", server.seq(), Vec::new(), Vec::new())), a));
// Create one valid branch to test mutations against.
assert!(!is_rejected(&server.receive(a, create_req("b1", "Clean", server.seq(), Vec::new(), Vec::new())), a));
// Invalid geometry (opacity out of 0..=1) and invalid image keys are rejected on branch edit.
let bad_opacity = Change::Set { id: rect, prop: Prop::Opacity, value: Json::of(&2.5f64).unwrap() };
assert!(is_rejected(&server.receive(a, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![bad_opacity] }))), a));
let bad_image = Change::Put {
entry: Entry::Image("../evil".into()),
value: Json::of(&serde_json::json!({"width": 1, "height": 1, "bytes": "AA=="})).unwrap(),
};
assert!(is_rejected(&server.receive(a, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![bad_image] }))), a));
// Client B cannot smuggle a node or style in client A's id space via create, edit or updateFromMain.
let foreign_node = NodeId((u64::from(a) << 32) | 500);
let foreign_style = format!("{STYLE_ID_PREFIX}{}", (u64::from(a) << 32) | 501);
assert!(is_rejected(
&server.receive(b, create_req("smuggle-node", "S", server.seq(), Vec::new(), vec![make_rect_change(foreign_node, frame, "S")])),
b
));
assert!(is_rejected(&server.receive(b, create_req("smuggle-style", "S", server.seq(), Vec::new(), vec![put_style(foreign_style.clone())])), b));
assert!(is_rejected(
&server
.receive(b, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![make_rect_change(foreign_node, frame, "S")] }))),
b
));
assert!(is_rejected(
&server.receive(b, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![put_style(foreign_style.clone())] }))),
b
));
assert!(is_rejected(
&server.receive(
b,
ClientMsg::Branch(Box::new(BranchReq::UpdateFromMain {
id: "b1".into(),
base_changes: Vec::new(),
head_changes: vec![make_rect_change(foreign_node, frame, "S")],
}))
),
b
));
assert!(is_rejected(
&server.receive(
b,
ClientMsg::Branch(Box::new(BranchReq::UpdateFromMain {
id: "b1".into(),
base_changes: Vec::new(),
head_changes: vec![put_style(foreign_style.clone())],
}))
),
b
));
// Because the branch rejected them, main still rejects client B creating client A's ids.
let reject_node =
server.receive(b, ClientMsg::Changes { base_seq: server.seq(), batch_id: 1, changes: vec![make_rect_change(foreign_node, frame, "S")] });
assert!(matches!(reject_node.as_slice(), [Outgoing::To(to, ServerMsg::Reject { .. })] if *to == b));
let reject_style = server.receive(b, ClientMsg::Changes { base_seq: server.seq(), batch_id: 2, changes: vec![put_style(foreign_style)] });
assert!(matches!(reject_style.as_slice(), [Outgoing::To(to, ServerMsg::Reject { .. })] if *to == b));
// Branch count is capped at MAX_SHARED_BRANCHES and the 65th gets an explicit Rejected event.
for i in 1..MAX_SHARED_BRANCHES {
assert!(!is_rejected(&server.receive(a, create_req(&format!("cap-{i}"), "B", server.seq(), Vec::new(), Vec::new())), a));
}
assert!(is_rejected(&server.receive(a, create_req("over-cap", "Overflow", server.seq(), Vec::new(), Vec::new())), a));
}
#[test]
fn shared_branch_undo_can_restore_a_peer_created_layer_and_style() {
let (d, _, frame, _) = doc();
let mut server = Server::new(d, "tok", Limits::default());
let a = join_editor(&mut server, "Ada");
let b = join_editor(&mut server, "Bo");
server.receive(a, create_req("b1", "Undo", server.seq(), Vec::new(), Vec::new()));
// Ada creates a layer and a style on the branch.
let ada_node = NodeId((u64::from(a) << 32) | 42);
let ada_style = format!("{STYLE_ID_PREFIX}{}", (u64::from(a) << 32) | 43);
assert!(!is_rejected(
&server.receive(
a,
ClientMsg::Branch(Box::new(BranchReq::Edit {
id: "b1".into(),
changes: vec![make_rect_change(ada_node, frame, "AdaCard"), put_style(ada_style.clone())],
}))
),
a
));
// Bo deletes both on the branch.
assert!(!is_rejected(
&server.receive(
b,
ClientMsg::Branch(Box::new(BranchReq::Edit {
id: "b1".into(),
changes: vec![Change::Delete { id: ada_node }, Change::Remove { entry: Entry::Style(ada_style.clone()) }],
}))
),
b
));
// Bo undoes the deletion (re-creating Ada's ids): server accepts both restorations.
let outs = server.receive(
b,
ClientMsg::Branch(Box::new(BranchReq::Edit {
id: "b1".into(),
changes: vec![make_rect_change(ada_node, frame, "AdaCard"), put_style(ada_style)],
})),
);
assert!(!is_rejected(&outs, b));
assert!(outs.iter().any(|o| matches!(
o,
Outgoing::To(to, ServerMsg::Branch(ev)) if *to == a && matches!(ev.as_ref(), BranchEvent::Edited { id, changes, .. } if id == "b1" && !changes.is_empty())
)));
}
#[test]
fn shared_branch_aggregate_wire_size_is_bounded() {
let (d, _, frame, _) = doc();
let mut server = Server::new(d, "tok", Limits { max_message_bytes: 512, ..Limits::default() });
let a = join_editor(&mut server, "Ada");
assert!(!is_rejected(&server.receive(a, create_req("b1", "Small", server.seq(), Vec::new(), Vec::new())), a));
let huge_name = "X".repeat(600);
let huge_node = NodeId((u64::from(a) << 32) | 1);
let outs = server
.receive(a, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![make_rect_change(huge_node, frame, &huge_name)] })));
assert!(is_rejected(&outs, a), "oversized branch edit must be rejected before bloating ServerMsg::Branches");
// Joining client receives a ServerMsg::Branches frame that fits within max_message_bytes.
let (_, join_out) = join_as(&mut server, hello("Bo"), Access::Edit);
let branches_msg = join_out.into_iter().find_map(|o| match o {
Outgoing::To(_, m @ ServerMsg::Branches(_)) => Some(m),
_ => None,
});
let encoded = crate::message::encode(&branches_msg.unwrap()).unwrap();
assert!(encoded.len() <= 512, "encoded branches frame {} > 512", encoded.len());
}
#[test]
fn shared_branch_journal_replay_and_state_round_trip() {
let (d, _, frame, rect) = doc();
let mut server = Server::new(d, "tok", Limits::default());
let a = join_editor(&mut server, "Ada");
let _b = join_editor(&mut server, "Bo");
let initial = server.state().unwrap();
server.journaling(true);
server.receive(a, create_req("b1", "Replay", server.seq(), Vec::new(), Vec::new()));
let added = NodeId((u64::from(a) << 32) | 10);
server.receive(a, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![make_rect_change(added, frame, "Card")] })));
server.receive(
a,
ClientMsg::Branch(Box::new(BranchReq::UpdateFromMain {
id: "b1".into(),
base_changes: vec![Change::Set { id: rect, prop: Prop::Name, value: Json::of("MainRect").unwrap() }],
head_changes: vec![Change::Set { id: rect, prop: Prop::Name, value: Json::of("MainRect").unwrap() }],
})),
);
server.receive(a, ClientMsg::Branch(Box::new(BranchReq::SetState { id: "b1".into(), status: BranchStatus::Archived })));
let journal = server.take_journal();
// Verify each branch operation actually produced a journal record and updated server state.
assert!(matches!(journal.first(), Some(Journal::BranchCreate(_))));
assert!(journal.iter().any(|j| matches!(j, Journal::BranchEdit { id, rev: 1, .. } if id == "b1")));
assert!(journal.iter().any(|j| matches!(j, Journal::BranchUpdateFromMain { id, rev: 2, .. } if id == "b1")));
assert!(journal.iter().any(|j| matches!(j, Journal::BranchState { id, rev: 3, status: BranchStatus::Archived } if id == "b1")));
let source = server.state().unwrap();
assert_eq!(source.branches.len(), 1);
assert_eq!(source.branches[0].rev, 3);
assert_eq!(source.branches[0].status, BranchStatus::Archived);
assert!(!source.branches[0].base_diff.is_empty());
assert!(!source.branches[0].head_diff.is_empty());
let mut replayed = Server::restore(initial, "tok", Limits::default()).unwrap();
for entry in journal {
replayed.replay(entry).unwrap();
}
assert_eq!(replayed.state().unwrap(), source);
// Restoring a snapshot with a u32::MAX branch client id does not saturate next_client.
let mut state = source;
state.branches.push(SharedBranch {
id: "max-client".into(),
name: "Max".into(),
time: 0,
client: u32::MAX,
status: BranchStatus::Active,
rev: 0,
base_diff: Vec::new(),
head_diff: Vec::new(),
});
let mut restored = Server::restore(state, "tok", Limits::default()).unwrap();
let next_id = join_editor(&mut restored, "Cy");
assert!(next_id < u32::MAX);
}
#[test]
fn concurrent_edits_on_a_shared_branch_converge_and_echo_to_sender() {
let (d, _, frame, rect) = doc();
let mut server = Server::new(d, "tok", Limits::default());
let a = join_editor(&mut server, "Ada");
let b = join_editor(&mut server, "Bo");
server.receive(a, create_req("b1", "CoEdit", server.seq(), Vec::new(), Vec::new()));
// Ada deletes rect on the branch; Bo concurrently edits the deleted rect AND renames frame.
let del_outs = server.receive(a, ClientMsg::Branch(Box::new(BranchReq::Edit { id: "b1".into(), changes: vec![Change::Delete { id: rect }] })));
assert!(!is_rejected(&del_outs, a));
let outs = server.receive(
b,
ClientMsg::Branch(Box::new(BranchReq::Edit {
id: "b1".into(),
changes: vec![
Change::Set { id: rect, prop: Prop::Name, value: Json::of("Stale").unwrap() },
Change::Set { id: frame, prop: Prop::Name, value: Json::of("Kept").unwrap() },
],
})),
);
// The stale edit to the deleted node is skipped while the valid edit to frame echoes to BOTH
// Ada and Bo in server order.
for peer in [a, b] {
assert!(outs.iter().any(|o| matches!(
o,
Outgoing::To(to, ServerMsg::Branch(ev))
if *to == peer && matches!(ev.as_ref(), BranchEvent::Edited { id, changes, .. } if id == "b1" && changes.len() == 1)
)));
}
// A newcomer gets the converged branch (rect gone, frame renamed to "Kept").
let (_, c_out) = join_as(&mut server, hello("Cy"), Access::Edit);
let branches = c_out
.into_iter()
.find_map(|o| match o {
Outgoing::To(_, ServerMsg::Branches(list)) => Some(list),
_ => None,
})
.unwrap();
assert_eq!(branches.len(), 1);
let mut rep = server.replica().clone();
rep.apply(&branches[0].base_diff, crate::Mode::Lenient).unwrap();
rep.apply(&branches[0].head_diff, crate::Mode::Lenient).unwrap();
assert!(!rep.document().contains(rect));
assert_eq!(rep.document().node(frame).unwrap().name, "Kept");
}
+7 -3
View File
@@ -464,9 +464,13 @@ impl Client {
}
// Cursor chat, spotlights and what a server says about its hosting are the app's (the
// transport hands them over).
ServerMsg::Pong | ServerMsg::Signal { .. } | ServerMsg::Hosting(_) | ServerMsg::Reported { .. } | ServerMsg::Resolved { .. } => {
Ok(Vec::new())
}
ServerMsg::Pong
| ServerMsg::Signal { .. }
| ServerMsg::Hosting(_)
| ServerMsg::Reported { .. }
| ServerMsg::Resolved { .. }
| ServerMsg::Branches(_)
| ServerMsg::Branch(_) => Ok(Vec::new()),
ServerMsg::Welcome { .. } if self.online => Err(Error::Protocol("already joined".into())),
ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret } => {
if session != self.session || client_id != self.id {
+37
View File
@@ -11,6 +11,43 @@ use crate::message::{
use crate::sim::Rng;
use crate::{Error, Replica, diff};
#[test]
fn legacy_welcome_without_secret_preserves_access_and_snapshot() {
for access in [Access::View, Access::Comment, Access::Edit] {
let welcome = ServerMsg::Welcome {
session: 77,
client_id: 4,
seq: 10,
catch_up: CatchUp::Snapshot(Replica::new(Document::new("Legacy share")).snapshot().unwrap()),
processed: Processed::default(),
peers: vec![],
access,
secret: 0,
};
let mut legacy = encode(&welcome).unwrap();
assert_eq!(legacy.pop(), Some(0), "omit only the final reconnect secret");
assert!(decode::<ServerMsg>(&legacy, legacy.len()).is_err(), "the strict decoder reproduces the old-host failure");
assert_eq!(crate::message::decode_server(&legacy, legacy.len()).unwrap(), welcome);
assert!(crate::message::decode_server(&legacy, legacy.len() - 1).is_err(), "keep the size limit");
assert!(crate::message::decode_server(&legacy[..legacy.len() - 1], legacy.len()).is_err(), "access is mandatory");
let mut partial_secret = legacy.clone();
partial_secret.push(0x80);
assert!(crate::message::decode_server(&partial_secret, usize::MAX).is_err(), "do not hide a truncated secret");
legacy[0] = WIRE_VERSION + 1;
assert!(crate::message::decode_server(&legacy, usize::MAX).is_err(), "keep the wire version check");
}
}
#[test]
fn server_compatibility_keeps_current_messages_and_rejects_trailing_bytes() {
for msg in samples().1 {
let mut bytes = encode(&msg).unwrap();
assert_eq!(crate::message::decode_server(&bytes, bytes.len()).unwrap(), msg);
bytes.push(0);
assert!(crate::message::decode_server(&bytes, usize::MAX).is_err(), "trailing bytes after {msg:?}");
}
}
#[test]
fn encoding_into_a_prefix_keeps_the_wire_body() {
let msg = moved_layer();
+6 -1
View File
@@ -42,7 +42,10 @@ pub use client::{Client, HISTORY_LIMIT};
pub use diff::{Diff, diff};
pub use figcraft_doc::{Document, NodeId};
pub use history::{BatchKind, Notice};
pub use message::{Accepted, Access, CatchUp, ClientMsg, EditingText, Hello, Peer, Presence, Processed, Resume, ServerMsg, Signal};
pub use message::{
Accepted, Access, BranchEvent, BranchReq, BranchStatus, CatchUp, ClientMsg, EditingText, Hello, Peer, Presence, Processed, Resume, ServerMsg,
SharedBranch, Signal,
};
pub use replica::{Applied, Mode, Replica};
pub use server::{COMMENT_ONLY, Journal, Outgoing, Server, SessionState, VIEW_ONLY};
@@ -130,6 +133,8 @@ impl Recompute for NoRecompute {
#[cfg(test)]
mod board_sync_tests;
#[cfg(test)]
mod branch_tests;
#[cfg(test)]
mod client_tests;
#[cfg(test)]
mod codec_tests;
+139 -1
View File
@@ -34,6 +34,10 @@ pub const COMMENTS: &str = "comments";
/// read it).
pub const PACKED: &str = "packed";
/// The word a client puts in its [`Hello::client_version`] when it reads [`ServerMsg::Branches`]
/// and [`ServerMsg::Branch`]: a server syncs shared branches only with clients that say so.
pub const BRANCHES: &str = "branches";
/// The word a client puts in its [`Hello::client_version`] when it reads
/// [`DocProp::DesignReview`](crate::DocProp::DesignReview): a server keeps review-setting changes
/// out of the batches, catch-up deltas and snapshots it sends to clients that don't say so
@@ -42,7 +46,7 @@ pub const DESIGN_REVIEW: &str = "design-review";
/// The `client_version` this build announces: its version, then what it reads beyond the protocol.
pub fn client_version() -> String {
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW}", env!("CARGO_PKG_VERSION"))
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES}", env!("CARGO_PKG_VERSION"))
}
/// Whether `client_version` announces `word`.
@@ -75,6 +79,11 @@ pub fn reads_design_review(client_version: &str) -> bool {
announces(client_version, DESIGN_REVIEW)
}
/// A [`Hello::client_version`] that announces [`BRANCHES`].
pub fn reads_branches(client_version: &str) -> bool {
announces(client_version, BRANCHES)
}
/// Join a file's session.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Hello {
@@ -832,6 +841,99 @@ pub enum PluginReply {
},
}
/// Most shared branches one session keeps.
pub const MAX_SHARED_BRANCHES: usize = 64;
/// Where a shared branch is in its life.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BranchStatus {
Active,
Merged,
Archived,
}
/// A shared branch kept by the server and sent to joining clients announcing [`BRANCHES`].
/// `base_diff` turns the server's current main document into the branch's base; `head_diff` turns
/// that base into the branch's head.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SharedBranch {
pub id: String,
pub name: String,
pub time: u64,
pub client: u32,
pub status: BranchStatus,
pub rev: u64,
pub base_diff: Vec<Change>,
pub head_diff: Vec<Change>,
}
/// Client -> server shared branch requests.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BranchReq {
Create { id: String, name: String, time: u64, base_seq: u64, base_diff: Vec<Change>, head_diff: Vec<Change> },
Edit { id: String, changes: Vec<Change> },
UpdateFromMain { id: String, base_changes: Vec<Change>, head_changes: Vec<Change> },
SetState { id: String, status: BranchStatus },
}
impl BranchReq {
/// The branch id this request targets.
pub fn id(&self) -> &str {
match self {
BranchReq::Create { id, .. } | BranchReq::Edit { id, .. } | BranchReq::UpdateFromMain { id, .. } | BranchReq::SetState { id, .. } => id,
}
}
}
/// Server -> client shared branch updates.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BranchEvent {
Created {
author: u32,
branch: SharedBranch,
},
Edited {
id: String,
author: u32,
rev: u64,
changes: Vec<Change>,
},
UpdatedFromMain {
id: String,
author: u32,
rev: u64,
base_changes: Vec<Change>,
head_changes: Vec<Change>,
},
State {
id: String,
author: u32,
rev: u64,
status: BranchStatus,
},
/// Sent only to the sender of a refused [`BranchReq`].
Rejected {
id: String,
reason: String,
},
}
impl BranchEvent {
/// The branch id this event targets.
pub fn id(&self) -> &str {
match self {
BranchEvent::Created { branch, .. } => &branch.id,
BranchEvent::Edited { id, .. }
| BranchEvent::UpdatedFromMain { id, .. }
| BranchEvent::State { id, .. }
| BranchEvent::Rejected { id, .. } => id,
}
}
}
/// Client → server.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -877,6 +979,8 @@ pub enum ClientMsg {
/// Ask for the link of a file on the server's team list (the first message on a connection,
/// instead of `Hello`).
ResolveTeam(ResolveTeam),
/// Shared branch actions (only to a server that sent [`ServerMsg::Branches`]).
Branch(Box<BranchReq>),
}
/// Server → client.
@@ -948,6 +1052,10 @@ pub enum ServerMsg {
file: String,
token: String,
},
/// The file's shared branches, sent right after `Welcome` to clients announcing [`BRANCHES`].
Branches(Vec<SharedBranch>),
/// A shared branch update, sent to clients announcing [`BRANCHES`].
Branch(Box<BranchEvent>),
}
/// (days since 1970-01-01, seconds-of-day, nanos) → (proleptic Gregorian year, the same wall-clock
@@ -1008,6 +1116,36 @@ pub fn decode<T: DeserializeOwned>(bytes: &[u8], max_bytes: usize) -> Result<T,
from_postcard(body)
}
/// Read a server message, including the original welcome without a reconnect secret.
/// `serde(default)` handles absent JSON fields, but postcard reports EOF for that missing
/// final field. Accept only a complete legacy welcome, including its explicit access level;
/// malformed messages, partial secrets and trailing bytes still fail closed.
pub fn decode_server(bytes: &[u8], max_bytes: usize) -> Result<ServerMsg, Error> {
let error = match decode(bytes, max_bytes) {
Ok(msg) => return Ok(msg),
Err(error) => error,
};
let Some(body) = bytes.strip_prefix(&[WIRE_VERSION, 0]) else { return Err(error) };
if bytes.len() > max_bytes {
return Err(error);
}
#[derive(Deserialize)]
struct LegacyWelcome {
session: u64,
client_id: u32,
seq: u64,
catch_up: CatchUp,
processed: Processed,
peers: Vec<Peer>,
access: Access,
}
let Ok(LegacyWelcome { session, client_id, seq, catch_up, processed, peers, access }) = from_postcard(body) else {
return Err(error);
};
// Zero is the existing sentinel for a host that supplied no reconnect credential.
Ok(ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret: 0 })
}
/// One postcard value that fills `body` (no trailing bytes).
fn from_postcard<T: DeserializeOwned>(body: &[u8]) -> Result<T, Error> {
let (msg, rest) = postcard::take_from_bytes::<T>(body).map_err(|e| Error::Decode(e.to_string()))?;
+1 -1
View File
@@ -326,7 +326,7 @@ impl Replica {
}
/// The checks a server makes on what a batch touched.
fn check(&self, touched: &BTreeSet<NodeId>) -> Result<(), Error> {
pub(crate) fn check(&self, touched: &BTreeSet<NodeId>) -> Result<(), Error> {
if self.doc.pages.is_empty() {
return Err(Error::Invalid("a file needs at least one page".into()));
}
+533 -35
View File
@@ -8,11 +8,11 @@ use serde::{Deserialize, Serialize};
use crate::change::{Change, Entry, Family, Prop, Target};
use crate::message::{
Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_design_review,
reads_signals,
Accepted, Access, BranchEvent, BranchReq, BranchStatus, CatchUp, ClientMsg, Hello, MAX_SHARED_BRANCHES, PROTOCOL, Peer, Presence, Processed,
Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_design_review, reads_signals,
};
use crate::replica::{Mode, Replica, create_change};
use crate::{Error, Limits, docprops, same_secret};
use crate::{Error, Limits, diff, docprops, same_secret};
/// A message for the transport to deliver.
#[derive(Clone, Debug, PartialEq)]
@@ -49,6 +49,31 @@ pub enum Journal {
Accepted(Accepted),
/// A client's batch was refused.
Refused { client: u32, batch_id: u64 },
/// A shared branch was created.
BranchCreate(SharedBranch),
/// A shared branch was edited.
BranchEdit { id: String, rev: u64, changes: Vec<Change> },
/// A shared branch was updated from main.
BranchUpdateFromMain { id: String, rev: u64, base_changes: Vec<Change>, head_changes: Vec<Change> },
/// A shared branch changed state (merged or archived).
BranchState { id: String, rev: u64, status: BranchStatus },
}
/// One shared branch kept on the server.
#[derive(Clone, Debug)]
struct BranchData {
id: String,
name: String,
time: u64,
client: u32,
status: BranchStatus,
rev: u64,
base: Replica,
head: Replica,
/// Node ids deleted on this branch (so undo can bring a peer-created layer back with its id).
deleted: BTreeSet<NodeId>,
/// Document-level entries removed on this branch (so undo can bring them back).
removed: BTreeSet<Entry>,
}
/// A session server for one file.
@@ -87,6 +112,10 @@ pub struct Server {
journal: Option<Vec<Journal>>,
/// The connected clients that read signals (cursor chat, spotlight).
signals: BTreeSet<u32>,
/// The connected clients that read shared branches.
branches_capable: BTreeSet<u32>,
/// Shared branches kept by this session, oldest first.
branches: Vec<BranchData>,
/// The connected clients that read the design review settings (`DocProp::DesignReview`): a
/// peer that doesn't announce them can't decode the variant, so the server keeps review
/// edits out of everything it sends them.
@@ -123,6 +152,9 @@ pub struct SessionState {
#[serde(default)]
pub removed: BTreeSet<Entry>,
pub log: Vec<Accepted>,
/// Absent in states saved before shared branches.
#[serde(default)]
pub branches: Vec<SharedBranch>,
}
impl Server {
@@ -151,6 +183,8 @@ impl Server {
limited: BTreeMap::new(),
journal: None,
signals: BTreeSet::new(),
branches_capable: BTreeSet::new(),
branches: Vec::new(),
design_review: BTreeSet::new(),
spotlight: None,
resync: false,
@@ -168,6 +202,7 @@ impl Server {
deleted: self.deleted.clone(),
removed: self.removed.clone(),
log: self.log.iter().cloned().collect(),
branches: self.wire_branches(),
})
}
@@ -205,6 +240,14 @@ impl Server {
server.remember(a);
}
}
for wb in state.branches.into_iter().take(MAX_SHARED_BRANCHES) {
if let Ok(b) = branch_from_wire(&server.state, wb) {
if b.client < u32::MAX {
server.next_client = server.next_client.max(b.client.saturating_add(1));
}
server.branches.push(b);
}
}
Ok(server)
}
@@ -262,6 +305,38 @@ impl Server {
}
Ok(())
}
Journal::BranchCreate(wb) => {
if !self.branches.iter().any(|b| b.id == wb.id) && self.branches.len() < MAX_SHARED_BRANCHES {
let b = branch_from_wire(&self.state, wb)?;
if b.client < u32::MAX {
self.next_client = self.next_client.max(b.client.saturating_add(1));
}
self.branches.push(b);
}
Ok(())
}
Journal::BranchEdit { id, rev, changes } => {
if let Some(b) = self.branches.iter_mut().find(|b| b.id == id && rev > b.rev) {
b.head.apply(&changes, Mode::Lenient)?;
b.rev = rev;
}
Ok(())
}
Journal::BranchUpdateFromMain { id, rev, base_changes, head_changes } => {
if let Some(b) = self.branches.iter_mut().find(|b| b.id == id && rev > b.rev) {
b.base.apply(&base_changes, Mode::Lenient)?;
b.head.apply(&head_changes, Mode::Lenient)?;
b.rev = rev;
}
Ok(())
}
Journal::BranchState { id, rev, status } => {
if let Some(b) = self.branches.iter_mut().find(|b| b.id == id && rev > b.rev) {
b.status = status;
b.rev = rev;
}
Ok(())
}
}
}
@@ -367,6 +442,7 @@ impl Server {
let processed = self.issued.get(&id).cloned().unwrap_or_default();
self.presence.remove(&id);
let signals = reads_signals(&hello.client_version);
let branches = reads_branches(&hello.client_version);
let peer = Peer { client_id: id, name: hello.name, color: hello.color };
let others = self.peers.values().filter(|p| p.client_id != id).cloned().collect();
let welcome = ServerMsg::Welcome { session: self.session, client_id: id, seq: self.seq, catch_up, processed, peers: others, access, secret };
@@ -386,6 +462,12 @@ impl Server {
} else {
self.signals.remove(&id);
}
if branches {
self.branches_capable.insert(id);
outs.push(Outgoing::To(id, ServerMsg::Branches(self.wire_branches_within_limit())));
} else {
self.branches_capable.remove(&id);
}
if reads_design_review {
self.design_review.insert(id);
} else {
@@ -416,6 +498,7 @@ impl Server {
self.acked.remove(&id);
self.limited.remove(&id);
self.signals.remove(&id);
self.branches_capable.remove(&id);
self.design_review.remove(&id);
if self.spotlight == Some(id) {
self.spotlight = None;
@@ -491,6 +574,7 @@ impl Server {
Vec::new()
}
ClientMsg::Ping => vec![Outgoing::To(from, ServerMsg::Pong)],
ClientMsg::Branch(req) => self.branch_request(from, *req),
ClientMsg::Manage(_)
| ClientMsg::Admin(_)
| ClientMsg::OpenLibrary(_)
@@ -575,6 +659,7 @@ impl Server {
&& !self.state.document().contains(*id)
&& !self.deleted.contains(id)
&& id.0 >> 32 != u64::from(from)
&& !self.in_branch(*id)
{
return Err(Error::Invalid(format!("new node {id} isn't in client {from}'s id space")));
}
@@ -610,42 +695,15 @@ impl Server {
/// [`NO_SESSION_SPACE`] (unless it was removed before: undo puts entries back); ids from
/// before the session (space 0, earlier sessions, other files) are fine.
fn check_entries(&self, from: u32, changes: &[Change], after: &Document) -> Result<Vec<(Entry, bool)>, Error> {
let before = self.state.document();
let mut touched: BTreeSet<Entry> = BTreeSet::new();
let mut listed: BTreeMap<Family, (BTreeSet<Entry>, BTreeSet<Entry>)> = BTreeMap::new();
for c in changes {
match c {
Change::Put { entry, .. } | Change::Remove { entry } if entry.id_space().is_some() => {
touched.insert(entry.clone());
}
// A whole list replaced (the fallback for lists whose ids aren't unique).
Change::SetDoc { prop, .. } => {
if let Some(Ok(family)) = prop.list() {
let (b, a) = (docprops::entries(before, family), docprops::entries(after, family));
touched.extend(b.iter().chain(&a).cloned());
// Looked up in sets below: a linear search per entry would be quadratic.
listed.entry(family).or_insert_with(|| (b.into_iter().collect(), a.into_iter().collect()));
}
}
_ => {}
}
}
let mut out = Vec::new();
for entry in touched {
let (was, now) = match entry.family().and_then(|f| listed.get(&f)) {
Some((b, a)) => (b.contains(&entry), a.contains(&entry)),
None => (docprops::has(before, &entry), docprops::has(after, &entry)),
};
if was == now {
continue;
}
if now
&& !self.removed.contains(&entry)
let out = touched_entries(self.state.document(), changes, after);
for (entry, now) in &out {
if *now
&& !self.removed.contains(entry)
&& !self.entry_in_branch(entry)
&& let Some(space) = entry.id_space().filter(|s| *s != from && (self.issued.contains_key(s) || *s >= NO_SESSION_SPACE))
{
return Err(Error::Invalid(format!("new {} isn't in client {from}'s id space (it is client {space}'s)", entry.describe())));
}
out.push((entry, now));
}
Ok(out)
}
@@ -712,6 +770,446 @@ impl Server {
nodes.extend(out);
Ok(nodes)
}
/// The shared branches encoded relative to the server's current main state.
fn wire_branches(&self) -> Vec<SharedBranch> {
self.branches
.iter()
.filter_map(|b| {
let base_diff = diff(&self.state, b.base.document()).ok()?.changes;
let head_diff = diff(&b.base, b.head.document()).ok()?.changes;
Some(SharedBranch {
id: b.id.clone(),
name: b.name.clone(),
time: b.time,
client: b.client,
status: b.status,
rev: b.rev,
base_diff,
head_diff,
})
})
.collect()
}
/// Whether node `id` exists in any shared branch kept by this server.
fn in_branch(&self, id: NodeId) -> bool {
self.branches.iter().any(|b| b.head.document().contains(id) || b.base.document().contains(id))
}
/// Whether document-level entry `entry` exists in any shared branch kept by this server.
fn entry_in_branch(&self, entry: &Entry) -> bool {
self.branches.iter().any(|b| docprops::has(b.head.document(), entry) || docprops::has(b.base.document(), entry))
}
/// The shared branches encoded relative to the server's current main state, bounded to fit
/// within [`Limits::max_message_bytes`] so a welcome never disconnects a joining client.
fn wire_branches_within_limit(&self) -> Vec<SharedBranch> {
let all = self.wire_branches();
if crate::message::encode(&ServerMsg::Branches(all.clone())).is_ok_and(|b| b.len() <= self.limits.max_message_bytes) {
return all;
}
let mut out = Vec::new();
for b in all {
out.push(b);
if !crate::message::encode(&ServerMsg::Branches(out.clone())).is_ok_and(|enc| enc.len() <= self.limits.max_message_bytes) {
out.pop();
break;
}
}
out
}
fn branches_fit_wire(&self, replace: Option<usize>, candidate: &BranchData) -> bool {
let mut list: Vec<SharedBranch> = Vec::with_capacity(self.branches.len() + 1);
for (i, b) in self.branches.iter().enumerate() {
let item = if replace == Some(i) { candidate } else { b };
let Some(wb) = self.wire_branch(item) else { return false };
list.push(wb);
}
if replace.is_none() {
let Some(wb) = self.wire_branch(candidate) else { return false };
list.push(wb);
}
crate::message::encode(&ServerMsg::Branches(list)).is_ok_and(|enc| enc.len() <= self.limits.max_message_bytes)
}
fn wire_branch(&self, b: &BranchData) -> Option<SharedBranch> {
let base_diff = diff(&self.state, b.base.document()).ok()?.changes;
let head_diff = diff(&b.base, b.head.document()).ok()?.changes;
Some(SharedBranch {
id: b.id.clone(),
name: b.name.clone(),
time: b.time,
client: b.client,
status: b.status,
rev: b.rev,
base_diff,
head_diff,
})
}
fn branch_reject(&self, from: u32, id: &str, reason: impl Into<String>) -> Vec<Outgoing> {
if !self.branches_capable.contains(&from) {
return Vec::new();
}
vec![Outgoing::To(from, ServerMsg::Branch(Box::new(BranchEvent::Rejected { id: id.to_string(), reason: reason.into() })))]
}
fn broadcast_branch(&self, skip: Option<u32>, ev: BranchEvent) -> Vec<Outgoing> {
self.branches_capable
.iter()
.copied()
.filter(|id| Some(*id) != skip)
.map(|id| Outgoing::To(id, ServerMsg::Branch(Box::new(ev.clone()))))
.collect()
}
fn branch_request(&mut self, from: u32, req: BranchReq) -> Vec<Outgoing> {
if let Some(access) = self.limited.get(&from) {
let why = if *access == Access::View { VIEW_ONLY } else { COMMENT_ONLY };
return self.branch_reject(from, req.id(), why);
}
match req {
BranchReq::Create { id, name, time, base_seq: _, base_diff, head_diff } => {
self.branch_create(from, NewBranch { id, name, time, base_diff, head_diff })
}
BranchReq::Edit { id, changes } => self.branch_edit(from, &id, &changes),
BranchReq::UpdateFromMain { id, base_changes, head_changes } => self.branch_update_from_main(from, &id, &base_changes, &head_changes),
BranchReq::SetState { id, status } => self.branch_set_state(from, &id, status),
}
}
fn branch_node_ids_ok(&self, from: u32, changes: &[Change], existing: &[&Document], deleted: Option<&BTreeSet<NodeId>>) -> bool {
changes.iter().all(|c| match c {
Change::Create { id, .. } => {
id.0 >> 32 == u64::from(from)
|| self.state.document().contains(*id)
|| self.deleted.contains(id)
|| deleted.is_some_and(|d| d.contains(id))
|| existing.iter().any(|d| d.contains(*id))
}
_ => true,
})
}
fn branch_entries_ok(
&self,
from: u32,
before: &Document,
changes: &[Change],
after: &Document,
existing: &[&Document],
removed: Option<&BTreeSet<Entry>>,
) -> Option<Vec<(Entry, bool)>> {
let entries = touched_entries(before, changes, after);
for (entry, now) in &entries {
if *now
&& !self.removed.contains(entry)
&& !removed.is_some_and(|r| r.contains(entry))
&& !existing.iter().any(|d| docprops::has(d, entry))
&& entry.id_space().is_some_and(|s| s != from && (self.issued.contains_key(&s) || s >= NO_SESSION_SPACE))
{
return None;
}
}
Some(entries)
}
fn apply_branch(&self, replica: &Replica, changes: &[Change]) -> Option<(Replica, Vec<NodeId>)> {
for c in changes {
if matches!(c, Change::Put { entry: Entry::Image(_), .. }) {
let mut probe = replica.clone();
probe.apply(std::slice::from_ref(c), Mode::Strict).ok()?;
}
}
let mut next = replica.clone();
let applied = next.apply(changes, Mode::Lenient).ok()?;
next.check(&applied.touched).ok()?;
(next.document().node_count() <= self.limits.max_nodes).then_some((next, applied.deleted))
}
fn branch_create(&mut self, from: u32, req: NewBranch) -> Vec<Outgoing> {
let NewBranch { id, name, time, base_diff, head_diff } = req;
if !valid_branch_id(&id) {
return self.branch_reject(from, &id, "invalid branch id");
}
if self.branches.len() >= MAX_SHARED_BRANCHES {
return self.branch_reject(from, &id, format!("the session has the most shared branches it can keep ({MAX_SHARED_BRANCHES})"));
}
if self.branches.iter().any(|b| b.id == id) {
return self.branch_reject(from, &id, "a shared branch with that id already exists");
}
if base_diff.len() > self.limits.max_changes || head_diff.len() > self.limits.max_changes {
return self.branch_reject(from, &id, "too many changes in one branch request");
}
if !self.branch_node_ids_ok(from, &base_diff, &[], None) {
return self.branch_reject(from, &id, "branch base uses a node id outside your id space");
}
let name = clean_branch_name(&name);
if name.is_empty() {
return self.branch_reject(from, &id, "branch name can't be empty");
}
let Some((base, _)) = self.apply_branch(&self.state, &base_diff) else {
return self.branch_reject(from, &id, "branch base couldn't be applied");
};
if self.branch_entries_ok(from, self.state.document(), &base_diff, base.document(), &[], None).is_none()
|| !self.branch_node_ids_ok(from, &head_diff, &[base.document()], None)
{
return self.branch_reject(from, &id, "branch uses an id outside your id space");
}
let Some((head, _)) = self.apply_branch(&base, &head_diff) else {
return self.branch_reject(from, &id, "branch edits couldn't be applied");
};
if self.branch_entries_ok(from, base.document(), &head_diff, head.document(), &[self.state.document()], None).is_none() {
return self.branch_reject(from, &id, "branch uses an entry id outside your id space");
}
let candidate = BranchData {
id: id.clone(),
name: name.clone(),
time,
client: from,
status: BranchStatus::Active,
rev: 0,
base,
head,
deleted: BTreeSet::new(),
removed: BTreeSet::new(),
};
if !self.branches_fit_wire(None, &candidate) {
return self.branch_reject(from, &id, "shared branches would exceed the session's message size limit");
}
let Some(wb) = self.wire_branch(&candidate) else {
return self.branch_reject(from, &id, "branch couldn't be encoded");
};
self.branches.push(candidate);
self.note(Journal::BranchCreate(wb.clone()));
self.broadcast_branch(None, BranchEvent::Created { author: from, branch: wb })
}
fn branch_edit(&mut self, from: u32, id: &str, changes: &[Change]) -> Vec<Outgoing> {
if changes.is_empty() || changes.len() > self.limits.max_changes {
return self.branch_reject(from, id, "invalid branch edit size");
}
let Some(bi) = self.branches.iter().position(|b| b.id == id && b.status == BranchStatus::Active) else {
return self.branch_reject(from, id, "the branch isn't active");
};
let branch = &self.branches[bi];
if !self.branch_node_ids_ok(from, changes, &[branch.head.document(), branch.base.document()], Some(&branch.deleted)) {
return self.branch_reject(from, id, "branch edit uses a node id outside your id space");
}
let Some((next, deleted)) = self.apply_branch(&branch.head, changes) else {
return self.branch_reject(from, id, "branch edit couldn't be applied");
};
let Some(entries) = self.branch_entries_ok(
from,
branch.head.document(),
changes,
next.document(),
&[self.state.document(), branch.base.document()],
Some(&branch.removed),
) else {
return self.branch_reject(from, id, "branch edit uses an entry id outside your id space");
};
let Ok(applied) = diff(&branch.head, next.document()) else {
return self.branch_reject(from, id, "branch edit couldn't be diffed");
};
if applied.changes.is_empty() {
// Still echo an empty no-op edit to the sender so pending queues drain cleanly.
return vec![Outgoing::To(
from,
ServerMsg::Branch(Box::new(BranchEvent::Edited { id: id.to_string(), author: from, rev: branch.rev, changes: Vec::new() })),
)];
}
let mut candidate = branch.clone();
candidate.head = next;
candidate.rev = branch.rev.saturating_add(1);
for c in &applied.changes {
if let Change::Create { id: nid, .. } = c {
candidate.deleted.remove(nid);
}
}
candidate.deleted.extend(deleted);
while candidate.deleted.len() > self.limits.max_nodes {
if candidate.deleted.pop_first().is_none() {
break;
}
}
for (entry, now) in entries {
if now {
candidate.removed.remove(&entry);
} else {
candidate.removed.insert(entry);
}
}
if !self.branches_fit_wire(Some(bi), &candidate) {
return self.branch_reject(from, id, "shared branches would exceed the session's message size limit");
}
let rev = candidate.rev;
if let Some(b) = self.branches.get_mut(bi) {
*b = candidate;
}
self.note(Journal::BranchEdit { id: id.to_string(), rev, changes: applied.changes.clone() });
self.broadcast_branch(None, BranchEvent::Edited { id: id.to_string(), author: from, rev, changes: applied.changes })
}
fn branch_update_from_main(&mut self, from: u32, id: &str, base_changes: &[Change], head_changes: &[Change]) -> Vec<Outgoing> {
if base_changes.len() > self.limits.max_changes || head_changes.len() > self.limits.max_changes {
return self.branch_reject(from, id, "too many changes in branch update");
}
let Some(bi) = self.branches.iter().position(|b| b.id == id && b.status == BranchStatus::Active) else {
return self.branch_reject(from, id, "the branch isn't active");
};
let branch = &self.branches[bi];
if !self.branch_node_ids_ok(from, base_changes, &[branch.base.document(), branch.head.document()], Some(&branch.deleted))
|| !self.branch_node_ids_ok(from, head_changes, &[branch.base.document(), branch.head.document()], Some(&branch.deleted))
{
return self.branch_reject(from, id, "branch update uses a node id outside your id space");
}
let Some((next_base, _)) = self.apply_branch(&branch.base, base_changes) else {
return self.branch_reject(from, id, "branch base update couldn't be applied");
};
let Some((next_head, deleted)) = self.apply_branch(&branch.head, head_changes) else {
return self.branch_reject(from, id, "branch head update couldn't be applied");
};
if self
.branch_entries_ok(
from,
branch.base.document(),
base_changes,
next_base.document(),
&[self.state.document(), branch.head.document()],
Some(&branch.removed),
)
.is_none()
{
return self.branch_reject(from, id, "branch base update uses an entry id outside your id space");
}
let Some(entries) = self.branch_entries_ok(
from,
branch.head.document(),
head_changes,
next_head.document(),
&[self.state.document(), branch.base.document(), next_base.document()],
Some(&branch.removed),
) else {
return self.branch_reject(from, id, "branch head update uses an entry id outside your id space");
};
let Ok(bd) = diff(&branch.base, next_base.document()) else {
return self.branch_reject(from, id, "branch base update couldn't be diffed");
};
let Ok(hd) = diff(&branch.head, next_head.document()) else {
return self.branch_reject(from, id, "branch head update couldn't be diffed");
};
let mut candidate = branch.clone();
candidate.base = next_base;
candidate.head = next_head;
candidate.rev = branch.rev.saturating_add(1);
candidate.deleted.extend(deleted);
for (entry, now) in entries {
if now {
candidate.removed.remove(&entry);
} else {
candidate.removed.insert(entry);
}
}
if !self.branches_fit_wire(Some(bi), &candidate) {
return self.branch_reject(from, id, "shared branches would exceed the session's message size limit");
}
let rev = candidate.rev;
if let Some(b) = self.branches.get_mut(bi) {
*b = candidate;
}
self.note(Journal::BranchUpdateFromMain { id: id.to_string(), rev, base_changes: bd.changes.clone(), head_changes: hd.changes.clone() });
self.broadcast_branch(
None,
BranchEvent::UpdatedFromMain { id: id.to_string(), author: from, rev, base_changes: bd.changes, head_changes: hd.changes },
)
}
fn branch_set_state(&mut self, from: u32, id: &str, status: BranchStatus) -> Vec<Outgoing> {
if status == BranchStatus::Active {
return self.branch_reject(from, id, "can't reopen a merged or archived branch");
}
let Some(b) = self.branches.iter_mut().find(|b| b.id == id && b.status == BranchStatus::Active) else {
return self.branch_reject(from, id, "the branch isn't active");
};
b.status = status;
b.rev = b.rev.saturating_add(1);
let rev = b.rev;
self.note(Journal::BranchState { id: id.to_string(), rev, status });
self.broadcast_branch(None, BranchEvent::State { id: id.to_string(), author: from, rev, status })
}
}
/// Document-level entries (styles, variables, collections, comments) that `changes` added or
/// removed between `before` and `after`, each paired with whether it exists in `after`.
fn touched_entries(before: &Document, changes: &[Change], after: &Document) -> Vec<(Entry, bool)> {
let mut touched: BTreeSet<Entry> = BTreeSet::new();
let mut listed: BTreeMap<Family, (BTreeSet<Entry>, BTreeSet<Entry>)> = BTreeMap::new();
for c in changes {
match c {
Change::Put { entry, .. } | Change::Remove { entry } if entry.id_space().is_some() => {
touched.insert(entry.clone());
}
// A whole list replaced (the fallback for lists whose ids aren't unique).
Change::SetDoc { prop, .. } => {
if let Some(Ok(family)) = prop.list() {
let (b, a) = (docprops::entries(before, family), docprops::entries(after, family));
touched.extend(b.iter().chain(&a).cloned());
// Looked up in sets below: a linear search per entry would be quadratic.
listed.entry(family).or_insert_with(|| (b.into_iter().collect(), a.into_iter().collect()));
}
}
_ => {}
}
}
let mut out = Vec::new();
for entry in touched {
let (was, now) = match entry.family().and_then(|f| listed.get(&f)) {
Some((b, a)) => (b.contains(&entry), a.contains(&entry)),
None => (docprops::has(before, &entry), docprops::has(after, &entry)),
};
if was != now {
out.push((entry, now));
}
}
out
}
struct NewBranch {
id: String,
name: String,
time: u64,
base_diff: Vec<Change>,
head_diff: Vec<Change>,
}
fn valid_branch_id(id: &str) -> bool {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
fn clean_branch_name(name: &str) -> String {
name.trim().chars().filter(|c| !c.is_control()).take(256).collect()
}
fn branch_from_wire(main: &Replica, wb: SharedBranch) -> Result<BranchData, Error> {
let mut base = main.clone();
base.apply(&wb.base_diff, Mode::Lenient)?;
let mut head = base.clone();
head.apply(&wb.head_diff, Mode::Lenient)?;
Ok(BranchData {
id: wb.id,
name: wb.name,
time: wb.time,
client: wb.client,
status: wb.status,
rev: wb.rev,
base,
head,
deleted: BTreeSet::new(),
removed: BTreeSet::new(),
})
}
/// A fresh session identity: random per server (std's hasher keys are seeded from the OS).
+37 -3
View File
@@ -151,8 +151,13 @@ fn near_path(path: &BezPath, p: Point, dist: f64) -> bool {
/// The innermost visible, unlocked node under `pt` (page coordinates), honouring clip content;
/// boolean groups are hit where their `result` is.
pub fn hit_leaf(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
hit_leaf_opts(doc, page, pt, tol, result, HitOpts::default())
}
/// [`hit_leaf`] with `opts` (a deep pick reaches through unfilled nested frames, see [`HitOpts::deep`]).
pub fn hit_leaf_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Option<NodeId> {
let p = doc.node(page)?;
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, HitOpts::default()).filter(|_| !masked_out(doc, p, *c, pt)))
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, opts).filter(|_| !masked_out(doc, p, *c, pt)))
}
/// Whether child `c` of `parent` is masked at `pt`: a visible mask below it (the nearest mask
@@ -175,7 +180,12 @@ fn covers(doc: &Document, id: NodeId, n: &Node, pt: Point, depth: usize) -> bool
/// Like [`hit_leaf`], but only within layer `root` (it included).
pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
hit_rec(doc, root, pt, tol, 0, result, None, HitOpts::default())
hit_in_opts(doc, root, pt, tol, result, HitOpts::default())
}
/// [`hit_in`] with `opts` (see [`hit_leaf_opts`]).
pub fn hit_in_opts(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Option<NodeId> {
hit_rec(doc, root, pt, tol, 0, result, None, opts)
}
/// [`hit_leaf`] (or [`hit_in`] for a `root` that isn't a page) in outline mode: shapes are hit
@@ -210,6 +220,30 @@ pub struct HitOpts {
/// Reach locked layers (and what a locked frame holds) too. A click, hover or marquee never
/// does; the Select layer list does.
pub locked: bool,
/// A deep pick (Cmd/Ctrl held): a frame, component or instance nested in another layer is hit
/// only where it has a visible fill, not across its whole box (its stroke doesn't count), so
/// the pick reaches the layers under an unfilled overlay such as a device chrome instance.
/// Boards (top-level frames and frames directly in a section) keep their box, as on a plain
/// pick. Observed in the reference app with synthetic files.
pub deep: bool,
}
/// Whether `pt` hits `n` itself for a pick with `opts` ([`hits_node_itself`], but see
/// [`HitOpts::deep`]).
fn hits_self(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool, opts: HitOpts) -> bool {
let see_through = opts.deep
&& !outline
&& n.kind.is_frame_like()
&& !n.is_board_atom()
&& !is_board(doc, n)
&& !n.fills.iter().any(|f| f.visible && f.opacity > 0.0);
!see_through && hits_node_itself(doc, id, n, pt, tol, outline)
}
/// Whether `n` sits on the page or directly in a section: a top-level frame, which a pick
/// treats like an artboard.
fn is_board(doc: &Document, n: &Node) -> bool {
n.parent.and_then(|p| doc.node(p)).is_none_or(|p| p.is_page() || matches!(p.kind, NodeKind::Section { .. }))
}
fn hit_rec(
@@ -249,7 +283,7 @@ fn hit_rec(
return Some(h);
}
}
if in_result == Some(true) || hits_node_itself(doc, id, n, pt, tol, outline) || also.is_some_and(|a| a.bounds) && on_box_edge(doc, id, n, pt, tol)
if in_result == Some(true) || hits_self(doc, id, n, pt, tol, outline, opts) || also.is_some_and(|a| a.bounds) && on_box_edge(doc, id, n, pt, tol)
{
return Some(id);
}
+80 -10
View File
@@ -23,6 +23,11 @@ pub struct Swapped {
pub styles: usize,
pub variables: usize,
pub unmatched: Vec<String>,
/// The old library's copies the swap removed because nothing in the document used them before
/// it (an imported component no instance shows, a variable nothing binds), named as in
/// `unmatched`. Copies that went because what used them moved to the other library aren't
/// listed.
pub dropped: Vec<String>,
/// Nothing of the old library is used any more: it was removed from the document.
pub removed: bool,
}
@@ -70,15 +75,75 @@ fn match_components(doc: &Document, records: &[ImportedComponent], m: &LibraryMa
pairs
}
/// `from`'s copies in `doc`, each by its local id with its name as [`Swapped::dropped`] gives it.
fn copies_of(doc: &Document, from: &str) -> Vec<(String, String)> {
let libs = &doc.libraries;
let coll_name = |id: &str| doc.variables.collection_by_id(id).map(|c| c.name.clone()).unwrap_or_default();
let components = libs
.components
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("node {}", r.root.0), format!("component {}", doc.node(r.root).map(|n| n.name.as_str()).unwrap_or_default())));
let styles = libs
.styles
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("style {}", r.local), format!("style {}", doc.style(&r.local).map(|st| st.name.as_str()).unwrap_or_default())));
let variables = libs.variables.iter().filter(|r| r.library == from).map(|r| {
let name = doc.variables.get_by_id(&r.local).map(|v| format!("{}/{}", coll_name(&v.collection), v.name)).unwrap_or_default();
(format!("variable {}", r.local), format!("variable {name}"))
});
let collections = libs
.collections
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("collection {}", r.local), format!("collection {}", coll_name(&r.local))));
components.chain(styles).chain(variables).chain(collections).collect()
}
/// A layer's explicit modes after a swap: a mode of A's collection becomes B's mode of the same
/// name (`colls`: A's collection → B's, and A's mode ids → B's), and stays as well while that
/// collection still has a variable on A (`still_a`). A mode the layer already chose of B's
/// collection wins over one moved from A's.
fn move_modes(
old: BTreeMap<String, String>,
colls: &BTreeMap<String, (String, BTreeMap<String, String>)>,
still_a: &BTreeSet<String>,
) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
let mut moved = Vec::new();
for (c, mode) in old {
match colls.get(&c).and_then(|(b, modes)| modes.get(&mode).map(|bm| (b.clone(), bm.clone()))) {
Some(to) => {
moved.push(to);
if still_a.contains(&c) {
out.insert(c, mode);
}
}
None => {
out.insert(c, mode);
}
}
}
for (c, mode) in moved {
out.entry(c).or_insert(mode);
}
out
}
/// Swap the copies of library `from` in `doc` to library `to` by names (see the module docs).
pub fn swap_library(doc: &mut Document, from: &str, to: &PublishedLibrary) -> Result<Swapped> {
let m = &to.manifest;
if m.id == from {
return Err(EngineError::Other("that is the same library".into()));
}
// Only what the document uses counts (copies nothing uses any more go first).
// Only what the document uses counts: copies nothing uses any more go first, and are listed
// (#2569). Those the final prune takes were in use, by what moved to B.
let before = copies_of(doc, from);
prune(doc, from)?;
let mut out = Swapped::default();
let kept: BTreeSet<String> = copies_of(doc, from).into_iter().map(|(id, _)| id).collect();
out.dropped = before.into_iter().filter(|(id, _)| !kept.contains(id)).map(|(_, name)| name).collect();
let store = doc.library_store();
let outside = |d: &Document, id: NodeId| store.is_none_or(|s| d.page_of(id) != Some(s));
@@ -210,8 +275,19 @@ pub fn swap_library(doc: &mut Document, from: &str, to: &PublishedLibrary) -> Re
out.unmatched.push(format!("extended collection {}", c.name));
}
// Re-point layers outside the library copies, and local variables aliasing A's.
let ids: Vec<NodeId> = doc.nodes().filter(|n| outside(doc, n.id)).map(|n| n.id).collect();
// Re-point the layers, and local variables aliasing A's. The library copies' own layers too:
// a copy B has no match for stays (A's, or another library's), and instances placed from it
// later must link what the ones re-pointed here link (#2568).
// A's collections that keep a variable on A (one B has no match for): a layer choosing a mode
// of one keeps that choice next to B's, so what still reads the A variable keeps its mode.
let still_a: BTreeSet<String> = doc
.libraries
.variables
.iter()
.filter(|r| r.library == from && !vars.contains_key(&r.local))
.filter_map(|r| doc.variables.get_by_id(&r.local).map(|v| v.collection.clone()))
.collect();
let ids: Vec<NodeId> = doc.nodes().map(|n| n.id).collect();
for id in ids {
let Ok(n) = doc.get_mut(id) else { continue };
for r in [&mut n.styles.fill, &mut n.styles.stroke, &mut n.styles.effect, &mut n.styles.grid, &mut n.styles.text] {
@@ -227,13 +303,7 @@ pub fn swap_library(doc: &mut Document, from: &str, to: &PublishedLibrary) -> Re
*v = b.clone();
}
}
n.var_modes = std::mem::take(&mut n.var_modes)
.into_iter()
.map(|(c, mode)| match colls.get(&c).and_then(|(b, modes)| modes.get(&mode).map(|bm| (b.clone(), bm.clone()))) {
Some(moved) => moved,
None => (c, mode),
})
.collect();
n.var_modes = move_modes(std::mem::take(&mut n.var_modes), &colls, &still_a);
}
for v in doc.variables.variables.iter_mut().filter(|v| !remote.contains(&v.id)) {
for r in v.values.values_mut().flat_map(VariableValue::references_mut) {
+156 -1
View File
@@ -31,6 +31,12 @@ impl Drop for Scratch {
/// A library file at `path` with "Button" (filled `color`, a "Label" text), a "Brand" paint style,
/// a "Theme" collection with an `accent` colour, and `extra` components; returns its id.
fn library(path: &str, color: &str, extra: &[&str]) -> String {
library_with(path, color, extra, false)
}
/// [`library`], and with `linked` also "Badge", filled by the Brand style, and "Dot", its fill
/// bound to `accent`: components whose own layers link the library's style and variable.
fn library_with(path: &str, color: &str, extra: &[&str], linked: bool) -> String {
let mut s = Session::new();
let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 40, "name": "Button"})));
ex(&mut s, "text.create", json!({"text": "OK", "x": 10, "y": 10, "parent": f, "props": {"name": "Label"}}));
@@ -41,6 +47,17 @@ fn library(path: &str, color: &str, extra: &[&str]) -> String {
ex(&mut s, "style.create", json!({"type": "paint", "name": "Brand", "from": r}));
ex(&mut s, "variable.createCollection", json!({"name": "Theme", "modes": ["Light", "Dark"]}));
ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "accent", "type": "color", "value": color}));
if linked {
let badge = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 300, "width": 30, "height": 30, "name": "Badge"})));
ex(&mut s, "style.apply", json!({"ids": [badge], "style": "Brand"}));
let dot = idv(&ex(&mut s, "frame.create", json!({"x": 50, "y": 300, "width": 30, "height": 30, "name": "Dot"})));
ex(&mut s, "variable.bind", json!({"ids": [dot], "field": "fill", "variable": "accent"}));
ex(&mut s, "component.create", json!({"ids": [badge]}));
ex(&mut s, "component.create", json!({"ids": [dot]}));
// A Theme variable no other library has, with a value of its own in Dark.
ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "glow", "type": "color", "value": "#111111"}));
ex(&mut s, "variable.set", json!({"variable": "glow", "mode": "Dark", "value": "#222222"}));
}
for (i, name) in extra.iter().enumerate() {
let e = idv(&ex(&mut s, "frame.create", json!({"x": 200 + 50 * i, "y": 0, "width": 20, "height": 20, "name": name})));
ex(&mut s, "component.create", json!({"ids": [e]}));
@@ -60,10 +77,15 @@ fn main_of(s: &Session, inst: NodeId) -> NodeId {
/// A session with libraries A (blue, plus `extra_a` components) and B (green) enabled, files in a
/// scratch directory named by `tag`; returns the directory guard, the session and both library ids.
fn two_libraries(tag: &str, extra_a: &[&str]) -> (Scratch, Session, String, String) {
two_libraries_with(tag, extra_a, false)
}
/// [`two_libraries`], with A made by [`library_with`] and `linked_a`.
fn two_libraries_with(tag: &str, extra_a: &[&str], linked_a: bool) -> (Scratch, Session, String, String) {
let dir = Scratch(std::env::temp_dir().join(format!("figcraft-libswap-{tag}-{}", std::process::id())));
std::fs::create_dir_all(&dir.0).unwrap();
let (pa, pb) = (dir.0.join("a.figcraft").to_string_lossy().into_owned(), dir.0.join("b.figcraft").to_string_lossy().into_owned());
let a = library(&pa, "#0000ff", extra_a);
let a = library_with(&pa, "#0000ff", extra_a, linked_a);
let b = library(&pb, "#00ff00", &[]);
let mut s = Session::new();
ex(&mut s, "library.add", json!({"path": pa}));
@@ -180,3 +202,136 @@ fn swap_repoints_colour_calculations() {
let reads: Vec<&VariableId> = ["veil", "wash"].iter().flat_map(|n| vars.get(n).unwrap().values.values()).flat_map(|v| v.references()).collect();
assert!(reads.iter().all(|r| doc.libraries.variable_import(r).is_some_and(|i| i.library == b)), "{reads:?}");
}
/// Copies of A nothing uses (a component imported but not placed, a variable imported but not
/// bound) go with the swap, as they did; the result now names them (#2569). A copy the swap moves
/// to B isn't among them.
#[test]
fn swap_lists_the_unused_copies_it_removes() {
let (_dir, mut s, a, b) = two_libraries("unused", &["Only in A"]);
let placed = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Button", "x": 0, "y": 0})));
let only = id_of(&ex(&mut s, "library.import", json!({"library": a, "component": "Only in A"}))["component"]).unwrap();
ex(&mut s, "library.importVariable", json!({"library": a, "variable": "accent"}));
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!(r["dropped"], json!(["component Only in A", "variable Theme/accent", "collection Theme"]), "{r}");
assert_eq!((r["components"].as_u64(), r["variables"].as_u64(), &r["unmatched"]), (Some(1), Some(0), &json!([])), "{r}");
assert_eq!(r["removed"], true, "{r}");
let doc = s.doc().unwrap();
assert!(!doc.contains(only), "the dropped copy is gone");
assert_eq!(library_of(doc, main_of(&s, placed)), Some(b.as_str()), "the placed Button moved, so it isn't listed");
assert!(doc.variables.variables.is_empty() && doc.variables.collections.is_empty(), "{:?}", doc.variables);
// One undo step brings them back.
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(doc.contains(only) && library_of(doc, only) == Some(a.as_str()));
assert_eq!(doc.variables.variables.len(), 1);
// A deleted instance leaves its copy unused, so it is listed too; a placed copy B has no match
// for stays and is listed as unmatched.
ex(&mut s, "edit.delete", json!({"ids": [placed]}));
let kept = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Only in A", "x": 0, "y": 0})));
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!(r["dropped"], json!(["component Button", "variable Theme/accent", "collection Theme"]), "{r}");
assert_eq!((&r["unmatched"], &r["removed"]), (&json!(["component Only in A"]), &json!(false)), "{r}");
assert_eq!(library_of(s.doc().unwrap(), main_of(&s, kept)), Some(a.as_str()));
}
/// A component B has no match for stays on A, but the Brand style and `accent` variable its own
/// layers link do have matches (#2568). The swap re-points them in A's read-only copy as on the
/// placed instances, so an instance placed after the swap looks like the ones placed before it,
/// and A's style and variable copies nothing links any more go.
#[test]
fn swap_repoints_the_styles_and_variables_of_component_copies_it_keeps() {
let (_dir, mut s, a, b) = two_libraries_with("copies", &[], true);
let badge = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Badge", "x": 0, "y": 0})));
let dot = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Dot", "x": 100, "y": 0})));
let fill = |s: &Session, id: NodeId| s.doc().unwrap().node(id).unwrap().fills[0].solid_color().unwrap().to_hex();
assert_eq!((fill(&s, badge), fill(&s, dot)), ("0000FF".to_string(), "0000FF".to_string()));
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!((r["components"].as_u64(), r["styles"].as_u64(), r["variables"].as_u64()), (Some(0), Some(1), Some(1)), "{r}");
assert_eq!(r["unmatched"], json!(["component Badge", "component Dot"]), "{r}");
let (badge_main, dot_main) = (main_of(&s, badge), main_of(&s, dot));
let doc = s.doc().unwrap();
assert_eq!((library_of(doc, badge_main), library_of(doc, dot_main)), (Some(a.as_str()), Some(a.as_str())), "no match: still A's");
// The copies link B's style and variable, as the instances do.
for (id, what) in [(badge_main, "the Badge copy"), (badge, "the Badge instance")] {
let style = doc.node(id).unwrap().styles.fill.clone().unwrap_or_default();
assert!(doc.libraries.style_import(&style).is_some_and(|i| i.library == b), "{what} links {style}");
}
for (id, what) in [(dot_main, "the Dot copy"), (dot, "the Dot instance")] {
let bound = doc.node(id).unwrap().bound.get("fill").cloned().unwrap_or_default();
assert!(doc.libraries.variable_import(&bound).is_some_and(|i| i.library == b), "{what} binds {bound}");
}
assert!(doc.libraries.styles.iter().all(|i| i.library == b), "A's Brand copy is linked by nothing: {:?}", doc.libraries.styles);
assert!(doc.libraries.variables.iter().all(|i| i.library == b), "A's accent copy is bound by nothing: {:?}", doc.libraries.variables);
assert!(doc.validate().is_empty(), "{:?}", doc.validate());
// Instances placed after the swap show B's colours, as those placed before it.
let late_badge = idv(&ex(&mut s, "instance.create", json!({"component": badge_main, "x": 0, "y": 100})));
let late_dot = idv(&ex(&mut s, "instance.create", json!({"component": dot_main, "x": 100, "y": 100})));
let shown: Vec<String> = [badge, dot, late_badge, late_dot].iter().map(|i| fill(&s, *i)).collect();
assert_eq!(shown, ["00FF00"; 4]);
// One undo of each instance and the swap puts the copies back on A's style and variable.
s.undo().unwrap();
s.undo().unwrap();
s.undo().unwrap();
let doc = s.doc().unwrap();
let style = doc.node(badge_main).unwrap().styles.fill.clone().unwrap_or_default();
assert!(doc.libraries.style_import(&style).is_some_and(|i| i.library == a), "{style}");
let bound = doc.node(dot_main).unwrap().bound.get("fill").cloned().unwrap_or_default();
assert!(doc.libraries.variable_import(&bound).is_some_and(|i| i.library == a), "{bound}");
assert_eq!((fill(&s, badge), fill(&s, dot)), ("0000FF".to_string(), "0000FF".to_string()));
}
/// A frame choosing A's Theme mode Dark holds a layer bound to `accent` (B has it) and one bound
/// to `glow` (only A has it). The swap gives the frame B's Dark for `accent` and keeps A's Dark for
/// `glow`, which stays on A, so it doesn't fall back to Light.
#[test]
fn swap_keeps_the_mode_of_a_collection_that_still_has_a_variable_on_the_old_library() {
let (_dir, mut s, a, b) = two_libraries_with("modes", &[], true);
let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 100})));
let rect = |s: &mut Session, x: f64| idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10, "parent": frame})));
let (accent, glow) = (rect(&mut s, 0.0), rect(&mut s, 20.0));
ex(&mut s, "library.bindVariable", json!({"library": a, "variable": "accent", "field": "fill", "ids": [accent]}));
ex(&mut s, "library.bindVariable", json!({"library": a, "variable": "glow", "field": "fill", "ids": [glow]}));
ex(&mut s, "library.setVariableMode", json!({"library": a, "collection": "Theme", "mode": "Dark", "ids": [frame]}));
let fill = |s: &Session, id: NodeId| s.doc().unwrap().node(id).unwrap().fills[0].solid_color().unwrap().to_hex();
assert_eq!(fill(&s, glow), "222222", "Dark before the swap");
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!((r["variables"].as_u64(), &r["unmatched"]), (Some(1), &json!(["variable Theme/glow"])), "{r}");
let doc = s.doc().unwrap();
let modes = &doc.node(frame).unwrap().var_modes;
let lib = |c: &str| doc.libraries.collection_import(c).map(|r| r.library.clone());
let mut owners: Vec<Option<String>> = modes.keys().map(|c| lib(c)).collect();
owners.sort();
let mut expected = vec![Some(a.clone()), Some(b.clone())];
expected.sort();
assert_eq!(owners, expected, "B's Theme mode, and A's kept: {modes:?}");
assert_eq!((fill(&s, accent), fill(&s, glow)), ("00FF00".to_string(), "222222".to_string()), "glow stays on A's Dark");
// A mode chosen of B's Theme since wins over A's Dark moved onto it by a second swap.
ex(&mut s, "library.setVariableMode", json!({"library": b, "collection": "Theme", "mode": "Light", "ids": [frame]}));
ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!(fill(&s, accent), "00FF00", "B's Light kept");
let doc = s.doc().unwrap();
let b_mode = doc
.node(frame)
.unwrap()
.var_modes
.iter()
.find(|(c, _)| doc.libraries.collection_import(c).is_some_and(|r| r.library == b))
.map(|(c, m)| (c.clone(), m.clone()));
let (b_coll, mode) = b_mode.unwrap();
assert_eq!(doc.variables.collection_by_id(&b_coll).and_then(|c| c.mode_by_id(&mode)).map(|m| m.name.as_str()), Some("Light"));
// With nothing left on A's Theme, its mode goes with it.
ex(&mut s, "edit.delete", json!({"ids": [glow]}));
ex(&mut s, "library.swap", json!({"from": a, "to": b}));
let doc = s.doc().unwrap();
assert!(doc.node(frame).unwrap().var_modes.keys().all(|c| doc.libraries.collection_import(c).is_some_and(|r| r.library == b)));
}
+5 -1
View File
@@ -55,5 +55,9 @@ pub fn openable(url: &str) -> bool {
// The authority is made of host characters only (an opener that can't parse the address may
// fall back to treating it as a file path).
let authority = after.split(['/', '?', '#']).next().unwrap_or_default();
authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
// A query, fragment, userinfo or port alone does not supply a host.
let host = authority.rsplit('@').next().unwrap_or_default();
!host.is_empty()
&& !host.starts_with(':')
&& authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
}
+182
View File
@@ -238,3 +238,185 @@ fn branch_commands_survive_junk_params_in_a_live_session() {
}
room.check();
}
#[test]
fn a_shared_branch_syncs_and_another_peer_can_review_and_merge_it() {
let mut room = Room::new(base(), 2, 19);
room.settle();
let (main0, main1) = (room.s(0).active, room.s(1).active);
let (f, r) = frame_and_rect(room.server.document());
// Person 0 creates a branch, edits a layer, adds a new layer and a style.
let id = ok(room.s(0), "branch.create", json!({"name": "New Header"}))["id"].as_str().unwrap().to_string();
ok(room.s(0), "fill.set", json!({"ids": [r], "color": "#00AA55"}));
let made = NodeId(ok(room.s(0), "shape.rectangle", json!({"x": 400, "y": 200, "width": 60, "height": 30}))["id"].as_u64().unwrap());
ok(room.s(0), "style.create", json!({"type": "paint", "name": "Accent", "from": r}));
room.settle();
// Main is untouched, while Person 1 sees the shared branch in their list.
assert!(!room.server.document().contains(made));
let branches = ok(room.s(1), "branch.list", json!({}));
let list = branches.as_array().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0]["id"], id);
assert_eq!(list[0]["name"], "New Header");
assert_eq!(list[0]["state"], "active");
// Person 1 opens Person 0's branch and sees the new layer and style.
ok(room.s(1), "branch.open", json!({"id": id}));
assert!(room.s(1).doc().unwrap().contains(made));
assert!(room.s(1).doc().unwrap().styles.iter().any(|st| st.name == "Accent"));
// Person 1 also edits main concurrently (non-conflicting rename on frame).
ok(room.s(1), "doc.switch", json!({"index": main1}));
ok(room.s(1), "node.set", json!({"id": f, "props": {"name": "Main Frame"}}));
room.settle();
// Person 1 reviews and merges Person 0's branch into main.
assert_eq!(conflict_keys(room.s(1), &id), Vec::<String>::new());
assert_eq!(ok(room.s(1), "branch.merge", json!({"id": id}))["merged"], true);
room.settle();
// Switch Person 0 back to main so room.check() compares main tabs.
ok(room.s(0), "doc.switch", json!({"index": main0}));
room.check();
let doc = room.server.document();
assert!(doc.contains(made), "Person 0's layer from the branch is now on main");
assert_eq!(doc.node(f).unwrap().name, "Main Frame");
assert!(doc.styles.iter().any(|st| st.name == "Accent"));
// Both peers see the branch marked merged.
assert_eq!(ok(room.s(0), "branch.list", json!({}))[0]["state"], "merged");
assert_eq!(ok(room.s(1), "branch.list", json!({}))[0]["state"], "merged");
}
#[test]
fn shared_branch_update_from_main_and_archive_sync_to_peers() {
let mut room = Room::new(base(), 2, 23);
room.settle();
let main0 = room.s(0).active;
let (f, _) = frame_and_rect(room.server.document());
let a = ok(room.s(0), "branch.create", json!({"name": "Keep"}))["id"].as_str().unwrap().to_string();
ok(room.s(0), "doc.switch", json!({"index": main0}));
let b = ok(room.s(0), "branch.create", json!({"name": "Drop"}))["id"].as_str().unwrap().to_string();
room.settle();
// Person 1 edits main and archives branch B.
ok(room.s(1), "node.set", json!({"id": f, "props": {"name": "Updated Main"}}));
ok(room.s(1), "branch.archive", json!({"id": b}));
room.settle();
// Person 0 sees branch B archived, and updates branch A from main.
let list0 = ok(room.s(0), "branch.list", json!({}));
assert_eq!(list0.as_array().unwrap().iter().find(|x| x["id"] == b).unwrap()["state"], "archived");
assert_eq!(ok(room.s(0), "branch.updateFromMain", json!({"id": a}))["updated"], true);
room.settle();
// Person 1 opens branch A and sees main's update in it.
ok(room.s(1), "branch.open", json!({"id": a}));
assert_eq!(room.s(1).doc().unwrap().node(f).unwrap().name, "Updated Main");
}
#[test]
fn remote_merge_closes_peers_open_branch_tab_and_switches_to_main() {
let mut room = Room::new(base(), 2, 29);
room.settle();
let main1 = room.s(1).active;
let tabs_before = room.s(1).docs.len();
let (_, r) = frame_and_rect(room.server.document());
let id = ok(room.s(0), "branch.create", json!({"name": "Card Polish"}))["id"].as_str().unwrap().to_string();
ok(room.s(0), "node.set", json!({"id": r, "props": {"name": "Polished"}}));
room.settle();
// Person 1 opens Person 0's branch tab so it is their active tab.
ok(room.s(1), "branch.open", json!({"id": id}));
assert_eq!(room.s(1).docs.len(), tabs_before + 1);
assert_ne!(room.s(1).active, main1);
// Person 0 merges the branch into main.
assert_eq!(ok(room.s(0), "branch.merge", json!({"id": id}))["merged"], true);
room.settle();
// Person 1's open branch tab closed and switched back to main with the merged change.
assert_eq!(room.s(1).docs.len(), tabs_before);
assert_eq!(room.s(1).active, main1);
assert_eq!(room.s(1).doc().unwrap().node(r).unwrap().name, "Polished");
assert!(room.s(1).message.as_deref().is_some_and(|m| m.contains("merged branch")));
room.check();
}
#[test]
fn concurrent_conflicting_renames_on_a_shared_branch_converge_to_server_order() {
let mut room = Room::new(base(), 2, 31);
room.settle();
let (_, r) = frame_and_rect(room.server.document());
let id = ok(room.s(0), "branch.create", json!({"name": "Race"}))["id"].as_str().unwrap().to_string();
room.settle();
ok(room.s(1), "branch.open", json!({"id": id}));
// Both peers rename the same layer on the shared branch before any messages are delivered.
ok(room.s(0), "node.set", json!({"id": r, "props": {"name": "AdaName"}}));
ok(room.s(1), "node.set", json!({"id": r, "props": {"name": "BoName"}}));
room.settle();
// Both peers must converge to the exact same final name (no stale local divergence).
let n0 = room.s(0).doc().unwrap().node(r).unwrap().name.clone();
let n1 = room.s(1).doc().unwrap().node(r).unwrap().name.clone();
assert_eq!(n0, n1);
assert!(n0 == "AdaName" || n0 == "BoName", "unexpected name {n0}");
}
#[test]
fn rejected_merge_batch_leaves_shared_branch_active() {
let limits = figcraft_collab::Limits { max_changes: 2, ..figcraft_collab::Limits::default() };
let mut room = Room::new_with_limits(base(), 2, 37, limits);
room.settle();
let (main0, _) = (room.s(0).active, room.s(1).active);
let (_, r) = frame_and_rect(room.server.document());
let id = ok(room.s(0), "branch.create", json!({"name": "BigMerge"}))["id"].as_str().unwrap().to_string();
room.settle();
// Each individual edit fits within max_changes = 2, so the branch accepts them one by one.
ok(room.s(0), "node.set", json!({"id": r, "props": {"name": "Changed"}}));
room.settle();
ok(room.s(0), "fill.set", json!({"ids": [r], "color": "#FF00AA"}));
room.settle();
let added = NodeId(ok(room.s(0), "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].as_u64().unwrap());
room.settle();
// Merging all three edits into main in one batch exceeds max_changes = 2, so the server rejects it.
assert_eq!(ok(room.s(0), "branch.merge", json!({"id": id}))["merged"], true);
room.settle();
// Because the main merge batch was rejected, main does NOT have `added`, and BOTH peers still
// see the branch as active (not prematurely marked merged).
assert!(!room.server.document().contains(added));
ok(room.s(0), "doc.switch", json!({"index": main0}));
assert_eq!(ok(room.s(0), "branch.list", json!({}))[0]["state"], "active");
assert_eq!(ok(room.s(1), "branch.list", json!({}))[0]["state"], "active");
}
#[test]
fn refused_branch_create_clears_shared_flag_and_surfaces_reason() {
let mut room = Room::new(base(), 2, 41);
room.settle();
let main0 = room.s(0).active;
// Fill up to MAX_SHARED_BRANCHES on the server.
for i in 0..figcraft_collab::message::MAX_SHARED_BRANCHES {
ok(room.s(0), "doc.switch", json!({"index": main0}));
ok(room.s(0), "branch.create", json!({"name": format!("B{i}")}));
room.settle();
}
ok(room.s(0), "doc.switch", json!({"index": main0}));
let main_uid = room.s(0).docs[main0].uid;
// One more branch exceeds the server cap (64): server rejects it with an explicit notice.
let extra = ok(room.s(0), "branch.create", json!({"name": "OverCap"}))["id"].as_str().unwrap().to_string();
room.settle();
assert!(!room.s(0).live_branch_shared(main_uid, &extra), "refused branch must not stay marked shared");
assert!(room.s(0).message.as_deref().is_some_and(|m| m.contains("wasn't synced")));
}
#[test]
fn shared_branch_preserves_and_syncs_edits_made_while_disconnected() {
let mut room = Room::new(base(), 2, 43);
room.settle();
let (_, r) = frame_and_rect(room.server.document());
let id = ok(room.s(0), "branch.create", json!({"name": "OfflineWork"}))["id"].as_str().unwrap().to_string();
room.settle();
ok(room.s(1), "branch.open", json!({"id": id}));
// Disconnect Person 0 (simulating a transient network drop).
room.disconnect(0);
// Person 0 edits the shared branch while disconnected; Person 1 adds another shape online.
ok(room.s(0), "node.set", json!({"id": r, "props": {"name": "EditedOffline"}}));
let online_shape = NodeId(ok(room.s(1), "shape.rectangle", json!({"x": 300, "y": 50, "width": 30, "height": 30}))["id"].as_u64().unwrap());
room.settle();
// Reconnect Person 0: offline branch edit must survive and sync to Person 1 alongside online_shape.
room.reconnect(0);
room.settle();
assert_eq!(room.s(0).doc().unwrap().node(r).unwrap().name, "EditedOffline");
assert!(room.s(0).doc().unwrap().contains(online_shape));
assert_eq!(room.s(1).doc().unwrap().node(r).unwrap().name, "EditedOffline");
assert!(room.s(1).doc().unwrap().contains(online_shape));
}
+1 -1
View File
@@ -656,7 +656,7 @@ impl Session {
fn builder_select(&mut self, ev: &PointerEvent) {
let Ok(ds) = self.ds() else { return };
let (doc, page, mut sel) = (ds.doc.clone(), ds.page, ds.selection.clone());
let Some(leaf) = self.hit(&doc, page, ev.p(), 2.0 / ev.zoom.max(1e-6)) else { return };
let Some(leaf) = self.hit_pick(&doc, page, ev.p(), 2.0 / ev.zoom.max(1e-6), ev.cmd) else { return };
let t = figcraft_doc::geometry::select_target(&doc, leaf, &sel, ev.cmd);
if ev.shift {
if let Some(i) = sel.iter().position(|x| *x == t) {
+3 -1
View File
@@ -92,7 +92,9 @@ impl Session {
if edits && matches!(self.tool.tool, ToolId::Move | ToolId::Scale) && !(ev.shift || ev.cmd) && self.edge_double_click(&doc, &sel, ev)? {
return Ok(());
}
let hit_here = self.hit(&doc, page, ev.p(), ev.tol() * 2.0);
// With Cmd/Ctrl, the pick reaches through an unfilled overlay as a Cmd/Ctrl-click does, so
// the layer under it is edited at once.
let hit_here = self.hit_pick(&doc, page, ev.p(), ev.tol() * 2.0, ev.cmd);
// A double-click anywhere on the one selected shape edits its points, like Enter: also
// inside a hollow (unfilled) closed shape, where the hit test finds nothing under the
// pointer (an open path or a line has no inside: only its stroke counts).
+12 -5
View File
@@ -91,7 +91,7 @@ impl Session {
})
};
let label = label_at(&doc, page, &self.tool.labels, ev.p());
let leaf = self.hit(&doc, page, ev.p(), ev.tol() * 2.0);
let leaf = self.hit_pick(&doc, page, ev.p(), ev.tol() * 2.0, ev.cmd);
let hit = label.or(leaf);
let background_under_cmd = leaf.filter(|l| ev.cmd && label.is_none() && board_background(*l));
let target = label.or_else(|| leaf.filter(|leaf| !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
@@ -102,11 +102,18 @@ impl Session {
// A press on a layer inside a selected one (a child of a selected frame) drags the
// selection too, and a click selects that layer; Cmd/Ctrl keeps the deep pick.
let in_selected = |t: NodeId| sel.iter().any(|s| *s != t && doc.is_ancestor(*s, t));
let behind_sel = |t: Option<NodeId>| {
t.is_none_or(|t| {
// With Cmd/Ctrl, a selected nested frame the deep pick went through here (no fill under the
// pointer, see `HitOpts::deep`) isn't pressed on: the layer under it is the pick, as when
// the frame isn't selected.
let passed_through =
|s: NodeId| ev.cmd && doc.node(s).is_some_and(|n| n.kind.is_frame_like()) && !hit.is_some_and(|h| h == s || doc.is_ancestor(s, h));
let behind_sel = |t: Option<NodeId>| match t {
// Reaching nothing counts only for a selected layer the press wasn't passed through.
None => sel.iter().any(|s| !passed_through(*s)),
Some(t) => {
(!ev.cmd && in_selected(t))
|| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))
})
|| sel.iter().any(|s| *s != t && !passed_through(*s) && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))
}
};
// What the press hit (a label or a painted layer): a click that doesn't become a drag
// selects just it. A press that reaches nothing above the selection uses the selection as
+10 -2
View File
@@ -58,6 +58,14 @@ impl Session {
/// frame's. Boolean groups are hit by their results ([`crate::booleans::result_outline`]); in
/// outline mode shapes only on their outlines.
pub fn hit(&self, doc: &Document, page: NodeId, p: Point, tol: f64) -> Option<NodeId> {
self.hit_pick(doc, page, p, tol, false)
}
/// [`Session::hit`] for a pick (a press, a hover, a right-click) with Cmd/Ctrl held when
/// `deep`: it reaches through a nested frame, component or instance where that has no
/// visible fill (see [`figcraft_doc::geometry::HitOpts::deep`]).
pub fn hit_pick(&self, doc: &Document, page: NodeId, p: Point, tol: f64, deep: bool) -> Option<NodeId> {
let opts = figcraft_doc::geometry::HitOpts { deep, ..Default::default() };
let sel = self.selection();
let result = crate::booleans::result_outline(doc, &sel);
let focus = self.ds().ok().and_then(crate::DocState::focused);
@@ -68,8 +76,8 @@ impl Session {
return figcraft_doc::geometry::hit_outlines(doc, focus.unwrap_or(page), p, tol, Some(&result), also);
}
match focus {
Some(f) => figcraft_doc::geometry::hit_in(doc, f, p, tol, Some(&result)),
None => doc.hit_test(page, p, tol, Some(&result)),
Some(f) => figcraft_doc::geometry::hit_in_opts(doc, f, p, tol, Some(&result), opts),
None => figcraft_doc::geometry::hit_leaf_opts(doc, page, p, tol, Some(&result), opts),
}
}
+1 -1
View File
@@ -291,7 +291,7 @@ impl Session {
if let Some(h) = handle_at(&doc, &sel, ev.p(), ev.zoom).filter(|_| !self.tool.dev_mode) {
cursor = resize_cursor(&doc, &sel, h);
} else {
let leaf = self.hit(&doc, page, ev.p(), ev.tol() * 2.0);
let leaf = self.hit_pick(&doc, page, ev.p(), ev.tol() * 2.0, ev.cmd);
if leaf.and_then(|l| crate::widgets::target_at(&doc, l, ev.p())).is_some() {
cursor = Cursor::Pointer;
}
+1
View File
@@ -102,6 +102,7 @@ fn registry() -> &'static Registry {
list.extend(crate::devinspect::specs());
list.extend(crate::design_context::specs());
list.extend(crate::asset_handoff::specs());
list.extend(crate::responsive::specs());
list.extend(crate::component_codegen::specs());
list.extend(crate::playground::specs());
list.extend(crate::code_connect::specs());
+1 -1
View File
@@ -8,7 +8,7 @@ pub(super) fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
let zoom = s.ds()?.view.zoom.max(1e-6);
let sel = s.selection();
let result = crate::booleans::result_outline(doc, &sel);
let opts = figcraft_doc::geometry::HitOpts { locked: true };
let opts = figcraft_doc::geometry::HitOpts { locked: true, ..Default::default() };
let layers: Vec<Value> = figcraft_doc::geometry::layers_at_opts(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result), opts)
.into_iter()
.filter_map(|(id, depth)| {
+4 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"library.swap",
"Swap library",
"{from (an enabled library: id, name or path), to (another enabled library)} re-points every component instance, style and variable copied from `from` to the published one of the same name in `to` (instances keep their overrides) → {components, styles, variables, unmatched: [names still from `from`], removed (nothing of `from` is used any more: it was removed)}",
"{from (an enabled library: id, name or path), to (another enabled library)} re-points every component instance, style and variable copied from `from` to the published one of the same name in `to` (instances keep their overrides) → {components, styles, variables, unmatched: [names still from `from`], dropped: [names of `from`'s copies nothing used (a component imported but not placed, a variable imported but not bound): removed, not moved], removed (nothing of `from` is used any more: it was removed)}",
true,
swap_cmd
),
@@ -599,7 +599,9 @@ fn swap_cmd(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`from` and `to` are the same library"));
}
let r = crate::library_swap::swap_library(s.doc_mut()?, &from, &lib)?;
Ok(json!({"components": r.components, "styles": r.styles, "variables": r.variables, "unmatched": r.unmatched, "removed": r.removed}))
Ok(
json!({"components": r.components, "styles": r.styles, "variables": r.variables, "unmatched": r.unmatched, "dropped": r.dropped, "removed": r.removed}),
)
}
fn assets_json(lib: &PublishedLibrary) -> Value {
+122
View File
@@ -2,6 +2,7 @@
//! duplicate and delete; extended collections (overrides, keeping them in step with what they
//! extend); alias checks; and which scope a bindable property belongs to.
use std::cmp::Ordering;
use std::collections::BTreeSet;
use figcraft_doc::{
@@ -25,6 +26,20 @@ pub fn specs() -> Vec<CommandSpec> {
update
),
spec!("variable.duplicate", "Duplicate variable", "{variable} → {id}", true, duplicate),
spec!(
"variable.move",
"Move variables",
"{variables [ids or names, one collection], before? (variable of that collection; default: the end)} the order the Variables window and pickers list them in",
true,
move_variables
),
spec!(
"variable.sort",
"Sort variables",
"{collection, group? (\"color/indigo\"; default: the whole collection), descending? (Z to A)} by name, numbers by value (50 before 100)",
true,
sort_variables
),
spec!("variable.renameMode", "Rename mode", "{collection, mode, name}", true, rename_mode),
spec!("variable.removeMode", "Delete mode", "{collection, mode} (a collection keeps at least one mode)", true, remove_mode),
spec!("variable.moveMode", "Move mode", "{collection, mode, to (index; 0 = the default mode, layers on Auto follow it)}", true, move_mode),
@@ -204,6 +219,113 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"id": id}))
}
/// Rearrange the variables at list positions `slots` (in list order) with `order`; each slot takes
/// the variable `order` leaves at its place.
fn rearrange(doc: &mut Document, slots: &[usize], order: impl FnOnce(&mut Vec<Variable>)) {
let vars = &mut doc.variables.variables;
let mut list: Vec<Variable> = slots.iter().filter_map(|&i| vars.get(i).cloned()).collect();
order(&mut list);
for (&i, v) in slots.iter().zip(list) {
if let Some(slot) = vars.get_mut(i) {
*slot = v;
}
}
}
fn move_variables(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "variable.move";
let doc = s.doc_mut()?;
let keys: Vec<&str> = match get(p, "variables") {
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
_ => return Err(bad(cmd, "`variables` must be a list of variable ids")),
};
let find = |k: &str| doc.variables.get(k).ok_or_else(|| bad(cmd, format!("no variable `{k}`")));
let picked: Vec<&Variable> = keys.iter().map(|k| find(k)).collect::<Result<_>>()?;
let cid = picked.first().map(|v| v.collection.clone()).ok_or_else(|| bad(cmd, "no variables to move"))?;
if picked.iter().any(|v| v.collection != cid) {
return Err(bad(cmd, "the variables to move must be in one collection"));
}
let picked: BTreeSet<VariableId> = picked.into_iter().map(|v| v.id.clone()).collect();
let before = match string(p, "before") {
Some(b) => {
let v = find(&b)?;
if v.collection != cid {
return Err(bad(cmd, "`before` must be in the same collection"));
}
if picked.contains(&v.id) {
return Err(bad(cmd, "`before` can't be one of the variables moved"));
}
Some(v.id.clone())
}
None => None,
};
let slots: Vec<usize> = doc.variables.variables.iter().enumerate().filter(|(_, v)| v.collection == cid).map(|(i, _)| i).collect();
rearrange(doc, &slots, |list| {
let (moved, mut rest): (Vec<Variable>, Vec<Variable>) = std::mem::take(list).into_iter().partition(|v| picked.contains(&v.id));
let at = before.and_then(|b| rest.iter().position(|v| v.id == b)).unwrap_or(rest.len());
rest.splice(at..at, moved);
*list = rest;
});
ok()
}
fn sort_variables(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "variable.sort";
let doc = s.doc_mut()?;
let ci = collection_index(doc, cmd, &req_string(cmd, p, "collection")?)?;
let cid = doc.variables.collections.get(ci).map(|c| c.id.clone()).ok_or_else(|| bad(cmd, "no such collection"))?;
let group = string(p, "group").and_then(|g| clean_name(&g));
let prefix = group.as_ref().map(|g| format!("{g}/"));
let slots: Vec<usize> = doc
.variables
.variables
.iter()
.enumerate()
.filter(|(_, v)| v.collection == cid && prefix.as_ref().is_none_or(|g| v.name.starts_with(g.as_str())))
.map(|(i, _)| i)
.collect();
if let Some(g) = group.filter(|_| slots.is_empty()) {
return Err(bad(cmd, format!("no variables in group `{g}`")));
}
let descending = boolean(p, "descending").unwrap_or(false);
rearrange(doc, &slots, |list| {
list.sort_by(|a, b| {
let o = natural_cmp(&a.name, &b.name);
if descending { o.reverse() } else { o }
});
});
ok()
}
/// Compare names with each run of digits as a number ("50" < "100" < "950") and letters ignoring
/// case; names equal that way compare as plain text.
fn natural_cmp(a: &str, b: &str) -> Ordering {
fn digits(it: &mut std::iter::Peekable<std::str::Chars>) -> String {
std::iter::from_fn(|| it.next_if(char::is_ascii_digit)).collect()
}
let (mut x, mut y) = (a.chars().peekable(), b.chars().peekable());
loop {
let o = match (x.peek().copied(), y.peek().copied()) {
(None, None) => return a.cmp(b),
(None, Some(_)) => return Ordering::Less,
(Some(_), None) => return Ordering::Greater,
(Some(c), Some(d)) if c.is_ascii_digit() && d.is_ascii_digit() => {
let (n, m) = (digits(&mut x), digits(&mut y));
let (n, m) = (n.trim_start_matches('0'), m.trim_start_matches('0'));
n.len().cmp(&m.len()).then_with(|| n.cmp(m))
}
(Some(c), Some(d)) => {
x.next();
y.next();
c.to_lowercase().cmp(d.to_lowercase())
}
};
if o.is_ne() {
return o;
}
}
}
/// The index of collection `c` (id or name).
fn collection_index(doc: &Document, cmd: &str, c: &str) -> Result<usize> {
doc.variables.collections.iter().position(|x| x.id == c || x.name == c).ok_or_else(|| bad(cmd, "no such collection"))
+13 -5
View File
@@ -44,7 +44,11 @@ fn welcome_of(out: &[Outgoing], id: u32) -> ServerMsg {
impl Room {
pub(crate) fn new(doc: Document, n: usize, seed: u64) -> Room {
let mut room = Room { server: Server::new(doc, "t", Limits::default()), people: Vec::new(), rng: Rng::new(seed) };
Self::new_with_limits(doc, n, seed, Limits::default())
}
pub(crate) fn new_with_limits(doc: Document, n: usize, seed: u64, limits: Limits) -> Room {
let mut room = Room { server: Server::new(doc, "t", limits), people: Vec::new(), rng: Rng::new(seed) };
for _ in 0..n {
let mut s = Session::new();
let script = Arc::new(Mutex::new(Script::default()));
@@ -73,7 +77,10 @@ impl Room {
Outgoing::All(m) => (m, (0..self.people.len()).collect()),
Outgoing::Others(id, m) => (m, (0..self.people.len()).filter(|i| self.people[*i].id != id).collect()),
};
if !matches!(msg, ServerMsg::Changes(_) | ServerMsg::Reject { .. } | ServerMsg::Welcome { .. }) {
if !matches!(
msg,
ServerMsg::Changes(_) | ServerMsg::Reject { .. } | ServerMsg::Welcome { .. } | ServerMsg::Branches(_) | ServerMsg::Branch(_)
) {
continue;
}
let to: Vec<usize> = to.into_iter().filter(|i| self.people[*i].online).collect();
@@ -127,7 +134,7 @@ impl Room {
}
/// Person `i`'s connection drops: what is in flight is lost; the link says it's reconnecting.
fn disconnect(&mut self, i: usize) {
pub(crate) fn disconnect(&mut self, i: usize) {
let p = &mut self.people[i];
p.up.clear();
p.down.clear();
@@ -139,10 +146,11 @@ impl Room {
}
/// Person `i` is back: the link says hello with the client's id and last sequence number.
fn reconnect(&mut self, i: usize) {
pub(crate) fn reconnect(&mut self, i: usize) {
let p = &mut self.people[i];
let ClientMsg::Hello(mut h) = Client::hello("f", "t", "Person", "") else { panic!("not a hello") };
h.resume = p.s.live().client().map(Client::resume);
let main_uid = p.s.docs[crate::branches::file_tab(&p.s)].uid;
h.resume = p.s.live_of(main_uid).client().map(Client::resume);
let (id, out) = self.server.join(h).unwrap();
assert_eq!(id, p.id, "the same client");
p.online = true;
+16
View File
@@ -433,3 +433,19 @@ fn code_links_keep_their_value_names_and_carry_source_and_notes() {
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
}
#[test]
fn stated_screen_sizes_come_with_the_context() {
let mut s = session();
let f = node(&mut s, json!({"type": "frame", "name": "Home", "width": 1440, "height": 900}));
let unmarked = context(&mut s, json!({"ids": [f]}));
assert_eq!(unmarked["responsive"]["explicit"], false, "{unmarked}");
let says = |v: &Value| v["missing"].as_array().unwrap().iter().any(|m| m["what"] == "responsive behaviour");
assert!(says(&unmarked), "nothing stated: the gap is named");
s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop"})).unwrap();
s.execute("responsive.rule", &json!({"id": f, "text": "Sidebar becomes a drawer below 768 px"})).unwrap();
let marked = context(&mut s, json!({"ids": [f]}));
assert_eq!(marked["responsive"]["explicit"], true, "{marked}");
assert_eq!(marked["responsive"]["rules"][0]["text"], "Sidebar becomes a drawer below 768 px");
assert!(!says(&marked), "{marked}");
}
+1
View File
@@ -8,4 +8,5 @@ pub mod dev_measurements;
pub mod dev_resources;
pub mod devcompare;
pub mod devinspect;
pub mod responsive;
pub mod tailwind;
+15 -13
View File
@@ -44,6 +44,18 @@ pub fn find_category<'a>(list: &'a [AnnotationCategory], key: &str) -> Option<&'
list.iter().find(|c| c.id == key).or_else(|| list.iter().find(|c| c.name.eq_ignore_ascii_case(key)))
}
/// A colour no category in `list` has, if there is one.
pub(crate) fn unused_color(list: &[AnnotationCategory]) -> figcraft_color::Color {
let used = |c: &figcraft_color::Color| list.iter().any(|x| x.color.to_hex() == c.to_hex());
let fallback = AnnotationCategory::COLORS.get(list.len() % AnnotationCategory::COLORS.len()).copied().unwrap_or(figcraft_color::Color::BLACK);
AnnotationCategory::COLORS.iter().find(|c| !used(c)).copied().unwrap_or(fallback)
}
/// An id no category in `list` has.
pub(crate) fn free_category_id(list: &[AnnotationCategory]) -> String {
(1..=MAX_CATEGORIES + 1).map(|k| format!("custom-{k}")).find(|i| !list.iter().any(|c| c.id == *i)).unwrap_or_default()
}
fn category_json(c: &AnnotationCategory) -> Value {
json!({"id": c.id, "name": c.name, "color": c.color.to_css_hex()})
}
@@ -188,7 +200,7 @@ fn parse_properties(cmd: &str, p: &Value) -> crate::Result<Option<Vec<String>>>
}
/// `label` from params, trimmed of trailing whitespace and capped.
fn parse_label(cmd: &str, p: &Value) -> crate::Result<Option<String>> {
pub(crate) fn parse_label(cmd: &str, p: &Value) -> crate::Result<Option<String>> {
match get(p, "label").or_else(|| get(p, "text")) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.trim_end().chars().take(MAX_LABEL).collect())),
@@ -381,18 +393,8 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad(cmd, format!("a file has at most {MAX_CATEGORIES} categories")));
}
let name = category_name(cmd, &list, None, p)?.ok_or_else(|| bad(cmd, "`name` required"))?;
let color = match category_color(cmd, p)? {
Some(c) => c,
None => {
let used = |c: &figcraft_color::Color| list.iter().any(|x| x.color.to_hex() == c.to_hex());
let fallback = AnnotationCategory::COLORS
.get(list.len() % AnnotationCategory::COLORS.len())
.copied()
.unwrap_or(figcraft_color::Color::BLACK);
AnnotationCategory::COLORS.iter().find(|c| !used(c)).copied().unwrap_or(fallback)
}
};
let id = (1..=MAX_CATEGORIES + 1).map(|k| format!("custom-{k}")).find(|i| !list.iter().any(|c| c.id == *i)).unwrap_or_default();
let color = category_color(cmd, p)?.unwrap_or_else(|| unused_color(&list));
let id = free_category_id(&list);
list.push(AnnotationCategory { id: id.clone(), name, color });
s.doc_mut()?.annotation_categories = Some(list);
Ok(json!({"id": id}))
+8 -4
View File
@@ -434,9 +434,12 @@ fn design_context(s: &mut Session, p: &Value) -> Result<Value> {
}
nodes.extend(layer(doc, *id, depth, cap, &mut used));
}
let mut missing = vec![
json!({"what": "responsive behaviour", "why": "the file stores no breakpoints: sizes are as designed here, and constraints, sizing and annotations are all it says about other widths"}),
];
// Only what the designer stated about other sizes; without it, the gap is named.
let responsive = crate::responsive::context(doc, &ids);
let mut missing = Vec::new();
if responsive["explicit"] != true {
missing.push(json!({"what": "responsive behaviour", "why": "the file stores no breakpoints: sizes are as designed here, and constraints, sizing and annotations are all it says about other widths"}));
}
let (joined, complete) = referenced(doc, &used.variables, &used.styles, MAX_VARIABLES);
let variables = variables_json(doc, &joined, &mut missing);
let styles = styles_json(doc, &used.styles, &mut missing);
@@ -457,6 +460,7 @@ fn design_context(s: &mut Session, p: &Value) -> Result<Value> {
"components": components,
"fonts": fonts,
"assets": assets,
"responsive": responsive,
"missing": missing,
});
if used.left_out > 0 || used.cut_by_depth {
@@ -473,7 +477,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![spec!(
"inspect.designContext",
"Design context",
"{ids? | id? (those layers), scope?: selection|page|document (default the selection, or the page with nothing selected), depth? (default 32), maxNodes? (default 2000)} everything needed to build them, in one read → {version, document, target {source, ids, layers}, nodes [{id, name, type, explicit, derived?, tokens?, unsupported? [{property, why}], code?, children?, childCount?}], variables, styles, components, fonts, assets, missing [{what, why}], truncated?}",
"{ids? | id? (those layers), scope?: selection|page|document (default the selection, or the page with nothing selected), depth? (default 32), maxNodes? (default 2000)} everything needed to build them, in one read → {version, document, target {source, ids, layers}, nodes [{id, name, type, explicit, derived?, tokens?, unsupported? [{property, why}], code?, children?, childCount?}], variables, styles, components, fonts, assets, responsive {explicit, versions, rules, truncated?}, missing [{what, why}], truncated?}",
false,
design_context
)]
+2 -2
View File
@@ -223,10 +223,10 @@ pub struct DevItem {
/// Whether Dev Mode runs command `id` from the menus and shortcuts: commands that don't edit the
/// document, and Dev Mode's own edits (annotations, statuses, dev resources, measurements, code
/// connections, comments). Choosing a tool other than moving around and commenting is refused too,
/// connections, screen size marks and rules, comments). Choosing a tool other than moving around and commenting is refused too,
/// and so is Revert to saved, which isn't an undo step but throws the design's unsaved edits away.
pub fn dev_mode_allows(id: &str) -> bool {
const OWN: [&str; 6] = ["annotation.", "dev.", "devMode.", "devResource.", "codeConnect.", "comment."];
const OWN: [&str; 7] = ["annotation.", "dev.", "devMode.", "devResource.", "codeConnect.", "responsive.", "comment."];
// Edits recorded as one grouped undo step, so their spec says no history of its own.
const GROUPED: [&str; 1] = ["data.fill"];
match id.strip_prefix("tool.") {
+243
View File
@@ -0,0 +1,243 @@
//! Responsive context: what the designer states about other screen sizes. A file has no
//! breakpoints, so this holds only what was said outright: frames marked as the mobile, tablet or
//! desktop version of one design (in layer data, so the file format doesn't change), and notes in
//! the Responsive annotation category. Nothing here is worked out from names or sizes: an agent
//! must never take a guess for the designer's word.
use std::collections::BTreeSet;
use figcraft_doc::{Annotation, AnnotationCategory, Document, Node, NodeId, NodeKind};
use serde_json::{Value, json};
use crate::annotations::{MAX_CATEGORIES, MAX_PER_LAYER, categories, category_of, find_category, free_category_id, parse_label, unused_color};
use crate::cmd::CommandSpec;
use crate::params::{get, req_targets};
use crate::{Result, Session, bad, spec};
/// Layer data key: which version of a design a frame is.
pub const VIEWPORT_KEY: &str = "figcraft.viewport";
/// Layer data key: which design it is a version of.
pub const GROUP_KEY: &str = "figcraft.viewportGroup";
/// The annotation category responsive rules go in.
pub const RULES_CATEGORY: &str = "Responsive";
/// The versions a frame can be.
pub const VIEWPORTS: [&str; 3] = ["mobile", "tablet", "desktop"];
/// Longest group name (chars).
const MAX_GROUP: usize = 100;
/// Most layers looked through for rules.
const MAX_WALK: usize = 50_000;
/// Whether a layer can be marked as a version of a design: frames and sections are screens.
pub fn can_mark(kind: &NodeKind) -> bool {
matches!(kind, NodeKind::Frame | NodeKind::Section { .. })
}
/// The version `n` is marked as. Layer data can hold anything (`node.set {pluginData}`), so
/// only the three versions count.
pub fn viewport_of(n: &Node) -> Option<&str> {
n.plugin_data.get(VIEWPORT_KEY).map(String::as_str).filter(|v| VIEWPORTS.contains(v))
}
/// The design `n` is a version of: its stored group, or its name when there is none, or the
/// stored one is empty or too long.
pub fn group_of(n: &Node) -> &str {
n.plugin_data.get(GROUP_KEY).map(|g| g.trim()).filter(|g| !g.is_empty() && g.chars().count() <= MAX_GROUP).unwrap_or(&n.name)
}
/// A marked frame as JSON.
fn frame_json(doc: &Document, id: NodeId) -> Option<Value> {
let n = doc.node(id)?;
Some(json!({"id": id, "name": n.name, "viewport": viewport_of(n)?, "width": n.width, "height": n.height, "page": doc.page_of(id)}))
}
/// Every design with marked frames, narrowest first.
pub fn groups(doc: &Document) -> Vec<(String, Vec<NodeId>)> {
let mut out: std::collections::BTreeMap<String, Vec<NodeId>> = std::collections::BTreeMap::new();
for n in doc.nodes().filter(|n| viewport_of(n).is_some()) {
out.entry(group_of(n).to_string()).or_default().push(n.id);
}
for frames in out.values_mut() {
frames.sort_by(|a, b| doc.node(*a).map_or(0.0, |n| n.width).total_cmp(&doc.node(*b).map_or(0.0, |n| n.width)));
}
out.into_iter().collect()
}
fn group_json(doc: &Document, group: &str, frames: &[NodeId]) -> Value {
json!({"group": group, "frames": frames.iter().filter_map(|f| frame_json(doc, *f)).collect::<Vec<_>>()})
}
/// Whether `a` is a responsive rule.
fn is_rule(doc: &Document, a: &Annotation) -> bool {
category_of(doc, a).is_some_and(|c| c.name.eq_ignore_ascii_case(RULES_CATEGORY))
}
/// Counts layer `id` into `seen`: false when it is new and `max` layers are already counted.
fn take(seen: &mut BTreeSet<NodeId>, id: NodeId, max: usize) -> bool {
seen.contains(&id) || (seen.len() < max && seen.insert(id))
}
/// `ids`, the layers above them and those under them, each once and at most `max` (sorted), and
/// whether some were left out. The walk stops at `max`: a huge subtree isn't collected first.
fn around(doc: &Document, ids: &[NodeId], max: usize) -> (Vec<NodeId>, bool) {
let mut seen = BTreeSet::new();
let mut walked = BTreeSet::new();
for id in ids {
for p in doc.ancestors(*id) {
if !take(&mut seen, p, max) {
return (seen.into_iter().collect(), true);
}
}
let mut stack = vec![*id];
while let Some(c) = stack.pop() {
// A layer under an earlier target was walked with it.
if !walked.insert(c) {
continue;
}
let Some(n) = doc.node(c) else { continue };
if !take(&mut seen, c, max) {
return (seen.into_iter().collect(), true);
}
stack.extend(n.children.iter().rev());
}
}
(seen.into_iter().collect(), false)
}
/// What the designer states about `ids` and the design they belong to.
pub fn context(doc: &Document, ids: &[NodeId]) -> Value {
context_within(doc, ids, MAX_WALK)
}
/// [`context`], looking through at most `max` layers.
pub(crate) fn context_within(doc: &Document, ids: &[NodeId], max: usize) -> Value {
let (near, cut) = around(doc, ids, max);
let rules: Vec<Value> = near
.iter()
.filter_map(|i| doc.node(*i).map(|n| (i, n)))
.flat_map(|(i, n)| n.annotations.iter().filter(|a| is_rule(doc, a)).map(move |a| json!({"id": i, "layer": n.name, "text": a.label})))
.collect();
let versions: Vec<Value> = groups(doc)
.iter()
.filter(|(_, frames)| frames.iter().any(|f| near.binary_search(f).is_ok()))
.map(|(group, frames)| group_json(doc, group, frames))
.collect();
let mut out = json!({"explicit": !rules.is_empty() || !versions.is_empty(), "versions": versions, "rules": rules});
if cut {
// Rules on the layers left out weren't read: say so rather than imply there are none.
out["truncated"] = json!(true);
}
out
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "responsive.set";
let ids = req_targets(cmd, s, p)?;
// `get` reads an explicit null as left out; here it means clear.
let viewport = match p.get("viewport") {
None => return Err(bad(cmd, "`viewport` required: mobile|tablet|desktop, or null to clear")),
Some(Value::Null) => None,
Some(Value::String(v)) if VIEWPORTS.contains(&v.as_str()) => Some(v.clone()),
Some(_) => return Err(bad(cmd, "viewport: mobile|tablet|desktop, or null to clear")),
};
// `group`: left out keeps it, null goes back to each frame's name.
let group = match p.get("group") {
None => None,
Some(Value::Null) => Some(None),
Some(Value::String(g)) if !g.trim().is_empty() && g.trim().chars().count() <= MAX_GROUP => Some(Some(g.trim().to_string())),
Some(_) => return Err(bad(cmd, format!("group: a name up to {MAX_GROUP} characters, or null for the frame's name"))),
};
let doc = s.doc_mut()?;
for id in &ids {
let n = doc.get(*id)?;
if !can_mark(&n.kind) {
return Err(bad(cmd, format!("{id} isn't a frame or section")));
}
}
for id in &ids {
let n = doc.get_mut(*id)?;
match &viewport {
Some(v) => {
n.plugin_data.insert(VIEWPORT_KEY.into(), v.clone());
match &group {
Some(Some(g)) => {
n.plugin_data.insert(GROUP_KEY.into(), g.clone());
}
Some(None) => {
n.plugin_data.remove(GROUP_KEY);
}
None => {}
}
}
None => {
n.plugin_data.remove(VIEWPORT_KEY);
n.plugin_data.remove(GROUP_KEY);
}
}
}
Ok(json!({"ids": ids, "viewport": viewport}))
}
fn rule(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "responsive.rule";
let id = req_targets(cmd, s, p)?.first().copied().ok_or_else(|| bad(cmd, "select a layer"))?;
// Capped like `annotation.add`'s note.
let text = parse_label(cmd, p)?.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).ok_or_else(|| bad(cmd, "`text` required"))?;
let doc = s.doc_mut()?;
let n = doc.get(id)?;
// As `annotation.add`: before anything is made.
if n.is_page() {
return Err(bad(cmd, "pages can't be annotated"));
}
if n.annotations.len() >= MAX_PER_LAYER {
return Err(bad(cmd, format!("a layer has at most {MAX_PER_LAYER} annotations")));
}
let mut list = categories(doc).to_vec();
let category = match find_category(&list, RULES_CATEGORY) {
Some(c) => c.id.clone(),
None if list.len() >= MAX_CATEGORIES => {
return Err(bad(cmd, format!("a file has at most {MAX_CATEGORIES} annotation categories, and none is {RULES_CATEGORY}")));
}
None => {
let (cid, color) = (free_category_id(&list), unused_color(&list));
list.push(AnnotationCategory { id: cid.clone(), name: RULES_CATEGORY.into(), color });
doc.annotation_categories = Some(list);
cid
}
};
let n = doc.get_mut(id)?;
n.annotations.push(Annotation { label: text, properties: Vec::new(), category: Some(category) });
Ok(json!({"id": id, "index": n.annotations.len() - 1}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!(
"responsive.set",
"Mark as screen size version",
"{ids? (frames or sections; default the selection), viewport: mobile|tablet|desktop (null: clear), group? (the design they are versions of; null or left out on a new mark: each frame's name)} says which version of a design a frame is, in its layer data",
true,
set
),
spec!(
"responsive.rule",
"Add responsive rule",
"{id? (default the first selected layer), text (e.g. \"Sidebar becomes a drawer below 768 px\")} a note in the Responsive annotation category, made if the file lacks it",
true,
rule
),
spec!(
"responsive.list",
"List screen size versions",
"{ids? | id? (what is stated about those layers; default every marked frame)} only what the designer stated, nothing inferred → {versions: [{group, frames: [{id, name, viewport, width, height, page}]}], rules?: [{id, layer, text}], explicit?, truncated? (true: too many layers to read every rule)}",
false,
|s, p| {
let doc = s.doc()?;
if get(p, "ids").is_some() || get(p, "id").is_some() {
let ids = req_targets("responsive.list", s, p)?;
return Ok(context(doc, &ids));
}
Ok(json!({"versions": groups(doc).iter().map(|(g, f)| group_json(doc, g, f)).collect::<Vec<_>>()}))
}
),
]
}
+10
View File
@@ -9,17 +9,27 @@ fn web_links_are_opened() {
"http://example.com",
"https://example.com",
"https://example.com/a/b?c=d#e",
"https://example.com?c=d",
"https://example.com#e",
"HTTPS://EXAMPLE.COM",
"HtTp://example.com",
"mailto:a@b.c",
"mailto:a@b.c?subject=hi",
" https://example.com ",
"https://user:pw@example.com:8443/p",
"https://user:pw@[::1]:8443/p",
] {
assert!(openable(url), "{url:?} should open");
}
}
#[test]
fn web_links_without_a_host_are_refused() {
for url in ["https://?c=d", "http://#e", "https://user@", "https://user@:443/p", "https://:443/p", "https://user:pw@?c=d", "https://@#e"] {
assert!(!openable(url), "{url:?} must be refused");
}
}
#[test]
fn script_and_handler_schemes_are_refused() {
for url in [
+3
View File
@@ -72,6 +72,7 @@ pub use dev::dev_measurements;
pub use dev::dev_resources;
pub use dev::devcompare;
pub use dev::devinspect;
pub use dev::responsive;
pub use dev::tailwind;
pub use extensions::plugin_directory;
pub use extensions::plugins;
@@ -560,6 +561,8 @@ mod proto_tail_tests;
#[cfg(test)]
mod reopen_tests;
#[cfg(test)]
mod responsive_tests;
#[cfg(test)]
mod rest_slot_tests;
#[cfg(test)]
mod retained_walk_tests;
+252
View File
@@ -0,0 +1,252 @@
//! Responsive context holds only what the designer stated.
use serde_json::{Value, json};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s
}
fn frame(s: &mut Session, name: &str, width: u32) -> u64 {
s.execute("node.create", &json!({"type": "frame", "name": name, "width": width, "height": 800})).unwrap()["id"].as_u64().unwrap()
}
/// What is stated about layer `id`.
fn context(s: &mut Session, id: u64) -> Value {
s.execute("responsive.list", &json!({"ids": [id]})).unwrap()
}
#[test]
fn nothing_is_inferred_from_names_or_sizes() {
let mut s = session();
let phone = frame(&mut s, "Home / Mobile", 390);
frame(&mut s, "Home / Desktop", 1440);
let v = context(&mut s, phone);
assert_eq!(v, json!({"explicit": false, "versions": [], "rules": []}));
}
#[test]
fn marked_frames_are_told_apart_and_come_with_their_alternates() {
let mut s = session();
let phone = frame(&mut s, "Home phone", 390);
let tablet = frame(&mut s, "Home tablet", 768);
let desk = frame(&mut s, "Home large", 1440);
let other = frame(&mut s, "About", 1440);
for (id, viewport) in [(desk, "desktop"), (phone, "mobile"), (tablet, "tablet")] {
s.execute("responsive.set", &json!({"id": id, "viewport": viewport, "group": "Home"})).unwrap();
}
s.execute("responsive.set", &json!({"id": other, "viewport": "desktop"})).unwrap();
let v = context(&mut s, desk);
assert_eq!(v["explicit"], true);
let versions = v["versions"].as_array().unwrap();
assert_eq!(versions.len(), 1, "other designs stay out: {versions:?}");
let frames: Vec<&str> = versions[0]["frames"].as_array().unwrap().iter().map(|f| f["viewport"].as_str().unwrap()).collect();
assert_eq!(frames, ["mobile", "tablet", "desktop"], "narrowest first");
let all = s.execute("responsive.list", &json!({})).unwrap();
assert_eq!(all["versions"].as_array().unwrap().len(), 2);
}
#[test]
fn a_rule_is_the_designers_words_in_their_category() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let side = s.execute("node.create", &json!({"type": "frame", "parent": f, "name": "Sidebar", "width": 240, "height": 800})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("responsive.rule", &json!({"id": side, "text": "Sidebar becomes a drawer below 768 px"})).unwrap();
s.execute("annotation.add", &json!({"id": side, "label": "Ordinary note"})).unwrap();
let v = context(&mut s, f);
let rules = v["rules"].as_array().unwrap();
assert_eq!(rules.len(), 1);
assert_eq!((rules[0]["layer"].as_str(), rules[0]["text"].as_str()), (Some("Sidebar"), Some("Sidebar becomes a drawer below 768 px")));
let kept = s.execute("annotation.categories", &json!({})).unwrap();
assert_eq!(kept["categories"].as_array().unwrap().iter().filter(|c| c["name"] == "Responsive").count(), 1);
s.execute("responsive.rule", &json!({"id": f, "text": "Second"})).unwrap();
let kept = s.execute("annotation.categories", &json!({})).unwrap();
assert_eq!(kept["categories"].as_array().unwrap().iter().filter(|c| c["name"] == "Responsive").count(), 1, "not made twice");
}
#[test]
fn a_rule_on_the_frame_reaches_a_layer_read_on_its_own() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let child = s.execute("node.create", &json!({"type": "rectangle", "parent": f, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("responsive.rule", &json!({"id": f, "text": "Cards stack on mobile"})).unwrap();
assert_eq!(context(&mut s, child)["rules"][0]["text"], "Cards stack on mobile");
}
#[test]
fn marking_is_undoable_saved_and_clearable() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
s.execute("responsive.set", &json!({"id": f, "viewport": "desktop", "group": "Home"})).unwrap();
let path = std::env::temp_dir().join(format!("figcraft-responsive-{}.figcraft", std::process::id()));
s.execute("file.save", &json!({"path": path})).unwrap();
let mut back = Session::new();
back.execute("file.open", &json!({"path": path})).unwrap();
assert_eq!(crate::responsive::groups(back.doc().unwrap()).len(), 1, "it survives saving");
let _ = std::fs::remove_file(&path);
s.execute("edit.undo", &json!({})).unwrap();
assert!(crate::responsive::groups(s.doc().unwrap()).is_empty());
s.execute("responsive.set", &json!({"id": f, "viewport": "mobile"})).unwrap();
s.execute("responsive.set", &json!({"id": f, "viewport": null})).unwrap();
assert!(crate::responsive::groups(s.doc().unwrap()).is_empty());
}
#[test]
fn bad_input_is_refused() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let r = s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
for p in [
json!({"id": f}),
json!({"id": f, "viewport": "watch"}),
json!({"id": r, "viewport": "mobile"}),
json!({"id": f, "viewport": "mobile", "group": " "}),
] {
assert!(s.execute("responsive.set", &p).is_err(), "{p}");
}
assert!(s.execute("responsive.rule", &json!({"id": f, "text": " "})).is_err());
assert!(s.execute("responsive.rule", &json!({"id": f})).is_err());
}
#[test]
fn malformed_targets_are_refused_rather_than_read_as_the_selection() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
s.execute("select.set", &json!({"ids": [f]})).unwrap();
let calls = [
("responsive.set", json!({"ids": [f, "nope"], "viewport": "mobile"})),
("responsive.set", json!({"ids": [999_999], "viewport": "mobile"})),
("responsive.rule", json!({"id": "not-an-id", "text": "A rule"})),
("responsive.list", json!({"id": "not-an-id"})),
("responsive.list", json!({"ids": [f, "nope"]})),
("responsive.list", json!({"ids": [999_999]})),
];
for (command, p) in calls {
assert!(s.execute(command, &p).is_err(), "{command} {p}");
}
assert!(s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations.is_empty(), "the selection wasn't used instead");
}
#[test]
fn a_rule_keeps_to_the_limits_annotations_have() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let long = "x".repeat(crate::annotations::MAX_LABEL + 50);
let at = s.execute("responsive.rule", &json!({"id": f, "text": long})).unwrap()["index"].as_u64().unwrap() as usize;
let label = s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations[at].label.chars().count();
assert_eq!(label, crate::annotations::MAX_LABEL, "capped like annotation.add");
while s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().annotations.len() < crate::annotations::MAX_PER_LAYER {
s.execute("annotation.add", &json!({"id": f, "label": "note"})).unwrap();
}
assert!(s.execute("responsive.rule", &json!({"id": f, "text": "One too many"})).is_err(), "a layer's annotation limit holds");
}
#[test]
fn no_responsive_category_is_made_past_the_category_limit() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let mut k = 0;
while s.execute("annotation.categories", &json!({})).unwrap()["categories"].as_array().unwrap().len() < crate::annotations::MAX_CATEGORIES {
s.execute("annotation.addCategory", &json!({"name": format!("Category {k}")})).unwrap();
k += 1;
}
assert!(s.execute("responsive.rule", &json!({"id": f, "text": "A rule"})).is_err());
}
#[test]
fn a_walk_stopped_at_its_cap_says_so() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
for _ in 0..10 {
s.execute("node.create", &json!({"type": "rectangle", "parent": f, "width": 4, "height": 4})).unwrap();
}
let doc = s.doc().unwrap();
let id = figcraft_doc::NodeId(f);
assert!(crate::responsive::context_within(doc, &[id], 100).get("truncated").is_none());
assert_eq!(crate::responsive::context_within(doc, &[id], 5)["truncated"], true);
}
#[test]
fn overlapping_targets_count_each_layer_once() {
let mut s = session();
let a = frame(&mut s, "A", 1440);
let c = s.execute("node.create", &json!({"type": "frame", "parent": a, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("node.create", &json!({"type": "rectangle", "parent": c, "width": 4, "height": 4})).unwrap();
let b = frame(&mut s, "B", 390);
s.execute("responsive.rule", &json!({"id": b, "text": "B stacks"})).unwrap();
let doc = s.doc().unwrap();
let ids = [figcraft_doc::NodeId(a), figcraft_doc::NodeId(c), figcraft_doc::NodeId(b)];
let distinct = {
let mut all: Vec<_> = ids.iter().flat_map(|i| doc.ancestors(*i).into_iter().chain(doc.subtree(*i))).collect();
all.sort_unstable();
all.dedup();
all.len()
};
let v = crate::responsive::context_within(doc, &ids, distinct);
assert!(v.get("truncated").is_none(), "{v}");
assert_eq!(v["rules"][0]["text"], "B stacks", "{v}");
assert_eq!(crate::responsive::context_within(doc, &ids, distinct - 1)["truncated"], true);
}
#[test]
fn a_page_takes_no_rule() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let page = s.doc().unwrap().node(figcraft_doc::NodeId(f)).unwrap().parent.unwrap();
let before = s.execute("annotation.categories", &json!({})).unwrap();
assert!(s.execute("responsive.rule", &json!({"id": page.0, "text": "A rule"})).is_err());
assert!(s.doc().unwrap().node(page).unwrap().annotations.is_empty());
assert_eq!(s.execute("annotation.categories", &json!({})).unwrap(), before, "no category made");
}
#[test]
fn frames_and_sections_are_marked_and_components_are_not() {
let mut s = session();
let f = frame(&mut s, "Card", 300);
let c = s.execute("component.create", &json!({"ids": [f]})).unwrap()["id"].as_u64().unwrap();
let i = s.execute("instance.create", &json!({"component": c})).unwrap()["id"].as_u64().unwrap();
for id in [c, i] {
assert!(s.execute("responsive.set", &json!({"ids": [id], "viewport": "mobile"})).is_err(), "{id}");
}
let section =
s.execute("node.create", &json!({"type": "section", "x": 2000, "y": 0, "width": 400, "height": 400})).unwrap()["id"].as_u64().unwrap();
let home = frame(&mut s, "Home", 1440);
s.execute("responsive.set", &json!({"ids": [section, home], "viewport": "desktop"})).unwrap();
}
#[test]
fn stored_values_that_arent_marks_are_left_out() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
let odd = frame(&mut s, "Odd", 800);
s.execute("node.set", &json!({"ids": [odd], "props": {"pluginData": {"figcraft.viewport": "watch"}}})).unwrap();
let long = "g".repeat(500);
s.execute("node.set", &json!({"ids": [f], "props": {"pluginData": {"figcraft.viewport": "desktop", "figcraft.viewportGroup": long}}})).unwrap();
let v = s.execute("responsive.list", &json!({})).unwrap();
let versions = v["versions"].as_array().unwrap();
assert_eq!(versions.len(), 1, "{v}");
assert_eq!(versions[0]["group"], "Home", "an over-long group reads as none: {v}");
assert_eq!(versions[0]["frames"][0]["id"], f);
}
#[test]
fn a_group_can_go_back_to_the_frames_name() {
let mut s = session();
let f = frame(&mut s, "Home", 1440);
s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop", "group": "Landing"})).unwrap();
assert_eq!(s.execute("responsive.list", &json!({})).unwrap()["versions"][0]["group"], "Landing");
s.execute("responsive.set", &json!({"ids": [f], "viewport": "desktop", "group": null})).unwrap();
assert_eq!(s.execute("responsive.list", &json!({})).unwrap()["versions"][0]["group"], "Home");
}
#[test]
fn developer_mode_makes_its_own_responsive_edits() {
for id in ["responsive.set", "responsive.rule", "responsive.list"] {
assert!(crate::devinspect::dev_mode_allows(id), "{id}");
}
}
@@ -180,6 +180,151 @@ fn clicking_selects_by_the_documented_rules() {
}
}
/// A screen with a device chrome overlay: the top-level frame `screen` (0,0 390×844) holds a text
/// at (40,200), the rectangle `content` (40,300) and, above them, `inst`, an unfilled instance of
/// a component the size of the screen with a status bar (`status`) at the top and a home
/// indicator at the bottom, nothing in between.
struct Chrome {
screen: NodeId,
text: NodeId,
content: NodeId,
inst: NodeId,
status: NodeId,
}
fn device_chrome(s: &mut Session) -> Chrome {
let screen = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 390, "height": 844})));
let text = id(&ex(s, "text.create", json!({"text": "Hello", "x": 40, "y": 200, "parent": screen})));
let content = rect(s, 40.0, 300.0, Some(screen));
let chrome = id(&ex(s, "frame.create", json!({"x": 600, "y": 0, "width": 390, "height": 844})));
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 390, "height": 47, "parent": chrome}));
ex(s, "shape.rectangle", json!({"x": 128, "y": 830, "width": 134, "height": 5, "parent": chrome}));
ex(s, "node.set", json!({"ids": [chrome], "props": {"fills": []}}));
let comp = id(&ex(s, "component.create", json!({"ids": [chrome]})));
let inst = id(&ex(s, "instance.create", json!({"component": comp, "x": 0, "y": 0, "parent": screen})));
let status = s.doc().unwrap().node(inst).unwrap().children[0];
ex(s, "select.none", json!({}));
Chrome { screen, text, content, inst, status }
}
/// Observed in the reference app with synthetic files: with Cmd/Ctrl held, a frame, component
/// or instance nested in another layer is hit only where it has a visible fill (its stroke and
/// its empty box let the pick through to the layers under it), while a plain click still picks
/// it by its box. A device chrome overlay shows it: a status bar and a home indicator in an
/// unfilled instance the size of the screen, over the screen's content.
#[test]
fn cmd_click_reaches_through_an_unfilled_nested_frame() {
let mut s = Session::new();
let Chrome { screen, content, inst, status, .. } = device_chrome(&mut s);
let unfilled = json!([]);
let filled = json!([{"type": "solid", "color": "#FFFFFF"}]);
let hidden = json!([{"type": "solid", "color": "#FFFFFF", "visible": false}]);
let clear = json!([{"type": "solid", "color": "#FFFFFF", "opacity": 0}]);
// (the instance's fills, point, modifiers, selection after, derivation)
let rows: Vec<(&Value, (f64, f64), Mods, NodeId, &str)> = vec![
(&unfilled, (60.0, 320.0), CMD, content, "Cmd/Ctrl-click reaches the layer under the unfilled instance"),
(&unfilled, (200.0, 600.0), CMD, screen, "with nothing under it there, the top-level frame is picked"),
(&unfilled, (200.0, 20.0), CMD, status, "a layer inside the instance is still the deepest layer"),
(&unfilled, (60.0, 320.0), NONE, inst, "a plain click still picks the instance by its box"),
(&filled, (200.0, 600.0), CMD, inst, "a visible fill makes the instance the deepest layer there"),
(&filled, (60.0, 320.0), CMD, inst, "and hides the layer under it"),
(&hidden, (60.0, 320.0), CMD, content, "a hidden fill paints nothing"),
(&clear, (60.0, 320.0), CMD, content, "a fill at 0% paints nothing"),
];
for (fills, p, m, after, why) in rows {
ex(&mut s, "node.set", json!({"ids": [inst], "props": {"fills": fills}}));
ex(&mut s, "select.none", json!({}));
click(&mut s, p.0, p.1, m);
assert_eq!(s.selection(), vec![after], "{why}");
}
ex(&mut s, "node.set", json!({"ids": [inst], "props": {"fills": []}}));
ex(&mut s, "stroke.add", json!({"ids": [inst]}));
ex(&mut s, "select.none", json!({}));
click(&mut s, 0.5, 600.0, CMD);
assert_eq!(s.selection(), vec![screen], "a frame's stroke doesn't count: the pick goes through it too");
s.pointer(&ev(PointerKind::Hover, 60.0, 320.0, CMD)).unwrap();
assert_eq!(s.ds().unwrap().hover, Some(content), "hover with Cmd/Ctrl held shows what a Cmd/Ctrl-click picks");
s.pointer(&ev(PointerKind::Hover, 60.0, 320.0, NONE)).unwrap();
assert_eq!(s.ds().unwrap().hover, Some(inst), "and without it, what a click picks");
// The instance being selected doesn't stop the pick: the press isn't on it there.
for (p, after, why) in [
((60.0, 320.0), content, "with the instance selected, Cmd/Ctrl-click still reaches the layer under it"),
((200.0, 600.0), screen, "and on an empty spot there, the top-level frame"),
] {
ex(&mut s, "select.set", json!({"ids": [inst]}));
click(&mut s, p.0, p.1, CMD);
assert_eq!(s.selection(), vec![after], "{why}");
}
// A plain nested frame does the same. A frame directly in a section is a board, like a
// top-level frame: it keeps its box.
let card = id(&ex(&mut s, "frame.create", json!({"x": 1000, "y": 0, "width": 300, "height": 300})));
let inside = rect(&mut s, 20.0, 20.0, Some(card));
let veil = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300, "parent": card})));
ex(&mut s, "node.set", json!({"ids": [veil], "props": {"fills": []}}));
let sec = id(&ex(&mut s, "node.create", json!({"type": "section", "x": 2000, "y": 0, "width": 400, "height": 400})));
let board = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 50, "y": 50, "width": 100, "height": 100, "parent": sec})));
ex(&mut s, "node.set", json!({"ids": [board], "props": {"fills": []}}));
for (p, after, why) in [
((1040.0, 40.0), inside, "an unfilled nested frame lets the pick through like an instance"),
((2100.0, 100.0), board, "Cmd/Ctrl-click on the background of a frame in a section picks the frame"),
] {
ex(&mut s, "select.none", json!({}));
click(&mut s, p.0, p.1, CMD);
assert_eq!(s.selection(), vec![after], "{why}");
}
}
/// With no board under it (a frame in a group on the page), a Cmd/Ctrl press in an unfilled
/// frame's empty part reaches nothing, whether the frame is selected or not: it starts a marquee
/// there and doesn't move the frame.
#[test]
fn a_cmd_press_through_a_selected_unfilled_frame_onto_nothing_starts_a_marquee() {
let gesture = |selected: bool| {
let mut s = Session::new();
let veil = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200})));
ex(&mut s, "node.set", json!({"ids": [veil], "props": {"fills": []}}));
let dot = rect(&mut s, 300.0, 0.0, None);
ex(&mut s, "object.group", json!({"ids": [veil, dot]}));
let before: Vec<NodeId> = if selected { vec![veil] } else { vec![] };
ex(&mut s, "select.set", json!({"ids": before}));
drag(&mut s, (100.0, 100.0), (150.0, 150.0), CMD);
let at = s.doc().unwrap().world_bounds(veil).unwrap();
(s.selection(), (at.x0, at.y0))
};
let (unselected, at) = gesture(false);
assert_eq!(at, (0.0, 0.0), "unselected, the press starts a marquee");
let (selected, at) = gesture(true);
assert_eq!(at, (0.0, 0.0), "selected, the frame doesn't move either: the press isn't on it");
assert_eq!(selected, unselected, "and the marquee picks the same layers");
}
/// A click and a double-click with `m` held on the middle of the layer `pick` chooses, in a fresh
/// device chrome scene.
fn double_click_on(m: Mods, pick: fn(&Chrome) -> NodeId) -> (Session, Chrome) {
let mut s = Session::new();
let k = device_chrome(&mut s);
let p = s.doc().unwrap().world_bounds(pick(&k)).unwrap().center();
click(&mut s, p.x, p.y, m);
s.pointer(&ev(PointerKind::DoubleClick, p.x, p.y, m)).unwrap();
(s, k)
}
/// Observed in the reference app with synthetic files: Cmd/Ctrl + double-click reaches a layer
/// under an unfilled overlay like a Cmd/Ctrl-click and edits it at once (a text goes into text
/// editing, a shape into vector edit mode). A plain double-click picks the overlay, which is
/// caught by its box and has nothing inside there to enter.
#[test]
fn cmd_double_click_edits_the_layer_under_an_unfilled_instance() {
let (s, k) = double_click_on(CMD, |k| k.text);
assert_eq!(s.ds().unwrap().text_edit.as_ref().map(|t| t.id), Some(k.text), "Cmd/Ctrl + double-click on a text edits it");
let (s, k) = double_click_on(CMD, |k| k.content);
assert_eq!(s.ds().unwrap().vector_edit.as_ref().map(|v| v.id), Some(k.content), "on a shape, it edits the shape's points");
let (s, k) = double_click_on(NONE, |k| k.text);
assert_eq!(s.selection(), vec![k.inst], "a plain double-click picks the overlay");
assert!(s.ds().unwrap().text_edit.is_none(), "and edits nothing");
}
/// The operand of boolean `u` under x (its children are the two rectangles).
fn sel_operand(s: &Session, u: NodeId, x: f64) -> NodeId {
let doc = s.doc().unwrap();
+32 -25
View File
@@ -5,12 +5,13 @@
//! branch tab's edits and its own version history go into its branch ([`sync`]) and are saved with
//! the main file. Merging adds a version to the main file's history; the branch keeps its own.
//!
//! In a live session a branch stays with the person who made it (others don't see it), and
//! merging it is one edit of the session document, which syncs to everyone like any other. The
//! session server takes new layers only in the sender's own id space, so a branch made in the
//! session makes its ids in yours, far above the ids the main file makes there ([`WINDOW`]).
//! Merging a branch made outside the session is refused when it adds layers, styles, variables or
//! comments (their ids are in another space).
//! In a live session whose server supports shared branches, branches sync across everyone in the
//! session (creation, edits, updates from main, merge and archive) so any editor can open, edit,
//! review and merge a peer's branch. On older servers without shared branches a branch stays with
//! the person who made it. Merging is one edit of the session document, which syncs to everyone
//! like any other. Each editor allocates new branch ids in their own client space, far above the
//! ids the main file makes there ([`WINDOW`]). Merging a branch made outside the session is refused
//! when it adds layers, styles, variables or comments (their ids are in another space).
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -35,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"branch.create",
"Create branch",
"{name?} a copy of the file to work on separately, opened in a new tab; it remembers the file as it is now (its base); in a live session it stays yours → {id, name, index (its tab)}",
"{name?} a copy of the file to work on separately, opened in a new tab; it remembers the file as it is now (its base); in a live session it syncs to peers when the server supports shared branches → {id, name, index (its tab)}",
false,
create
),
@@ -323,18 +324,12 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
let id = crate::cmd::file::unique_id(|id| ds.branches.iter().any(|b| b.id == id));
let uid = ds.uid;
let time = crate::cmd::comment::now_secs();
s.ds_mut()?.branches_mut().push(Branch {
id: id.clone(),
name: name.clone(),
time,
client,
state: BranchState::Active,
base,
head: Arc::new(head),
versions: Vec::new(),
});
let branch =
Branch { id: id.clone(), name: name.clone(), time, client, state: BranchState::Active, base, head: Arc::new(head), versions: Vec::new() };
s.ds_mut()?.branches_mut().push(branch.clone());
if live.is_some() {
s.live_branch_base(uid, &id);
s.live_branch_create(uid, &branch);
}
let index = open_tab(s, uid, &id)?;
if let Some(tab) = s.docs.get_mut(index) {
@@ -350,16 +345,19 @@ fn open_tab(s: &mut Session, main: u64, id: &str) -> Result<usize> {
return Ok(i);
}
let live = s.live_client_id("branch.open", main)?;
let shared = s.live_branch_shared(main, id);
let m = s.docs.iter().find(|d| d.uid == main).ok_or(EngineError::NoDocument)?;
let b = m.branches.iter().find(|b| b.id == id).ok_or_else(|| bad("branch.open", format!("no branch `{id}`")))?;
let mut doc = (*b.head).clone();
// A branch read from a file has no client id yet.
doc.set_client_id(b.client);
// A branch read from a file has no client id yet. On a shared branch in a live session,
// allocate new ids in your own client space so multiple people can edit the same branch.
let owner_client = if shared { live.unwrap_or(b.client) } else { b.client };
doc.set_client_id(owner_client);
// In your live session, a branch that would make ids right where the main file makes them (one
// read from a file that made none yet) moves up.
if live == Some(b.client)
// read from a file that made none yet, or a peer's shared branch you opened) moves up.
if live == Some(owner_client)
&& doc.next_id().0.abs_diff(m.doc.next_id().0) < WINDOW
&& let Some(start) = live_window(s, main, b.client)
&& let Some(start) = live_window(s, main, owner_client)
{
doc.reserve_ids(NodeId(start.0 - 1));
}
@@ -402,6 +400,7 @@ fn archive(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(b) = m.branches_mut().get_mut(bi) {
b.state = BranchState::Archived;
}
s.live_branch_set_state(uid, &id, BranchState::Archived);
close_tabs(s, uid, Some(&id));
Ok(json!({"archived": true}))
}
@@ -439,6 +438,11 @@ fn combine(s: &mut Session, p: &Value, from: Side) -> Result<Value> {
}
let live = s.live_client_id(cmd, main_uid)?;
let picks = resolutions(cmd, p)?;
// Flush any local edits on a shared branch before merging into main so the server already
// holds every node/entry the merge brings in.
if from == Side::Branch {
s.live_branch_edit(main_uid, &id);
}
let (base, head, main) = documents(s, mi, bi).ok_or(EngineError::NoDocument)?;
let plan = merge::plan(&base, &head, &main).map_err(|e| EngineError::Other(e.to_string()))?;
let pick = |k: &Key| picks.get(&k.to_string()).copied();
@@ -448,7 +452,7 @@ fn combine(s: &mut Session, p: &Value, from: Side) -> Result<Value> {
}
let into = if from == Side::Branch { &main } else { &head };
let (mut doc, touched) = plan.merge(into, from, &pick).map_err(|e| EngineError::Other(format!("can't merge: {e}")))?;
if let Some(client) = live.filter(|_| from == Side::Branch)
if let Some(client) = live.filter(|_| from == Side::Branch && !s.live_branch_shared(main_uid, &id))
&& let Some(what) = foreign(&plan, &base, &main, &doc, client, s.live_branch_in_session(main_uid, &id))
{
let why = format!(
@@ -472,7 +476,9 @@ fn combine(s: &mut Session, p: &Value, from: Side) -> Result<Value> {
if let Some(b) = m.branches_mut().get_mut(bi) {
b.state = BranchState::Merged;
}
let before_batch = s.live_last_batch(main_uid);
s.record(main_uid, Some("Merge branch"), main, selection, page);
s.live_branch_merge(main_uid, &id, before_batch);
close_tabs(s, main_uid, Some(&id));
s.active = s.docs.iter().position(|d| d.uid == main_uid).unwrap_or(s.active);
out["merged"] = json!(true);
@@ -485,11 +491,12 @@ fn combine(s: &mut Session, p: &Value, from: Side) -> Result<Value> {
t.history.redo.clear();
}
if let Some(b) = s.docs.get_mut(mi).and_then(|m| m.branches_mut().get_mut(bi)) {
b.base = main;
b.head = doc;
b.base = main.clone();
b.head = doc.clone();
}
if live.is_some() {
s.live_branch_base(main_uid, &id);
s.live_branch_update_from_main(main_uid, &id, &main, &doc);
}
note(s, mi, bi, UPDATED);
out["updated"] = json!(true);
+10
View File
@@ -59,6 +59,7 @@ use crate::params::{get, num, req_string, string};
use crate::tools::ToolId;
use crate::{DocState, EngineError, Result, Session, TextEdit, ViewState, bad, spec};
mod branches;
mod events;
mod host;
mod join;
@@ -140,6 +141,15 @@ pub struct Live {
/// The branches of the session's file made or last updated from main in this session: every
/// layer of their base was in it (see [`crate::branches`]).
branch_bases: BTreeSet<String>,
/// The server supports shared branches (it sent [`ServerMsg::Branches`] after the welcome).
pub shared_branches: bool,
/// Synced replicas of each shared branch on this client.
branch_replicas: BTreeMap<String, branches::SyncedBranch>,
/// Shared-branch merges waiting for their main `ClientMsg::Changes` batch (`batch_id`) to be
/// accepted by the server before marking the branch `Merged` (`batch_id` -> `branch_id`).
pending_merges: BTreeMap<u64, String>,
/// Batch id of the most recent main-document `ClientMsg::Changes` sent in this session.
last_batch: Option<u64>,
/// You were in this session and aren't now: what joining it again takes (`collab.reconnect`).
stranded: Option<Stranded>,
}
+590
View File
@@ -0,0 +1,590 @@
//! Shared branches in a live session: sync branch creation, edits, updates from main, and
//! merge/archive state changes across everyone connected to the same server file.
use std::sync::Arc;
use figcraft_collab::message::{BranchEvent, BranchReq, BranchStatus, ClientMsg, SharedBranch};
use figcraft_collab::{Access, Change, Mode, Replica, diff};
use figcraft_doc::Document;
use figcraft_format::{Branch, BranchState};
use super::types::SessionId;
use super::{Session, busy};
use crate::branches;
/// Synced state of one shared branch on this client.
pub(super) struct SyncedBranch {
/// Confirmed base on the server.
pub(super) base: Replica,
/// Confirmed head on the server (updated only from server events).
pub(super) confirmed: Replica,
/// Optimistic local view (`confirmed` with `pending` applied on top).
pub(super) view: Replica,
/// Local edits awaiting server echo (or reconnect).
pub(super) pending: Vec<Vec<Change>>,
/// The tab document as last diffed or installed.
pub(super) synced: Arc<Document>,
/// Whether the server has confirmed this branch exists.
pub(super) confirmed_on_server: bool,
/// Original create request while awaiting server confirmation.
pub(super) pending_create: Option<BranchReq>,
}
impl SyncedBranch {
fn rebuild_view(&mut self) {
let mut next = self.confirmed.clone();
for batch in &self.pending {
let _ = next.apply(batch, Mode::Lenient);
}
self.view = next;
}
}
fn to_status(s: BranchState) -> BranchStatus {
match s {
BranchState::Active => BranchStatus::Active,
BranchState::Merged => BranchStatus::Merged,
BranchState::Archived => BranchStatus::Archived,
}
}
fn from_status(s: BranchStatus) -> BranchState {
match s {
BranchStatus::Active => BranchState::Active,
BranchStatus::Merged => BranchState::Merged,
BranchStatus::Archived => BranchState::Archived,
}
}
impl Session {
/// Whether branch `id` of document `uid` is synced with the live session's server.
pub(crate) fn live_branch_shared(&self, uid: u64, id: &str) -> bool {
self.live.doc(uid).is_some_and(|l| l.syncing() && l.shared_branches && l.branch_replicas.contains_key(id))
}
/// Share a newly created branch of live document `uid` with the server.
pub(crate) fn live_branch_create(&mut self, uid: u64, branch: &Branch) {
let Some((session_id, base_seq, confirmed)) = self
.live
.doc(uid)
.filter(|l| l.shared_branches && l.client.as_ref().is_some_and(|c| c.access() == Access::Edit))
.and_then(|l| l.client.as_ref().map(|c| (l.id, c.seq(), c.confirmed().clone())))
else {
return;
};
let Ok(base_diff) = diff(&confirmed, &branch.base) else { return };
let base_rep = base_diff.replica;
let Ok(head_diff) = diff(&base_rep, &branch.head) else { return };
let head_rep = head_diff.replica;
let synced = branch.head.clone();
let req = BranchReq::Create {
id: branch.id.clone(),
name: branch.name.clone(),
time: branch.time,
base_seq,
base_diff: base_diff.changes,
head_diff: head_diff.changes,
};
if let Some(live) = self.live.sessions.get_mut(&session_id) {
live.branch_replicas.insert(
branch.id.clone(),
SyncedBranch {
base: base_rep,
confirmed: head_rep.clone(),
view: head_rep,
pending: Vec::new(),
synced,
confirmed_on_server: false,
pending_create: Some(req.clone()),
},
);
}
self.live.send(session_id, [ClientMsg::Branch(Box::new(req))]);
}
/// Push local edits of shared branch `branch_id` (of main document `main_uid`) to the server,
/// or queue them in `pending` while disconnected.
pub(crate) fn live_branch_edit(&mut self, main_uid: u64, branch_id: &str) {
let Some(tab_idx) = branches::tab_of(self, main_uid, branch_id) else { return };
let Some(tab) = self.docs.get(tab_idx) else { return };
if busy(tab) {
return;
}
let doc = tab.document_itself().clone();
let Some(live) = self.live.doc_mut(main_uid) else { return };
if !live.client.as_ref().is_some_and(|c| c.access() == Access::Edit) {
return;
}
let session_id = live.id;
let send_now = live.shared_branches;
let Some(sb) = live.branch_replicas.get_mut(branch_id) else { return };
if Arc::ptr_eq(&sb.synced, &doc) {
return;
}
let Ok(d) = diff(&sb.view, &doc) else { return };
sb.view = d.replica;
sb.synced = doc.clone();
if !d.changes.is_empty() {
sb.pending.push(d.changes.clone());
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == branch_id)
{
b.head = doc;
}
if send_now {
self.live.send(session_id, [ClientMsg::Branch(Box::new(BranchReq::Edit { id: branch_id.to_string(), changes: d.changes }))]);
}
}
}
/// Sync edits on all open shared branch tabs belonging to live document `main_uid`.
pub(super) fn live_branches_sync(&mut self, main_uid: u64) {
let can_sync =
self.live.doc(main_uid).is_some_and(|l| !l.branch_replicas.is_empty() && l.client.as_ref().is_some_and(|c| c.access() == Access::Edit));
if !can_sync {
return;
}
let ids: Vec<String> = branches::tabs(self, main_uid).filter_map(|t| t.branch_of.as_ref().map(|(_, id)| id.clone())).collect();
for id in ids {
self.live_branch_edit(main_uid, &id);
}
}
/// Tell the server that shared branch `branch_id` was updated from main.
pub(crate) fn live_branch_update_from_main(&mut self, main_uid: u64, branch_id: &str, new_base: &Arc<Document>, new_head: &Arc<Document>) {
let Some(live) = self.live.doc_mut(main_uid) else { return };
if !live.shared_branches || !live.client.as_ref().is_some_and(|c| c.access() == Access::Edit) {
return;
}
let session_id = live.id;
let Some(sb) = live.branch_replicas.get_mut(branch_id) else { return };
let Ok(bd) = diff(&sb.base, new_base) else { return };
let Ok(hd) = diff(&sb.view, new_head) else { return };
sb.base = bd.replica;
sb.view = hd.replica;
sb.synced = new_head.clone();
sb.pending.push(hd.changes.clone());
let req = BranchReq::UpdateFromMain { id: branch_id.to_string(), base_changes: bd.changes, head_changes: hd.changes };
self.live.send(session_id, [ClientMsg::Branch(Box::new(req))]);
}
/// Most recent main-document `ClientMsg::Changes` batch id sent for live document `main_uid`.
pub(crate) fn live_last_batch(&self, main_uid: u64) -> Option<u64> {
self.live.doc(main_uid).and_then(|l| l.last_batch)
}
/// Flush the main-document merge batch for shared branch `branch_id` and defer
/// `SetState(Merged)` until the server confirms that batch (`before_batch`: the last batch id
/// sent before the merge was recorded).
pub(crate) fn live_branch_merge(&mut self, main_uid: u64, branch_id: &str, before_batch: Option<u64>) {
if !self.live_branch_shared(main_uid, branch_id) {
return;
}
let _ = self.live_edit_batch(main_uid, Some("Merge branch"));
let sent = self.live_last_batch(main_uid).filter(|b| Some(*b) != before_batch);
if let Some(batch_id) = sent {
if let Some(live) = self.live.doc_mut(main_uid) {
live.pending_merges.insert(batch_id, branch_id.to_string());
}
} else {
self.live_branch_set_state(main_uid, branch_id, BranchState::Merged);
}
}
/// Complete or roll back a deferred shared-branch merge once the server accepts or rejects its
/// main-document batch.
pub(super) fn live_branch_merge_finished(&mut self, main_uid: u64, branch_id: &str, accepted: bool) {
if accepted {
self.live_branch_set_state(main_uid, branch_id, BranchState::Merged);
} else if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == branch_id && b.state == BranchState::Merged)
{
b.state = BranchState::Active;
}
}
/// Tell the server that shared branch `branch_id` was merged or archived.
pub(crate) fn live_branch_set_state(&mut self, main_uid: u64, branch_id: &str, state: BranchState) {
let Some(session_id) = self
.live
.doc(main_uid)
.filter(|l| {
l.shared_branches && l.branch_replicas.contains_key(branch_id) && l.client.as_ref().is_some_and(|c| c.access() == Access::Edit)
})
.map(|l| l.id)
else {
return;
};
let req = BranchReq::SetState { id: branch_id.to_string(), status: to_status(state) };
self.live.send(session_id, [ClientMsg::Branch(Box::new(req))]);
}
/// Initial list of shared branches sent by the server right after `Welcome` (or after a
/// reconnect). Preserves and resends any pending or offline edits made on shared branches.
pub(super) fn live_branches_welcome(&mut self, session_id: SessionId, list: Vec<SharedBranch>) {
let Some((main_uid, can_edit, confirmed)) = self.live.sessions.get(&session_id).and_then(|l| {
let uid = l.doc_uid?;
let c = l.client.as_ref()?;
Some((uid, c.access() == Access::Edit, c.confirmed().clone()))
}) else {
return;
};
// Capture any edits made on open branch tabs while disconnected before reconciling.
self.live_branches_sync(main_uid);
let mut previous = match self.live.sessions.get_mut(&session_id) {
Some(l) => {
l.shared_branches = true;
std::mem::take(&mut l.branch_replicas)
}
None => return,
};
let mut resend = Vec::new();
for wb in list {
let old = previous.remove(&wb.id);
if let Some(msg) = self.install_welcome_branch(session_id, main_uid, &confirmed, wb, old, can_edit) {
resend.push(msg);
}
}
// Re-send any branch created right before a disconnect that never reached the server.
if can_edit {
for (id, old) in previous {
if !old.confirmed_on_server
&& let Some(create_req) = old.pending_create.clone()
{
resend.push(ClientMsg::Branch(Box::new(create_req)));
for batch in &old.pending {
if !batch.is_empty() {
resend.push(ClientMsg::Branch(Box::new(BranchReq::Edit { id: id.clone(), changes: batch.clone() })));
}
}
if let Some(live) = self.live.sessions.get_mut(&session_id) {
live.branch_replicas.insert(id, old);
}
}
}
}
if !resend.is_empty() {
self.live.send(session_id, resend);
}
}
fn install_welcome_branch(
&mut self,
session_id: SessionId,
main_uid: u64,
confirmed: &Replica,
wb: SharedBranch,
previous: Option<SyncedBranch>,
can_edit: bool,
) -> Option<ClientMsg> {
let mut base_rep = confirmed.clone();
if base_rep.apply(&wb.base_diff, Mode::Lenient).is_err() {
return None;
}
let mut head_rep = base_rep.clone();
if head_rep.apply(&wb.head_diff, Mode::Lenient).is_err() {
return None;
}
let mut pending = Vec::new();
let mut view_rep = head_rep.clone();
let mut to_send = None;
if can_edit
&& wb.status == BranchStatus::Active
&& let Some(old) = previous
&& !old.pending.is_empty()
{
let mut replayed = head_rep.clone();
for batch in &old.pending {
let _ = replayed.apply(batch, Mode::Lenient);
}
if let Ok(net) = diff(&head_rep, replayed.document())
&& !net.changes.is_empty()
{
view_rep = net.replica;
pending.push(net.changes.clone());
to_send = Some(ClientMsg::Branch(Box::new(BranchReq::Edit { id: wb.id.clone(), changes: net.changes })));
}
}
let base_doc = Arc::new(base_rep.document().clone());
let head_doc = Arc::new(view_rep.document().clone());
let id = wb.id.clone();
let state = from_status(wb.status);
if state == BranchState::Active
&& let Some(live) = self.live.sessions.get_mut(&session_id)
{
live.branch_replicas.insert(
id.clone(),
SyncedBranch {
base: base_rep,
confirmed: head_rep,
view: view_rep,
pending,
synced: head_doc.clone(),
confirmed_on_server: true,
pending_create: None,
},
);
}
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid) {
if let Some(existing) = m.branches.iter_mut().find(|b| b.id == id) {
existing.name = wb.name;
existing.state = state;
existing.base = base_doc;
existing.head = head_doc.clone();
} else {
m.branches.push(Branch {
id: wb.id,
name: wb.name,
time: wb.time,
client: wb.client,
state,
base: base_doc,
head: head_doc.clone(),
versions: Vec::new(),
});
}
}
self.update_open_branch_tab(session_id, main_uid, &id, head_doc);
to_send
}
/// A live shared-branch update from the server.
pub(super) fn live_branch_event(&mut self, session_id: SessionId, ev: BranchEvent) {
let Some((main_uid, me, confirmed)) =
self.live.sessions.get(&session_id).and_then(|l| Some((l.doc_uid?, l.client.as_ref()?.id(), l.client.as_ref()?.confirmed().clone())))
else {
return;
};
match ev {
BranchEvent::Created { author, branch } => {
let name = branch.name.clone();
self.install_shared_branch(session_id, main_uid, &confirmed, branch, author == me);
if author != me {
let who = self.peer_name(session_id, author);
self.message = Some(format!("{who} created branch “{name}”"));
}
}
BranchEvent::Edited { id, author, changes, .. } => {
self.apply_remote_branch_edit(session_id, main_uid, &id, author == me, &changes);
}
BranchEvent::UpdatedFromMain { id, author, base_changes, head_changes, .. } => {
self.apply_remote_branch_update(session_id, main_uid, &id, author == me, &base_changes, &head_changes);
}
BranchEvent::State { id, author, status, .. } => {
let state = from_status(status);
let mut name = None;
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.state = state;
name = Some(b.name.clone());
}
if state != BranchState::Active {
if let Some(live) = self.live.sessions.get_mut(&session_id) {
live.branch_replicas.remove(&id);
}
if author != me {
let was_active = branches::tab_of(self, main_uid, &id) == Some(self.active);
branches::close_tabs(self, main_uid, Some(&id));
if was_active && let Some(mi) = self.docs.iter().position(|d| d.uid == main_uid) {
self.active = mi;
}
}
}
if author != me
&& let Some(name) = name
{
let who = self.peer_name(session_id, author);
let verb = if state == BranchState::Merged { "merged" } else { "archived" };
self.message = Some(format!("{who} {verb} branch “{name}”"));
}
}
BranchEvent::Rejected { id, reason } => {
self.handle_branch_rejected(session_id, main_uid, &id, &reason);
}
}
}
fn peer_name(&self, session_id: SessionId, peer_id: u32) -> String {
self.live.sessions.get(&session_id).and_then(|l| l.peers.get(&peer_id)).map_or_else(|| "Someone".to_string(), |p| p.name.clone())
}
fn handle_branch_rejected(&mut self, session_id: SessionId, main_uid: u64, id: &str, reason: &str) {
let Some(live) = self.live.sessions.get_mut(&session_id) else { return };
let Some(sb) = live.branch_replicas.get_mut(id) else {
self.message = Some(format!("Shared branch change refused: {reason}"));
return;
};
if !sb.confirmed_on_server {
live.branch_replicas.remove(id);
self.message = Some(format!("Shared branch wasn't synced: {reason}"));
return;
}
sb.pending.clear();
sb.view = sb.confirmed.clone();
let rollback = Arc::new(sb.confirmed.document().clone());
sb.synced = rollback.clone();
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.head = rollback.clone();
}
self.update_open_branch_tab(session_id, main_uid, id, rollback);
self.message = Some(format!("Shared branch change refused: {reason}"));
}
fn install_shared_branch(&mut self, session_id: SessionId, main_uid: u64, confirmed: &Replica, wb: SharedBranch, own_echo: bool) {
let mut base_rep = confirmed.clone();
if base_rep.apply(&wb.base_diff, Mode::Lenient).is_err() {
return;
}
let mut head_rep = base_rep.clone();
if head_rep.apply(&wb.head_diff, Mode::Lenient).is_err() {
return;
}
let base_doc = Arc::new(base_rep.document().clone());
let id = wb.id.clone();
if own_echo {
// Confirm server creation and keep both base and confirmed head in step with the server
// (replaying any local edits the author already made on top).
let head_doc = if let Some(live) = self.live.sessions.get_mut(&session_id)
&& let Some(sb) = live.branch_replicas.get_mut(&id)
{
sb.confirmed_on_server = true;
sb.pending_create = None;
sb.base = base_rep;
sb.confirmed = head_rep;
sb.rebuild_view();
let doc = Arc::new(sb.view.document().clone());
sb.synced = doc.clone();
Some(doc)
} else {
None
};
if let Some(head_doc) = head_doc {
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.base = base_doc;
b.head = head_doc.clone();
}
self.update_open_branch_tab(session_id, main_uid, &id, head_doc);
}
return;
}
let head_doc = Arc::new(head_rep.document().clone());
if let Some(live) = self.live.sessions.get_mut(&session_id) {
live.branch_replicas.insert(
id.clone(),
SyncedBranch {
base: base_rep,
confirmed: head_rep.clone(),
view: head_rep,
pending: Vec::new(),
synced: head_doc.clone(),
confirmed_on_server: true,
pending_create: None,
},
);
}
let state = from_status(wb.status);
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid) {
if let Some(existing) = m.branches.iter_mut().find(|b| b.id == id) {
existing.name = wb.name;
existing.state = state;
existing.base = base_doc;
existing.head = head_doc.clone();
} else {
m.branches.push(Branch {
id: wb.id,
name: wb.name,
time: wb.time,
client: wb.client,
state,
base: base_doc,
head: head_doc.clone(),
versions: Vec::new(),
});
}
}
self.update_open_branch_tab(session_id, main_uid, &id, head_doc);
}
fn apply_remote_branch_edit(&mut self, session_id: SessionId, main_uid: u64, id: &str, own_echo: bool, changes: &[Change]) {
let Some(live) = self.live.sessions.get_mut(&session_id) else { return };
let Some(sb) = live.branch_replicas.get_mut(id) else { return };
if !changes.is_empty() && sb.confirmed.apply(changes, Mode::Lenient).is_err() {
return;
}
if own_echo && !sb.pending.is_empty() {
sb.pending.remove(0);
}
sb.rebuild_view();
let head_doc = Arc::new(sb.view.document().clone());
sb.synced = head_doc.clone();
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.head = head_doc.clone();
}
self.update_open_branch_tab(session_id, main_uid, id, head_doc);
}
fn apply_remote_branch_update(
&mut self,
session_id: SessionId,
main_uid: u64,
id: &str,
own_echo: bool,
base_changes: &[Change],
head_changes: &[Change],
) {
let Some(live) = self.live.sessions.get_mut(&session_id) else { return };
let Some(sb) = live.branch_replicas.get_mut(id) else { return };
if sb.base.apply(base_changes, Mode::Lenient).is_err() || sb.confirmed.apply(head_changes, Mode::Lenient).is_err() {
return;
}
if own_echo && !sb.pending.is_empty() {
sb.pending.remove(0);
}
sb.rebuild_view();
let base_doc = Arc::new(sb.base.document().clone());
let head_doc = Arc::new(sb.view.document().clone());
sb.synced = head_doc.clone();
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.base = base_doc;
b.head = head_doc.clone();
}
self.update_open_branch_tab(session_id, main_uid, id, head_doc);
}
fn update_open_branch_tab(&mut self, session_id: SessionId, main_uid: u64, id: &str, head_doc: Arc<Document>) {
if let Some(ti) = branches::tab_of(self, main_uid, id)
&& let Some(tab) = self.docs.get(ti)
&& !busy(tab)
{
let tab_uid = tab.uid;
let client_id = tab.doc.client_id();
let mut doc = (*head_doc).clone();
doc.set_client_id(client_id);
let next_id = tab.doc.next_id();
if next_id.0 > doc.next_id().0 {
doc.reserve_ids(figcraft_doc::NodeId(next_id.0 - 1));
}
let doc = Arc::new(doc);
if let Some(live) = self.live.sessions.get_mut(&session_id)
&& let Some(sb) = live.branch_replicas.get_mut(id)
{
sb.synced = doc.clone();
}
if let Some(m) = self.docs.iter_mut().find(|d| d.uid == main_uid)
&& let Some(b) = m.branches.iter_mut().find(|b| b.id == id)
{
b.head = doc.clone();
}
self.apply_remote(tab_uid, doc);
}
}
}
+1
View File
@@ -22,6 +22,7 @@ fn reset_for_reconnect(live: &mut Live) {
live.presence.clear();
live.sent = None;
live.signals = false;
live.shared_branches = false;
live.chats.clear();
live.chat.clear();
live.spotlight = None;
+88 -20
View File
@@ -39,10 +39,16 @@ impl Session {
/// called `label`, or not undoable (`None`: also what changed it outside a command). Nothing
/// while a gesture or preview shows, or inside a group (it syncs when the group ends).
pub(crate) fn live_edit(&mut self, uid: u64, label: Option<&str>) {
let Some(ds) = self.docs.iter().find(|d| d.uid == uid) else { return };
let Some(live) = self.live.doc(uid) else { return };
let _ = self.live_edit_batch(uid, label);
}
/// Like [`live_edit`](Self::live_edit), returning the sent `ClientMsg::Changes` batch id when
/// one was produced.
pub(crate) fn live_edit_batch(&mut self, uid: u64, label: Option<&str>) -> Option<u64> {
let ds = self.docs.iter().find(|d| d.uid == uid)?;
let live = self.live.doc(uid)?;
if live.hold > 0 || busy(ds) || live.synced.as_ref().is_some_and(|s| Arc::ptr_eq(s, &ds.doc)) {
return;
return None;
}
let (id, doc, synced) = (live.id, ds.doc.clone(), live.synced.clone());
if self.live_read_only(uid).is_some() && !self.live_comment_edit(uid, &doc) {
@@ -50,16 +56,27 @@ impl Session {
if let Some(s) = synced {
self.apply_remote(uid, s);
}
return;
return None;
}
let Some(live) = self.live.sessions.get_mut(&id) else { return };
let Some(client) = live.client.as_mut() else { return };
let live = self.live.sessions.get_mut(&id)?;
let client = live.client.as_mut()?;
match client.edit_with(&doc, label) {
Ok(msg) => {
let batch_id = match &msg {
Some(figcraft_collab::ClientMsg::Changes { batch_id, .. }) => {
live.last_batch = Some(*batch_id);
Some(*batch_id)
}
_ => None,
};
live.synced = Some(doc);
self.live.send(id, msg);
batch_id
}
Err(e) => {
self.live_fail(id, format!("Couldn't sync an edit: {e}"));
None
}
Err(e) => self.live_fail(id, format!("Couldn't sync an edit: {e}")),
}
}
@@ -112,11 +129,44 @@ impl Session {
}
// Your own edits first: the client replays them over what others did.
self.live_edit(uid, None);
let Some(live) = self.live.sessions.get_mut(&id) else { return };
let Some(client) = live.client.as_mut() else { return };
self.live_branches_sync(uid);
let waiting = {
let Some(live) = self.live.sessions.get_mut(&id) else { return };
std::mem::take(&mut live.deferred)
};
let mut waiting = waiting.into_iter();
let mut still_waiting = Vec::new();
let mut out = Vec::new();
let mut waiting = std::mem::take(&mut live.deferred).into_iter();
let mut changed_main = false;
while let Some(m) = waiting.next() {
match m {
ServerMsg::Branches(list) => {
self.live_branches_welcome(id, list);
continue;
}
ServerMsg::Branch(ev) => {
let tab_busy = crate::branches::tab_of(self, uid, ev.id()).and_then(|ti| self.docs.get(ti)).is_some_and(busy);
if tab_busy {
still_waiting.push(ServerMsg::Branch(ev));
} else {
self.live_branch_event(id, *ev);
}
continue;
}
_ => {}
}
let merge_outcome = match &m {
ServerMsg::Changes(acc) => self.live.sessions.get_mut(&id).and_then(|live| {
let me = live.client.as_ref()?.id();
(acc.author == me).then(|| live.pending_merges.remove(&acc.batch_id)).flatten().map(|bid| (bid, true))
}),
ServerMsg::Reject { batch_id, .. } => {
self.live.sessions.get_mut(&id).and_then(|live| live.pending_merges.remove(batch_id)).map(|bid| (bid, false))
}
_ => None,
};
let Some(live) = self.live.sessions.get_mut(&id) else { return };
let Some(client) = live.client.as_mut() else { return };
// The server no longer knows this client (it restarted without its saved state, say):
// it welcomed you as someone new. What you did goes on top like after any rejoin.
if let ServerMsg::Welcome { session, client_id, .. } = &m {
@@ -124,7 +174,8 @@ impl Session {
if (*session, *client_id) != (me.session, me.client_id) {
live.hold();
live.client = None;
let rest: Vec<_> = waiting.collect();
let mut rest: Vec<_> = still_waiting;
rest.extend(waiting);
self.live_welcome(id, m);
if let Some(live) = self.live.sessions.get_mut(&id) {
live.deferred = rest;
@@ -133,7 +184,10 @@ impl Session {
}
}
match client.receive(m, &EngineRecompute) {
Ok(more) => out.extend(more),
Ok(more) => {
out.extend(more);
changed_main = true;
}
Err(e) => {
self.live_fail(id, format!("The live session got out of step ({e})"));
// A fresh join has nothing to get out of step with.
@@ -143,16 +197,29 @@ impl Session {
return;
}
}
if let Some((branch_id, accepted)) = merge_outcome {
self.live_branch_merge_finished(uid, &branch_id, accepted);
}
}
let doc = Arc::new(client.document().clone());
// Edits the server refused were rolled back: say why (the UI's toast).
let notices: Vec<String> = client.take_notices().iter().map(figcraft_collab::Notice::message).collect();
live.synced = Some(doc.clone());
if !notices.is_empty() {
self.message = Some(notices.join("; "));
if !still_waiting.is_empty()
&& let Some(live) = self.live.sessions.get_mut(&id)
{
still_waiting.extend(std::mem::take(&mut live.deferred));
live.deferred = still_waiting;
}
if changed_main {
let Some(live) = self.live.sessions.get_mut(&id) else { return };
let Some(client) = live.client.as_mut() else { return };
let doc = Arc::new(client.document().clone());
// Edits the server refused were rolled back: say why (the UI's toast).
let notices: Vec<String> = client.take_notices().iter().map(figcraft_collab::Notice::message).collect();
live.synced = Some(doc.clone());
if !notices.is_empty() {
self.message = Some(notices.join("; "));
}
self.live.send(id, out);
self.apply_remote(uid, doc);
}
self.live.send(id, out);
self.apply_remote(uid, doc);
}
/// Show the peer followed in session `id`: their viewport (and their page, in the session's
@@ -227,6 +294,7 @@ impl Session {
self.live_deferred(id);
if let Some(uid) = self.live.get(id).and_then(|l| l.doc_uid) {
self.live_edit(uid, None);
self.live_branches_sync(uid);
}
self.live_present(id);
}
@@ -200,3 +200,56 @@ fn stored_variable_ids_keep_collection_edits_on_the_resolved_collection() {
assert!(s.execute("variable.removeMode", &json!({"collection": "Extended", "mode": "Dark"})).is_err());
assert_eq!(s.doc().unwrap(), &before);
}
/// The names of collection `c`'s variables in their stored order.
fn names_in(s: &Session, c: &str) -> Vec<String> {
let vars = &s.doc().unwrap().variables;
let cid = vars.collection(c).unwrap().id.clone();
vars.variables.iter().filter(|v| v.collection == cid).map(|v| v.name.clone()).collect()
}
#[test]
fn moving_variables_reorders_their_collection_only_and_undoes() {
let mut s = Session::new();
tokens(&mut s);
ex(&mut s, "variable.createCollection", json!({"name": "Other"}));
ex(&mut s, "variable.create", json!({"collection": "Other", "name": "gap", "type": "number", "value": 4}));
ex(&mut s, "variable.create", json!({"collection": "Tokens", "name": "space/lg", "type": "number", "value": 24}));
let before = names_in(&s, "Tokens");
ex(&mut s, "variable.move", json!({"variables": ["space/lg", "brand"], "before": "space/sm"}));
let after = names_in(&s, "Tokens");
let at = |list: &[String], n: &str| list.iter().position(|x| x == n).unwrap();
// The moved ones come first, keeping their own order; the rest keep theirs.
assert!(at(&after, "brand") < at(&after, "space/lg") && at(&after, "space/lg") < at(&after, "space/sm"));
assert!(at(&after, "space/sm") < at(&after, "space/md"));
assert_eq!(names_in(&s, "Other"), ["gap"]);
// Without `before` they go last; a variable of another collection is refused.
ex(&mut s, "variable.move", json!({"variables": ["space/sm"]}));
assert_eq!(names_in(&s, "Tokens").last().map(String::as_str), Some("space/sm"));
assert!(s.execute("variable.move", &json!({"variables": ["brand"], "before": "gap"})).is_err());
assert!(s.execute("variable.move", &json!({"variables": ["brand", "gap"]})).is_err());
ex(&mut s, "edit.undo", json!({}));
ex(&mut s, "edit.undo", json!({}));
assert_eq!(names_in(&s, "Tokens"), before);
}
#[test]
fn sorting_orders_numbers_by_value_within_the_group_asked() {
let mut s = Session::new();
ex(&mut s, "variable.createCollection", json!({"name": "Palette"}));
for n in ["indigo/500", "indigo/50", "zinc", "indigo/950", "indigo/100", "amber"] {
ex(&mut s, "variable.create", json!({"collection": "Palette", "name": n, "type": "color", "value": "#336699"}));
}
ex(&mut s, "variable.sort", json!({"collection": "Palette", "group": "indigo"}));
let names = names_in(&s, "Palette");
let shades: Vec<&str> = names.iter().map(String::as_str).filter(|n| n.starts_with("indigo/")).collect();
assert_eq!(shades, ["indigo/50", "indigo/100", "indigo/500", "indigo/950"]);
// Variables outside the group stay where they were.
assert_eq!(names.iter().position(|n| n == "zinc"), Some(2));
ex(&mut s, "variable.sort", json!({"collection": "Palette", "descending": true}));
let names = names_in(&s, "Palette");
assert_eq!(names.first().map(String::as_str), Some("zinc"));
assert_eq!(names.last().map(String::as_str), Some("amber"));
assert!(names.iter().position(|n| n == "indigo/950") < names.iter().position(|n| n == "indigo/50"));
assert!(s.execute("variable.sort", &json!({"collection": "Palette", "group": "teal"})).is_err());
}
+16
View File
@@ -117,6 +117,22 @@ pub(crate) fn replace(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, clip: Opti
fx::overlap_rows(dst, at, src, |dp, sp, r, c0| {
let Some((m, (mx, my))) = clip else { return dp.copy_from_slice(sp) };
let (mw, mh, my) = (i64::from(m.width()), i64::from(m.height()), r + i64::from(my));
// Most rows of a clip lie wholly inside it (or outside): copied (or kept) in one piece.
let cols = (dp.len() / 4) as i64;
let first = c0 + i64::from(mx);
if my >= 0
&& my < mh
&& first >= 0
&& first + cols <= mw
&& let Some(row) = m.data().get((my * mw + first) as usize..(my * mw + first + cols) as usize)
{
if row.iter().all(|k| *k == 255) {
return dp.copy_from_slice(sp);
}
if row.iter().all(|k| *k == 0) {
return;
}
}
for (c, (d, s)) in (c0..).zip(dp.chunks_exact_mut(4).zip(sp.chunks_exact(4))) {
let mx = c + i64::from(mx);
let k = if mx >= 0 && my >= 0 && mx < mw && my < mh { u32::from(m.data().get((my * mw + mx) as usize).copied().unwrap_or(0)) } else { 0 };
+119
View File
@@ -0,0 +1,119 @@
//! A clipping frame that takes in the whole pixmap cuts nothing off there: its children draw
//! without a layer, a mask or a copy back, and look the same.
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, NodeId, NodeKind};
use figcraft_geom::Affine;
use crate::draw::{NO_COVER_SHORTCUTS, clip_covers};
use crate::retained_tests::assert_same;
use crate::{Options, Pixmap, View, render_view_single};
fn white() -> Options {
Options { background: Some(Color::WHITE), ..Default::default() }
}
/// A screen (clipping) > a list (clipping) > a card (rounded, clipping) > a picture (rounded,
/// clipping) > a shape; the document, its page and the shape.
fn card() -> (Document, NodeId, NodeId) {
let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
let mut d = Document::new("clips");
let page = d.first_page().unwrap();
let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap();
fill(&mut d, screen, "F4F6F5");
let list = d.create(screen, NodeKind::Frame, "List", 24.0, 261.0, 342.0, 312.0).unwrap();
let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap();
fill(&mut d, card, "FFFFFF");
d.get_mut(card).unwrap().corners.radii = [20.0; 4];
let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap();
fill(&mut d, picture, "CFE3DA");
d.get_mut(picture).unwrap().corners.radii = [14.0; 4];
let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap();
fill(&mut d, shape, "7FAE9C");
(d, page, shape)
}
/// A `width` × `height` view at `scale` with the shape in the middle.
fn close_up(d: &Document, shape: NodeId, scale: f64, width: u32, height: u32) -> View {
let b = crate::draw::paint_bounds(d, shape).unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
View { origin: (cx - f64::from(width) / scale / 2.0, cy - f64::from(height) / scale / 2.0), scale, width, height }
}
/// The view rendered with and without the shortcut for clips that cut nothing.
fn both(d: &Document, page: NodeId, v: &View) -> (Pixmap, Pixmap) {
let new = render_view_single(d, page, v, &white()).unwrap();
NO_COVER_SHORTCUTS.with(|f| f.set(true));
let old = render_view_single(d, page, v, &white());
NO_COVER_SHORTCUTS.with(|f| f.set(false));
(new, old.unwrap())
}
#[test]
fn views_inside_and_across_clipping_frames_look_the_same() {
let (d, page, shape) = card();
let views = [
// Inside the card and its picture; across the picture's round corner; across the card's
// edge and the list's; the whole screen; on fractional pixels.
close_up(&d, shape, 38.66, 300, 200),
View { origin: (504.0, 440.0), scale: 9.0, width: 300, height: 260 },
View { origin: (480.0, 440.0), scale: 6.0, width: 400, height: 300 },
View { origin: (460.0, -10.0), scale: 0.5, width: 220, height: 440 },
View { origin: (500.37, 381.21), scale: 3.3, width: 300, height: 260 },
];
for v in &views {
let (new, old) = both(&d, page, v);
assert_same(&new, &old, &format!("{:?} at {}", v.origin, v.scale));
}
}
#[test]
fn a_rotated_frame_clips_as_it_did() {
let mut d = Document::new("rotated");
let page = d.first_page().unwrap();
let f = d.create(page, NodeKind::Frame, "F", 100.0, 100.0, 300.0, 200.0).unwrap();
d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::from_hex("FFE0B0").unwrap())];
d.get_mut(f).unwrap().transform = figcraft_geom::set_rotation_about_center(d.node(f).unwrap().transform, 300.0, 200.0, 25.0);
let c = d.create(f, NodeKind::Rectangle, "C", -40.0, 40.0, 420.0, 60.0).unwrap();
d.get_mut(c).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
// The frame's middle (inside it whole), and its corner (cut by two edges).
for v in
[View { origin: (220.0, 170.0), scale: 4.0, width: 200, height: 160 }, View { origin: (60.0, 60.0), scale: 2.0, width: 300, height: 300 }]
{
let (new, old) = both(&d, page, &v);
assert_same(&new, &old, &format!("{:?}", v.origin));
}
}
#[test]
fn a_pixmap_in_a_round_corner_is_not_taken_in() {
let mut d = Document::new("corner");
let page = d.first_page().unwrap();
let f = d.create(page, NodeKind::Frame, "F", 0.0, 0.0, 200.0, 100.0).unwrap();
d.get_mut(f).unwrap().corners.radii = [40.0, 0.0, 0.0, 0.0];
let at = |d: &Document, x: f64, y: f64| clip_covers(d.node(f).unwrap(), Affine::translate((-x, -y)), (10, 10));
assert!(at(&d, 100.0, 40.0), "the middle");
assert!(at(&d, 190.0, 0.0), "a square corner, up to the edges");
assert!(!at(&d, 195.0, 0.0), "across the right edge");
assert!(!at(&d, 2.0, 2.0), "outside the arc of the round corner");
assert!(at(&d, 20.0, 20.0), "inside the arc");
assert!(!at(&d, 5.0, 20.0), "across the arc");
// A smoothed corner turns further along its edges: its whole square counts as cut off.
d.get_mut(f).unwrap().corners.smoothing = 0.6;
assert!(!at(&d, 20.0, 20.0), "smoothed: the corner's square is left out");
assert!(at(&d, 100.0, 40.0), "smoothed: the middle");
}
#[test]
fn a_view_inside_clipping_frames_holds_no_layer_for_them() {
let (d, page, shape) = card();
let v = close_up(&d, shape, 38.66, 600, 300);
let held = || crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&d, page, &v, &Options::default())).1;
// The view lies inside the screen, the list, the card and the picture: none of their clips
// cuts it. Each held a copy of the view while its children drew.
assert_eq!(held(), 0, "no layer for a clip that cuts nothing");
NO_COVER_SHORTCUTS.with(|f| f.set(true));
let before = held();
NO_COVER_SHORTCUTS.with(|f| f.set(false));
assert!(before >= u64::from(v.width) * u64::from(v.height) * 4, "as it was: {before} bytes held");
}
+211 -47
View File
@@ -207,46 +207,59 @@ fn side_strokes(n: &Node) -> Option<Arc<BezPath>> {
}))
}
/// A plain stroke: no dashes, width profile or brush.
fn plain_stroke(n: &Node) -> bool {
let props = &n.stroke;
props.dashes.is_empty() && props.profile().is_none() && props.brush.is_none()
}
/// Whether a closed node's inside/outside stroke is an even-odd ring of two outlines ([`ring`]).
fn ring_stroke(n: &Node, closed: bool) -> bool {
let props = &n.stroke;
plain_stroke(n) && closed && props.align != StrokeAlign::Center
// An outside ring grows square corners as miters; other joins take the generic outline.
&& !(props.align == StrokeAlign::Outside && props.join != StrokeJoin::Miter && n.corners.radii.contains(&0.0))
}
/// A rect's or full ellipse's outline moved `inset` inwards (outwards when negative), `None` for
/// other shapes or one inset to nothing.
fn ring(n: &Node, inset: f64) -> Option<BezPath> {
let (x0, y0, ww, hh) = (inset, inset, n.width - 2.0 * inset, n.height - 2.0 * inset);
if ww <= 0.0 || hh <= 0.0 {
return None;
}
match n.kind {
NodeKind::Rectangle
| NodeKind::Frame
| NodeKind::Component { .. }
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. }
if n.corners.smoothing == 0.0 =>
{
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
p.apply_affine(Affine::translate((x0, y0)));
Some(p)
}
NodeKind::Ellipse { sweep, inner, .. } if figcraft_geom::full_sweep(sweep) && inner == 0.0 => {
Some(figcraft_geom::kurbo::Ellipse::from_rect(Rect::new(x0, y0, x0 + ww, y0 + hh)).to_path(0.05))
}
_ => None,
}
}
/// The stroke area of a node in local coordinates.
pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
let props = &n.stroke;
if let Some(p) = side_strokes(n) {
return p;
}
// Rect/ellipse inside/outside strokes without booleans: an even-odd ring of two outlines.
if props.dashes.is_empty() && props.profile().is_none() && props.brush.is_none() && closed && props.align != StrokeAlign::Center
// An outside ring grows square corners as miters; other joins take the generic outline.
&& !(props.align == StrokeAlign::Outside && props.join != StrokeJoin::Miter && n.corners.radii.contains(&0.0))
{
let w = props.weight;
let ring = |inset: f64| -> Option<BezPath> {
let (x0, y0, ww, hh) = (inset, inset, n.width - 2.0 * inset, n.height - 2.0 * inset);
if ww <= 0.0 || hh <= 0.0 {
return None;
}
match n.kind {
NodeKind::Rectangle
| NodeKind::Frame
| NodeKind::Component { .. }
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. }
if n.corners.smoothing == 0.0 =>
{
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
p.apply_affine(Affine::translate((x0, y0)));
Some(p)
}
NodeKind::Ellipse { sweep, inner, .. } if figcraft_geom::full_sweep(sweep) && inner == 0.0 => {
Some(figcraft_geom::kurbo::Ellipse::from_rect(Rect::new(x0, y0, x0 + ww, y0 + hh)).to_path(0.05))
}
_ => None,
}
};
let (outer, inner) = match props.align {
StrokeAlign::Inside => (ring(0.0), ring(w)),
_ => (ring(-w), ring(0.0)),
if ring_stroke(n, closed) {
let w = n.stroke.weight;
let (outer, inner) = match n.stroke.align {
StrokeAlign::Inside => (ring(n, 0.0), ring(n, w)),
_ => (ring(n, -w), ring(n, 0.0)),
};
if let Some(mut o) = outer {
if let Some(i) = inner {
@@ -258,6 +271,54 @@ pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
cached_stroke_outline(n, path, closed)
}
/// What a closed node with outline `path` (filled by `rule`) fills under an inside or outside
/// stroke that hides what is under it: out to the middle of the stroke, so the fill neither shows
/// at the stroke's outer edge (a light fringe on an inside stroke) nor leaves a gap at its inner
/// edge (what is behind showing between an outside stroke and the fill) (#2635). `None`: fill
/// `path` as it is.
fn fill_to_stroke_middle(n: &Node, path: &BezPath, rule: FillRule) -> Option<(Arc<BezPath>, FillRule)> {
let props = &n.stroke;
let opaque = n
.strokes
.iter()
.rev()
.find(|p| p.visible && p.opacity > 0.0)
.is_some_and(|p| p.blend == BlendMode::Normal && p.opacity >= 1.0 && matches!(p.kind, PaintKind::Solid { color } if color.a >= 1.0));
if !(opaque && plain_stroke(n) && props.sides.is_none() && props.align != StrokeAlign::Center && n.has_visible_stroke()) {
return None;
}
let half = match props.align {
StrokeAlign::Inside => props.weight / 2.0,
_ => -props.weight / 2.0,
};
if ring_stroke(n, true)
&& let Some(r) = ring(n, half)
{
return Some((Arc::new(r), FillRule::Winding));
}
// shortcut: even-odd outlines (booleans, even-odd networks) keep filling as they are, until
// the boolean below reads them by their own rule.
if rule != FillRule::Winding {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
hash_path(path, &mut h);
("fill to stroke middle", props.weight.to_bits(), props.align as u8, props.join as u8, props.miter_limit.to_bits()).hash(&mut h);
let key = h.finish();
let cached = locked(stroke_cache()).get(key);
let out = match cached {
Some(p) => p,
None => {
let centre = figcraft_pathops::stroke_center(path, props.weight, props);
let op = if half > 0.0 { figcraft_doc::BoolOp::Subtract } else { figcraft_doc::BoolOp::Union };
let p = Arc::new(figcraft_pathops::boolean_step(path, &centre, op).ok()?);
locked(stroke_cache()).insert(key, p.clone());
p
}
};
Some((out, FillRule::EvenOdd))
}
/// The stroke a boolean operand contributes: like [`stroke_area`], but never an even-odd ring
/// (boolean folding uses non-zero winding).
fn operand_stroke(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
@@ -550,6 +611,12 @@ pub(crate) const MAX_REACH: f64 = 1e12;
/// result (drop shadows from the blurred layer, a backdrop blurred with it), so the largest of
/// those reaches comes on top. Each reach counts up to [`MAX_REACH`], so the sum stays finite.
pub fn effect_margin(n: &Node) -> f64 {
margin_of(n, true)
}
/// [`effect_margin`], with or without what drop shadows reach (`drops`): shadows cast from the
/// layer's outline ([`shadow::outline_caster`]) read none of its pixels.
fn margin_of(n: &Node, drops: bool) -> f64 {
let visible = || n.effects.iter().filter(|e| e.visible);
let finite = |m: f64| if m.is_finite() { m.clamp(0.0, MAX_REACH) } else { 0.0 };
let layer: f64 = visible()
@@ -563,7 +630,9 @@ pub fn effect_margin(n: &Node) -> f64 {
let others = visible()
.map(|e| match &e.kind {
EffectKind::BackgroundBlur { .. } | EffectKind::Glass(_) => e.backdrop_radius() * 2.0,
EffectKind::DropShadow(s) => s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs(),
EffectKind::DropShadow(s) if drops => {
s.radius * 2.0 + s.spread.abs() * figcraft_doc::SPREAD_MITER_LIMIT + s.offset.0.abs() + s.offset.1.abs()
}
// Inner shadows cast from around a layer's pixels (groups, image fills with alpha; any
// image counts here): a layer cut off at the view would cast one from the cut.
EffectKind::InnerShadow(s)
@@ -711,6 +780,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
// Isolated layer covering the node's paint bounds, clipped to the visible area + margin. Its
// origin can be negative (inside the margin); the size counts from there, or a layer starting
// above or left of the pixmap came out short by the margin (a band missing at its far edge).
// Drop shadows cast from the layer's outline need none of its pixels: the layer then ends
// where the pixmap does (plus what its other effects read), however far the shadows reach.
let cast_outline = if ctx.lod || backdrop::has_effects(n) { None } else { shadow::outline_caster(ctx.doc, n) };
let view = match &cast_outline {
Some(_) => {
let m = (margin_of(n, false) * ctx.scale).min(MAX_EFFECT_MARGIN_PX);
Rect::new(0.0, 0.0, f64::from(pw), f64::from(ph)).inflate(m, m)
}
None => view,
};
let vis = dev.intersect(view);
let (x0, y0) = (vis.x0.floor(), vis.y0.floor());
let (w, h) = (vis.x1.ceil() - x0, vis.y1.ceil() - y0);
@@ -782,7 +861,16 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
layer_effects(ctx, &mut layer, n, id, lxf);
}
// Drop shadows go under the layer, in effect-list order.
{
if let Some(outlines) = &cast_outline {
let cover = shadow::hiding_cover(ctx.doc, n);
for e in n.effects.iter().filter(|e| e.visible) {
if let EffectKind::DropShadow(s) = &e.kind
&& let Some((sh, at)) = shadow::outline_drop_shadow(outlines, cover.as_deref().unwrap_or(outlines), s, xf, ctx.scale, (pw, ph))
{
composite(pix, at, &sh, op, s.blend);
}
}
} else {
// Kept apart, the backdrop isn't in the layer yet: the shadows are cast from the content
// with the layer effects it will get (a copy only when it gets some).
let layer_fx =
@@ -887,6 +975,16 @@ fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft
}
}
/// Fills `n`'s closed outline `path` (by `rule`, drawn at `xf`) with `paints`, out to the middle of
/// a stroke that hides it ([`fill_to_stroke_middle`]).
fn fill_outline(ctx: &Ctx, pix: &mut Pixmap, n: &Node, paints: &[Paint], path: &BezPath, rule: FillRule, xf: Affine) {
let under = fill_to_stroke_middle(n, path, rule);
let (path, rule) = under.as_ref().map_or((path, rule), |(p, r)| (&**p, *r));
if let Some(tp) = ts_path(path) {
fill_with(pix, &tp, paints, n.width, n.height, xf, rule, ctx, None);
}
}
/// Fills, `over_fills`, children (clipped), strokes and text of a node, without opacity/effects.
fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, over_fills: OverFills) {
let doc = ctx.doc;
@@ -933,8 +1031,8 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize,
// strokes on top.
for k in &keys {
let fills = layout.styles.get(*k).and_then(|s| s.fills.as_ref()).unwrap_or(&n.fills);
if let Some(tp) = by_style.get(k).and_then(ts_path) {
fill_with(pix, &tp, fills, w, h, gxf, FillRule::Winding, ctx, None);
if let Some(path) = by_style.get(k) {
fill_outline(ctx, pix, n, fills, path, FillRule::Winding, gxf);
}
for (_, item) in ink.iter().filter(|(style, _)| style == k) {
match item {
@@ -975,10 +1073,8 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize,
if !splatted && closed {
if let Some(network) = styled_network {
fill_vector_regions(ctx, pix, n, network, xf);
} else if let Some((path, rule)) = &outline
&& let Some(tp) = ts_path(path)
{
fill_with(pix, &tp, &n.fills, w, h, xf, *rule, ctx, None);
} else if let Some((path, rule)) = &outline {
fill_outline(ctx, pix, n, &n.fills, path, *rule, xf);
}
}
if let Some(f) = over_fills {
@@ -1118,6 +1214,12 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept
let (pw, ph) = (pix.width(), pix.height());
let dev = device_rect(xf, n.local_rect());
let Some(ir) = int_rect(dev, (pw, ph)) else { return };
// A clip that takes in the whole pixmap cuts nothing off here (a frame larger than the view,
// or than the band or patch of it being drawn): the children draw as they are.
if clip_covers(n, xf, (pw, ph)) {
draw_children(ctx, pix, n, xf, depth);
return;
}
let Some(_held) = crate::layer_budget::Held::take(ir.width(), ir.height(), 1) else { return };
let (lx, ly) = (ir.x(), ir.y());
// The layer starts as what lies under it and goes back in its place through the clip:
@@ -1126,7 +1228,7 @@ fn draw_children_clipped(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, dept
let Some(mut layer) = pix.clone_rect(ir) else { return };
let lxf = Affine::translate((-f64::from(lx), -f64::from(ly))) * xf;
let square_aligned = n.corners.uniform() == Some(0.0) && is_axis_aligned(xf);
let rect_clip = square_aligned && on_whole_pixels(dev);
let rect_clip = square_aligned && on_whole_pixels(dev, (pw, ph));
// The clip (a rectangular one on whole pixels is the layer's own box) is known before the
// children draw, so their backdrops are clipped the way the layer will be. An axis-aligned
// square frame with fractional edges gets an anti-aliased mask of its box so its edge pixels
@@ -1177,8 +1279,70 @@ fn fract_ok(_v: f64) -> bool {
true
}
/// Whether all four edges of the device rectangle `r` lie on whole pixels, up to the float noise
/// `snap_px` forgives.
fn on_whole_pixels(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].into_iter().all(|v| (snap_px(v) - v.round()).abs() < 1e-9)
#[cfg(test)]
thread_local! {
/// Tests: no clip or shadow is skipped for taking in the whole pixmap ([`clip_covers`]).
pub(crate) static NO_COVER_SHORTCUTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether the edges of the device rectangle `r` that cross a `size` pixmap lie on whole pixels,
/// up to the float noise `snap_px` forgives. An edge at or past the pixmap's own cuts no pixel
/// of it in part, wherever it lies.
fn on_whole_pixels(r: Rect, size: (u32, u32)) -> bool {
let whole = |v: f64| (snap_px(v) - v.round()).abs() < 1e-9;
let (w, h) = (f64::from(size.0), f64::from(size.1));
(r.x0 <= 0.0 || whole(r.x0)) && (r.y0 <= 0.0 || whole(r.y0)) && (r.x1 >= w || whole(r.x1)) && (r.y1 >= h || whole(r.y1))
}
/// Whether the box of frame `n` (its rounded corners cut off), drawn at `xf`, takes in every
/// pixel of a `size` pixmap: its clip then cuts nothing there. Errs towards `false`: smoothed
/// corners count as cut off square.
pub(crate) fn clip_covers(n: &Node, xf: Affine, size: (u32, u32)) -> bool {
#[cfg(test)]
if NO_COVER_SHORTCUTS.with(std::cell::Cell::get) {
return false;
}
let (w, h) = (n.width, n.height);
let det = xf.determinant();
if !(det.is_finite() && det.abs() > 1e-12 && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return false;
}
let max_r = w.min(h) / 2.0;
let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 };
// Top-left, top-right, bottom-right, bottom-left: the corner and its radius.
let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r });
let corners = [(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])];
let inside = |p: figcraft_geom::Point| {
if !(p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) {
return false;
}
corners.iter().all(|(cx, cy, r)| {
let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs());
let zone = r * (1.0 + smooth);
// Outside the corner's square, or (a round corner) within its arc.
dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r)
})
};
let inv = xf.inverse();
let (pw, ph) = (f64::from(size.0), f64::from(size.1));
[(0.0, 0.0), (pw, 0.0), (pw, ph), (0.0, ph)].into_iter().all(|p| inside(inv * figcraft_geom::Point::new(p.0, p.1)))
}
/// Whether point `p` (local) lies in the box of `n`, its rounded corners cut off. Errs towards
/// `false`: smoothed corners count as cut off square.
pub(crate) fn in_box(n: &Node, p: figcraft_geom::Point) -> bool {
let (w, h) = (n.width, n.height);
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 && p.x >= 0.0 && p.y >= 0.0 && p.x <= w && p.y <= h) {
return false;
}
let max_r = w.min(h) / 2.0;
let smooth = if n.corners.smoothing > 0.0 || !n.corners.smoothing.is_finite() { 1.0 } else { 0.0 };
// Top-left, top-right, bottom-right, bottom-left: the corner and its radius.
let r = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, max_r) } else { max_r });
[(0.0, 0.0, r[0]), (w, 0.0, r[1]), (w, h, r[2]), (0.0, h, r[3])].iter().all(|(cx, cy, r)| {
let (dx, dy) = ((p.x - cx).abs(), (p.y - cy).abs());
let zone = r * (1.0 + smooth);
// Outside the corner's square, or (a round corner) within its arc.
dx >= zone || dy >= zone || (smooth == 0.0 && (r - dx).powi(2) + (r - dy).powi(2) <= r * r)
})
}
+84
View File
@@ -242,6 +242,90 @@ pub fn tint(p: &mut Pixmap, color: [f32; 4]) {
}
}
/// What [`tint`] makes of each alpha: the premultiplied pixel of `color` at that coverage.
pub fn tints(color: [f32; 4]) -> [[u8; 4]; 256] {
let [r, g, b, a] = color;
let mut out = [[0u8; 4]; 256];
for (i, px) in out.iter_mut().enumerate() {
let alpha = i as f32 / 255.0 * a;
let q = |c: f32| (c * alpha * 255.0).round().clamp(0.0, 255.0) as u8;
*px = [q(r), q(g), q(b), (alpha * 255.0).round().clamp(0.0, 255.0) as u8];
}
out
}
/// `dst` from the alpha of `src`, tinted (see [`tints`]): `dst`'s pixel (0, 0) is `src`'s pixel
/// `at`; past `src`'s edges is empty.
pub fn copy_alpha(src: &Pixmap, dst: &mut Pixmap, at: (i32, i32), tints: &[[u8; 4]; 256]) {
let (sw, sh, dw) = (i64::from(src.width()), i64::from(src.height()), dst.width() as usize);
let s = src.data().as_chunks::<4>().0;
for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw.max(1)).enumerate() {
let sy = y as i64 + i64::from(at.1);
for (x, px) in row.iter_mut().enumerate() {
let sx = x as i64 + i64::from(at.0);
let a = if (0..sw).contains(&sx) && (0..sh).contains(&sy) { s.get((sy * sw + sx) as usize).map_or(0, |p| p[3]) } else { 0 };
*px = tints.get(usize::from(a)).copied().unwrap_or_default();
}
}
}
/// Steps between two samples of [`enlarge_alpha`] (a power of two: weights are whole numbers).
const LERP_STEPS: i64 = 256;
/// Where on a line of `len` samples position `at` lies: the sample before it and how far on to
/// the next it is, in [`LERP_STEPS`]; `None` further than a sample past either end.
fn lerp_at(at: f64, len: usize) -> Option<(i64, u32)> {
// Rounded to a step first: positions a float's noise apart then weigh the same.
let steps = (at * LERP_STEPS as f64).round();
if !(steps.is_finite() && steps >= -(LERP_STEPS as f64) && steps <= (len as f64) * LERP_STEPS as f64) {
return None;
}
let steps = steps as i64;
Some((steps.div_euclid(LERP_STEPS), steps.rem_euclid(LERP_STEPS) as u32))
}
/// `dst` from the alpha of `src` drawn larger, between its samples (bilinear), tinted (see
/// [`tints`]): `dst`'s pixel (0, 0) lies at position `at` among `src`'s pixel centres and each
/// pixel on is `step` of a `src` pixel further. Past `src`'s edges is empty.
pub fn enlarge_alpha(src: &Pixmap, dst: &mut Pixmap, at: (f64, f64), step: f64, tints: &[[u8; 4]; 256]) {
let (sw, sh, dw) = (src.width() as usize, src.height() as usize, dst.width() as usize);
if sw == 0 || sh == 0 || dw == 0 {
return;
}
let s = src.data().as_chunks::<4>().0;
let cols: Vec<Option<(i64, u32)>> = (0..dw).map(|x| lerp_at(at.0 + x as f64 * step, sw)).collect();
// One row of `src` between its samples, for every column of `dst`, in 1/256ths of 255.
let line = |y: i64, out: &mut [u32]| {
let row = usize::try_from(y).ok().filter(|y| *y < sh).and_then(|y| s.get(y * sw..(y + 1) * sw));
let a = |x: i64| row.and_then(|r| usize::try_from(x).ok().and_then(|x| r.get(x))).map_or(0, |p| u32::from(p[3]));
for (o, c) in out.iter_mut().zip(&cols) {
*o = c.map_or(0, |(x, t)| a(x) * (LERP_STEPS as u32 - t) + a(x + 1) * t);
}
};
let (mut top, mut bottom) = (vec![0u32; dw], vec![0u32; dw]);
let mut held: Option<i64> = None;
for (y, row) in dst.data_mut().as_chunks_mut::<4>().0.chunks_mut(dw).enumerate() {
let Some((sy, t)) = lerp_at(at.1 + y as f64 * step, sh) else {
row.fill([0; 4]);
continue;
};
if held != Some(sy) {
if held == Some(sy - 1) {
std::mem::swap(&mut top, &mut bottom);
} else {
line(sy, &mut top);
}
line(sy + 1, &mut bottom);
held = Some(sy);
}
let half = (LERP_STEPS * LERP_STEPS / 2) as u32;
for ((px, a), b) in row.iter_mut().zip(&top).zip(&bottom) {
let v = (a * (LERP_STEPS as u32 - t) + b * t + half) / (LERP_STEPS * LERP_STEPS) as u32;
*px = tints.get(v.min(255) as usize).copied().unwrap_or_default();
}
}
}
/// Invert the alpha (premultiplied white with alpha 1-a): used for inner shadows.
pub fn invert_alpha(p: &mut Pixmap) {
for px in p.data_mut().as_chunks_mut::<4>().0 {
+8
View File
@@ -675,6 +675,8 @@ mod boolean_radius_tests;
#[cfg(test)]
mod bounds_memo_tests;
#[cfg(test)]
mod clip_cover_tests;
#[cfg(test)]
mod dots_tests;
#[cfg(test)]
mod effect_order_tests;
@@ -709,6 +711,8 @@ mod magnified_image_tests;
#[cfg(test)]
mod mask_bounds_tests;
#[cfg(test)]
mod outline_shadow_tests;
#[cfg(test)]
mod paint_behaviour_tests;
#[cfg(test)]
mod pan_bench_tests;
@@ -727,8 +731,12 @@ mod solo_tests;
#[cfg(test)]
mod spread_tests;
#[cfg(test)]
mod stroke_fringe_tests;
#[cfg(test)]
mod stroke_reach_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod width_tests;
#[cfg(test)]
mod zoom_bench_tests;
+212
View File
@@ -0,0 +1,212 @@
//! Drop shadows cast from a layer's outline ([`crate::shadow::outline_caster`]) look as the ones
//! cast from its pixels do, in every piece a view is rendered in, and cost what shows of them.
use figcraft_color::{Color, Paint};
use figcraft_doc::{EffectKind, NodeId, Shadow};
use crate::shadow::FROM_PIXELS;
use crate::zoom_bench_tests::{Card, SCALE, card, close_up};
use crate::{Options, Pixmap, View, render_band, render_view_single};
fn white() -> Options {
Options { background: Some(Color::WHITE), ..Default::default() }
}
/// The view rendered with shadows cast from outlines, and from pixels (as they all were).
fn both(c: &Card, v: &View) -> (Pixmap, Pixmap) {
let new = render_view_single(&c.doc, c.page, v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(true));
let old = render_view_single(&c.doc, c.page, v, &white());
FROM_PIXELS.with(|f| f.set(false));
(new, old.unwrap())
}
/// The largest difference of a channel between two renders of view `v`, under the card: where
/// only its shadow paints. (The card's own edges differ a little with where a layer's pixmap
/// ends, whatever casts the shadow: curves are flattened from where the pixmap cuts them.)
fn furthest(v: &View, a: &Pixmap, b: &Pixmap) -> u8 {
let from = (((CARD_BOTTOM - v.origin.1) * v.scale).ceil() as usize + 2) * v.width as usize * 4;
assert!(from < a.data().len(), "the view shows what is under the card");
a.data().iter().zip(b.data()).skip(from).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0)
}
/// The card's bottom edge on the page.
const CARD_BOTTOM: f64 = 465.0;
fn shadow_of(c: &mut Card, f: impl FnOnce(&mut Shadow)) {
for e in &mut c.doc.get_mut(c.card).unwrap().effects {
if let EffectKind::DropShadow(s) = &mut e.kind {
f(s);
return;
}
}
}
/// The card's bottom-left corner and the shadow under it, `scale` device pixels a unit.
fn corner(scale: f64) -> View {
View { origin: (480.0, 440.0), scale, width: (50.0 * scale) as u32, height: (40.0 * scale) as u32 }
}
fn darkest(p: &Pixmap) -> u8 {
p.data().as_chunks::<4>().0.iter().map(|c| c[0]).min().unwrap_or(255)
}
#[test]
fn a_shadow_blurred_little_is_the_one_cast_from_the_layers_pixels() {
let mut c = card(true);
// A blur of 3 device pixels: drawn at full resolution, a dark shadow so it shows.
shadow_of(&mut c, |s| (s.radius, s.color) = (6.0, Color { a: 0.8, ..Color::BLACK }));
for scale in [1.0, 1.37] {
let (new, old) = both(&c, &corner(scale));
assert!(darkest(&new) < 120, "a shadow shows at {scale}");
assert_eq!(furthest(&corner(scale), &new, &old), 0, "at {scale}");
}
}
#[test]
fn a_shadow_blurred_widely_looks_as_the_one_cast_from_the_layers_pixels() {
for (spread, offset, behind) in [(0.0, (0.0, 4.0), false), (3.0, (2.5, 4.0), false), (-2.0, (0.0, 6.0), false), (0.0, (0.0, 4.0), true)] {
let mut c = card(true);
shadow_of(&mut c, |s| {
(s.spread, s.offset, s.show_behind, s.color) = (spread, offset, behind, Color { a: 0.8, ..Color::BLACK });
});
// A frame's shadow spreads from its outline when it clips (from its pixels otherwise).
c.doc.get_mut(c.card).unwrap().clip = spread != 0.0;
if behind {
// What shows of a shadow behind its layer: through a see-through picture, not the card.
let n = c.doc.get_mut(c.card).unwrap();
n.fills = vec![Paint::solid(Color::WHITE)];
}
// Blurs of 16 to 309 device pixels: drawn 4 to 64 times smaller.
for scale in [4.0, 9.3, SCALE] {
let v = if scale == SCALE { View { origin: (488.0, 452.0), scale, width: 700, height: 900 } } else { corner(scale) };
let (new, old) = both(&c, &v);
assert!(darkest(&new) < 200, "a shadow shows at {scale}");
let d = furthest(&v, &new, &old);
assert!(d <= 4, "spread {spread}, offset {offset:?}, behind {behind}, at {scale}: {d} apart");
}
}
}
#[test]
fn bands_and_one_piece_draw_the_same_wide_shadow() {
let mut c = card(true);
shadow_of(&mut c, |s| s.color = Color { a: 0.8, ..Color::BLACK });
for scale in [9.3, SCALE] {
let v = View { origin: (488.3, 452.7), scale, width: 640, height: 600 };
let whole = render_view_single(&c.doc, c.page, &v, &white()).unwrap();
let mut bands = Pixmap::new(v.width, v.height).unwrap();
for y0 in (0..v.height).step_by(75) {
let part = render_band(&c.doc, c.page, &v, &white(), y0, 75, 0).unwrap();
crate::put_band(&mut bands, y0, &part);
}
assert_eq!(furthest(&v, &bands, &whole), 0, "at {scale}");
}
}
#[test]
fn a_layer_with_a_shadow_holds_no_more_than_the_view() {
let c = card(true);
let v = close_up(&c, 1200, 800);
let view_bytes = u64::from(v.width) * u64::from(v.height) * 4;
let (pix, peak) = crate::layer_budget::within(crate::layer_budget::BUDGET, || render_view_single(&c.doc, c.page, &v, &Options::default()));
assert!(pix.is_some());
// The card's layer, and the clips inside and around it: each the view at most. Cast from the
// layer's pixels, the layer alone was the view and 1,392 pixels more each way.
assert!(peak <= view_bytes * 6, "{} MB held for a view of {} MB", peak >> 20, view_bytes >> 20);
}
#[test]
fn layers_that_are_not_their_outline_cast_from_their_pixels() {
let caster = |f: fn(&mut Card) -> NodeId| {
let mut c = card(true);
let id = f(&mut c);
crate::shadow::outline_caster(&c.doc, c.doc.node(id).unwrap()).is_some()
};
assert!(caster(|c| c.card), "an opaque frame whose children stay inside it");
assert!(caster(|c| {
c.doc.get_mut(c.card).unwrap().clip = true;
c.card
}));
assert!(!caster(|c| {
c.doc.get_mut(c.card).unwrap().fills = vec![Paint::solid(Color { a: 0.5, ..Color::WHITE })];
c.card
}));
// A child past the card's edge, or in the corner its rounding cuts off, casts a shadow too.
assert!(!caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((300.0, 12.0));
c.card
}));
assert!(!caster(|c| {
shadow_of(c, |s| s.spread = 2.0);
c.card
}));
assert!(!caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0));
c.card
}));
assert!(caster(|c| {
let picture = c.doc.node(c.shape).unwrap().parent.unwrap();
c.doc.get_mut(picture).unwrap().transform = figcraft_geom::Affine::translate((1.0, 1.0));
c.doc.get_mut(c.card).unwrap().clip = true;
c.card
}));
assert!(!caster(|c| {
c.doc
.get_mut(c.card)
.unwrap()
.effects
.push(figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(2.0)), visible: true });
c.card
}));
}
/// A rectangle with a dark shadow of `radius` and `spread`, drawn through `transform`.
fn slab(transform: figcraft_geom::Affine, size: (f64, f64), radius: f64, spread: f64) -> (figcraft_doc::Document, NodeId) {
let mut d = figcraft_doc::Document::new("slab");
let page = d.first_page().unwrap();
let r = d.create(page, figcraft_doc::NodeKind::Rectangle, "Slab", 0.0, 0.0, size.0, size.1).unwrap();
let n = d.get_mut(r).unwrap();
n.transform = transform;
n.fills = vec![Paint::solid(Color::WHITE)];
n.effects.push(figcraft_doc::Effect {
kind: EffectKind::DropShadow(Shadow { radius, spread, offset: (0.0, 0.0), color: Color::BLACK, ..Shadow::default() }),
visible: true,
});
(d, page)
}
/// A spread grows the outline in the layer's own units: stretched six times one way and squeezed
/// as much the other, it reaches six times as far that way, not as far as the scale of an area
/// (here 1) says.
#[test]
fn a_spread_reaches_as_far_as_the_layer_is_stretched() {
let stretched = figcraft_geom::Affine::translate((120.0, 60.0)) * figcraft_geom::Affine::scale_non_uniform(6.0, 1.0 / 6.0);
let (d, page) = slab(stretched, (20.0, 240.0), 0.0, 10.0);
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 360, height: 160 };
let new = render_view_single(&d, page, &v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(true));
let old = render_view_single(&d, page, &v, &white()).unwrap();
FROM_PIXELS.with(|f| f.set(false));
// Black 50 pixels left of the slab (its spread is 60 there), in both.
let at = |p: &Pixmap, x: usize, y: usize| p.data()[(y * 360 + x) * 4];
assert_eq!((at(&new, 70, 80), at(&old, 70, 80)), (0, 0), "the shadow 50 pixels out");
let apart = new.data().iter().zip(old.data()).filter(|(a, b)| a.abs_diff(**b) > 8).count();
assert!(apart < 400, "{apart} channels apart");
}
/// A shadow across a view as wide as a pixmap gets is drawn: the pixmap it is blurred in is a
/// blur's reach wider still.
#[test]
fn a_shadow_shows_across_the_widest_view() {
let (d, page) = slab(figcraft_geom::Affine::translate((-100.0, 4.0)), (17_000.0, 10.0), 6.0, 0.0);
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 16_384, height: 30 };
let pix = render_view_single(&d, page, &v, &white()).unwrap();
// Two rows under the slab (white without a shadow), at both ends and in the middle.
for x in [10usize, 8_000, 16_370] {
let red = pix.data()[(16 * 16_384 + x) * 4];
assert!(red < 245, "a shadow under the slab at {x}: {red}");
}
}
+151 -12
View File
@@ -10,7 +10,7 @@ use std::sync::Arc;
use figcraft_doc::{Document, EffectKind, NodeId, NodeKind};
use figcraft_geom::Rect;
use tiny_skia::{IntRect, Pixmap, PixmapPaint, Transform};
use tiny_skia::Pixmap;
use crate::{Options, View, draw, render_view};
@@ -373,6 +373,11 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
}
out.push(draw::paint_bounds(doc, parent)?);
}
ancestor_areas(doc, id, out)
}
/// The areas of the ancestors of `id` that a change to it affects, beyond its own.
fn ancestor_areas(doc: &Document, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// Ancestors that paint from their children's pixels (booleans, effects, masks): all of them.
for a in doc.ancestors(id) {
let Some(an) = doc.node(a) else { break };
@@ -386,6 +391,138 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
Some(())
}
/// Page areas in which `id` looks different in `after` than in `before` (where it was and where
/// it is now, and what of its ancestors follows); `None` when only a full render will do.
fn edited_areas(before: &Document, after: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// A vector whose points moved looks different only around them.
if let Some(area) = moved_points_area(before, after, page, id) {
out.push(area);
ancestor_areas(before, id, out)?;
return ancestor_areas(after, id, out);
}
changed_areas(before, page, id, out)?;
changed_areas(after, page, id, out)
}
/// Vectors with more points than this are drawn again whole when they change.
const MAX_MOVED_POINTS: usize = 4096;
/// Whether every visible paint of `paints` is one colour: it looks the same wherever the layer's
/// box lies (a gradient or an image is laid out in the box).
fn plain(paints: &[figcraft_color::Paint]) -> bool {
paints.iter().filter(|p| p.visible).all(|p| matches!(p.kind, figcraft_color::PaintKind::Solid { .. }))
}
/// The page area in which vector `id` looks different in `after` than in `before`, when all that
/// changed is where its points and handles are (a point dragged in the vector editor): around the
/// segments that moved and their neighbours (whose joins and rounded corners follow them), as far
/// out as the stroke reaches. The rest of a large shape keeps its pixels, however much of the
/// view it fills. `None` when anything else changed or the look depends on the whole outline
/// (dashes, a width profile, a brush, gradients and images laid out in the box, effects, a mask):
/// the layer is then drawn again whole.
fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: NodeId) -> Option<Rect> {
let (a, b) = (before.node(id)?, after.node(id)?);
let (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) = (&a.kind, &b.kind) else { return None };
if after.page_of(id) != Some(page) || before.page_of(id) != Some(page) {
return None;
}
let simple = |n: &figcraft_doc::Node, net: &figcraft_doc::VectorNetwork| {
!n.is_mask
&& n.visible
&& !n.effects.iter().any(|e| e.visible)
&& n.stroke.dashes.is_empty()
&& n.stroke.width_profile.is_none()
&& n.stroke.brush.is_none()
&& plain(&n.fills)
&& plain(&n.strokes)
&& net.regions.iter().all(|r| r.fills.as_deref().is_none_or(plain))
};
let same_shape = na.vertices.len() == nb.vertices.len()
&& na.vertices.len() <= MAX_MOVED_POINTS
&& na.segments.len() == nb.segments.len()
&& na.segments.iter().zip(&nb.segments).all(|(x, y)| (x.a, x.b) == (y.a, y.b))
&& na.regions.len() == nb.regions.len()
&& na.regions.iter().zip(&nb.regions).all(|(x, y)| x.loops == y.loops && x.winding == y.winding && x.fills == y.fills);
if !(simple(a, na) && simple(b, nb) && same_shape) {
return None;
}
// A fill closes an open path with a line between its ends that is no segment: it moves
// with either end, across the whole shape.
let mut ends = vec![0u8; na.vertices.len()];
for s in &na.segments {
for i in [s.a, s.b] {
let n = ends.get_mut(i)?;
*n = n.saturating_add(1);
}
}
let filled = a.fills.iter().any(|f| f.visible) || !na.regions.is_empty();
if filled && ends.contains(&1) {
return None;
}
// Nothing but the geometry differs: the box follows the points, and with it the transform.
let mut as_after = a.clone();
as_after.kind = b.kind.clone();
(as_after.transform, as_after.width, as_after.height) = (b.transform, b.width, b.height);
if as_after != *b {
return None;
}
let (wa, wb) = (before.world_transform(id), after.world_transform(id));
// The box following the points moves the layer; anything else a transform does (a scale, a
// turn) changes every stroke's width or direction on the page, whether its path moved or not.
let (ca, cb) = (wa.as_coeffs(), wb.as_coeffs());
if ca.iter().zip(&cb).take(4).any(|(x, y)| (x - y).abs() > 1e-12 * x.abs().max(1.0)) {
return None;
}
// A segment on the page: its ends and handles.
let hull = |w: figcraft_geom::Affine, net: &figcraft_doc::VectorNetwork, s: &figcraft_doc::Segment| {
let (pa, pb) = (net.vertices.get(s.a)?.point(), net.vertices.get(s.b)?.point());
let pts = [pa, pa + figcraft_geom::Vec2::new(s.ta.0, s.ta.1), pb + figcraft_geom::Vec2::new(s.tb.0, s.tb.1), pb].map(|p| w * p);
pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()).then_some(pts)
};
let mut moved = vec![false; na.vertices.len()];
let mut hulls = Vec::with_capacity(na.segments.len());
for (sa, sb) in na.segments.iter().zip(&nb.segments) {
let (ha, hb) = (hull(wa, na, sa)?, hull(wb, nb, sb)?);
// Apart by more than float noise. When the box follows a moved point every local
// coordinate shifts and the transform shifts back: a point that stayed put comes out a
// few ulps from where it was. 64 of them is far above that and far under a pixel at any
// zoom, wherever on the page the vector lies (a tenth of a millionth of a unit at
// coordinates of ten million).
let near = |x: f64, y: f64| (x - y).abs() <= 64.0 * f64::EPSILON * x.abs().max(y.abs()).max(1.0);
let apart = ha.iter().zip(&hb).any(|(p, q)| !(near(p.x, q.x) && near(p.y, q.y)));
let styled =
|i: usize| na.vertices.get(i).zip(nb.vertices.get(i)).is_none_or(|(x, y)| (x.radius, x.cap, x.join) != (y.radius, y.cap, y.join));
if apart || styled(sa.a) || styled(sa.b) {
for i in [sa.a, sa.b] {
*moved.get_mut(i)? = true;
}
}
hulls.push((ha, hb));
}
// Every segment at a point of a segment that moved: its join or rounded corner there follows.
let mut area: Option<Rect> = None;
for (s, (ha, hb)) in na.segments.iter().zip(&hulls) {
if moved.get(s.a).copied().unwrap_or(true) || moved.get(s.b).copied().unwrap_or(true) {
for p in ha.iter().chain(hb) {
let r = Rect::from_points(*p, *p);
area = Some(area.map_or(r, |a| a.union(r)));
}
}
}
let area = area?;
// As far as the stroke reaches from the path, on the page.
// The most the transform stretches a length in any direction (its largest singular value):
// under a skew that is more than either axis is stretched.
let stretch = |w: figcraft_geom::Affine| {
let c = w.as_coeffs();
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
let det = c[0] * c[3] - c[1] * c[2];
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
};
let reach = (a.outline_reach() * stretch(wa)).max(b.outline_reach() * stretch(wb));
reach.is_finite().then(|| area.inflate(reach, reach))
}
/// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None`
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered.
fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> {
@@ -434,8 +571,7 @@ fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64,
if in_pattern_source(doc, s, id) || in_pattern_source(&last.doc, &last.sensitive, id) {
return None;
}
changed_areas(&last.doc, page, id, &mut areas)?;
changed_areas(doc, page, id, &mut areas)?;
edited_areas(&last.doc, doc, page, id, &mut areas)?;
}
for r in areas {
if let Some(p) = to_px(r, view.scale, px) {
@@ -554,14 +690,17 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) ->
// The same pixel grid as the frame: origin (px + offset) / scale.
let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh };
let part = crate::render_part(doc, page, &sub, opts)?;
let inner = IntRect::from_xywh(
i32::try_from(d.x0 - ox).ok()?,
i32::try_from(d.y0 - oy).ok()?,
u32::try_from(d.x1 - d.x0).ok()?,
u32::try_from(d.y1 - d.y0).ok()?,
)?;
let inner = part.clone_rect(inner)?;
let copy = PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() };
pix.draw_pixmap(i32::try_from(d.x0).ok()?, i32::try_from(d.y0).ok()?, inner.as_ref(), &copy, Transform::identity(), None);
// The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the
// copy took longer than rendering a simple part).
let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?);
let (cols, rows) = (usize::try_from(d.x1 - d.x0).ok()?, usize::try_from(d.y1 - d.y0).ok()?);
let (at_x, at_y) = (usize::try_from(d.x0).ok()?, usize::try_from(d.y0).ok()?);
let (src_w, dst_w) = (part.width() as usize, pix.width() as usize);
let dst = pix.data_mut();
for (r, row) in part.data().chunks_exact(src_w.max(1) * 4).skip(skip_y).take(rows).enumerate() {
let from = row.get(skip_x * 4..(skip_x + cols) * 4)?;
let start = ((at_y + r) * dst_w + at_x) * 4;
dst.get_mut(start..start + cols * 4)?.copy_from_slice(from);
}
Some(())
}
+133
View File
@@ -65,3 +65,136 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() {
assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}"));
}
}
/// A closed zigzag of `2 * teeth + 2` points, 240 × 120 units at (20, 20): a ridge.
fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId {
let mut pts = vec![figcraft_geom::Point::new(0.0, 120.0)];
for i in 0..=teeth * 2 {
pts.push(figcraft_geom::Point::new(240.0 * i as f64 / (teeth * 2) as f64, if i % 2 == 0 { 60.0 } else { 10.0 }));
}
pts.push(figcraft_geom::Point::new(240.0, 120.0));
let network = figcraft_doc::VectorNetwork::from_points(&pts, true);
let id = d.create(page, NodeKind::Vector { network }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap();
d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())];
id
}
fn move_point(d: &mut Document, id: NodeId, point: usize, by: (f64, f64)) {
if let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind {
network.vertices[point].x += by.0;
network.vertices[point].y += by.1;
}
}
/// A point of a vector dragged while the vector fills the view (zoomed to it, as the vector
/// editor does): the shape looks different only around the point's segments, and only that is
/// drawn again. (Its whole box was, and past 60 % of the view that made every frame of the
/// drag a full render.)
#[test]
fn a_moved_point_redraws_the_vector_around_it_only() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 4] = [
("filled", |_| {}),
("stroked, mitred", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 6.0;
n.stroke.miter_limit = 4.0;
}),
("rounded points", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.vertices.iter_mut().for_each(|v| v.radius = 9.0);
}
}),
("stroked only", |n| {
n.fills.clear();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
// The ridge is 720 × 360 of the view's 780 × 420 pixels.
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
let (_, _, work) = r.render(&d2, page, &v, &Options::default()).unwrap();
let Work::Partial { pixels } = work else { panic!("{what}: a full render ({work:?})") };
// A tooth of six each way from the point, and what the stroke adds (36 pixels each way
// for the mitred one); the ridge's box is 259,200 pixels.
assert!(pixels < 780 * 420 * 2 / 5, "{what}: {pixels} pixels drawn again");
check(&mut r, &d2, page, &v, what);
// And back: the same again.
let (_, _, work) = r.render(&doc, page, &v, &Options::default()).unwrap();
assert!(matches!(work, Work::Partial { .. }), "{what}: {work:?}");
check(&mut r, &doc, page, &v, what);
}
}
/// What depends on the whole outline is drawn again whole: a gradient laid out in the vector's
/// box, dashes that run on from the moved point, an open path's closing line.
#[test]
fn a_moved_point_redraws_a_vector_whole_when_its_look_depends_on_all_of_it() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 3] = [
("dashed", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
n.stroke.dashes = vec![8.0, 5.0];
}),
("a shadow", |n| n.effects.push(Effect::inner_shadow())),
("an open path", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.segments.pop();
}
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
assert_eq!(r.render(&d2, page, &v, &Options::default()).unwrap().2, Work::Full, "{what}");
check(&mut r, &d2, page, &v, what);
}
}
/// A vector's strokes are as wide on the page as its transform makes them. Scaled up with its
/// points scaled down to match, its paths stay where they were and every stroke doubles: with a
/// point moved too, all of it is drawn again, not the area around that point.
#[test]
fn a_moved_point_with_a_scaled_vector_redraws_all_of_it() {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
let n = d.get_mut(id).unwrap();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, "first");
let mut d2 = (*doc).clone();
let n = d2.get_mut(id).unwrap();
n.transform *= Affine::scale(2.0);
(n.width, n.height) = (n.width / 2.0, n.height / 2.0);
if let NodeKind::Vector { network } = &mut n.kind {
for p in &mut network.vertices {
(p.x, p.y) = (p.x / 2.0, p.y / 2.0);
}
}
move_point(&mut d2, id, 6, (2.0, -3.5));
check(&mut r, &Arc::new(d2), page, &v, "scaled, a point moved");
}
+153 -1
View File
@@ -61,10 +61,15 @@ pub fn inner_from_pixels(doc: &Document, n: &Node) -> bool {
}
fn outlines(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool) -> Option<Vec<Outline>> {
outlines_with(doc, n, fill_counts, false)
}
/// [`outlines`]; `kids_within`: the caller knows the children paint nothing outside the outline.
fn outlines_with(doc: &Document, n: &Node, fill_counts: fn(&Paint) -> bool, kids_within: bool) -> Option<Vec<Outline>> {
let has_fill = n.fills.iter().any(fill_counts);
let is_bool = matches!(n.kind, NodeKind::BooleanOp { .. });
let is_text = matches!(n.kind, NodeKind::Text(_));
let kids = !is_bool && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible));
let kids = !is_bool && !kids_within && n.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.visible));
if matches!(n.kind, NodeKind::Group | NodeKind::Page { .. })
|| (kids && !(n.kind.is_frame_like() && n.clip && has_fill))
|| (is_text && n.has_visible_stroke())
@@ -286,3 +291,150 @@ fn inner_from(mut big: Pixmap, pad: u32, cover: &Pixmap, scale: f64, s: &Shadow)
fx::tint(&mut out, color4(s.color));
Some(out)
}
/// Whether `p` paints every pixel it covers at full alpha: a visible, opaque solid colour.
fn opaque(p: &Paint) -> bool {
p.visible && p.opacity >= 1.0 && p.blend == figcraft_color::BlendMode::Normal && matches!(&p.kind, PaintKind::Solid { color } if color.a >= 1.0)
}
/// The outlines node `n`'s drop shadows are cast from when its pixels are those outlines, filled:
/// a shape or a clipping frame whose paints are opaque colours and that has no effect that moves
/// its pixels. Such a shadow needs none of the layer's pixels, so it is drawn only where it
/// shows and blurred at the resolution its radius needs ([`outline_drop_shadow`]), not from a
/// copy of the layer reaching past the view. `None`: the shadows come from the layer's pixels.
pub fn outline_caster(doc: &Document, n: &Node) -> Option<Vec<Outline>> {
#[cfg(test)]
if FROM_PIXELS.with(std::cell::Cell::get) {
return None;
}
let shape =
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Polygon { .. } | NodeKind::Star { .. });
let plain = n.effects.iter().filter(|e| e.visible).all(|e| matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_)));
let fills = n.fills.iter().any(opaque);
let strokes = !n.has_visible_stroke() || n.strokes.iter().filter(|s| s.visible).all(opaque);
if !(shape && plain && fills && strokes && figcraft_doc::geometry::is_closed(n)) {
return None;
}
// A frame that doesn't clip is its outline too while its children stay inside it. Its
// shadows spread as its pixels do (see the module docs), not as an outline: those stay.
let within = n.kind.is_frame_like() && !n.clip && drop_shadows(n).all(|s| s.spread == 0.0) && children_within(doc, n);
outlines_with(doc, n, |f| f.visible && f.opacity > 0.0, within)
}
/// Whether everything the children of frame `n` paint (effects and all) lies inside its box, its
/// rounded corners cut off: they then add nothing to the pixels its fill covers.
fn children_within(doc: &Document, n: &Node) -> bool {
let world = doc.world_transform(n.id);
let det = world.determinant();
if !(det.is_finite() && det.abs() > 1e-12) {
return false;
}
let to_local = world.inverse();
n.children.iter().filter(|c| doc.node(**c).is_some_and(|c| c.visible)).all(|c| {
crate::draw::paint_bounds(doc, *c).is_some_and(|b| {
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)]
.into_iter()
.all(|p| crate::draw::in_box(n, to_local * figcraft_geom::Point::new(p.0, p.1)))
})
})
}
#[cfg(test)]
thread_local! {
/// Tests: every drop shadow is cast from its layer's pixels, as before [`outline_caster`].
pub(crate) static FROM_PIXELS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Shadows blurred by less than this many device pixels (standard deviation) are drawn at full
/// resolution, as they always were.
const FULL_RES_SIGMA: f64 = 8.0;
/// The most a shadow is drawn smaller by before its blur: a blur of 4 to 8 small pixels.
const MAX_SMALLER: u32 = 256;
/// The longest side of a pixmap.
const MAX_SIDE: u32 = 16_384;
/// What the pixmap a shadow is blurred in may have more than [`MAX_SIDE`] a side: the blur's
/// reach both ways at full resolution (under [`FULL_RES_SIGMA`]: 34 pixels) and a pixel's slack.
/// Drawn smaller, it is far under the limit.
const BLUR_ROOM: u32 = 128;
/// A whole pixel range `[lo, hi)` as `(start, length)`; `None` when empty or longer than `most`.
fn span(lo: f64, hi: f64, most: u32) -> Option<(i32, u32)> {
if !(lo.is_finite() && hi.is_finite() && hi > lo && lo.abs() < 1e9 && hi.abs() < 1e9) {
return None;
}
let len = (hi - lo) as u32;
(1..=most).contains(&len).then_some((lo as i32, len))
}
/// The most `xf` stretches a length, in any direction (its largest singular value): how far a
/// distance in local units can reach on the pixmap.
fn stretch(xf: Affine) -> f64 {
let c = xf.as_coeffs();
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
let det = c[0] * c[3] - c[1] * c[2];
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
}
/// The drop shadow `s` cast by `outlines` (local space, drawn at `xf` into a `size` pixmap), where
/// it shows on that pixmap: the shadow's pixels and where their top-left goes. Unless it shows
/// behind the layer, it is hidden behind `cover`.
///
/// A shadow blurred widely is drawn `k` times smaller, blurred there and scaled back up: a wide
/// blur has no detail a pixel across. The small pixels line up with the shape, not with the
/// pixmap, so every render of a view (a band, a patch, the whole of it) draws the same shadow.
pub fn outline_drop_shadow(
outlines: &[Outline],
cover: &[Outline],
s: &Shadow,
xf: Affine,
scale: f64,
size: (u32, u32),
) -> Option<(Pixmap, (i32, i32))> {
let spread = if s.spread.is_finite() { s.spread } else { 0.0 };
let sigma = (s.radius / 2.0 * scale).min(fx::MAX_SIGMA);
let sigma = if sigma.is_finite() && sigma > 0.3 { sigma } else { 0.0 };
// As from the layer's pixels: without a spread the offset is whole pixels.
let (dx, dy) = (s.offset.0 * scale, s.offset.1 * scale);
let (dx, dy) = if spread != 0.0 && dx.is_finite() && dy.is_finite() { (dx, dy) } else { (f64::from(whole_px(dx)), f64::from(whole_px(dy))) };
let cast = Affine::translate((dx, dy)) * xf;
// Where the shadow can show: its outlines, spread and blurred, on the pixmap.
let reach = (sigma * 4.0).ceil() + 2.0;
// A spread grows the outline in local units: on the pixmap, as far as the transform
// stretches them the most (it need not scale both ways alike).
let px = stretch(xf);
let grown = if px.is_finite() { (spread.abs() * px * SPREAD_MITER_LIMIT).min(MAX_SPREAD_PX) } else { 0.0 };
let shape =
outlines.iter().map(|(p, _)| figcraft_geom::transform_rect_bbox(cast, figcraft_geom::Shape::bounding_box(p))).reduce(|a, b| a.union(b))?;
let shows = shape.inflate(grown + reach, grown + reach).intersect(figcraft_geom::Rect::new(0.0, 0.0, f64::from(size.0), f64::from(size.1)));
let (x0, w) = span(shows.x0.floor(), shows.x1.ceil(), MAX_SIDE)?;
let (y0, h) = span(shows.y0.floor(), shows.y1.ceil(), MAX_SIDE)?;
let smaller = if sigma >= FULL_RES_SIGMA { (2f64.powi((sigma / 4.0).log2().floor() as i32) as u32).clamp(1, MAX_SMALLER) } else { 1 };
let k = f64::from(smaller);
// The small pixmap's pixels are `k` device pixels a side, counted from the shape's origin
// (the pixmap's own pixels when nothing is drawn smaller): those the shadow's area and
// what blurs into it take in.
let c = cast.as_coeffs();
let (ax, ay) = if smaller > 1 { (c[4], c[5]) } else { (0.0, 0.0) };
let (i0, lw) =
span(((f64::from(x0) - reach - ax) / k).floor() - 1.0, ((f64::from(x0) + f64::from(w) + reach - ax) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?;
let (j0, lh) =
span(((f64::from(y0) - reach - ay) / k).floor() - 1.0, ((f64::from(y0) + f64::from(h) + reach - ay) / k).ceil() + 1.0, MAX_SIDE + BLUR_ROOM)?;
let small = Affine::new([c[0] / k, c[1] / k, c[2] / k, c[3] / k, (c[4] - ax) / k - f64::from(i0), (c[5] - ay) / k - f64::from(j0)]);
let mut low = spread_alpha(outlines, spread, small, lw, lh)?;
fx::blur(&mut low, sigma / k);
let mut out = Pixmap::new(w, h)?;
let tints = fx::tints(color4(s.color));
if smaller > 1 {
// Device pixel centre → small pixel centres.
let at = |v: i32, a: f64, first: i32| (f64::from(v) + 0.5 - a) / k - 0.5 - f64::from(first);
fx::enlarge_alpha(&low, &mut out, (at(x0, ax, i0), at(y0, ay, j0)), 1.0 / k, &tints);
} else {
fx::copy_alpha(&low, &mut out, (x0 - i0, y0 - j0), &tints);
}
if !s.show_behind {
let hides = spread_alpha(cover, 0.0, Affine::translate((-f64::from(x0), -f64::from(y0))) * xf, w, h)?;
fx::mask_by(&mut out, &hides, true);
}
Some((out, (x0, y0)))
}
+60
View File
@@ -0,0 +1,60 @@
//! An opaque stroke meets what lies on each side of it with nothing else showing between: no
//! light fill fringe along an inside stroke's outer edge, no background gap along an outside
//! stroke's inner edge (#2635).
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, NodeKind, StrokeAlign};
use super::*;
const DARK: Color = Color { r: 30.0 / 255.0, g: 27.0 / 255.0, b: 75.0 / 255.0, a: 1.0 };
/// The red channel along the middle row of a 40-unit `kind` at (`at`, `at`) with a black 4-unit
/// stroke, its fill `fill`, over `background`.
fn middle_row(kind: &NodeKind, smoothing: f64, align: StrokeAlign, at: f64, fill: Color, background: Color) -> Vec<u8> {
let mut d = Document::new("fringe");
let p = d.first_page().unwrap();
let n = d.create(p, kind.clone(), "S", at, at, 40.0, 40.0).unwrap();
let node = d.get_mut(n).unwrap();
node.fills = vec![Paint::solid(fill)];
node.strokes = vec![Paint::solid(Color::BLACK)];
(node.stroke.weight, node.stroke.align, node.corners.smoothing) = (4.0, align, smoothing);
if smoothing > 0.0 {
node.corners.radii = [8.0; 4];
}
let mut pix = Pixmap::new(80, 80).unwrap();
let c = |v: f32| (v * 255.0).round() as u8;
pix.fill(tiny_skia::Color::from_rgba8(c(background.r), c(background.g), c(background.b), 255));
render_nodes_into(&d, &[n], &View { origin: (0.0, 0.0), scale: 1.0, width: 80, height: 80 }, &mut pix);
let y = (at + 20.0) as u32;
(0..80).map(|x| pix.pixel(x, y).unwrap().red()).collect()
}
#[test]
fn an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge() {
let dark = (DARK.r * 255.0).round() as u8;
let ellipse = NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 };
// Smoothed corners take the general outline rather than the rect ring.
let shapes = [(&NodeKind::Frame, 0.0), (&NodeKind::Rectangle, 0.0), (&ellipse, 0.0), (&NodeKind::Rectangle, 0.6)];
for (kind, smoothing) in shapes {
for align in [StrokeAlign::Inside, StrokeAlign::Center, StrokeAlign::Outside] {
for at in [20.4, 20.7] {
let middle = at
+ match align {
StrokeAlign::Inside => 2.0,
StrokeAlign::Center => 0.0,
StrokeAlign::Outside => -2.0,
};
let centre = (at + 20.0) as usize;
// Outside the stroke's middle on a dark page under a white fill, then inside it
// under a dark fill on a white page: no pixel lighter than the dark side.
let outer = middle_row(kind, smoothing, align, at, Color::WHITE, DARK);
let outer = &outer[..middle.floor() as usize];
let inner = middle_row(kind, smoothing, align, at, DARK, Color::WHITE);
let inner = &inner[middle.ceil() as usize..centre];
assert!(outer.iter().all(|&r| r <= dark), "{kind:?} smoothing {smoothing}, {align:?} at {at}: outer edge {outer:?}");
assert!(inner.iter().all(|&r| r <= dark), "{kind:?} smoothing {smoothing}, {align:?} at {at}: inner edge {inner:?}");
}
}
}
}
+126
View File
@@ -0,0 +1,126 @@
//! Timings of a shadowed card seen close up: a small shape inside a rounded picture inside a
//! rounded card with a drop shadow, inside two stacks and a screen, at 1,933% on a 2× display
//! (38.66 device pixels a unit, 4112 × 2292 device pixels). The mobile app template's trail card,
//! where the browser took 16.6 s for one render and 2 s for each frame of an edit.
//!
//! Run in release, on one thread as the browser does:
//! `RAYON_NUM_THREADS=1 cargo test --release -p figcraft-render --lib zoomed_card_timings -- --ignored --nocapture`.
use std::sync::Arc;
use std::time::Instant;
use figcraft_color::{Color, Paint};
use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow};
use crate::{Begun, Options, Retained, View, Work, render_view_single};
/// Device pixels a document unit: 1,933% at a pixel ratio of 2.
pub(crate) const SCALE: f64 = 38.66;
pub(crate) struct Card {
pub doc: Document,
pub page: NodeId,
pub card: NodeId,
/// The shape in the card's picture.
pub shape: NodeId,
}
/// The card: screen (clipping) > content > list > card (rounded, white, a drop shadow; like
/// the two stacks around it, not clipping) > picture (rounded, clipping) > shape.
pub(crate) fn card(shadow: bool) -> Card {
let fill = |d: &mut Document, id: NodeId, hex: &str| d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
let mut d = Document::new("zoomed card");
let page = d.first_page().unwrap();
let screen = d.create(page, NodeKind::Frame, "Screen", 470.0, 0.0, 390.0, 844.0).unwrap();
fill(&mut d, screen, "F4F6F5");
let content = d.create(screen, NodeKind::Frame, "Content", 0.0, 81.0, 390.0, 763.0).unwrap();
let list = d.create(content, NodeKind::Frame, "List", 24.0, 180.0, 342.0, 312.0).unwrap();
let card = d.create(list, NodeKind::Frame, "Card", 0.0, 108.0, 342.0, 96.0).unwrap();
fill(&mut d, card, "FFFFFF");
let n = d.get_mut(card).unwrap();
n.corners.radii = [20.0; 4];
if shadow {
n.effects.push(Effect {
kind: EffectKind::DropShadow(Shadow { offset: (0.0, 4.0), radius: 16.0, color: Color { a: 0.08, ..Color::BLACK }, ..Shadow::default() }),
visible: true,
});
}
for stack in [content, list, card] {
d.get_mut(stack).unwrap().clip = false;
}
let picture = d.create(card, NodeKind::Frame, "Picture", 12.0, 12.0, 72.0, 72.0).unwrap();
fill(&mut d, picture, "CFE3DA");
d.get_mut(picture).unwrap().corners.radii = [14.0; 4];
let shape = d.create(picture, NodeKind::Polygon { count: 5 }, "Shape", 0.0, 23.0, 72.0, 49.0).unwrap();
fill(&mut d, shape, "7FAE9C");
Card { doc: d, page, card, shape }
}
/// The view the canvas has after zooming to the shape: the shape in the middle.
pub(crate) fn close_up(c: &Card, width: u32, height: u32) -> View {
let b = crate::draw::paint_bounds(&c.doc, c.shape).unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
View { origin: (cx - f64::from(width) / SCALE / 2.0, cy - f64::from(height) / SCALE / 2.0), scale: SCALE, width, height }
}
fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
/// A full render drawn in the browser's bands: (all of it, the slowest band), in milliseconds.
fn banded(c: &Card, v: &View) -> (f64, f64) {
let doc = Arc::new(c.doc.clone());
let mut r = Retained::default();
let band_h = (v.height + 1).div_ceil(8).max(64);
let t = Instant::now();
let mut slowest = 0.0f64;
match r.begin(&doc, c.page, v, &Options::default(), band_h).unwrap() {
Begun::Done(..) => {}
Begun::Steps(mut steps) => loop {
let b = Instant::now();
let done = steps.step();
slowest = slowest.max(ms(b));
if done {
break;
}
},
}
(ms(t), slowest)
}
/// Mean milliseconds of a canvas frame after an edit of the shape, and what the last one took.
fn edits(c: &Card, v: &View) -> (f64, Work) {
const RUNS: u32 = 6;
let mut r = Retained::default();
let mut doc = Arc::new(c.doc.clone());
let _ = r.render(&doc, c.page, v, &Options::default());
let mut work = Work::Reused;
let t = Instant::now();
for i in 1..=RUNS {
let mut next = (*doc).clone();
next.get_mut(c.shape).unwrap().height = 49.0 - f64::from(i);
doc = Arc::new(next);
work = r.render(&doc, c.page, v, &Options::default()).unwrap().2;
}
(ms(t) / f64::from(RUNS), work)
}
#[test]
#[ignore = "timing: run in release with --ignored --nocapture"]
fn zoomed_card_timings() {
println!("zoomed card timings ({} build, 4112 × 2292 px, ms)", if cfg!(debug_assertions) { "debug" } else { "release" });
println!("| render | shadow | no shadow |\n|---|---:|---:|");
let (with, without) = (card(true), card(false));
let v = close_up(&with, 4112, 2292);
let piece = |c: &Card| {
let t = Instant::now();
assert!(render_view_single(&c.doc, c.page, &v, &Options::default()).is_some());
ms(t)
};
println!("| the view in one piece | {:.0} | {:.0} |", piece(&with), piece(&without));
let (a, b) = (banded(&with, &v), banded(&without, &v));
println!("| the view in 8 bands | {:.0} | {:.0} |", a.0, b.0);
println!("| the slowest band | {:.0} | {:.0} |", a.1, b.1);
let (a, b) = (edits(&with, &v), edits(&without, &v));
println!("| a frame after an edit of the shape | {:.0} ({:?}) | {:.0} ({:?}) |", a.0, a.1, b.0, b.1);
}
+9
View File
@@ -45,6 +45,7 @@ name = "English"
"Add a layer or component to tile first" = "Add a layer or component to tile first"
"Add a minute" = "Add a minute"
"Add a note for developers" = "Add a note for developers"
"Add a rule" = "Add a rule"
"Add action" = "Add action"
"Add actions for when no condition holds" = "Add actions for when no condition holds"
"Add an annotation for developers" = "Add an annotation for developers"
@@ -72,6 +73,7 @@ name = "English"
"Add properties to make instances configurable" = "Add properties to make instances configurable"
"Add reaction" = "Add reaction"
"Add row" = "Add row"
"Add rule" = "Add rule"
"Add starting point" = "Add starting point"
"Add stroke" = "Add stroke"
"Add variant" = "Add variant"
@@ -475,6 +477,7 @@ name = "English"
"Description" = "Description"
"Description (optional)" = "Description (optional)"
"Design" = "Design"
"Design it's a version of" = "Design it's a version of"
"Design panel" = "Design panel"
"Design system starter" = "Design system starter"
"Desktop" = "Desktop"
@@ -937,6 +940,7 @@ name = "English"
"Mixed" = "Mixed"
"Mixed fonts" = "Mixed fonts"
"Mixed interactions: click + to replace them" = "Mixed interactions: click + to replace them"
"Mobile" = "Mobile"
"Mobile app" = "Mobile app"
"Mode" = "Mode"
"Model" = "Model"
@@ -1343,6 +1347,7 @@ name = "English"
"Rows" = "Rows"
"Rows {count}" = "Rows {count}"
"Rulers" = "Rulers"
"Rules appear under Annotations, in the Responsive category." = "Rules appear under Annotations, in the Responsive category."
"Run" = "Run"
"Run {label}" = "Run {label}"
"Save file" = "Save file"
@@ -1365,6 +1370,7 @@ name = "English"
"Scatter" = "Scatter"
"Scoping: where pickers offer it" = "Scoping: where pickers offer it"
"Screen" = "Screen"
"Screen sizes" = "Screen sizes"
"Scroll behavior" = "Scroll behavior"
"Scroll to" = "Scroll to"
"Scroll to layer" = "Scroll to layer"
@@ -1458,6 +1464,7 @@ name = "English"
"Show/Hide UI" = "Show/Hide UI"
"Side by side" = "Side by side"
"Sidebar" = "Sidebar"
"Sidebar becomes a drawer below 768 px" = "Sidebar becomes a drawer below 768 px"
"Simplify stroke" = "Simplify stroke"
"Size" = "Size"
"Size jitter" = "Size jitter"
@@ -1482,6 +1489,8 @@ name = "English"
"Solid" = "Solid"
"Some variants have the same property values: give each one a unique combination" = "Some variants have the same property values: give each one a unique combination"
"Sort" = "Sort"
"Sort A to Z" = "Sort A to Z"
"Sort Z to A" = "Sort Z to A"
"Sort by" = "Sort by"
"Sort by date" = "Sort by date"
"Sort by page" = "Sort by page"
+1 -1
View File
@@ -480,7 +480,7 @@ pub fn open_context_menu(app: &mut FigApp, pos: Pos2, deep: bool) {
let (doc, page, sel, zoom) = (ds.doc.clone(), ds.page, ds.selection.clone(), ds.view.zoom.max(1e-6));
// A frame's name label is the frame, as on a press, even where it sits over a section.
let label = figcraft_engine::tools::label_at(&doc, page, &app.session.tool.labels, p);
let hit = app.session.hit(&doc, page, p, 2.0 / zoom);
let hit = app.session.hit_pick(&doc, page, p, 2.0 / zoom, deep);
let target = label.or_else(|| hit.map(|leaf| figcraft_doc::geometry::select_target(&doc, leaf, &sel, deep)));
if let Some(target) = target
&& !sel.contains(&target)
+17
View File
@@ -240,3 +240,20 @@ fn the_toolbar_keeps_the_inspect_tab_for_the_annotation_tool() {
crate::toolbar::choose(&mut u.app, figcraft_engine::ToolId::Rectangle);
assert_eq!(u.app.ui.right_tab, crate::RightTab::Design, "a drawing tool leaves it");
}
#[test]
fn a_rule_draft_belongs_to_its_document_and_outlives_a_refusal() {
let (mut u, f, _) = setup();
let gone = NodeId(999_999);
let field = crate::dev_mode::rule_draft(&u.app, gone);
u.ctx.data_mut(|d| d.insert_temp(field, "Cards stack".to_string()));
crate::dev_mode::add_rule(&mut u.app, &u.ctx, gone, "Cards stack");
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(field)).as_deref(), Some("Cards stack"), "a refused rule keeps its text");
let field = crate::dev_mode::rule_draft(&u.app, f);
u.ctx.data_mut(|d| d.insert_temp(field, "Cards stack".to_string()));
crate::dev_mode::add_rule(&mut u.app, &u.ctx, f, "Cards stack");
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(field)), None, "an added rule clears it");
// Another document's layer with the same id has a draft of its own.
u.run("file.new", json!({}));
assert_ne!(crate::dev_mode::rule_draft(&u.app, f), field);
}
@@ -512,6 +512,9 @@ fn collection_row(app: &mut FigApp, ui: &mut Ui, view: &View, c: &Collection, st
extend(app, view.id(), &c.id, st);
ui.close();
}
if view.editable() {
sort_items(app, ui, json!({"collection": c.id}));
}
if view.editable() && menu_item(ui, tr("Delete collection"), "") {
app.run("variable.deleteCollection", json!({"collection": c.id}));
ui.close();
@@ -597,6 +600,7 @@ fn group_rows(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
duplicate_group(app, &members, &list, g);
ui.close();
}
sort_items(app, ui, json!({"collection": coll.id, "group": g}));
if menu_item(ui, tr("Delete group"), "") {
let steps: Vec<serde_json::Value> = members
.iter()
@@ -676,6 +680,35 @@ fn duplicate_group(app: &mut FigApp, members: &[&Variable], list: &[String], g:
app.run("command.batch", json!({"label": "Duplicate group", "commands": steps}));
}
/// Sort by name, A to Z and Z to A, menu items for the variables `scope` names (`variable.sort`'s
/// collection and group).
fn sort_items(app: &mut FigApp, ui: &mut Ui, scope: Value) {
for (label, descending) in [(tr_noop("Sort A to Z"), false), (tr_noop("Sort Z to A"), true)] {
if menu_item(ui, tr(label), "") {
let mut p = scope.clone();
p["descending"] = json!(descending);
app.run("variable.sort", p);
ui.close();
}
}
}
/// The `variable.move` params that move `v` one row up (or `down`) past its neighbour among the
/// table's rows of its group; None at the group's end.
fn step_move(view: &View, coll: &Collection, st: &Editor, v: &Variable, down: bool) -> Option<Value> {
let g = group_of(&v.name);
let rows: Vec<&String> = st.order.iter().filter(|id| view.vars.get_by_id(id).is_some_and(|x| group_of(&x.name) == g)).collect();
let i = rows.iter().position(|id| **id == v.id)?;
if !down {
return Some(json!({"variables": [v.id], "before": rows.get(i.checked_sub(1)?)?}));
}
let next = rows.get(i + 1)?;
// Right after the next row: before what follows it in the collection, else last.
let all: Vec<&Variable> = view.in_collection(&coll.id).collect();
let after = all.iter().position(|x| x.id == **next).and_then(|k| all.get(k + 1)).map(|x| &x.id);
Some(json!({"variables": [v.id], "before": after}))
}
fn create_collection(app: &mut FigApp, vars: &Variables, st: &mut Editor) {
let name = unique("Collection", |n| vars.collections.iter().any(|c| c.name == n));
if let Some(id) =
@@ -769,6 +802,21 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) {
{
st.selected.clear();
}
// Alt+Up / Alt+Down move the one selected variable past its neighbour in its group.
if let [id] = st.selected.as_slice()
&& view.editable()
&& st.rename.is_none()
&& !crate::a11y::field_focused(ui.ctx())
&& let Some(v) = view.vars.get_by_id(id)
{
let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowDown));
let up = !down && ui.input_mut(|i| i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowUp));
if (up || down)
&& let Some(p) = step_move(view, coll, st, v, down)
{
app.run("variable.move", p);
}
}
let width = (NAME_W + coll.modes.len() as f32 * MODE_W + 40.0).max(ui.available_width());
egui::ScrollArea::both().id_salt("vars_table").auto_shrink([false, false]).show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
@@ -944,6 +992,14 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va
app.run("variable.duplicate", json!({"variable": v.id}));
ui.close();
}
for (label, key, down) in [(tr_noop("Move up"), "Alt+ArrowUp", false), (tr_noop("Move down"), "Alt+ArrowDown", true)] {
if let Some(p) = step_move(view, coll, st, v, down)
&& menu_item(ui, tr(label), &crate::toolbar::pretty_shortcut(key))
{
app.run("variable.move", p);
ui.close();
}
}
if !inherited && menu_item(ui, tr("Delete variable"), "") {
app.run("variable.delete", json!({"variable": v.id}));
ui.close();
+1 -1
View File
@@ -24,7 +24,7 @@ pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2,
let p = app.to_page(pos);
let Ok(ds) = app.session.ds() else { return false };
let tol = 2.0 / ds.view.zoom.max(1e-6);
let opts = figcraft_doc::geometry::HitOpts { locked: true };
let opts = figcraft_doc::geometry::HitOpts { locked: true, ..Default::default() };
let layers: Vec<(figcraft_doc::NodeId, usize, String, bool)> = {
let result = figcraft_engine::booleans::result_outline(&ds.doc, &ds.selection);
figcraft_doc::geometry::layers_at_opts(&ds.doc, ds.page, p, tol, Some(&result), opts)
+60 -1
View File
@@ -15,7 +15,7 @@ use figcraft_engine::dev_measurements::{self, Placed};
use figcraft_engine::devinspect::{self, DevItem, Prop};
use figcraft_engine::plugins::Access;
use figcraft_engine::snap::Guide;
use figcraft_engine::{components, dev_resources};
use figcraft_engine::{components, dev_resources, responsive};
use serde_json::json;
use crate::a11y::Tip;
@@ -548,6 +548,65 @@ fn variant_values(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId,
app.run("codeConnect.set", json!({"id": owner, "language": lang.id(), "values": values}));
}
/// Screen sizes for a frame: which version of a design it is, and rules for other sizes. What's
/// here is the designer's word: agents read it instead of guessing.
pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId) {
// Screens are frames and sections: a component isn't a version of one.
let Some(n) = doc.node(id).filter(|n| responsive::can_mark(&n.kind)) else { return };
let t = Tokens::get(ui.ctx());
let current = responsive::viewport_of(n);
widgets::separator(ui);
widgets::section_header(ui, tr("Screen sizes"), &[], current.is_none());
let labels = [(tr("Mobile"), "mobile"), (tr("Tablet"), "tablet"), (tr("Desktop"), "desktop")];
row(ui, 32.0, |ui| {
ui.spacing_mut().item_spacing.x = 4.0;
for (label, viewport) in labels {
let on = current == Some(viewport);
if widgets::button(ui, label, on, true).clicked() {
app.run("responsive.set", json!({"id": id, "viewport": if on { json!(null) } else { json!(viewport) }}));
}
}
});
if current.is_some() {
widgets::sublabels(ui, tr("Design it's a version of"), None);
let group = responsive::group_of(n);
row(ui, 32.0, |ui| {
let width = ui.available_width() - 2.0 * PAD;
if let Some(v) = widgets::text_field(ui, Id::unique(("responsive_group", id)), group, width, tr("Design it's a version of")) {
// Emptied: back to the frame's name.
let group = if v.trim().is_empty() { json!(null) } else { json!(v) };
app.run("responsive.set", json!({"id": id, "viewport": current, "group": group}));
}
});
}
let field = rule_draft(app, id);
let draft = ui.data(|d| d.get_temp::<String>(field)).unwrap_or_default();
widgets::sublabels(ui, tr("Add a rule"), None);
if let Some(v) = widgets::multiline_field(ui, field, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) {
ui.data_mut(|d| d.insert_temp(field, v));
}
row(ui, 32.0, |ui| {
if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() {
add_rule(app, ui.ctx(), id, &draft);
}
});
widgets::note(ui, tr("Rules appear under Annotations, in the Responsive category."), t.text_secondary);
}
/// Where the Screen sizes section keeps the rule being typed for layer `id`.
pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id {
// Layer ids repeat across open documents.
Id::unique(("responsive_rule", app.session.ds().ok().map(|d| d.uid), id))
}
/// Add `text` as a rule on `id`. The draft stays when the rule is refused, so nothing typed is lost.
pub(crate) fn add_rule(app: &mut FigApp, ctx: &egui::Context, id: NodeId, text: &str) {
let field = rule_draft(app, id);
if app.run("responsive.rule", json!({"id": id, "text": text})).is_some() {
ctx.data_mut(|d| d.remove_temp::<String>(field));
}
}
/// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab.
pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) {
let runnable: Vec<(String, String, String)> = app
@@ -206,6 +206,7 @@ pub(super) fn inspect(app: &mut FigApp, ui: &mut Ui) {
}
crate::dev_mode::status(app, ui, &doc, &sel);
crate::dev_mode::annotations_section(app, ui, &doc, first);
crate::dev_mode::responsive_section(app, ui, &doc, first);
crate::dev_mode::dev_resources_section(app, ui, &doc, first);
crate::dev_mode::measurements_section(app, ui, &doc, &sel);
use figcraft_engine::devinspect::ColorFormat;
+6 -3
View File
@@ -126,7 +126,7 @@ page 1 "Screens": 380 nodes, 4 top-level
### `export <file> -o <out> [--format png|jpg|svg|webp|pdf|xml|fig|penpot] [--scale N] [--page NAME] [--node ID|NAME] [--bleed LENGTH] [--crop-marks] [--bleed-marks] [--cmyk] [--vd-compat bestEffort|exact|ignore]`
- `<out>` is a directory: one file per top-level frame of the page (default the first page), named
- `<out>` is a directory: one file per top-level frame of the selected page, named
after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer.
The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |`
and control characters), which become `_`, and leading or trailing spaces and dots, which are
@@ -135,6 +135,9 @@ page 1 "Screens": 380 nodes, 4 top-level
characters (there a `/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`…
With `--node`, the CLI writes one file named after the selected layer, including a nested layer.
- `<out>` has an image extension: one file with the given `--node`, or the whole page composited.
- `--page` defaults to the first non-divider page: empty pages whose names start with `-` are
skipped. If all pages are dividers, the first is used. `--page NAME` can select one explicitly.
The `.fig` and `.penpot` formats export the whole document and ignore `--page`.
- `--node` takes a layer id (`12` or `0:12`) or a layer name.
- `--format fig` (or an `<out>` ending in `.fig`) writes the whole file as `.fig`, experimental:
written from public format notes, including variables with their modes and bindings and shared
@@ -198,8 +201,8 @@ When converting from a `.penpot` file, import warnings are printed to stderr as
### `render <file> -o <out.png> [--scale N] [--page NAME]`
The whole page (default the first) with its background, as png, jpg or webp. Large pages are scaled
down to fit 16384 px.
The whole page with its background, as png, jpg or webp. `--page` defaults to the first non-divider
page, as for `export`. Large pages are scaled down to fit 16384 px.
### `run <script.json|script.jsonl> [--in <file>] [--out <file>]`
+18 -9
View File
@@ -99,15 +99,24 @@ fit FigCraft's architecture:
collide with what a connected client makes, because a client's numbers continue above every id of
its space already in the document. Removed entries are part of the saved session state
(`SessionState::removed`).
- **Branches** of a file in a session stay with the person who made them; nothing about them goes
over the wire until a merge, which is an ordinary batch from that person (no message or format
change). So that the server takes the layers a branch made, a branch made in the session makes
its ids in its author's own client space, 2^24 above every id made there on the main file and the
author's other branches. Layers of the branch's base that main deleted during the session come
back with their ids (the server accepts re-creating deleted ids). Merging a branch whose new
layers, styles, variables or comments lie in another id space (one made offline or in an earlier
session) is refused by the app before anything is sent, since the server would refuse it (see
`crates/engine/src/sharing/branches.rs`).
- **Branches** of a file in a live session sync across everyone when both sides announce the
`branches` capability in `Hello::client_version` (older clients never receive branch messages, and
clients connected to an older server keep branches local to their author). Right after `Welcome`,
the server sends `ServerMsg::Branches(Vec<SharedBranch>)` with each branch encoded as diffs from
the current main state (`base_diff` to base, `head_diff` to head; at most `MAX_SHARED_BRANCHES`,
64). Editors send `ClientMsg::Branch(BranchReq)` (`Create`, `Edit`, `UpdateFromMain`, `SetState`
for `Merged`/`Archived`) and peers receive `ServerMsg::Branch(BranchEvent)`. The server refuses
branch mutations from view or comment links, stamps `client` from the authenticated sender, checks
node/entry id spaces, geometry, and image entries on every branch change, and persists branches in
`SessionState::branches` and the server journal (`Journal::BranchCreate` / `BranchEdit` /
`BranchUpdateFromMain` / `BranchState`; `figcraft-server` falls back to decoding pre-branch
snapshots without `branches`). Each editor allocates new branch ids in their own client space,
2^24 above every id made there on the main file and its branches. When any editor merges a shared
branch, the merge goes out as one ordinary batch on main (the server accepts node and entry ids
that already belong to a kept shared branch), and peers with that branch tab open have it closed.
Merging an offline or earlier-session branch whose new layers, styles, variables or comments lie
in another id space is still refused by the app before anything is sent (see
`crates/engine/src/sharing/branches.rs` and `crates/engine/src/sharing/live/branches.rs`).
- Objects inside an entry are not separate objects: modes are part of their collection, a
variable's values per mode part of the variable and replies part of their comment thread. Two
people adding a mode to the same collection, editing different modes of one variable, or replying
+5 -3
View File
@@ -1,6 +1,6 @@
# Collaboration parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-26 · **Change:** minor (legacy welcomes without a reconnect secret are accepted with their explicit access level, and reconnects re-authenticate with the share link (#2365); a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); shared branches sync across live sessions and survive `figcraft-server` restarts, capability-gated on `branches`; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
@@ -16,10 +16,10 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Live cursors, selections, viewports; follow / observation mode; spotlight | yes | **done, in live sessions**: named cursors (one name for live sessions and comments: Preferences ▸ Your name, also in the Share popover and the Join dialog, kept in the browser too; a rename shows at once in the sessions you're in, #1380), selection outlines, avatars (an AI agent attached over MCP also shows its avatar and an outline around the layers it last edited or selected while it works, in or out of a session, #1416), follow (click an avatar), others' text carets and selected characters with their names, a note when two people type in one layer; spotlight (your avatar's menu, `collab.spotlight`): everyone follows your view and page, people who join later too, anyone who moves their view stops following and a banner offers to follow again, a newer spotlight takes over. Left: polish (no accounts, so anyone in the session can spotlight) | 2–4 |
| Cursor chat, audio, high-fives | yes | **partial, in live sessions**: cursor chat (`/` opens a bubble at your pointer; everyone sees it as you type, it fades a few seconds after the last change, Enter sends and Escape takes it back, 100 characters; `collab.cursorChat` for agents); sent as ephemeral presence the host checks and rate-limits, never stored. No audio, high-fives or emote reactions | 2–5 |
| Opening page of a shared file | the page a link names, else the first | **partial**: a file joined from a server opens on its opening page, which is the open document's current page: the page the file was opened on (the page stored in the file when it was opened, else the first page) until someone sets one, not always the first page; a later page switch, a save on another page or publishing does not move it (a local save stamps the page being viewed into the saved file's bytes for the next time that file is opened, but does not change the open document's opening page, which is the synced property, and a link cannot name a page; `page.setOpening {id?}` (the pages list's Set as opening page, the MCP server too) writes it as a document change, one undo step, so everyone who joins afterwards lands on it, unless a spotlight is on, in which case they follow the spotlighter's page instead; each viewer's own page stays their own (#1817) | — |
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 |
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. Older servers whose `Welcome` ends after its access level can be joined without a reconnect secret; reconnects authenticate with the share link again, without reusing an unauthenticated client id. No accounts, teams or projects | 8–17 |
| Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) |
| Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Developer Mode compares a ready-for-dev layer with its state when marked) | — |
| Branching and merging | yes (paid plans) | **done, also in live sessions**: branches saved in the `.figcraft` file, each opened in its own tab; Review and merge shows both sides' changes since the branch was made and the conflicts (the same property on both sides, or a layer deleted on one side and edited on the other), each resolved for the branch or main; merge as one undo step (the branch is archived, the main file's history gets a version for the merge), update from main, archive. Each branch keeps its own version history (saved, viewed and restored on the branch tab, kept when it is merged or archived; entries for its creation and updates from main); fills, strokes, effects, layout grids, export settings, guides, interactions, annotations and Developer Mode resources merge item by item. Auto layout settings (a frame's and a child's) merge field by field, each field changed both ways a conflict of its own (`<id>/layout.padding`), and sizes and places auto layout works out (hugging, filling, a child's place) or that an instance takes from its main are no conflict: the merged file lays them out again. In a live session a branch stays with its author (its ids in their own client space, far above the main file's) and merging it is one edit everyone gets; peers' edits merge against the branch's own base and conflicts resolve as offline; a view link refuses merging. Left: others in the session can't see or open your branches (the server would have to keep them); text runs conflict as a whole; a branch made offline that adds layers merges only outside a session | 1–2 |
| Branching and merging | yes (paid plans) | **done, also shared in live sessions**: branches saved in the `.figcraft` file, each opened in its own tab; Review and merge shows both sides' changes since the branch was made and the conflicts (the same property on both sides, or a layer deleted on one side and edited on the other), each resolved for the branch or main; merge as one undo step (the branch is archived, the main file's history gets a version for the merge), update from main, archive. Each branch keeps its own version history (saved, viewed and restored on the branch tab, kept when it is merged or archived; entries for its creation and updates from main); fills, strokes, effects, layout grids, export settings, guides, interactions, annotations and Developer Mode resources merge item by item. Auto layout settings (a frame's and a child's) merge field by field, each field changed both ways a conflict of its own (`<id>/layout.padding`), and sizes and places auto layout works out (hugging, filling, a child's place) or that an instance takes from its main are no conflict: the merged file lays them out again. In a live session whose server supports shared branches (`branches` capability), branch creation, edits, updates from main, and merge/archive state sync across everyone in the session and persist across `figcraft-server` restarts (up to 64 branches; view and comment links cannot mutate branches; older clients and servers fall back to local-only branches); any editor can open, co-edit, review and merge a peer's branch, with each editor allocating ids in their own client space far above main's and merging as one edit everyone gets (closing open tabs on peers). Left: text runs conflict as a whole; a branch's own version history stays local; a branch made offline that adds layers merges only outside a session | 1–2 |
| Team / organization libraries | yes | **partial**: a file's library is published to `figcraft-server` under the file and enabled in other files by a share link (per-asset versions, background update checks, overrides kept), usage counts per component and file, swapping a library by names ([components-parity](components-parity.md), [server.md](server.md#team-libraries)). No team-wide library list, accounts or analytics over time | 4–8 |
| Notifications, activity | yes | no | with sharing |
@@ -27,6 +27,8 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | M10, gap 17: shared branches sync across live sessions. Capability-gated on `branches` in `Hello::client_version` (`ServerMsg::Branches` / `Branch`, `ClientMsg::Branch` with `Create`, `Edit`, `UpdateFromMain`, `SetState`), persisted in `SessionState::branches` and the server journal (with fallback decoding for pre-branch `figcraft-server` snapshots). Any editor can open, co-edit, update from main, review, archive and merge another peer's branch (remote merges/archives close open branch tabs on peers and switch back to main); view and comment links are refused; node/entry id spaces, geometry and image entries are validated on every branch mutation; older clients and servers stay compatible (local-only branches). Tests: `collab::branch_tests`, `engine::branch_live_tests`, `figcraft-server::server_tests::shared_branches_sync_and_survive_a_server_restart`, `figcraft-server::disk::tests::decode_snapshot_reads_pre_branch_v1_snapshots`. Numbers unchanged. |
| 2026-11-16 | patch | M9, #2365: a server predating reconnect secrets sends a complete `Welcome` ending at `access`; postcard does not honor a missing trailing field through `serde(default)`. The client reads that exact legacy layout, preserves access, and keeps strict size, version and message-boundary checks. Native and browser transports use this reader; reconnects without a secret send a fresh authenticated hello. Covered by codec and connection-driver regressions. A patched 0.15.1 desktop build was also checked against the public service with separate view-only access and annotation reads; writes remained denied. The public server still needs upgrading. Numbers unchanged. |
| 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. |
| 2026-11-04 | minor | M9, #1817: a file on a server opened on the page that was current at publish time, with no way to change it: `DocProp::CurrentPage` was synced but nothing wrote it. `page.setOpening {id?}` (the pages list's "Set as opening page", the MCP server too) writes the opening page as a document change, one undo step, so everyone who joins afterwards lands on it; a divider is refused; nobody's own page moves. Tests: `page_opening_tests`, `collab_live_tests::the_opening_page_syncs_and_moves_no_ones_view`. Numbers unchanged. |
| 2026-11-04 | minor | M9: a session you joined no longer turns into a local file by itself. A dropped connection reconnects until you leave (a minute's pause after each 12 attempts, a pause Retry now skips); only the host ending the session and refusals that are for good stop it; queued messages go out paced. While disconnected the tab shows a red mark and a strip across the canvas says so; a session that ended stays on its tab with Try again, Save a copy and Dismiss |
+7 -2
View File
@@ -1,6 +1,6 @@
# Components, variants, styles and variables parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-23 · **Change:** minor (with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; 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; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamedLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; 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; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every Line truncated
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
@@ -56,7 +56,8 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Library updates available; overrides kept | done | a library file saved again within two seconds of being read, at the same length, is read again (its time stamp can't prove it unchanged; #652) |
| Team libraries: publish to a `figcraft-server` under the file, enable by a share link (a view link reads it), background update checks | done | [server.md](server.md#team-libraries); no team-wide library list or accounts ([gaps](gaps.md) #10) |
| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, with their insertions and detachments over the same periods, no modes; no chart |
| Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step |
| Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step; copies nothing used before the swap (imported, never placed or bound) are removed and listed in `dropped` (#2569) |
| Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step; a library copy that stays (no match, or another library's) links the swapped styles and variables too, so instances placed after the swap look like those placed before it (`library_swap/tests.rs`, #2568) |
## Styles and variables
@@ -67,6 +68,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) |
| Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) |
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); Create variable makes the variable in the group shown, and a row's rename edits the name's last part; the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 |
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); variables keep the order they are put in: Move up / Move down (Alt+↑ / Alt+↓) on a row and Sort A to Z / Z to A on a collection or group, numbers by value (`variable.move`, `variable.sort`, #2633); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 |
| Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay |
| Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show |
| Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values |
@@ -87,6 +89,9 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| 2026-11-19 | patch | M3: overrides found by comparing a layer with its main (`rebase_instance`: linking instances after a Figma or REST import, detaching an outer instance, restoring a main) counted values only, so a layer bound to a variable the main layer doesn't bind, resolving to the main's colour, wasn't an override; the next copy or edit of the main (a library update reaching another file) reset it to the main's unbound paint. Icons inside buttons of a design system imported from Figma lost their colour variable this way in the files using it. A binding that differs from the main's is now an override there, and an edit that sets the value back to the main's (hiding and showing the fill) no longer clears an override the binding still makes; `fill` and `fills/0/color` count as one binding. Tests: `nested_binding_tests` |
| 2026-11-19 | patch | M3: with a group selected in the Local variables window, + Create variable named the new variable without the group, so it went to the collection's top level and the table, showing the group, didn't show it; only All variables did. It's now made in the group shown (`space/Number`), as in Figma, where duplicating already kept the group. Renaming a variable in its row edited its whole name while the row shows the last part, so typing a name over a new grouped variable moved it out of the group; the field now edits the part shown and keeps the group (the Edit variable window still edits the whole name), and ignores a name of slashes alone. Creating a collection clears the group shown. Tests: `variables_group_create_tests` |
| 2026-11-18 | patch | M3: enabled libraries were read only while the Assets panel showed, so after a file was opened the Design panel's style pickers offered none of their styles (a library's text styles read "No text styles yet") until the Assets tab had been opened. They are refreshed from the app's background tick now, a local library not read yet at once. The style picker has a source menu under its search field, as in Figma: All libraries (the default), This file, or one enabled library. Test: `style_picker::tests::a_reopened_files_text_styles_picker_lists_its_librarys_styles_without_the_assets_tab` |
| 2026-11-23 | patch | M3, #2569: `library.swap {from, to}` removes `from`'s copies that nothing in the file uses before it starts (a component imported with `library.import` but not placed, a variable imported but not bound), as `library.remove` does, but its result didn't say so: `{"components": 0, "unmatched": [], "removed": true}` after an imported component had been deleted. The result now names them in `dropped` (`component auth-button`, `variable Theme/accent`, `collection Theme`), apart from copies that went because what used them moved to `to`. Test: `library_swap/tests.rs` (`swap_lists_the_unused_copies_it_removes`) |
| 2026-11-27 | minor | M3, #2633: variables in the Local variables window stayed in creation order. A row's menu has Move up and Move down (Alt+↑ / Alt+↓ with one row selected), moving it past its neighbour in its group; a collection's and a group's menus have Sort A to Z and Sort Z to A, by name with each run of digits compared as a number, so `50, 100, 200 … 950` come in that order. The order is the stored one, so files, exports and the variable pickers follow it. New commands `variable.move {variables, before?}` and `variable.sort {collection, group?, descending?}`, one undo step each. Drag to reorder is not built. Tests: `variables_editor_tests::moving_variables_reorders_their_collection_only_and_undoes`, `variables_editor_tests::sorting_orders_numbers_by_value_within_the_group_asked`. Grade unchanged. |
| 2026-11-23 | patch | M3, #2568: `library.swap {from, to}` re-pointed style links and variable bindings only on layers outside the read-only library copies. A copy the swap keeps (a component of `from` that `to` has no match for, or another library's component using `from`'s style) kept `from`'s style and variable, so instances placed after the swap showed the old colours while those placed before showed the new ones. The swap now re-points the copies' own layers too, with the same maps, and `from`'s style and variable copies that nothing links any more go. A layer's explicit mode for one of `from`'s collections stays next to `to`'s while a variable of that collection is left on `from` (no match), so that variable keeps its mode instead of falling back to the default. Tests: `library_swap/tests.rs` (`swap_repoints_the_styles_and_variables_of_component_copies_it_keeps`, `swap_keeps_the_mode_of_a_collection_that_still_has_a_variable_on_the_old_library`) |
| 2026-11-19 | patch | M3, #2414: a kit's style used by a component of a second library reached a file linking both as a second, unbound copy (`<auth>:<kit>:S:1`) frozen in the kit's default mode, so a mode set on the kit's collection didn't colour it (from two hops on, every such style). Publishing now keeps the variables the published styles bind and where the file's copies of other libraries' styles, variables and collections came from; importing files such a copy under that library when the file links it, so it is the file's own bound copy. Test: `library_style_hops_tests::a_kit_style_through_another_library_is_the_kits_bound_copy`; the issue's four-file chain renders Brand and Alt everywhere. Grade unchanged. |
| 2026-11-19 | patch | M3, #2349: with one variant of a set selected, the Design panel's variant property dropdowns showed the set's default values, and choosing a value set the default, so the variants swapped places. They now show the selected variant's own values (hover: "This variant's value"), and choosing one renames that variant only; with the set selected they still set its default. Test: `variant_own_value_tests::a_selected_variants_dropdown_shows_and_sets_its_own_value`. Grade unchanged. |
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
+4
View File
@@ -3,6 +3,8 @@
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7)
>
> **2026-11-24 patch:** vector code export uses a self-contained SVG asset instead of inventing a box around its bounds: web markup embeds the node-local SVG as a data URI inside a node-sized wrapper with the SVG's painted bounds, and CSS, SwiftUI and ArkUI no longer draw a rectangle from the path stroke (#2270).
>
> **2026-11-19 minor:** Screen sizes: a frame or section can be marked as the mobile, tablet or desktop version of a design and carry rules for other sizes in the Responsive annotation category, from the Inspect tab or `responsive.set`, `responsive.rule` and `responsive.list`.
**Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect
to the code components of a repository (with their imports, also inside generated layer trees),
@@ -20,6 +22,7 @@ repository, third-party integrations. Remaining: 1–2 h.
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) |
| Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours |
| Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
| Screen sizes (which version of a design a frame is, rules for other sizes) | done | ours: the incumbent has no such field. A frame or section is marked mobile, tablet or desktop and named after the design it is a version of (layer data, so no file format change); rules are notes in the Responsive annotation category. Agents read only what was stated (`responsive.list`, `design_context`'s `responsive`); nothing is inferred from names or sizes |
| Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) |
| Focus view (one frame, previous / next) | done | |
| Compare changes (before/after side by side or overlaid, property diffs) | done | against the snapshot taken when a frame was first changed after it was marked ready, or any saved version (`dev.compare {version}`; the view's Compare with menu); a frame that isn't ready for dev compares with versions |
@@ -34,6 +37,7 @@ repository, third-party integrations. Remaining: 1–2 h.
| Date | Change | Summary |
|---|---|---|
| 2026-11-24 | patch | Vector code export embeds a self-contained SVG asset, not a rectangle made from the path's stroke (#2270). Percentages and hours unchanged. |
| 2026-11-19 | minor | Screen sizes: the Inspect tab's Screen sizes section, `responsive.set` (frames and sections; `group: null` goes back to the frame's name), `responsive.rule` (a note in the Responsive annotation category, with `annotation.add`'s limits; pages refused) and `responsive.list`. Developer Mode makes these edits, like its annotations. Stored values that aren't a version are ignored. `inspect.designContext` returns the target's under `responsive` and names the missing breakpoints only when nothing was stated. Percentages and hours unchanged |
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. |
| 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged |
| 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
+48 -5
View File
@@ -1,6 +1,6 @@
# Where FigCraft falls short of Figma
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); 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 pasteLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (gap 7: drop shadows of opaque shapes are cast from their outline, where they show, at the resolution their blur needs; gap 7: a clipping frame that takes in the whole pixmap costs no layer, mask or copy; gap 7: a patch goes into the kept canvas image row by row; gap 7: the browser build compiles the rasteriser for speed; gap 7: a moved point redraws its vector around it only; gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); 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 fLine truncated
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
@@ -30,7 +30,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
| 14 | Variables: extended collections checked on real libraries (the tail landed 2026-10-12) | Feature | 0–1 | [components-parity](components-parity.md) |
| 15 | Prototyping: media triggers and actions; controllers on macOS, Linux and FreeBSD (controller buttons on key/gamepad triggers, widgets in prototypes landed) | Feature | 2–5 | [prototyping-parity](prototyping-parity.md) |
| 16 | Dev Mode: renaming the file in Dev Mode to check; the editor extension is left to the MCP server (publishing mappings from the code repository landed 2026-10-30) | Feature | 1–2 | [dev-mode-parity](dev-mode-parity.md) |
| 17 | Branching: text runs merged whole, branches only their author sees in a live session (branches in live sessions, export settings and guides item by item, and history entries for creation and updates landed 2026-10-24) | Feature | 1–2 | [collaboration-parity](collaboration-parity.md) |
| 17 | Branching: text runs merged whole, branch version history stays local (shared branches in live sessions landed 2026-11-26; live branches, export settings and guides item by item, and history entries for creation and updates landed 2026-10-24) | Feature | 1–2 | [collaboration-parity](collaboration-parity.md) |
| 18 | Display P3 on screen: blocked upstream (egui-wgpu picks an 8-bit sRGB surface); gamut warning and soft-proof sRGB landed, as did several windows | Hardware | 4–8 | [hardware-parity](hardware-parity.md) |
| 19 | AI features | AI | 30–60 | [target-app-parity](target-app-parity.md) |
| 20 | Mobile apps (view, mirror, comment) | Platforms | 20–40 | [hardware-parity](hardware-parity.md) |
@@ -287,6 +287,39 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
sixteenth of the pixels first, then refined. With no measure to go by (the first render, another
page, a zoom after quick renders), a watchdog thread previews any such render still running
after 12 ms (desktop only; the browser renders inline).
- **Landed (2026-11-24):** a moved point redraws its vector around it only. A point dragged in the
vector editor changed the vector, so its whole box was drawn again; zoomed to the vector, as the
editor does, that is most of the view, past the share a patch may cover (60%), and every frame of
the drag was a full render. A vector that differs only in where its points and handles are now
redraws the segments that moved and their neighbours (whose joins and rounded corners follow
them), as far out as its stroke reaches: 41,866 of a view's 328,801 pixels for a point of a
filled twelve-tooth zigzag that fills the view (`a_moved_point_redraws_the_vector_around_it_only`).
Dashes, width profiles, brushes, gradients and images, effects, masks and open filled paths
depend on the whole outline: those vectors are drawn again whole.
- **Landed (2026-11-24):** a patch goes into the kept image row by row. A re-rendered area was
cut out of its render into a pixmap of its own and that drawn onto the kept image: two more
passes over it, which for simple content took far longer than rendering it. A 4.7 megapixel
patch of two flat fills (a 4112 × 2292 view, release, one thread): 16.9 → 2.8 ms a frame.
- **Landed (2026-11-24):** a clipping frame that takes in the whole pixmap costs no layer, mask
or copy there. Close up, the view (or the band or patch of it being drawn) lies inside its
clipping frames; each still copied the pixmap, filled a mask for it and put the copy back
through the mask pixel by pixel, because a frame with an edge off screen on a fraction of a
pixel never took the whole-pixel path. A clip that takes in the whole pixmap now draws its
children as they are, edges at or past the pixmap's count as whole, and rows of a mask that are
all in or all out are copied or kept in one piece. A view inside four nested clipping frames
at 1,933% on a 2× display (4112 × 2292 device pixels, release, one thread): 119 → 87 ms, a band
of it 18 → 12 ms.
- **Landed (2026-11-24):** a drop shadow of a shape or frame with opaque paints is cast from its
outline: drawn only where it shows on the pixmap, and a blur of 8 device pixels or more is drawn
smaller, blurred and scaled back up, on a grid that follows the shape (bands, patches and whole
views draw the same shadow). A frame that doesn't clip counts while its children stay inside its
box. The shadow was blurred at full resolution from a copy of the layer that reached past the
pixmap by the shadow's reach (1,392 pixels each way for a 16 px blur at 1,933% on a 2× display),
once for every band of a full render: 17.4 s for one render of the mobile app template's trail
card in the browser (0.18.1, 4112 × 2292 device pixels). `zoomed_card_timings` (release, one
thread, that view): 8 bands 4,576 → 152 ms, the slowest band 598 → 21 ms. Layers that aren't
their outline (see-through fills, groups, children past the box, layer blurs) cast from their
pixels as before, and are as slow close up; an edit inside the card still redraws all of it.
- **Landed (2026-10-29):** the browser draws a zoom's full render a band at a time (`Retained::begin`,
`Steps`; at least a band a frame and at most eight bands, so a frame draws a part of the render
where it drew the whole of it: 0.7–1.4 s where the render took 3.7–4.0 s in the measurement of
@@ -542,10 +575,15 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
entries for its creation and each update from main. Engine tests through a session server with
several people, a fuzz test with random real commands (export settings and guides included,
offline and live) and a junk-parameter sweep of the branch commands in a session.
- **Landed (2026-11-26):** shared branches in live sessions: branch creation, edits, updates from
main, and merge/archive state sync across everyone in a session (capability-gated on `branches`,
capped at 64 branches, persisted in `figcraft-server` snapshots and logs with fallback decoding
for existing snapshots). Any editor can open, co-edit, review, archive and merge a peer's branch;
remote merges and archives close open branch tabs on peers; view and comment links cannot mutate
shared branches; older clients and servers fall back to local-only branches.
- **Missing:** text runs still conflict as a whole (runs are character ranges into the text, so
lining them up item by item would need a text diff, not positions); branches in a live session
are their author's only (others can't see or open them: that needs the server to keep them);
a branch made offline that adds layers merges only outside a session.
lining them up item by item would need a text diff, not positions); a branch's own version history
stays local; a branch made offline that adds layers merges only outside a session.
- **Estimate:** 1–2 h.
### 18. Display P3 on screen (several windows landed)
@@ -615,6 +653,11 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
| Date | Change | Summary |
|---|---|---|
| 2026-11-24 | minor | Gap 7: a point moved in the vector editor redraws the segments that moved and their neighbours, not the vector's whole box (a full render of the view when the vector fills it). Numbers unchanged |
| 2026-11-24 | minor | Gap 7: the browser build compiles tiny-skia, tiny-skia-path and figcraft-render at opt-level 3 (the rest stays at "z" for the size gate): a full render of a close-up view took 117 ms where it took 296 ms in a 0.18.1 build; the bundle grows by about 0.2 MB. Numbers unchanged |
| 2026-11-24 | minor | Gap 7: a re-rendered area is copied into the kept canvas image row by row, not cut out and drawn (16.9 → 2.8 ms a frame for a 4.7 megapixel patch of flat fills, one thread). Numbers unchanged |
| 2026-11-24 | minor | Gap 7: a clipping frame that takes in the whole pixmap draws its children without a layer, a mask or a copy back; frame edges past the pixmap count as on whole pixels (119 → 87 ms for a view inside four nested clipping frames close up, one thread). Numbers unchanged |
| 2026-11-24 | minor | Gap 7: a drop shadow of a shape or frame with opaque paints is cast from its outline, drawn where it shows and blurred at the resolution its radius needs (`zoomed_card_timings`: 4,576 → 152 ms for a card close up, 8 bands, one thread). Numbers unchanged |
| 2026-11-19 | minor | Gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`; a block is as tall as its lines and keeps its text plain code, #2237); the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. |
| 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. |
| 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. |
+1
View File
@@ -51,6 +51,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import).
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. |
| 2026-11-24 | minor | M8: drop shadows of opaque shapes and frames are cast from their outline, drawn where they show and blurred at the resolution their radius needs: a card with a 16 px shadow at 1,933% on a 2× display renders in 152 ms (8 bands, one thread) where it took 4,576 ms. Tests: `outline_shadow_tests`; timings: `zoomed_card_timings`. Numbers unchanged |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. |
| 2026-11-10 | patch | M10, #1343 (also #1422, #2233): Windows: the window no longer draws below a hidden caption. FigCraft draws its own title bar on Windows and opens undecorated windows, but winit 0.30 still gives them `WS_CAPTION` and `WS_BORDER`; on some systems the desktop compositor reserves that caption, so the content was drawn about 30 px low (a black band above it) while clicks kept the client coordinates and landed above what was drawn. A per-frame step (`apps/figcraft/src/window_frame.rs`, safe `winsafe` calls, Windows only) clears `WS_CAPTION` and `WS_BORDER` from every FigCraft window, the main one and the others, keeping the sizing border and window buttons so edge resizing and snap work, and writes only when a style changed (winit puts them back on maximize and restore). The same fix as DesignCraft #2139 and PhotoCraft #2401; the maximize-to-work-area trim from DesignCraft is left for a later change. Not run on a Windows machine that shows the offset: the style math and the per-frame hook are tested, the window itself needs a live check. Tests: `window_frame_tests`. Numbers unchanged |
+22 -3
View File
@@ -374,7 +374,10 @@ Or in a project's `.mcp.json`:
tracking shortcuts, a canvas drag) detaches that field's variable; fields the edit
left as they were stay bound.
`variable.addMode {from}` duplicates a mode, `variable.moveMode {collection, mode, to}` reorders
(index 0 is the default mode, which layers on Auto follow). `variable.update {codeSyntax: {WEB?,
(index 0 is the default mode, which layers on Auto follow). `variable.move {variables, before?}`
reorders variables within their collection (the order the Variables window and the pickers list),
`variable.sort {collection, group?, descending?}` sorts them by name, numbers by value (50 before
100). `variable.update {codeSyntax: {WEB?,
iOS?, ANDROID?}}` sets code names (`""` clears); generated CSS uses the Web one, SwiftUI the iOS one and
Compose the Android one (a variable without one keeps its value there).
- **Live previews**: `text.preview {command, params}` shows what `style.apply`,
@@ -439,7 +442,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
| `components` | By id: `name`, `type`, `properties` with variants, `codeLinks` |
| `fonts` | `family`, `styles`, and whether it's `installed` |
| `assets` | What `inspect.assets` lists, for the layers in the tree |
| `missing` | `{what, why}`: what the design doesn't specify. Always says that the file stores no breakpoints |
| `responsive` | What the designer stated about other screen sizes, as `responsive.list` gives it for the target: `explicit`, `versions`, `rules`. Nothing is inferred from names or sizes |
| `missing` | `{what, why}`: what the design doesn't specify. Says that the file stores no breakpoints unless `responsive` is `explicit` |
| `truncated` | When `depth` or `maxNodes` cut the tree, or `maxBytes` made the tool ask for fewer layers: `layersLeftOut`, `assetsLeftOut`, `depth`, `maxNodes`; and `variables` when aliases went deeper than the 10,000 variables followed |
Each layer in `nodes` has `id`, `name`, `type` and:
@@ -1124,7 +1128,9 @@ most when it can't be reached).
by name in their set, styles by name and type, variables by collection, name and type, modes by
name), keeping overrides; one undo step → `{components, styles, variables, unmatched: [names
still from `from`, including this file's collections that extend one of its collections],
removed (nothing of `from` was left, so it was removed)}`.
dropped: [`from`'s copies nothing used before the swap, which it removed rather than moved: a
component imported but not placed, or whose instances were deleted; a variable imported but not
bound], removed (nothing of `from` was left, so it was removed)}`.
### Overrides and variants
@@ -1966,6 +1972,19 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path
the defaults (old files open with the defaults). In the app, with nothing selected, the Inspect
tab filters the callouts by category and edits the categories (colour, name, delete, add); each
note has a category menu.
- **Screen sizes:** a file has no breakpoints, so the designer states what happens at other sizes and
agents read that rather than guess. Undoable `responsive.set {ids?, viewport, group?}` marks frames
or sections as the `mobile`, `tablet` or `desktop` version of a design (`null` clears the mark;
`group` names the design, and `null` goes back to each frame's name). Undoable `responsive.rule {id?,
text}` adds a note to the **Responsive** annotation category, making the category if the file lacks
it; the note keeps to `annotation.add`'s limits, and pages are refused. Developer Mode makes both
edits, as it does annotations. `responsive.list {}` → `{versions: [{group, frames: [{id, name, viewport,
width, height, page}]}]}`, narrowest first; with `ids` or `id`, what is stated about those layers,
the layers above them and those inside them: `{explicit, versions, rules: [{id, layer, text}],
truncated?}` (`truncated`: too many layers to read every rule). Nothing is inferred from names or
sizes, and stored values that aren't one of the three versions are ignored. `design_context` gives
the same for its target under `responsive`. Marks are layer data (`figcraft.viewport`, `figcraft.viewportGroup`), so they save and sync
with no change to the file format. In the app, a frame's or section's Inspect tab has a **Screen sizes** section.
- **Ready for dev:** frames at the top of a page or section, and sections, carry a handoff status
(`node.set {devStatus: none|readyForDev|completed}`; other layers are refused a status).
`inspect.readyForDev {status?: readyForDev|changed|completed|any, page?}` lists them across pages
+2 -1
View File
@@ -1,6 +1,6 @@
# FigCraft parity with Figma
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-27 · **Change:** minor (M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS)
The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md)
summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is
@@ -652,6 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | patch | M8, #2635: a stroked layer showed a thin light line along the outer edge of an inside stroke (the fill under the stroke's anti-aliased edge showed through it), and what lies behind showed between an outside stroke and the fill. Where the stroke hides what is under it (its top paint an opaque solid colour, normal blend, one weight all round, no dashes, width profile or brush), the fill now reaches the middle of the stroke, so neither edge has the fill or the background showing through: rectangles, frames and ellipses by their inset or grown outline, other shapes and text by their outline less or plus the centred stroke. Translucent, gradient and image strokes and even-odd outlines fill as before. Test: `stroke_fringe_tests::an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge` (fails on main). |
| 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged |
+2 -1
View File
@@ -58,7 +58,7 @@ interaction feel only partly compared: the interactions measured so far, case by
| Item | Status | Notes |
|---|---|---|
| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child, as in Figma (#2360; `a_drag_from_a_child_of_a_selected_frame_moves_the_frame`, `a_click_on_a_child_of_a_selected_frame_selects_the_child`); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (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 | |
| Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | Cmd/Ctrl-click, and hover with it held, reach through a frame, component or instance nested in another layer where it has no visible fill (a hidden or 0% fill and its stroke don't count): the layer under it is picked, or the top-level frame when nothing else is there. A device chrome instance over a screen no longer catches every pick. Cmd/Ctrl + double-click reaches the same layer and edits it at once (text editing for a text, vector edit mode for a shape). Top-level frames and frames directly in a section keep their box, and a plain click or double-click still picks a nested frame by its box (measured in Figma's web app, 2026-11-20; `cmd_click_reaches_through_an_unfilled_nested_frame`, `cmd_double_click_edits_the_layer_under_an_unfilled_instance`) |
| Select layer menu (every layer under the click) | done | shown only with more than one layer under the pointer; locked layers are listed with a padlock in the leading column and are selectable there, as Lock and unlock layers' note says (measured in Figma's web app, 2026-11-10; the "more than one layer" gate was measured on a single locked layer only) (`select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`) |
| Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) |
| Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming |
@@ -232,6 +232,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
| 2026-11-15 | patch | M1: Frame selection (Alt+Cmd/Ctrl+G) gave the new frame the white fill a drawn frame gets, which covered the page behind the framed layers. It now has no fill; a frame drawn with the Frame tool keeps its white fill. Test: `frames_behaviour_tests` |
| 2026-11-18 | patch | M1: a double-click with Shift held, on a layer in another artboard than the selected one, left only that artboard's layer selected, so layers nested in neighbouring artboards couldn't be selected together. It now goes a level deeper as a double-click does and keeps the rest of the selection: the selected layer it went into, or the layer a click would select there, is replaced by the one a level below, as in Figma. Where nothing on that branch is selected it starts beside the selection, just inside the deepest layer the branch shares with a selected one, so a Shift double-click on the next row of a list adds that row's label beside the selected label instead of collapsing the selection to the list. The selection it works from is the one before the double-click's two clicks, which Shift had already toggled. Test: `shift_double_click_tests` |
| 2026-11-15 | patch | M4: the eyedropper (I, Ctrl+C on macOS) gave a selected layer that had only a stroke a new fill. Such a layer now takes the colour on its stroke; other layers take it on their fill as before, and a mixed selection changes in one undo step. With a colour picker open on a fill or a stroke, the shortcut samples for that paint, as the picker's own eyedropper button does. A swatch beside the pointer shows the colour under it, read from the canvas image already on screen. Tests: `eyedropper_stroke_tests`, `colorpicker_eyedropper_tests` |
| 2026-11-21 | patch | M1: Cmd/Ctrl-click caught a nested frame, component or instance across its whole box, so an unfilled overlay (a device chrome instance over a screen) took every deep pick inside it. It now reaches the layer under the overlay's empty parts, as in Figma: a nested frame-like layer counts only where it has a visible fill, hover with Cmd/Ctrl held shows the same pick, and Cmd/Ctrl + double-click edits that layer (a text or a shape's points). Plain clicks, plain double-clicks and boards are unchanged. |
| 2026-11-19 | patch | M4, #2338: superscript and subscript were drawn (#1868) but nothing in the interface set them. Type settings ▸ Details now starts with Position: None, Superscript (X²) or Subscript (X₂), for the selected text layers, through `text.setFeatures` (`sups`, `subs`; choosing one clears the other). It shows the layers' current position, none when they differ. Raising a range of characters on its own needs per-run features and is left for a separate change. Test: `typography::variable_tests::details_position_sets_superscript_subscript_or_neither`. |
| 2026-11-19 | patch | M1, #2447: Shift did nothing with the Pencil: a stroke stayed freehand while the Line tool and the Pen keep theirs to 45° steps. With Shift held, the Pencil (and the Marker and Highlighter) now draws one straight segment from where the stroke started to the pointer, at the nearest 45° step; the preview shows it. A Shift-click without a move draws nothing, as before. Tests: `pencil_shift_tests`. |
| 2026-11-19 | patch | M3, #2347: with one component or component set selected, the Design panel's header said only "Component" or "Component set", so the selected one's name was only in the Layers panel. It now shows the name after a component icon (cut short with an ellipsis clear of the quick actions), with the type, and the whole name when cut, on hover. Other layers keep their type. Test: `component_header_tests::the_header_names_the_selected_component_or_set`. |