mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # docs/gaps.md
This commit is contained in:
commit
00439a3bb5
34 files changed
+2522
-122
No files matched your search
+2
-1
@@ -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; 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
|
||||
> **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
|
||||
@@ -379,6 +379,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
|
||||
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
| 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-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it; `bound` holds the ids `meta.variables` is keyed by for variables of the exported collections, so an export filtered by `collections` can name variables it doesn't include), and `variable.import` reads it back (styles merged by name, bindings re-pointed; a binding to a variable the JSON lacks is kept without a warning when the existing style already holds that same variable, and otherwise dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only |
|
||||
| 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. |
|
||||
|
||||
@@ -189,9 +189,13 @@ fn guests_join_and_see_each_other() {
|
||||
let Some(Event::Welcome { info, peers }) = ap.events.iter().rev().find(|e| matches!(e, Event::Welcome { .. })) else { panic!("no welcome") };
|
||||
assert_eq!(info.name, "Ada");
|
||||
assert!(
|
||||
ap.events.iter().any(
|
||||
|e| matches!(e, Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty())
|
||||
),
|
||||
ap.events.iter().any(|e| matches!(
|
||||
e,
|
||||
Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty()
|
||||
) || matches!(
|
||||
e,
|
||||
Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::DeltaSnapshot(bytes), .. }) if !bytes.is_empty()
|
||||
)),
|
||||
"the welcome carries the document for the sync client"
|
||||
);
|
||||
assert_eq!(peers.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Hana"], "the host is already here");
|
||||
@@ -670,12 +674,21 @@ fn welcomes_are_packed_only_for_clients_that_read_them() {
|
||||
let addr: SocketAddr = invite.server.host.parse().unwrap();
|
||||
let mut old = Raw::connect(addr);
|
||||
let ClientMsg::Hello(h) = Client::hello(FILE, TOKEN, "Old", "") else { panic!("not a hello") };
|
||||
assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h })));
|
||||
assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h.clone() })));
|
||||
let Some(ServerMsg::Welcome { catch_up: CatchUp::Snapshot(plain), .. }) = old.next() else { panic!("no plain welcome") };
|
||||
let mut mid = Raw::connect(addr);
|
||||
assert!(mid.send(&ClientMsg::Hello(Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..h })));
|
||||
let Some(mut packed_welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = mid.next() else { panic!("no packed welcome") };
|
||||
message::unpack(&mut packed_welcome, 64 << 20).unwrap();
|
||||
assert!(matches!(packed_welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
|
||||
let mut new = Raw::hello(addr, TOKEN);
|
||||
let Some(mut welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = new.next() else { panic!("no packed welcome") };
|
||||
message::unpack(&mut welcome, 64 << 20).unwrap();
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
|
||||
let Some(mut delta_welcome @ ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }) = new.next() else {
|
||||
panic!("no delta snapshot welcome")
|
||||
};
|
||||
message::unpack(&mut delta_welcome, 64 << 20).unwrap();
|
||||
let delta_doc = Client::join(delta_welcome).unwrap().document().clone();
|
||||
let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone();
|
||||
assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document");
|
||||
host.stop();
|
||||
}
|
||||
|
||||
|
||||
+43
-22
@@ -86,10 +86,19 @@ impl Client {
|
||||
|
||||
/// Start from the server's `Welcome` (which must carry a snapshot).
|
||||
pub fn join(welcome: ServerMsg) -> Result<Client, Error> {
|
||||
let ServerMsg::Welcome { session, client_id, seq, catch_up: CatchUp::Snapshot(snapshot), processed, peers, access, secret } = welcome else {
|
||||
let ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret } = welcome else {
|
||||
return Err(Error::Protocol("expected a welcome with the document".into()));
|
||||
};
|
||||
let mut confirmed = Replica::from_snapshot(&snapshot)?;
|
||||
let mut confirmed = match catch_up {
|
||||
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?,
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
let limits = crate::Limits::default();
|
||||
crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?
|
||||
}
|
||||
CatchUp::Delta(_) | CatchUp::Packed(_) => {
|
||||
return Err(Error::Protocol("expected a welcome with the document".into()));
|
||||
}
|
||||
};
|
||||
confirmed.document_mut().set_client_id(client_id);
|
||||
let next_id = confirmed.document().next_id();
|
||||
Ok(Client {
|
||||
@@ -597,26 +606,13 @@ impl Client {
|
||||
CatchUp::Snapshot(snapshot) => {
|
||||
let mut confirmed = Replica::from_snapshot(&snapshot)?;
|
||||
confirmed.document_mut().set_client_id(self.id);
|
||||
self.confirmed = confirmed;
|
||||
self.seq = seq;
|
||||
// What the server accepted meanwhile is in the snapshot. Which of the batches since
|
||||
// were others' isn't known, so the steps check every value they wrote below.
|
||||
while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
|
||||
self.pending.pop_front();
|
||||
if processed.refused.contains(&p.batch_id) {
|
||||
self.refused(&p, offline());
|
||||
} else if p.kind != BatchKind::FollowUp
|
||||
&& let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
|
||||
{
|
||||
s.settle(p.kind);
|
||||
}
|
||||
}
|
||||
for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
|
||||
s.verify(&self.confirmed)?;
|
||||
}
|
||||
for p in &mut self.pending {
|
||||
p.rebased = true;
|
||||
}
|
||||
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
|
||||
}
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
let limits = crate::Limits::default();
|
||||
let mut confirmed = crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?;
|
||||
confirmed.document_mut().set_client_id(self.id);
|
||||
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
|
||||
}
|
||||
}
|
||||
if self.seq != seq {
|
||||
@@ -636,6 +632,31 @@ impl Client {
|
||||
Ok(self.flush(recompute))
|
||||
}
|
||||
|
||||
fn rejoin_with_confirmed(&mut self, confirmed: Replica, seq: u64, last_batch: u64, processed: &Processed) -> Result<(), Error> {
|
||||
let offline = || "it no longer applied when the connection came back".to_string();
|
||||
self.confirmed = confirmed;
|
||||
self.seq = seq;
|
||||
// What the server accepted meanwhile is in the snapshot. Which of the batches since
|
||||
// were others' isn't known, so the steps check every value they wrote below.
|
||||
while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
|
||||
self.pending.pop_front();
|
||||
if processed.refused.contains(&p.batch_id) {
|
||||
self.refused(&p, offline());
|
||||
} else if p.kind != BatchKind::FollowUp
|
||||
&& let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
|
||||
{
|
||||
s.settle(p.kind);
|
||||
}
|
||||
}
|
||||
for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
|
||||
s.verify(&self.confirmed)?;
|
||||
}
|
||||
for p in &mut self.pending {
|
||||
p.rebased = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A session that doesn't know this client (it restarted without its saved state) welcomed
|
||||
/// it as new: start over from its document; unconfirmed work and the undo history are gone.
|
||||
fn restart(&mut self, welcome: ServerMsg) -> Result<Vec<ClientMsg>, Error> {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Multi-seed mixed-version DST for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Document, NodeId};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::delta_snapshot::{decode_delta_snapshot, encode_delta_snapshot};
|
||||
use crate::delta_snapshot_tests::{LEGACY_CLIENT_VERSION, assert_docs_json_eq, design_system_doc};
|
||||
use crate::message::{CatchUp, ClientMsg, Hello, ServerMsg};
|
||||
use crate::sim::Rng;
|
||||
use crate::{Client, Limits, NoRecompute, Outgoing, Server};
|
||||
|
||||
fn deliver_outgoing(clients: &mut [(Client, Hello, bool)], outs: Vec<Outgoing>) {
|
||||
for out in outs {
|
||||
match out {
|
||||
Outgoing::All(m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Outgoing::To(target, m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() && c.id() == target {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Outgoing::Others(skip, m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() && c.id() != skip {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnect_dst_client(server: &mut Server, clients: &mut [(Client, Hello, bool)], idx: usize) -> (bool, bool) {
|
||||
let (c, base_h, delta_capable) = &mut clients[idx];
|
||||
let ClientMsg::Hello(mut rh) = c.reconnect(base_h.clone()) else { panic!("expected Hello") };
|
||||
if !*delta_capable {
|
||||
rh.client_version = base_h.client_version.clone();
|
||||
}
|
||||
let (id, outs) = server.join(rh).unwrap();
|
||||
let welcome = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let is_delta_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. });
|
||||
let is_legacy_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. });
|
||||
let follow = c.receive(welcome, &NoRecompute).unwrap();
|
||||
let cid = c.id();
|
||||
for msg in follow {
|
||||
let rep = server.receive(cid, msg);
|
||||
deliver_outgoing(clients, rep);
|
||||
}
|
||||
(is_delta_snap, is_legacy_snap)
|
||||
}
|
||||
|
||||
fn apply_random_dst_edit(edited: &mut Document, rng: &mut Rng, comp: NodeId, main_children: &[NodeId], seed: u64, step: usize) {
|
||||
let all_ids: Vec<NodeId> = edited.ids().filter(|id| !edited.node(*id).unwrap().is_page()).collect();
|
||||
match rng.below(4) {
|
||||
0 => {
|
||||
let target = *rng.pick(main_children).unwrap();
|
||||
if let Some(n) = edited.node_mut(target) {
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(rng.below(255) as u8, 80, 140))];
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
let text_mirrors: Vec<NodeId> =
|
||||
all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some() && n.kind.text().is_some())).collect();
|
||||
if let Some(&target) = rng.pick(&text_mirrors)
|
||||
&& let Some(n) = edited.node_mut(target)
|
||||
{
|
||||
if let Some(t) = n.kind.text_mut() {
|
||||
t.characters = format!("S{seed}-T{step}");
|
||||
}
|
||||
if rng.chance(0.5) {
|
||||
n.overrides.clear();
|
||||
} else {
|
||||
n.overrides.insert("characters".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
let mirrors: Vec<NodeId> = all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some())).collect();
|
||||
if let Some(&target) = rng.pick(&mirrors)
|
||||
&& let Some(n) = edited.node_mut(target)
|
||||
{
|
||||
n.transform = Affine::translate((rng.below(400) as f64, rng.below(200) as f64));
|
||||
n.width = 20.0 + rng.below(120) as f64;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(n) = edited.node_mut(comp) {
|
||||
n.name = format!("Card-v{step}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_dst_invariants(server: &Server, clients: &[(Client, Hello, bool)], seed: u64, step: usize) {
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(server.replica()).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
|
||||
assert_docs_json_eq(server.document(), decoded.document(), &format!("seed={seed} step={step} roundtrip"));
|
||||
for (i, (c, _, _)) in clients.iter().enumerate() {
|
||||
if c.is_online() {
|
||||
assert_docs_json_eq(server.document(), c.document(), &format!("seed={seed} step={step} client {i}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_dst_seed(seed: u64) {
|
||||
let mut rng = Rng::new(seed);
|
||||
let (doc, comp, main_children) = design_system_doc(6);
|
||||
let limits = Limits { max_log_batches: 2, ..Limits::default() };
|
||||
let mut server = Server::new(doc, "dst-secret", limits);
|
||||
|
||||
let join_client = |srv: &mut Server, name: &str, delta_capable: bool| -> (Client, Hello) {
|
||||
let ClientMsg::Hello(mut h) = Client::hello("dst", "dst-secret", name, "#2266EE") else { panic!() };
|
||||
if !delta_capable {
|
||||
h.client_version = LEGACY_CLIENT_VERSION.into();
|
||||
}
|
||||
let (id, outs) = srv.join(h.clone()).unwrap();
|
||||
let welcome = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
if delta_capable {
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }));
|
||||
} else {
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }));
|
||||
}
|
||||
(Client::join(welcome).unwrap(), h)
|
||||
};
|
||||
|
||||
let (c0, h0) = join_client(&mut server, "Delta-A", true);
|
||||
let (c1, h1) = join_client(&mut server, "Delta-B", true);
|
||||
let (c2, h2) = join_client(&mut server, "Legacy-C", false);
|
||||
let mut clients = vec![(c0, h0, true), (c1, h1, true), (c2, h2, false)];
|
||||
let (mut delta_snap_rejoins, mut legacy_snap_rejoins) = (0usize, 0usize);
|
||||
|
||||
for step in 0..30usize {
|
||||
if step == 15 {
|
||||
let saved = server.state().unwrap();
|
||||
server = Server::restore(saved, "dst-secret", limits).unwrap();
|
||||
for (c, _, _) in &mut clients {
|
||||
c.disconnect();
|
||||
}
|
||||
for idx in 0..clients.len() {
|
||||
let _ = reconnect_dst_client(&mut server, &mut clients, idx);
|
||||
}
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
continue;
|
||||
}
|
||||
|
||||
if step == 6 || step == 20 {
|
||||
let victim = if step == 6 { 1 } else { 2 };
|
||||
clients[victim].0.disconnect();
|
||||
server.leave(clients[victim].0.id());
|
||||
|
||||
let mut off_doc = clients[victim].0.document().clone();
|
||||
if let Some(p) = off_doc.first_page()
|
||||
&& let Some(n) = off_doc.node_mut(p)
|
||||
{
|
||||
n.name = format!("Offline-{seed}-{step}");
|
||||
}
|
||||
let _ = clients[victim].0.edit(&off_doc).unwrap();
|
||||
|
||||
for sub in 0..4 {
|
||||
let mut edited = clients[0].0.document().clone();
|
||||
apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step * 10 + sub);
|
||||
if let Some(msg) = clients[0].0.edit(&edited).unwrap() {
|
||||
let outs = server.receive(clients[0].0.id(), msg);
|
||||
deliver_outgoing(&mut clients, outs);
|
||||
}
|
||||
}
|
||||
|
||||
let (was_delta, was_legacy) = reconnect_dst_client(&mut server, &mut clients, victim);
|
||||
delta_snap_rejoins += usize::from(was_delta);
|
||||
legacy_snap_rejoins += usize::from(was_legacy);
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
continue;
|
||||
}
|
||||
|
||||
let actor_idx = rng.below(clients.len());
|
||||
let mut edited = clients[actor_idx].0.document().clone();
|
||||
apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step);
|
||||
if let Some(msg) = clients[actor_idx].0.edit(&edited).unwrap() {
|
||||
let outs = server.receive(clients[actor_idx].0.id(), msg);
|
||||
deliver_outgoing(&mut clients, outs);
|
||||
}
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
}
|
||||
|
||||
assert!(delta_snap_rejoins > 0 && legacy_snap_rejoins > 0, "seed={seed}: must exercise both snapshot rejoin paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_mixed_delta_and_legacy_clients_converge_under_faults_and_restarts() {
|
||||
let seeds: Vec<u64> = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse::<u64>().ok()) {
|
||||
Some(single) => vec![single],
|
||||
None => vec![1, 7, 42, 1337, 2026],
|
||||
};
|
||||
for seed in seeds {
|
||||
run_dst_seed(seed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
//! Streaming decode and memory-budget enforcement for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::fmt;
|
||||
use std::io::Read;
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::color::Paint;
|
||||
use figcraft_doc::proto::Interaction;
|
||||
use figcraft_doc::{
|
||||
Annotation, CodeLink, DevResource, Document, Effect, ExportSetting, Guide, LayoutGrid, Measurement, Node, NodeId, NodeKind, Region, Segment,
|
||||
VectorNetwork, Vertex,
|
||||
};
|
||||
use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
|
||||
|
||||
use super::fields::{FieldDelta, apply_field_delta};
|
||||
use super::{DEFAULT_MAX_MATERIALIZED_BYTES, HEADER_LEN, WireMeta, WireRecord, parse_header};
|
||||
use crate::Error;
|
||||
use crate::docprops::{clamp_design_review_config, validate_image_base64};
|
||||
use crate::frac;
|
||||
use crate::replica::{Positions, Replica};
|
||||
|
||||
/// Maximum ratio of estimated materialized bytes to declared uncompressed JSON bytes.
|
||||
/// Heavy design-system files sit around 15x to 35x; amplification bombs exceed 1,000x.
|
||||
const MAX_AMPLIFICATION_FACTOR: usize = 64;
|
||||
const MIN_MATERIALIZED_FLOOR: usize = 16 << 20;
|
||||
|
||||
/// Decode a compressed `CatchUp::DeltaSnapshot` payload into a validated [`Replica`].
|
||||
pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -> Result<Replica, Error> {
|
||||
decode_delta_snapshot_with_budget(bytes, max_bytes, max_nodes, DEFAULT_MAX_MATERIALIZED_BYTES)
|
||||
}
|
||||
|
||||
/// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated
|
||||
/// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`.
|
||||
pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
|
||||
let declared = parse_header(bytes)?;
|
||||
if declared > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
let body = bytes.get(HEADER_LEN..).ok_or_else(|| Error::Decode("delta snapshot body missing".into()))?;
|
||||
// Stop inflating at `declared + 1` so a forged small length aborts immediately.
|
||||
let limit = u64::try_from(declared).unwrap_or(u64::MAX).saturating_add(1);
|
||||
let prealloc = declared.min(bytes.len().saturating_mul(8)).min(1 << 20);
|
||||
let mut raw = Vec::with_capacity(prealloc);
|
||||
flate2::read::DeflateDecoder::new(body).take(limit).read_to_end(&mut raw).map_err(|e| Error::Decode(format!("delta snapshot deflate: {e}")))?;
|
||||
if raw.len() > declared {
|
||||
return Err(Error::TooLarge(declared));
|
||||
}
|
||||
if raw.len() != declared {
|
||||
return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len())));
|
||||
}
|
||||
|
||||
let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR);
|
||||
stream_decode_wire(&raw, max_nodes, max_materialized_bytes.min(cap))
|
||||
}
|
||||
|
||||
fn est_str_map(m: &BTreeMap<String, String>) -> usize {
|
||||
m.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len()).saturating_add(48))
|
||||
}
|
||||
|
||||
fn est_vector_bytes(net: &VectorNetwork) -> usize {
|
||||
let regs = net.regions.iter().fold(0usize, |acc, r| {
|
||||
let loops = r.loops.iter().fold(0usize, |a, l| a.saturating_add(l.len().saturating_mul(size_of::<usize>())));
|
||||
let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::<Paint>()));
|
||||
acc.saturating_add(size_of::<Region>()).saturating_add(loops).saturating_add(fills)
|
||||
});
|
||||
size_of::<VectorNetwork>()
|
||||
.saturating_add(net.vertices.len().saturating_mul(size_of::<Vertex>()))
|
||||
.saturating_add(net.segments.len().saturating_mul(size_of::<Segment>()))
|
||||
.saturating_add(regs)
|
||||
}
|
||||
|
||||
fn est_kind_bytes(kind: &NodeKind) -> usize {
|
||||
match kind {
|
||||
NodeKind::Vector { network } => est_vector_bytes(network),
|
||||
NodeKind::Text(t) => t.characters.len().saturating_add(t.runs.len().saturating_mul(64)),
|
||||
NodeKind::Component { description, props, prop_order } => {
|
||||
description.len().saturating_add(props.len().saturating_mul(96)).saturating_add(prop_order.len().saturating_mul(32))
|
||||
}
|
||||
NodeKind::Instance { props, .. } => props.len().saturating_mul(96),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn est_node_bytes(n: &Node) -> usize {
|
||||
let ov: usize = n.overrides.iter().fold(0, |a, s| a.saturating_add(s.len()).saturating_add(24));
|
||||
size_of::<Node>()
|
||||
.saturating_add(n.name.len())
|
||||
.saturating_add(n.dev_note.len())
|
||||
.saturating_add(n.fills.len().saturating_mul(size_of::<Paint>()))
|
||||
.saturating_add(n.strokes.len().saturating_mul(size_of::<Paint>()))
|
||||
.saturating_add(n.effects.len().saturating_mul(size_of::<Effect>()))
|
||||
.saturating_add(n.grids.len().saturating_mul(size_of::<LayoutGrid>()))
|
||||
.saturating_add(n.guides.len().saturating_mul(size_of::<Guide>()))
|
||||
.saturating_add(n.exports.len().saturating_mul(size_of::<ExportSetting>()))
|
||||
.saturating_add(n.interactions.len().saturating_mul(size_of::<Interaction>()))
|
||||
.saturating_add(n.annotations.len().saturating_mul(size_of::<Annotation>()))
|
||||
.saturating_add(n.code_links.len().saturating_mul(size_of::<CodeLink>()))
|
||||
.saturating_add(n.dev_resources.len().saturating_mul(size_of::<DevResource>()))
|
||||
.saturating_add(n.measurements.len().saturating_mul(size_of::<Measurement>()))
|
||||
.saturating_add(est_kind_bytes(&n.kind))
|
||||
.saturating_add(ov)
|
||||
.saturating_add(est_str_map(&n.plugin_data))
|
||||
.saturating_add(est_str_map(&n.prop_refs))
|
||||
}
|
||||
|
||||
fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize {
|
||||
deltas.iter().fold(0usize, |acc, d| {
|
||||
let extra = match d {
|
||||
FieldDelta::Name(s) | FieldDelta::DevNote(s) => s.len(),
|
||||
FieldDelta::Kind(k) => est_kind_bytes(k),
|
||||
FieldDelta::VectorRef(idx) => usize::try_from(*idx).ok().and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0),
|
||||
FieldDelta::Fills(v) | FieldDelta::Strokes(v) => v.len().saturating_mul(size_of::<Paint>()),
|
||||
FieldDelta::Effects(v) => v.len().saturating_mul(size_of::<Effect>()),
|
||||
FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m),
|
||||
FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::<Annotation>()),
|
||||
_ => 0,
|
||||
};
|
||||
acc.saturating_add(extra)
|
||||
})
|
||||
}
|
||||
|
||||
struct DecodeState {
|
||||
doc: Document,
|
||||
positions: Positions,
|
||||
touched: BTreeSet<NodeId>,
|
||||
vectors: Vec<VectorNetwork>,
|
||||
vector_sizes: Vec<usize>,
|
||||
node_sizes: HashMap<NodeId, usize>,
|
||||
meta: Option<WireMeta>,
|
||||
records_seen: usize,
|
||||
max_nodes: usize,
|
||||
materialized_bytes: usize,
|
||||
max_materialized_bytes: usize,
|
||||
abort: Option<Error>,
|
||||
}
|
||||
|
||||
impl DecodeState {
|
||||
fn new(max_nodes: usize, max_materialized_bytes: usize) -> Self {
|
||||
Self {
|
||||
doc: Document::without_pages(""),
|
||||
positions: Positions::new(),
|
||||
touched: BTreeSet::new(),
|
||||
vectors: Vec::new(),
|
||||
vector_sizes: Vec::new(),
|
||||
node_sizes: HashMap::new(),
|
||||
meta: None,
|
||||
records_seen: 0,
|
||||
max_nodes,
|
||||
materialized_bytes: 0,
|
||||
max_materialized_bytes,
|
||||
abort: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn charge(&mut self, bytes: usize) -> Result<(), Error> {
|
||||
self.materialized_bytes = self.materialized_bytes.saturating_add(bytes);
|
||||
if self.materialized_bytes > self.max_materialized_bytes {
|
||||
return Err(Error::TooLarge(self.max_materialized_bytes));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fail<E: de::Error>(&mut self, err: Error) -> E {
|
||||
let msg = err.to_string();
|
||||
self.abort = Some(err);
|
||||
E::custom(msg)
|
||||
}
|
||||
|
||||
fn ingest_record(&mut self, rec: WireRecord) -> Result<(), Error> {
|
||||
let (node, pos, size) = match rec {
|
||||
WireRecord::Full { pos, mut node, vref } => {
|
||||
frac::validate(&pos).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
if self.doc.contains(node.id) {
|
||||
return Err(Error::Invalid(format!("node {} already exists", node.id)));
|
||||
}
|
||||
node.children.clear();
|
||||
let mut est = est_node_bytes(&node).saturating_add(pos.len());
|
||||
if let Some(idx) = vref {
|
||||
let i = usize::try_from(idx).map_err(|_| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
let vsize = self.vector_sizes.get(i).copied().ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
est = est.saturating_add(vsize);
|
||||
self.charge(est)?;
|
||||
let net = self.vectors.get(i).ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
} else {
|
||||
self.charge(est)?;
|
||||
}
|
||||
(*node, pos, est)
|
||||
}
|
||||
WireRecord::Mirror(m) => {
|
||||
frac::validate(&m.pos).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
if self.doc.contains(m.id) {
|
||||
return Err(Error::Invalid(format!("node {} already exists", m.id)));
|
||||
}
|
||||
let missing = || Error::Invalid(format!("mirror {} references missing or cyclic source {}", m.id, m.source));
|
||||
let src_size = self.node_sizes.get(&m.source).copied().ok_or_else(missing)?;
|
||||
let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &self.vector_sizes)).saturating_add(m.pos.len());
|
||||
self.charge(est)?;
|
||||
let src = self.doc.node(m.source).ok_or_else(missing)?;
|
||||
let mut node = src.clone();
|
||||
node.id = m.id;
|
||||
node.parent = m.parent;
|
||||
node.children.clear();
|
||||
node.source = Some(m.source);
|
||||
node.overrides = m.overrides;
|
||||
for delta in m.deltas {
|
||||
apply_field_delta(&mut node, delta, &self.vectors)?;
|
||||
}
|
||||
let actual = est_node_bytes(&node).saturating_add(m.pos.len());
|
||||
(node, m.pos, actual)
|
||||
}
|
||||
};
|
||||
|
||||
let id = node.id;
|
||||
insert_decoded_node(&mut self.doc, &mut self.positions, node, pos)?;
|
||||
self.touched.insert(id);
|
||||
self.node_sizes.insert(id, size);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct VectorsSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for VectorsSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for VectorsSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("vector networks")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
|
||||
while let Some(net) = seq.next_element::<VectorNetwork>()? {
|
||||
let size = est_vector_bytes(&net);
|
||||
if let Err(err) = self.0.charge(size) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
self.0.vector_sizes.push(size);
|
||||
self.0.vectors.push(net);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct RecordsSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for RecordsSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for RecordsSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("delta snapshot records")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
|
||||
loop {
|
||||
if self.0.records_seen >= self.0.max_nodes {
|
||||
if seq.next_element::<de::IgnoredAny>()?.is_some() {
|
||||
let max = self.0.max_nodes;
|
||||
return Err(self.0.fail(Error::Invalid(format!("delta snapshot exceeds the {max}-node limit"))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
let Some(rec) = seq.next_element::<WireRecord>()? else {
|
||||
break;
|
||||
};
|
||||
self.0.records_seen += 1;
|
||||
if let Err(err) = self.0.ingest_record(rec) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct DeltaWireSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for DeltaWireSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_map(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for DeltaWireSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("delta snapshot payload")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
match key.as_str() {
|
||||
"meta" => {
|
||||
let meta: WireMeta = map.next_value()?;
|
||||
let img_bytes = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.bytes.len()));
|
||||
if let Err(err) = self.0.charge(img_bytes) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
self.0.meta = Some(meta);
|
||||
}
|
||||
"vectors" => map.next_value_seed(VectorsSeed(self.0))?,
|
||||
"records" => map.next_value_seed(RecordsSeed(self.0))?,
|
||||
_ => {
|
||||
let _ = map.next_value::<de::IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_decode_wire(raw: &[u8], max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
|
||||
let mut state = DecodeState::new(max_nodes, max_materialized_bytes);
|
||||
let mut de = serde_json::Deserializer::from_slice(raw);
|
||||
let res = DeltaWireSeed(&mut state).deserialize(&mut de);
|
||||
if let Some(err) = state.abort {
|
||||
return Err(err);
|
||||
}
|
||||
res.map_err(|e| Error::Decode(format!("delta snapshot json: {e}")))?;
|
||||
de.end().map_err(|e| Error::Decode(format!("delta snapshot trailing data: {e}")))?;
|
||||
|
||||
let meta = state.meta.ok_or_else(|| Error::Decode("delta snapshot missing meta".into()))?;
|
||||
apply_meta(&mut state.doc, meta);
|
||||
relist_pages(&mut state.doc, &state.positions);
|
||||
if state.doc.pages.is_empty() {
|
||||
return Err(Error::Invalid("a snapshot needs a page".into()));
|
||||
}
|
||||
state.doc.published = None;
|
||||
state.doc.take_dirty();
|
||||
let replica = Replica::from_parts(state.doc, state.positions);
|
||||
replica.check(&state.touched)?;
|
||||
Ok(replica)
|
||||
}
|
||||
|
||||
fn insert_decoded_node(doc: &mut Document, positions: &mut Positions, node: Node, pos: String) -> Result<(), Error> {
|
||||
let (id, is_page, parent) = (node.id, node.is_page(), node.parent);
|
||||
match (is_page, parent) {
|
||||
(true, None) => {
|
||||
doc.insert_page(node).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
}
|
||||
(false, Some(p)) => {
|
||||
let siblings = &doc.get(p).map_err(|e| Error::Invalid(e.to_string()))?.children;
|
||||
let at = siblings.partition_point(|c| (positions.get(c).map_or("", String::as_str), *c) < (pos.as_str(), id));
|
||||
doc.insert(node, p, Some(at)).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
}
|
||||
_ => return Err(Error::Invalid("pages, and only pages, have no parent".into())),
|
||||
}
|
||||
positions.insert(id, pos);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_meta(doc: &mut Document, mut meta: WireMeta) {
|
||||
doc.name = meta.name;
|
||||
doc.kind = meta.kind;
|
||||
doc.styles = meta.styles;
|
||||
doc.variables = meta.variables;
|
||||
doc.current_page = meta.current_page;
|
||||
doc.document_colors = meta.document_colors;
|
||||
doc.comments = meta.comments;
|
||||
doc.libraries = Arc::new(meta.libraries);
|
||||
doc.color_profile = meta.color_profile;
|
||||
doc.image_presets = meta.image_presets;
|
||||
clamp_design_review_config(&mut meta.design_review);
|
||||
doc.design_review = meta.design_review;
|
||||
doc.annotation_categories = meta.annotation_categories;
|
||||
doc.dev_snapshots = meta.dev_snapshots.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
|
||||
doc.timer = meta.timer;
|
||||
doc.vote = meta.vote;
|
||||
doc.votes = meta.votes;
|
||||
doc.vote_history = meta.vote_history;
|
||||
for wi in meta.images {
|
||||
// Leave out images that fail validation or attempt to replace bytes under an existing
|
||||
// key, matching legacy `Replica::from_snapshot_leaving_out`.
|
||||
let Ok(img) = validate_image_base64(&wi.key, wi.width, wi.height, &wi.bytes) else {
|
||||
continue;
|
||||
};
|
||||
if doc.images.get(&wi.key).is_some_and(|old| old.bytes != img.bytes) {
|
||||
continue;
|
||||
}
|
||||
doc.images.insert(wi.key, img);
|
||||
}
|
||||
}
|
||||
|
||||
fn relist_pages(doc: &mut Document, positions: &Positions) {
|
||||
let store = doc.libraries.store;
|
||||
let mut pages: Vec<NodeId> = doc.nodes().filter(|n| n.is_page() && Some(n.id) != store).map(|n| n.id).collect();
|
||||
pages.sort_by(|a, b| (positions.get(a).map_or("", String::as_str), *a).cmp(&(positions.get(b).map_or("", String::as_str), *b)));
|
||||
doc.pages = pages;
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Topological ordering, vector interning and deflate framing for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind, VectorNetwork};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
use super::fields::{diff_mirror_fields, exact_vector_network_eq};
|
||||
use super::{DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord};
|
||||
use crate::Error;
|
||||
use crate::replica::Replica;
|
||||
|
||||
/// Content-addressed deduplicator for `VectorNetwork`s within one snapshot.
|
||||
#[derive(Default)]
|
||||
pub(super) struct VectorInterner {
|
||||
by_hash: HashMap<[u8; 32], Vec<u32>>,
|
||||
table: Vec<VectorNetwork>,
|
||||
}
|
||||
|
||||
impl VectorInterner {
|
||||
pub(super) fn intern(&mut self, net: &VectorNetwork) -> Result<u32, Error> {
|
||||
let raw = serde_json::to_vec(net).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
let digest: [u8; 32] = Sha256::digest(&raw).into();
|
||||
if let Some(bucket) = self.by_hash.get(&digest) {
|
||||
for &idx in bucket {
|
||||
if usize::try_from(idx).ok().and_then(|i| self.table.get(i)).is_some_and(|existing| exact_vector_network_eq(existing, net)) {
|
||||
return Ok(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
let idx = u32::try_from(self.table.len()).map_err(|_| Error::Encode("too many distinct vector networks".into()))?;
|
||||
self.table.push(net.clone());
|
||||
self.by_hash.entry(digest).or_default().push(idx);
|
||||
Ok(idx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Kahn topological order over `(parent, source)` edges (in-degree at most 2 per node).
|
||||
///
|
||||
/// Every parent precedes its children and every acyclic source precedes its mirrors. Nodes
|
||||
/// caught in a `source` cycle are appended in parent-first order and emitted as `Full`.
|
||||
fn topo_order(doc: &Document) -> Vec<NodeId> {
|
||||
let mut roots = doc.pages.clone();
|
||||
roots.extend(doc.nodes().filter(|n| n.parent.is_none() && !doc.pages.contains(&n.id)).map(|n| n.id));
|
||||
let mut parent_order = Vec::with_capacity(doc.node_count());
|
||||
for r in roots {
|
||||
parent_order.extend(doc.subtree(r));
|
||||
}
|
||||
|
||||
let present: HashSet<NodeId> = parent_order.iter().copied().collect();
|
||||
let mut indeg: HashMap<NodeId, u8> = HashMap::with_capacity(present.len());
|
||||
let mut deps_of: HashMap<NodeId, Vec<NodeId>> = HashMap::with_capacity(present.len());
|
||||
|
||||
for &id in &parent_order {
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let mut d: u8 = 0;
|
||||
let p = n.parent.filter(|p| *p != id && present.contains(p));
|
||||
let s = n.source.filter(|s| *s != id && Some(*s) != p && present.contains(s));
|
||||
if let Some(pid) = p {
|
||||
deps_of.entry(pid).or_default().push(id);
|
||||
d += 1;
|
||||
}
|
||||
if let Some(sid) = s {
|
||||
deps_of.entry(sid).or_default().push(id);
|
||||
d += 1;
|
||||
}
|
||||
indeg.insert(id, d);
|
||||
}
|
||||
|
||||
let mut q: VecDeque<NodeId> = parent_order.iter().copied().filter(|id| indeg.get(id).copied() == Some(0)).collect();
|
||||
let mut ordered = Vec::with_capacity(parent_order.len());
|
||||
let mut placed: HashSet<NodeId> = HashSet::with_capacity(parent_order.len());
|
||||
|
||||
while let Some(u) = q.pop_front() {
|
||||
if !placed.insert(u) {
|
||||
continue;
|
||||
}
|
||||
ordered.push(u);
|
||||
if let Some(nexts) = deps_of.get(&u) {
|
||||
for &v in nexts {
|
||||
if let Some(deg) = indeg.get_mut(&v)
|
||||
&& *deg > 0
|
||||
{
|
||||
*deg -= 1;
|
||||
if *deg == 0 {
|
||||
q.push_back(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ordered.len() < parent_order.len() {
|
||||
for id in parent_order {
|
||||
if placed.insert(id) {
|
||||
ordered.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ordered
|
||||
}
|
||||
|
||||
/// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload.
|
||||
pub fn encode_delta_snapshot(replica: &Replica) -> Result<Vec<u8>, Error> {
|
||||
let doc = replica.document();
|
||||
let order = topo_order(doc);
|
||||
let mut interner = VectorInterner::default();
|
||||
let mut seen: HashMap<NodeId, &Node> = HashMap::with_capacity(order.len());
|
||||
let mut records = Vec::with_capacity(order.len());
|
||||
|
||||
for id in order {
|
||||
let Some(node) = doc.node(id) else { continue };
|
||||
let pos = replica.key(id).to_string();
|
||||
let rec = encode_one_node(node, pos, &seen, &mut interner)?;
|
||||
records.push(rec);
|
||||
seen.insert(id, node);
|
||||
}
|
||||
|
||||
let meta = build_meta(doc);
|
||||
let wire = DeltaWireRef { meta: &meta, vectors: &interner.table, records: &records };
|
||||
compress_wire(&wire)
|
||||
}
|
||||
|
||||
fn encode_one_node(node: &Node, pos: String, seen: &HashMap<NodeId, &Node>, interner: &mut VectorInterner) -> Result<WireRecord, Error> {
|
||||
if let Some(src_id) = node.source
|
||||
&& let Some(src) = seen.get(&src_id)
|
||||
{
|
||||
let deltas = diff_mirror_fields(src, node, interner)?;
|
||||
return Ok(WireRecord::Mirror(Box::new(MirrorWire {
|
||||
id: node.id,
|
||||
parent: node.parent,
|
||||
pos,
|
||||
source: src_id,
|
||||
overrides: node.overrides.clone(),
|
||||
deltas,
|
||||
})));
|
||||
}
|
||||
|
||||
let mut stripped = node.clone();
|
||||
// Children are rebuilt from `(parent, pos)` on decode.
|
||||
stripped.children.clear();
|
||||
let vref = match &mut stripped.kind {
|
||||
NodeKind::Vector { network } if !network.vertices.is_empty() || !network.segments.is_empty() || !network.regions.is_empty() => {
|
||||
let idx = interner.intern(network)?;
|
||||
*network = VectorNetwork::default();
|
||||
Some(idx)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok(WireRecord::Full { pos, node: Box::new(stripped), vref })
|
||||
}
|
||||
|
||||
fn build_meta(doc: &Document) -> WireMeta {
|
||||
use base64::Engine as _;
|
||||
let images = doc
|
||||
.images
|
||||
.iter()
|
||||
.map(|(key, img)| WireImage {
|
||||
key: key.clone(),
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
bytes: base64::engine::general_purpose::STANDARD.encode(img.bytes.as_slice()),
|
||||
})
|
||||
.collect();
|
||||
WireMeta {
|
||||
name: doc.name.clone(),
|
||||
kind: doc.kind,
|
||||
styles: doc.styles.clone(),
|
||||
variables: doc.variables.clone(),
|
||||
current_page: doc.current_page,
|
||||
document_colors: doc.document_colors.clone(),
|
||||
comments: doc.comments.clone(),
|
||||
libraries: (*doc.libraries).clone(),
|
||||
color_profile: doc.color_profile,
|
||||
image_presets: doc.image_presets.clone(),
|
||||
design_review: doc.design_review.clone(),
|
||||
annotation_categories: doc.annotation_categories.clone(),
|
||||
dev_snapshots: doc.dev_snapshots.iter().map(|(k, v)| (*k, (**v).clone())).collect(),
|
||||
timer: doc.timer,
|
||||
vote: doc.vote.clone(),
|
||||
votes: doc.votes.clone(),
|
||||
vote_history: doc.vote_history.clone(),
|
||||
images,
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingWriter<W> {
|
||||
inner: W,
|
||||
written: usize,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for CountingWriter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.write(buf)?;
|
||||
self.written = self.written.saturating_add(n);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<Vec<u8>, Error> {
|
||||
let mut out = Vec::with_capacity(4096);
|
||||
out.extend_from_slice(DELTA_MAGIC);
|
||||
out.push(DELTA_VERSION);
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// Buffer writes into 64 KiB chunks so serde_json's small token writes do not enter deflate individually.
|
||||
let encoder = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
|
||||
let mut buffered = BufWriter::with_capacity(64 * 1024, CountingWriter { inner: encoder, written: 0 });
|
||||
serde_json::to_writer(&mut buffered, wire).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
let counting = buffered.into_inner().map_err(|e| Error::Encode(e.into_error().to_string()))?;
|
||||
let len_u32 = u32::try_from(counting.written).map_err(|_| Error::TooLarge(u32::MAX as usize))?;
|
||||
let mut out = counting.inner.finish().map_err(|e| Error::Encode(e.to_string()))?;
|
||||
if let Some(slot) = out.get_mut(5..9) {
|
||||
slot.copy_from_slice(&len_u32.to_le_bytes());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Mirror field deltas and structural equality checks.
|
||||
//!
|
||||
//! `Paint` ignores `color_alpha` in `PartialEq`, and IEEE-754 equates `-0.0` with `0.0`.
|
||||
//! Float and paint fields therefore compare bit-for-bit or via serialized JSON so mirror
|
||||
//! encoding never drops data that legacy snapshots preserve.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use figcraft_doc::color::{BlendMode, Paint, PaintKind};
|
||||
use figcraft_doc::geom::Affine;
|
||||
use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition};
|
||||
use figcraft_doc::{
|
||||
Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect,
|
||||
ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, StrokeProps, StyleRefs, VariableId,
|
||||
VectorNetwork, Vertex,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::encode::VectorInterner;
|
||||
use crate::Error;
|
||||
|
||||
/// Defines `FieldDelta`, mirror diffing and delta application from one field table so adding
|
||||
/// or editing a field keeps all three in lockstep.
|
||||
///
|
||||
/// New variants must be appended and gated behind a version or capability bump because older
|
||||
/// clients reject unknown variants during deserialization.
|
||||
macro_rules! delta_fields {
|
||||
(
|
||||
boxed: [ $( $bvar:ident ( $bty:ty ) => $bfield:ident via $beq:ident ),* $(,)? ],
|
||||
value: [ $( $vvar:ident ( $vty:ty ) => $vfield:ident via $veq:ident ),* $(,)? ]
|
||||
) => {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum FieldDelta {
|
||||
Kind(Box<NodeKind>),
|
||||
VectorRef(u32),
|
||||
$( $bvar(Box<$bty>), )*
|
||||
$( $vvar($vty), )*
|
||||
}
|
||||
|
||||
fn diff_table_fields(src: &Node, node: &Node, out: &mut Vec<FieldDelta>) {
|
||||
$(
|
||||
if !$beq(&node.$bfield, &src.$bfield) {
|
||||
out.push(FieldDelta::$bvar(Box::new(node.$bfield.clone())));
|
||||
}
|
||||
)*
|
||||
$(
|
||||
if !$veq(&node.$vfield, &src.$vfield) {
|
||||
out.push(FieldDelta::$vvar(node.$vfield.clone()));
|
||||
}
|
||||
)*
|
||||
}
|
||||
|
||||
pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[VectorNetwork]) -> Result<(), Error> {
|
||||
match delta {
|
||||
FieldDelta::Kind(v) => node.kind = *v,
|
||||
FieldDelta::VectorRef(idx) => {
|
||||
let net = usize::try_from(idx)
|
||||
.ok()
|
||||
.and_then(|i| vectors.get(i))
|
||||
.ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
}
|
||||
$( FieldDelta::$bvar(v) => node.$bfield = *v, )*
|
||||
$( FieldDelta::$vvar(v) => node.$vfield = v, )*
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
delta_fields! {
|
||||
boxed: [
|
||||
Stroke(StrokeProps) => stroke via eq_exact,
|
||||
ChildLayout(ChildLayout) => child_layout via eq_exact,
|
||||
Styles(StyleRefs) => styles via eq_plain,
|
||||
],
|
||||
value: [
|
||||
Name(String) => name via eq_plain,
|
||||
Visible(bool) => visible via eq_plain,
|
||||
Locked(bool) => locked via eq_plain,
|
||||
Opacity(f32) => opacity via eq_f32,
|
||||
Blend(BlendMode) => blend via eq_plain,
|
||||
Transform(Affine) => transform via eq_affine,
|
||||
Width(f64) => width via eq_f64,
|
||||
Height(f64) => height via eq_f64,
|
||||
Fills(Vec<Paint>) => fills via eq_paint_vec,
|
||||
Strokes(Vec<Paint>) => strokes via eq_paint_vec,
|
||||
Effects(Vec<Effect>) => effects via eq_vec_exact,
|
||||
Corners(Corners) => corners via eq_exact,
|
||||
Constraints(Constraints) => constraints via eq_plain,
|
||||
Layout(Option<AutoLayout>) => layout via eq_opt_exact,
|
||||
Clip(bool) => clip via eq_plain,
|
||||
IsMask(bool) => is_mask via eq_plain,
|
||||
MaskType(MaskType) => mask_type via eq_plain,
|
||||
Grids(Vec<LayoutGrid>) => grids via eq_vec_exact,
|
||||
Guides(Vec<Guide>) => guides via eq_vec_exact,
|
||||
Exports(Vec<ExportSetting>) => exports via eq_vec_exact,
|
||||
Interactions(Vec<Interaction>) => interactions via eq_vec_exact,
|
||||
Overflow(Overflow) => overflow via eq_plain,
|
||||
ScrollPosition(ScrollPosition) => scroll_position via eq_exact,
|
||||
Bound(BTreeMap<String, VariableId>) => bound via eq_plain,
|
||||
VarModes(BTreeMap<CollectionId, ModeId>) => var_modes via eq_plain,
|
||||
ScaleFactor(f64) => scale_factor via eq_f64,
|
||||
BoolOp(Option<BoolOp>) => bool_op via eq_plain,
|
||||
ConstrainProportions(bool) => constrain_proportions via eq_plain,
|
||||
Exposed(bool) => exposed via eq_plain,
|
||||
DevStatus(DevStatus) => dev_status via eq_plain,
|
||||
DevChanged(bool) => dev_changed via eq_plain,
|
||||
DevNote(String) => dev_note via eq_plain,
|
||||
PropRefs(BTreeMap<String, String>) => prop_refs via eq_plain,
|
||||
PluginData(BTreeMap<String, String>) => plugin_data via eq_plain,
|
||||
Annotations(Vec<Annotation>) => annotations via eq_vec_exact,
|
||||
CodeLinks(Vec<CodeLink>) => code_links via eq_plain,
|
||||
DevResources(Vec<DevResource>) => dev_resources via eq_plain,
|
||||
Measurements(Vec<Measurement>) => measurements via eq_vec_exact,
|
||||
Board(Option<BoardItem>) => board via eq_opt_exact,
|
||||
]
|
||||
}
|
||||
|
||||
/// Fails to compile if a new field is added to `figcraft_doc::Node` without updating `delta_fields!`.
|
||||
#[allow(dead_code)]
|
||||
fn every_node_field_visited(n: &Node) {
|
||||
let Node {
|
||||
id: _,
|
||||
name: _,
|
||||
kind: _,
|
||||
parent: _,
|
||||
children: _,
|
||||
visible: _,
|
||||
locked: _,
|
||||
opacity: _,
|
||||
blend: _,
|
||||
transform: _,
|
||||
width: _,
|
||||
height: _,
|
||||
fills: _,
|
||||
strokes: _,
|
||||
stroke: _,
|
||||
effects: _,
|
||||
corners: _,
|
||||
constraints: _,
|
||||
layout: _,
|
||||
child_layout: _,
|
||||
clip: _,
|
||||
is_mask: _,
|
||||
mask_type: _,
|
||||
grids: _,
|
||||
guides: _,
|
||||
exports: _,
|
||||
interactions: _,
|
||||
overflow: _,
|
||||
scroll_position: _,
|
||||
styles: _,
|
||||
bound: _,
|
||||
var_modes: _,
|
||||
scale_factor: _,
|
||||
bool_op: _,
|
||||
constrain_proportions: _,
|
||||
source: _,
|
||||
exposed: _,
|
||||
dev_status: _,
|
||||
dev_changed: _,
|
||||
dev_note: _,
|
||||
overrides: _,
|
||||
prop_refs: _,
|
||||
plugin_data: _,
|
||||
annotations: _,
|
||||
code_links: _,
|
||||
dev_resources: _,
|
||||
measurements: _,
|
||||
board: _,
|
||||
} = n;
|
||||
}
|
||||
|
||||
pub(super) fn diff_mirror_fields(src: &Node, node: &Node, interner: &mut VectorInterner) -> Result<Vec<FieldDelta>, Error> {
|
||||
let mut deltas = Vec::new();
|
||||
if !exact_kind_eq(&node.kind, &src.kind) {
|
||||
match &node.kind {
|
||||
NodeKind::Vector { network } => deltas.push(FieldDelta::VectorRef(interner.intern(network)?)),
|
||||
other => deltas.push(FieldDelta::Kind(Box::new(other.clone()))),
|
||||
}
|
||||
}
|
||||
diff_table_fields(src, node, &mut deltas);
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_plain<T: PartialEq>(a: &T, b: &T) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_f64(a: &f64, b: &f64) -> bool {
|
||||
a.to_bits() == b.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_f32(a: &f32, b: &f32) -> bool {
|
||||
a.to_bits() == b.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_affine(a: &Affine, b: &Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| x.to_bits() == y.to_bits())
|
||||
}
|
||||
|
||||
fn eq_json<T: Serialize + ?Sized>(a: &T, b: &T) -> bool {
|
||||
matches!((serde_json::to_vec(a), serde_json::to_vec(b)), (Ok(x), Ok(y)) if x == y)
|
||||
}
|
||||
|
||||
fn eq_exact<T: Serialize + PartialEq>(a: &T, b: &T) -> bool {
|
||||
a == b && eq_json(a, b)
|
||||
}
|
||||
|
||||
fn eq_vec_exact<T: Serialize + PartialEq>(a: &[T], b: &[T]) -> bool {
|
||||
(a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b))
|
||||
}
|
||||
|
||||
fn eq_opt_exact<T: Serialize + PartialEq>(a: &Option<T>, b: &Option<T>) -> bool {
|
||||
match (a, b) {
|
||||
(None, None) => true,
|
||||
(Some(x), Some(y)) => x == y && eq_json(x, y),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn eq_paint(a: &Paint, b: &Paint) -> bool {
|
||||
if a.visible != b.visible || a.blend != b.blend || !eq_f32(&a.opacity, &b.opacity) || !eq_f32(&a.color_alpha, &b.color_alpha) {
|
||||
return false;
|
||||
}
|
||||
match (&a.kind, &b.kind) {
|
||||
(PaintKind::Solid { color: ca }, PaintKind::Solid { color: cb }) => {
|
||||
eq_f32(&ca.r, &cb.r) && eq_f32(&ca.g, &cb.g) && eq_f32(&ca.b, &cb.b) && eq_f32(&ca.a, &cb.a)
|
||||
}
|
||||
_ => a.kind == b.kind && eq_json(&a.kind, &b.kind),
|
||||
}
|
||||
}
|
||||
|
||||
fn eq_paint_vec(a: &[Paint], b: &[Paint]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| eq_paint(x, y))
|
||||
}
|
||||
|
||||
fn eq_vertex(a: &Vertex, b: &Vertex) -> bool {
|
||||
eq_f64(&a.x, &b.x) && eq_f64(&a.y, &b.y) && eq_f64(&a.radius, &b.radius) && a.mirror == b.mirror && a.cap == b.cap && a.join == b.join
|
||||
}
|
||||
|
||||
fn eq_segment(a: &Segment, b: &Segment) -> bool {
|
||||
a.a == b.a && a.b == b.b && eq_f64(&a.ta.0, &b.ta.0) && eq_f64(&a.ta.1, &b.ta.1) && eq_f64(&a.tb.0, &b.tb.0) && eq_f64(&a.tb.1, &b.tb.1)
|
||||
}
|
||||
|
||||
fn eq_region(a: &Region, b: &Region) -> bool {
|
||||
let fills_ok = match (&a.fills, &b.fills) {
|
||||
(None, None) => true,
|
||||
(Some(fa), Some(fb)) => eq_paint_vec(fa, fb),
|
||||
_ => false,
|
||||
};
|
||||
let space_ok = match (a.paint_space, b.paint_space) {
|
||||
(None, None) => true,
|
||||
(Some(pa), Some(pb)) => eq_f64(&pa.width, &pb.width) && eq_f64(&pa.height, &pb.height) && eq_affine(&pa.transform, &pb.transform),
|
||||
_ => false,
|
||||
};
|
||||
a.winding == b.winding && a.loops == b.loops && fills_ok && space_ok
|
||||
}
|
||||
|
||||
pub(super) fn exact_vector_network_eq(a: &VectorNetwork, b: &VectorNetwork) -> bool {
|
||||
a.vertices.len() == b.vertices.len()
|
||||
&& a.segments.len() == b.segments.len()
|
||||
&& a.regions.len() == b.regions.len()
|
||||
&& a.vertices.iter().zip(&b.vertices).all(|(x, y)| eq_vertex(x, y))
|
||||
&& a.segments.iter().zip(&b.segments).all(|(x, y)| eq_segment(x, y))
|
||||
&& a.regions.iter().zip(&b.regions).all(|(x, y)| eq_region(x, y))
|
||||
}
|
||||
|
||||
fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool {
|
||||
match (a, b) {
|
||||
(NodeKind::Frame, NodeKind::Frame)
|
||||
| (NodeKind::Group, NodeKind::Group)
|
||||
| (NodeKind::Rectangle, NodeKind::Rectangle)
|
||||
| (NodeKind::Line, NodeKind::Line) => true,
|
||||
(NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => exact_vector_network_eq(na, nb),
|
||||
_ => eq_exact(a, b),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Direct mirror-delta and deduplicated-vector snapshots (`CatchUp::DeltaSnapshot`).
|
||||
//!
|
||||
//! Used for clients whose hello announces `delta-snapshot` and `design-review`.
|
||||
//! Nodes are ordered topologically over `(parent, source)` edges so parents precede
|
||||
//! children and acyclic sources precede their mirrors. Mirrors diff field values
|
||||
//! structurally instead of trusting `Node::overrides`. Decoding streams records
|
||||
//! one at a time under inflated-byte, exact declared-length, node-count and
|
||||
//! materialized-memory budgets.
|
||||
|
||||
mod decode;
|
||||
mod encode;
|
||||
mod fields;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_doc::color::{Color, ColorProfile};
|
||||
use figcraft_doc::{
|
||||
AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, FileKind, ImagePreset, Libraries, Node, NodeId, VectorNetwork, Vote,
|
||||
VoteRecord,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Error;
|
||||
use fields::FieldDelta;
|
||||
|
||||
pub use decode::{decode_delta_snapshot, decode_delta_snapshot_with_budget};
|
||||
pub use encode::encode_delta_snapshot;
|
||||
|
||||
/// Wire header magic for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
|
||||
pub const DELTA_MAGIC: &[u8; 4] = b"FCDS";
|
||||
/// Wire format version for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
|
||||
pub const DELTA_VERSION: u8 = 1;
|
||||
/// Fixed header size: 4-byte magic, 1-byte version, 4-byte little-endian uncompressed length.
|
||||
const HEADER_LEN: usize = 9;
|
||||
/// Default ceiling on estimated materialized bytes during decode.
|
||||
pub const DEFAULT_MAX_MATERIALIZED_BYTES: usize = 512 << 20;
|
||||
|
||||
/// Check the fixed header and declared uncompressed length in O(1).
|
||||
///
|
||||
/// Combined with [`decode_delta_snapshot_with_budget`] requiring `inflated.len() == declared`,
|
||||
/// this prevents a client from inflating past `max_bytes`.
|
||||
pub fn check_header_limit(bytes: &[u8], max_bytes: usize) -> Result<(), Error> {
|
||||
let declared = parse_header(bytes)?;
|
||||
if declared > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_header(bytes: &[u8]) -> Result<usize, Error> {
|
||||
let header = bytes.get(..HEADER_LEN).ok_or_else(|| Error::Decode("delta snapshot header is truncated".into()))?;
|
||||
if header.get(..4) != Some(DELTA_MAGIC.as_slice()) {
|
||||
return Err(Error::Decode("delta snapshot magic mismatch".into()));
|
||||
}
|
||||
let version = header.get(4).copied().ok_or_else(|| Error::Decode("delta snapshot version missing".into()))?;
|
||||
if version != DELTA_VERSION {
|
||||
return Err(Error::Decode(format!("unsupported delta snapshot version {version}")));
|
||||
}
|
||||
let len_slice = header.get(5..9).ok_or_else(|| Error::Decode("delta snapshot length missing".into()))?;
|
||||
let len_bytes: [u8; 4] = len_slice.try_into().map_err(|_| Error::Decode("delta snapshot length".into()))?;
|
||||
usize::try_from(u32::from_le_bytes(len_bytes)).map_err(|_| Error::TooLarge(usize::MAX))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "r", rename_all = "camelCase")]
|
||||
enum WireRecord {
|
||||
Full {
|
||||
pos: String,
|
||||
node: Box<Node>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
vref: Option<u32>,
|
||||
},
|
||||
Mirror(Box<MirrorWire>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MirrorWire {
|
||||
id: NodeId,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
parent: Option<NodeId>,
|
||||
pos: String,
|
||||
source: NodeId,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
overrides: BTreeSet<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
deltas: Vec<FieldDelta>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct WireImage {
|
||||
key: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
bytes: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WireMeta {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
kind: FileKind,
|
||||
#[serde(default)]
|
||||
styles: Vec<figcraft_doc::Style>,
|
||||
#[serde(default)]
|
||||
variables: figcraft_doc::Variables,
|
||||
#[serde(default)]
|
||||
current_page: Option<NodeId>,
|
||||
#[serde(default)]
|
||||
document_colors: Vec<Color>,
|
||||
#[serde(default)]
|
||||
comments: Vec<Comment>,
|
||||
#[serde(default)]
|
||||
libraries: Libraries,
|
||||
#[serde(default)]
|
||||
color_profile: ColorProfile,
|
||||
#[serde(default)]
|
||||
image_presets: Vec<ImagePreset>,
|
||||
#[serde(default)]
|
||||
design_review: DesignReview,
|
||||
#[serde(default)]
|
||||
annotation_categories: Option<Vec<AnnotationCategory>>,
|
||||
#[serde(default)]
|
||||
dev_snapshots: BTreeMap<NodeId, DevSnapshot>,
|
||||
#[serde(default)]
|
||||
timer: Option<BoardTimer>,
|
||||
#[serde(default)]
|
||||
vote: Option<Vote>,
|
||||
#[serde(default)]
|
||||
votes: Ballots,
|
||||
#[serde(default)]
|
||||
vote_history: Vec<VoteRecord>,
|
||||
#[serde(default)]
|
||||
images: Vec<WireImage>,
|
||||
}
|
||||
|
||||
/// Serialization envelope written in canonical order (`meta`, `vectors`, `records`).
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DeltaWireRef<'a> {
|
||||
meta: &'a WireMeta,
|
||||
#[serde(skip_serializing_if = "<[VectorNetwork]>::is_empty")]
|
||||
vectors: &'a [VectorNetwork],
|
||||
records: &'a [WireRecord],
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Parity, exact-equality and hostile-input tests for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{
|
||||
BoardTimer, Comment, DesignReview, DevSnapshot, Document, ImageData, ImagePreset, Libraries, NodeId, NodeKind, Segment, TextData, VectorNetwork,
|
||||
Vertex, Vote, VoteRecord,
|
||||
};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::delta_snapshot::{DELTA_MAGIC, DELTA_VERSION, decode_delta_snapshot, decode_delta_snapshot_with_budget, encode_delta_snapshot};
|
||||
use crate::message::{self, CatchUp, ClientMsg, ServerMsg};
|
||||
use crate::{Client, Error, Limits, Outgoing, Replica, Server};
|
||||
|
||||
pub(crate) const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches";
|
||||
|
||||
/// Compare two documents via serialized JSON (excluding per-client `next_id`) so
|
||||
/// non-structural `PartialEq` cannot hide silent data loss.
|
||||
pub(crate) fn assert_docs_json_eq(left: &Document, right: &Document, context: &str) {
|
||||
let mut lj = serde_json::to_value(left).expect("serialize left doc");
|
||||
let mut rj = serde_json::to_value(right).expect("serialize right doc");
|
||||
if let Some(m) = lj.as_object_mut() {
|
||||
m.remove("next_id");
|
||||
}
|
||||
if let Some(m) = rj.as_object_mut() {
|
||||
m.remove("next_id");
|
||||
}
|
||||
assert_eq!(lj, rj, "{context}: serialized JSON mismatch");
|
||||
}
|
||||
|
||||
fn make_raw_delta_payload(json: &str, declared_override: Option<u32>) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(DELTA_MAGIC);
|
||||
out.push(DELTA_VERSION);
|
||||
let len = declared_override.unwrap_or(u32::try_from(json.len()).unwrap());
|
||||
out.extend_from_slice(&len.to_le_bytes());
|
||||
let mut z = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
|
||||
z.write_all(json.as_bytes()).unwrap();
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn sample_vector_icon(seed: usize, vertex_count: usize) -> VectorNetwork {
|
||||
let mut vertices = Vec::with_capacity(vertex_count);
|
||||
let mut segments = Vec::with_capacity(vertex_count);
|
||||
for i in 0..vertex_count {
|
||||
let a = (i as f64) * std::f64::consts::TAU / (vertex_count as f64) + (seed as f64) * 0.1;
|
||||
vertices.push(Vertex::new(16.0 + 12.0 * a.cos(), 16.0 + 12.0 * a.sin()));
|
||||
segments.push(Segment { a: i, b: (i + 1) % vertex_count, ta: (1.5, -0.5), tb: (-1.5, 0.5) });
|
||||
}
|
||||
VectorNetwork { vertices, segments, regions: Vec::new() }
|
||||
}
|
||||
|
||||
/// Build a document with cross-page instances (main component on page 2, instances on page 1),
|
||||
/// depth-2 mirror chains, repeated vector icons and stale empty `overrides` (#1819).
|
||||
pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec<NodeId>) {
|
||||
let mut doc = Document::new("DesignSystemDST");
|
||||
let page1 = doc.first_page().unwrap();
|
||||
let page2 = doc.add_page("Components");
|
||||
|
||||
let comp = doc
|
||||
.create(
|
||||
page2,
|
||||
NodeKind::Component { description: "Card".into(), props: BTreeMap::new(), prop_order: Vec::new() },
|
||||
"Card",
|
||||
0.0,
|
||||
0.0,
|
||||
320.0,
|
||||
200.0,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let icon_a = sample_vector_icon(1, 24);
|
||||
let icon_b = sample_vector_icon(2, 24);
|
||||
let mut main_children = Vec::new();
|
||||
for i in 0..6 {
|
||||
let kind = match i {
|
||||
0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}"))),
|
||||
2 => NodeKind::Vector { network: icon_a.clone() },
|
||||
3 => NodeKind::Vector { network: icon_b.clone() },
|
||||
_ => NodeKind::Rectangle,
|
||||
};
|
||||
let cid = doc.create(comp, kind, &format!("Part {i}"), i as f64 * 24.0, 8.0, 32.0, 32.0).unwrap();
|
||||
if let Some(n) = doc.node_mut(cid) {
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(40, 100, (i * 30) as u8))];
|
||||
}
|
||||
main_children.push(cid);
|
||||
}
|
||||
|
||||
let main_snapshots: Vec<_> = main_children.iter().map(|id| doc.node(*id).unwrap().clone()).collect();
|
||||
let mut prev_inst_children: Option<Vec<NodeId>> = None;
|
||||
|
||||
for idx in 0..num_instances {
|
||||
let mut root = doc.node(comp).unwrap().clone();
|
||||
let inst_id = doc.alloc_id();
|
||||
root.id = inst_id;
|
||||
root.name = format!("Card #{idx}");
|
||||
root.kind = NodeKind::Instance { component: comp, props: BTreeMap::new() };
|
||||
root.children.clear();
|
||||
root.parent = None;
|
||||
root.source = Some(comp);
|
||||
root.transform = Affine::translate((idx as f64 * 340.0, 0.0));
|
||||
doc.insert(root, page1, None).unwrap();
|
||||
|
||||
let mut this_children = Vec::new();
|
||||
for (j, src) in main_snapshots.iter().enumerate() {
|
||||
let mut child = src.clone();
|
||||
child.id = doc.alloc_id();
|
||||
child.parent = None;
|
||||
child.children.clear();
|
||||
let chain_src = prev_inst_children.as_ref().filter(|_| idx % 3 == 2).map_or(src.id, |prev| prev[j]);
|
||||
child.source = Some(chain_src);
|
||||
|
||||
if j == 0 && idx % 2 == 0 {
|
||||
if let NodeKind::Text(t) = &mut child.kind {
|
||||
t.characters = format!("Overridden {idx}");
|
||||
}
|
||||
if idx % 4 != 0 {
|
||||
child.overrides.insert("characters".to_string());
|
||||
}
|
||||
}
|
||||
if j == 4 && idx % 5 == 0 {
|
||||
child.width = 99.0;
|
||||
child.transform = Affine::translate((12.0, 24.0));
|
||||
}
|
||||
let child_id = child.id;
|
||||
doc.insert(child, inst_id, None).unwrap();
|
||||
this_children.push(child_id);
|
||||
}
|
||||
prev_inst_children = Some(this_children);
|
||||
}
|
||||
|
||||
doc.take_dirty();
|
||||
(doc, comp, main_children)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() {
|
||||
let mut doc = Document::new("ExactEq");
|
||||
let page = doc.first_page().unwrap();
|
||||
let src = doc.create(page, NodeKind::Rectangle, "Src", 0.0, 0.0, 100.0, 50.0).unwrap();
|
||||
let mut src_paint = Paint::solid(Color::from_rgb8_const(20, 80, 200));
|
||||
src_paint.opacity = 0.5;
|
||||
src_paint.color_alpha = 0.5;
|
||||
if let Some(n) = doc.node_mut(src) {
|
||||
n.fills = vec![src_paint.clone()];
|
||||
n.strokes = vec![src_paint];
|
||||
}
|
||||
|
||||
let mut mirror = doc.node(src).unwrap().clone();
|
||||
mirror.id = doc.alloc_id();
|
||||
mirror.parent = None;
|
||||
mirror.source = Some(src);
|
||||
mirror.fills[0].color_alpha = 1.0;
|
||||
mirror.strokes[0].color_alpha = 0.25;
|
||||
mirror.width = -0.0;
|
||||
mirror.transform = Affine::translate((-0.0, 0.0));
|
||||
assert_eq!(doc.node(src).unwrap().fills, mirror.fills, "Paint PartialEq ignores color_alpha");
|
||||
doc.insert(mirror, page, None).unwrap();
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap();
|
||||
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
|
||||
assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality");
|
||||
assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_hash_image_matches_legacy_join_parity() {
|
||||
let mut doc = Document::new("BadImage");
|
||||
let page = doc.first_page().unwrap();
|
||||
doc.create(page, NodeKind::Rectangle, "Box", 0.0, 0.0, 40.0, 40.0).unwrap();
|
||||
let bad_key = "0".repeat(64);
|
||||
doc.images.insert(bad_key.clone(), ImageData { bytes: Arc::new(b"not-matching-sha256".to_vec()), width: 10, height: 10 });
|
||||
doc.images.insert("svg_icon_1".into(), ImageData { bytes: Arc::new(b"valid-bytes".to_vec()), width: 16, height: 16 });
|
||||
doc.take_dirty();
|
||||
|
||||
let mut srv = Server::new(doc, "tok", Limits::default());
|
||||
let join_with = |srv: &mut Server, ver: Option<&str>| -> Client {
|
||||
let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "u", "#111") else { panic!() };
|
||||
if let Some(v) = ver {
|
||||
h.client_version = v.into();
|
||||
}
|
||||
let (id, outs) = srv.join(h).unwrap();
|
||||
let w = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
Client::join(w).unwrap()
|
||||
};
|
||||
|
||||
let legacy_client = join_with(&mut srv, Some(LEGACY_CLIENT_VERSION));
|
||||
let delta_client = join_with(&mut srv, None);
|
||||
assert!(!delta_client.document().images.contains_key(&bad_key));
|
||||
assert!(delta_client.document().images.contains_key("svg_icon_1"));
|
||||
assert_docs_json_eq(legacy_client.document(), delta_client.document(), "corrupt-image parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forged_declared_length_cannot_bypass_unpack_limit() {
|
||||
let huge_json = format!(
|
||||
r#"{{"meta":{{"name":"Bomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"{}","type":"page","width":0,"height":0}}}}]}}"#,
|
||||
"A".repeat(4 << 20)
|
||||
);
|
||||
let mut welcome = ServerMsg::Welcome {
|
||||
session: 1,
|
||||
client_id: 1,
|
||||
seq: 0,
|
||||
catch_up: CatchUp::DeltaSnapshot(make_raw_delta_payload(&huge_json, Some(10))),
|
||||
processed: message::Processed::default(),
|
||||
peers: Vec::new(),
|
||||
access: message::Access::Edit,
|
||||
secret: 1,
|
||||
};
|
||||
message::unpack(&mut welcome, 1 << 20).unwrap();
|
||||
let err = Client::join(welcome).unwrap_err();
|
||||
assert!(matches!(err, Error::TooLarge(10)), "forged length must abort at declared+1, got {err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_and_vref_amplification_bombs_are_rejected_within_memory_budget() {
|
||||
let big_text = "X".repeat(256 * 1024);
|
||||
let mut mirror_recs = String::from(
|
||||
r#"{"meta":{"name":"MirrorBomb"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},"#,
|
||||
);
|
||||
mirror_recs.push_str(&format!(
|
||||
r#"{{"r":"full","pos":"a0","node":{{"id":2,"name":"Big","parent":1,"type":"text","characters":"{big_text}","width":10,"height":10}}}}"#
|
||||
));
|
||||
for i in 3..2003u64 {
|
||||
mirror_recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#));
|
||||
}
|
||||
mirror_recs.push_str("]}");
|
||||
let err1 = decode_delta_snapshot(&make_raw_delta_payload(&mirror_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
|
||||
assert!(matches!(err1, Error::TooLarge(_)), "mirror bomb must fail TooLarge, got {err1:?}");
|
||||
|
||||
let net_json = serde_json::to_string(&sample_vector_icon(1, 20_000)).unwrap();
|
||||
let mut vref_recs = format!(
|
||||
r#"{{"meta":{{"name":"VrefBomb"}},"vectors":[{net_json}],"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}"#
|
||||
);
|
||||
for i in 2..3002u64 {
|
||||
vref_recs.push_str(&format!(
|
||||
r#",{{"r":"full","pos":"a{i:04}1","vref":0,"node":{{"id":{i},"name":"V","parent":1,"type":"vector","network":{{"vertices":[],"segments":[]}},"width":10,"height":10}}}}"#
|
||||
));
|
||||
}
|
||||
vref_recs.push_str("]}");
|
||||
let err2 = decode_delta_snapshot(&make_raw_delta_payload(&vref_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
|
||||
assert!(matches!(err2, Error::TooLarge(_)), "vref bomb must fail TooLarge, got {err2:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_node_budget_and_hostile_inputs_are_rejected_cleanly() {
|
||||
let mut many =
|
||||
String::from(r#"{"meta":{"name":"Many"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}"#);
|
||||
for i in 2..502u64 {
|
||||
many.push_str(&format!(
|
||||
r#",{{"r":"full","pos":"a{i:04}1","node":{{"id":{i},"name":"R","parent":1,"type":"rectangle","width":1,"height":1}}}}"#
|
||||
));
|
||||
}
|
||||
many.push_str("]}");
|
||||
let err = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&many, None), 16 << 20, 10, 64 << 20).unwrap_err();
|
||||
assert!(matches!(&err, Error::Invalid(msg) if msg.contains("10-node limit")), "got {err:?}");
|
||||
|
||||
let cyclic = r#"{"meta":{"name":"Evil"},"records":[
|
||||
{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
|
||||
{"r":"mirror","id":2,"parent":1,"pos":"a0","source":3},
|
||||
{"r":"mirror","id":3,"parent":1,"pos":"a1","source":2}
|
||||
]}"#;
|
||||
let self_cycle = r#"{"meta":{"name":"Self"},"records":[
|
||||
{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
|
||||
{"r":"mirror","id":2,"parent":1,"pos":"a0","source":2}
|
||||
]}"#;
|
||||
assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(cyclic, None), 1 << 20, 100), Err(Error::Invalid(_))));
|
||||
assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(self_cycle, None), 1 << 20, 100), Err(Error::Invalid(_))));
|
||||
|
||||
for bad in [vec![], b"FCD".to_vec(), b"XXXX\x01\x00\x00\x00\x00".to_vec(), b"FCDS\x99\x00\x00\x00\x00".to_vec(), vec![0xFF; 64]] {
|
||||
assert!(decode_delta_snapshot(&bad, 1 << 20, 1000).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_metadata_and_design_review_roundtrip_matches_legacy_json() {
|
||||
let (mut doc, _, _) = design_system_doc(4);
|
||||
let page = doc.first_page().unwrap();
|
||||
doc.comments.push(Comment {
|
||||
id: 7,
|
||||
page,
|
||||
x: 10.0,
|
||||
y: 20.0,
|
||||
anchor: None,
|
||||
first: figcraft_doc::Message::new("Alice", "Check contrast", 1_700_000_000),
|
||||
resolved: false,
|
||||
replies: Vec::new(),
|
||||
read_by: None,
|
||||
});
|
||||
doc.dev_snapshots.insert(page, Arc::new(DevSnapshot { nodes: vec![Arc::new(doc.node(page).unwrap().clone())] }));
|
||||
doc.timer = Some(BoardTimer::Paused { left: 120_000 });
|
||||
let vote = Vote { per_person: 3, scope: Default::default(), ended: false, by: "Alice".into() };
|
||||
doc.vote = Some(vote.clone());
|
||||
doc.votes.entry("alice".into()).or_default().push(page);
|
||||
doc.vote_history.push(VoteRecord { vote, ballots: doc.votes.clone(), names: BTreeMap::new(), ended: 1_700_000_000 });
|
||||
doc.libraries = Arc::new(Libraries::default());
|
||||
doc.image_presets.push(ImagePreset { name: "Warm".into(), filters: Default::default() });
|
||||
doc.images.insert("logo_1".into(), ImageData { bytes: Arc::new(b"png-bytes".to_vec()), width: 32, height: 32 });
|
||||
doc.design_review = DesignReview { radii: vec![4.0; figcraft_doc::MAX_RADII + 10], ..DesignReview::default() };
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
|
||||
assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII);
|
||||
assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_safely_roundtrips_cyclic_source_references_as_full_records() {
|
||||
let mut doc = Document::new("CyclicInMemory");
|
||||
let page = doc.first_page().unwrap();
|
||||
let a = doc.create(page, NodeKind::Rectangle, "A", 0.0, 0.0, 50.0, 50.0).unwrap();
|
||||
let b = doc.create(page, NodeKind::Rectangle, "B", 60.0, 0.0, 50.0, 50.0).unwrap();
|
||||
doc.node_mut(a).unwrap().source = Some(b);
|
||||
doc.node_mut(b).unwrap().source = Some(a);
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let back = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 1 << 20, 100).unwrap();
|
||||
assert_docs_json_eq(replica.document(), back.document(), "cyclic source roundtrip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() {
|
||||
let (doc, _, _) = design_system_doc(2);
|
||||
let valid = encode_delta_snapshot(&Replica::new(doc)).unwrap();
|
||||
// Truncations across header and compressed body.
|
||||
for cut in [0, 1, 4, 8, 9, 10, valid.len() / 2, valid.len() - 1] {
|
||||
assert!(decode_delta_snapshot(&valid[..cut], 16 << 20, 10_000).is_err());
|
||||
}
|
||||
// Single-bit flips across header and body must either error cleanly or produce a valid Replica.
|
||||
let stride = (valid.len() / 64).max(1);
|
||||
for idx in (0..valid.len()).step_by(stride) {
|
||||
let mut mutated = valid.clone();
|
||||
mutated[idx] ^= 0x80;
|
||||
let _ = decode_delta_snapshot(&mutated, 16 << 20, 10_000);
|
||||
}
|
||||
}
|
||||
@@ -290,27 +290,61 @@ fn image_of(key: &str, value: &Json) -> Result<ImageData, Error> {
|
||||
image_within(key, value, ImageData::MAX_BYTES)
|
||||
}
|
||||
|
||||
/// [`image_of`] with `max_bytes` for the decoded size.
|
||||
pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
/// Validate raw image bytes and dimensions under the same security rules as [`image_of`] (#1086).
|
||||
pub(crate) fn validate_image_raw_within(key: &str, width: u32, height: u32, bytes: Vec<u8>, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
let v: ImageValue = value.read("image")?;
|
||||
if v.width > MAX_IMAGE_SIDE || v.height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {}×{} passes the {} a side may be", v.width, v.height, MAX_IMAGE_SIDE)));
|
||||
if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
|
||||
}
|
||||
let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
|
||||
if u64::try_from(v.bytes.len()).unwrap_or(u64::MAX) > max_encoded {
|
||||
return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
|
||||
}
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(v.bytes.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
|
||||
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_bytes {
|
||||
return Err(Error::Invalid(format!("image: {} bytes pass the {max_bytes} an image may be", bytes.len())));
|
||||
}
|
||||
if ImageData::claims_content_hash(key) && key != sha256_hex(&bytes) {
|
||||
return Err(Error::Invalid(format!("image: the bytes aren't what their key {key} hashes to")));
|
||||
}
|
||||
Ok(ImageData { bytes: Arc::new(bytes), width: v.width, height: v.height })
|
||||
Ok(ImageData { bytes: Arc::new(bytes), width, height })
|
||||
}
|
||||
|
||||
/// Validate base64-encoded image bytes and dimensions under [`ImageData::MAX_BYTES`].
|
||||
pub(crate) fn validate_image_base64(key: &str, width: u32, height: u32, encoded: &str) -> Result<ImageData, Error> {
|
||||
validate_image_base64_within(key, width, height, encoded, ImageData::MAX_BYTES)
|
||||
}
|
||||
|
||||
fn validate_image_base64_within(key: &str, width: u32, height: u32, encoded: &str, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
|
||||
}
|
||||
let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
|
||||
if u64::try_from(encoded.len()).unwrap_or(u64::MAX) > max_encoded {
|
||||
return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
|
||||
}
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(encoded.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
|
||||
validate_image_raw_within(key, width, height, bytes, max_bytes)
|
||||
}
|
||||
|
||||
/// Clamp oversized review settings in place (matches [`clamp_snapshot_design_review`]).
|
||||
pub(crate) fn clamp_design_review_config(config: &mut figcraft_doc::DesignReview) -> bool {
|
||||
if config.over_limits().is_empty() {
|
||||
return false;
|
||||
}
|
||||
config.radii.truncate(figcraft_doc::MAX_RADII);
|
||||
config.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
|
||||
config.disabled.truncate(figcraft_doc::MAX_DISABLED);
|
||||
true
|
||||
}
|
||||
|
||||
/// [`image_of`] with `max_bytes` for the decoded size.
|
||||
pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
let v: ImageValue = value.read("image")?;
|
||||
validate_image_base64_within(key, v.width, v.height, &v.bytes, max_bytes)
|
||||
}
|
||||
|
||||
macro_rules! doc_scalars {
|
||||
@@ -413,17 +447,12 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec<Change>) -> bool {
|
||||
let mut clamped_any = false;
|
||||
for c in changes {
|
||||
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
|
||||
&& let Ok(config) = value.read::<figcraft_doc::DesignReview>("design review")
|
||||
&& !config.over_limits().is_empty()
|
||||
&& let Ok(mut clamped) = value.read::<figcraft_doc::DesignReview>("design review")
|
||||
&& clamp_design_review_config(&mut clamped)
|
||||
&& let Ok(v) = Json::of(&clamped)
|
||||
{
|
||||
let mut clamped = config;
|
||||
clamped.radii.truncate(figcraft_doc::MAX_RADII);
|
||||
clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
|
||||
clamped.disabled.truncate(figcraft_doc::MAX_DISABLED);
|
||||
if let Ok(v) = Json::of(&clamped) {
|
||||
*value = v;
|
||||
clamped_any = true;
|
||||
}
|
||||
*value = v;
|
||||
clamped_any = true;
|
||||
}
|
||||
}
|
||||
clamped_any
|
||||
|
||||
@@ -303,7 +303,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
|
||||
let (key, bytes) = crate::image_tests::forged();
|
||||
state.snapshot.push(crate::image_tests::put(&key, 2, 1, bytes));
|
||||
let mut r = Server::restore(state, "", Limits::default()).unwrap();
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on restore");
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on restore");
|
||||
|
||||
// Left out on replay.
|
||||
let mut s = Server::new(base(), "", Limits::default());
|
||||
@@ -312,7 +312,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
|
||||
let mut r = Server::restore(state.clone(), "", Limits::default()).unwrap();
|
||||
let batch = vec![crate::image_tests::put(&key, 2, 1, bytes)];
|
||||
r.replay(Journal::Accepted(message::Accepted { seq: state.seq + 1, author: a.id(), batch_id: 90, changes: batch })).unwrap();
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on replay");
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on replay");
|
||||
}
|
||||
|
||||
/// A restart that left nothing out keeps resuming clients on the cheaper delta.
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
pub mod change;
|
||||
pub mod client;
|
||||
pub mod code;
|
||||
pub mod delta_snapshot;
|
||||
mod diff;
|
||||
mod docprops;
|
||||
pub mod frac;
|
||||
@@ -143,6 +144,10 @@ mod comment_access_tests;
|
||||
#[cfg(test)]
|
||||
mod deleted_cap_tests;
|
||||
#[cfg(test)]
|
||||
mod delta_dst_tests;
|
||||
#[cfg(test)]
|
||||
mod delta_snapshot_tests;
|
||||
#[cfg(test)]
|
||||
mod diff_tests;
|
||||
#[cfg(test)]
|
||||
mod entry_ids_tests;
|
||||
|
||||
@@ -44,9 +44,14 @@ pub const BRANCHES: &str = "branches";
|
||||
/// (older ones couldn't decode the variant at all).
|
||||
pub const DESIGN_REVIEW: &str = "design-review";
|
||||
|
||||
/// The word a client puts in its [`Hello::client_version`] when it reads
|
||||
/// [`CatchUp::DeltaSnapshot`]: a server sends a direct value-checked mirror-delta + vector-dedup
|
||||
/// compressed snapshot instead of `Vec<Change>` (#1819, #2041).
|
||||
pub const DELTA_SNAPSHOT: &str = "delta-snapshot";
|
||||
|
||||
/// 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} {BRANCHES}", env!("CARGO_PKG_VERSION"))
|
||||
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES} {DELTA_SNAPSHOT}", env!("CARGO_PKG_VERSION"))
|
||||
}
|
||||
|
||||
/// Whether `client_version` announces `word`.
|
||||
@@ -84,6 +89,11 @@ pub fn reads_branches(client_version: &str) -> bool {
|
||||
announces(client_version, BRANCHES)
|
||||
}
|
||||
|
||||
/// A [`Hello::client_version`] that announces [`DELTA_SNAPSHOT`].
|
||||
pub fn reads_delta_snapshot(client_version: &str) -> bool {
|
||||
announces(client_version, DELTA_SNAPSHOT)
|
||||
}
|
||||
|
||||
/// Join a file's session.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Hello {
|
||||
@@ -353,6 +363,10 @@ pub enum CatchUp {
|
||||
/// [`PACKED`]: a document's changes shrink several times over. The client reads it with
|
||||
/// [`unpack`] before anything else sees the welcome.
|
||||
Packed(Vec<u8>),
|
||||
/// A direct compressed mirror-delta & vector-deduplicated snapshot
|
||||
/// ([`crate::delta_snapshot`]), for a client whose hello announced [`DELTA_SNAPSHOT`].
|
||||
/// Appended last so earlier postcard discriminants remain unchanged.
|
||||
DeltaSnapshot(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Opens a connection that manages a server's files (instead of [`Hello`]): the server's admin
|
||||
@@ -1175,19 +1189,25 @@ pub fn pack(msg: &mut ServerMsg) -> Result<(), Error> {
|
||||
/// past `max_bytes` (untrusted input: the limit an unpacked welcome would have had to fit).
|
||||
/// Anything else is left as it is.
|
||||
pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> {
|
||||
if let ServerMsg::Welcome { catch_up, .. } = msg
|
||||
&& let CatchUp::Packed(packed) = catch_up
|
||||
{
|
||||
let mut raw = Vec::new();
|
||||
let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
|
||||
flate2::read::DeflateDecoder::new(packed.as_slice())
|
||||
.take(limit)
|
||||
.read_to_end(&mut raw)
|
||||
.map_err(|e| Error::Decode(format!("packed document: {e}")))?;
|
||||
if raw.len() > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
if let ServerMsg::Welcome { catch_up, .. } = msg {
|
||||
match catch_up {
|
||||
CatchUp::Packed(packed) => {
|
||||
let mut raw = Vec::new();
|
||||
let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
|
||||
flate2::read::DeflateDecoder::new(packed.as_slice())
|
||||
.take(limit)
|
||||
.read_to_end(&mut raw)
|
||||
.map_err(|e| Error::Decode(format!("packed document: {e}")))?;
|
||||
if raw.len() > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
*catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
|
||||
}
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
crate::delta_snapshot::check_header_limit(bytes, max_bytes)?;
|
||||
}
|
||||
CatchUp::Snapshot(_) | CatchUp::Delta(_) => {}
|
||||
}
|
||||
*catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -23,7 +23,9 @@ fn welcome() -> ServerMsg {
|
||||
}
|
||||
doc.repair();
|
||||
let mut s = Server::new(doc, "tok", Limits::default());
|
||||
let ClientMsg::Hello(h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
|
||||
let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
|
||||
// Test the legacy `packed` welcome path (a client from before `delta-snapshot`).
|
||||
h.client_version = "0.18.1 signals hosting comments packed design-review branches".into();
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
out.into_iter().find_map(|o| if let Outgoing::To(_, m @ ServerMsg::Welcome { .. }) = o { Some(m) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ fn a_long_absence_catches_up_with_a_snapshot() {
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
// A short absence gets the missed batches only.
|
||||
@@ -154,7 +154,7 @@ fn the_default_log_is_bounded_in_bytes_and_a_client_behind_it_catches_up_with_a_
|
||||
assert!(s.log_bytes() > 0, "recent batches are still kept");
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
// Within the log, a short absence still gets the missed batch only.
|
||||
@@ -195,7 +195,7 @@ fn after_a_snapshot_undo_leaves_what_others_changed_meanwhile() {
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
// Undo: the page name goes back, the frame keeps b's later name.
|
||||
let msgs = a.undo(&NoRecompute).unwrap();
|
||||
@@ -326,7 +326,7 @@ fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() {
|
||||
let (id, out) = restored.join(h).unwrap();
|
||||
assert_eq!(id, b.id(), "a reconnecting client keeps its id");
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })),
|
||||
"a clamped session hands out the snapshot, not a batch past the limits: {out:?}"
|
||||
);
|
||||
deliver(&mut b, &out);
|
||||
@@ -394,3 +394,33 @@ fn resume_needs_the_issued_secret() {
|
||||
let resend = come_back(&mut s, &mut host);
|
||||
assert!(resend.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_client_without_delta_snapshot_catches_up_with_a_legacy_snapshot() {
|
||||
let mut s = Server::new(base(), "tok", Limits { max_log_batches: 2, ..Limits::default() });
|
||||
let legacy_hello = || Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..hello() };
|
||||
let (_, out) = s.join(legacy_hello()).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
let Outgoing::To(_, w) = out.into_iter().next().unwrap() else { panic!() };
|
||||
let mut a = Client::join(w).unwrap();
|
||||
let mut b = join(&mut s);
|
||||
let page = s.document().first_page().unwrap();
|
||||
|
||||
// Disconnect legacy client `a` and overflow the 2-batch server log so `a` must catch up via
|
||||
// legacy `CatchUp::Snapshot` (never `DeltaSnapshot`).
|
||||
a.disconnect();
|
||||
s.leave(a.id());
|
||||
for i in 0..4 {
|
||||
let m = edit(&mut b, |d| d.node_mut(page).unwrap().name = format!("Legacy {i}")).unwrap();
|
||||
let out = s.receive(b.id(), m);
|
||||
deliver(&mut b, &out);
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(legacy_hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
|
||||
"legacy client without delta-snapshot must receive CatchUp::Snapshot on rejoin"
|
||||
);
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::change::{Change, Entry, Family, Prop, Target};
|
||||
use crate::message::{
|
||||
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,
|
||||
Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_delta_snapshot, reads_design_review, reads_signals,
|
||||
};
|
||||
use crate::replica::{Mode, Replica, create_change};
|
||||
use crate::{Error, Limits, diff, docprops, same_secret};
|
||||
@@ -126,6 +126,9 @@ pub struct Server {
|
||||
/// resuming client other bytes under a key it holds): every resuming client catches up with
|
||||
/// the snapshot, not the log.
|
||||
resync: bool,
|
||||
/// Cached compressed [`CatchUp::DeltaSnapshot`] for `self.seq`, so repeated joins of large
|
||||
/// files pay ~0 ms server CPU while no edit has arrived (#1819).
|
||||
delta_cache: Option<(u64, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// The most client ids a session remembers for reconnecting (the oldest disconnected ones go
|
||||
@@ -188,6 +191,7 @@ impl Server {
|
||||
design_review: BTreeSet::new(),
|
||||
spotlight: None,
|
||||
resync: false,
|
||||
delta_cache: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,10 +421,18 @@ impl Server {
|
||||
// The log holds every batch after `floor`.
|
||||
let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1));
|
||||
let reads_design_review = reads_design_review(&hello.client_version);
|
||||
let reads_delta = reads_delta_snapshot(&hello.client_version);
|
||||
let catch_up = match resume {
|
||||
Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => {
|
||||
CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect())
|
||||
}
|
||||
// Only send the cached delta snapshot to peers that also read `design-review`, since
|
||||
// the compressed payload carries the document's review config without per-peer filtering.
|
||||
// If delta encoding ever fails, fall back to the legacy snapshot instead of refusing join.
|
||||
_ if reads_delta && reads_design_review => match self.cached_delta_snapshot() {
|
||||
Ok(bytes) => CatchUp::DeltaSnapshot(bytes),
|
||||
Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
|
||||
},
|
||||
_ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
|
||||
};
|
||||
// A peer that doesn't read the review settings can't decode them: its catch-up carries
|
||||
@@ -686,9 +698,27 @@ impl Server {
|
||||
}
|
||||
self.state = next;
|
||||
self.seq += 1;
|
||||
self.delta_cache = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the cached compressed delta snapshot for `self.seq`, building it once on cache miss.
|
||||
/// Snapshots larger than 16 MiB compressed (e.g. files with large embedded images) are still
|
||||
/// sent, but are not pinned in `self.delta_cache` so room memory stays bounded.
|
||||
fn cached_delta_snapshot(&mut self) -> Result<Vec<u8>, Error> {
|
||||
const MAX_DELTA_CACHE_BYTES: usize = 16 << 20;
|
||||
if let Some((seq, bytes)) = &self.delta_cache
|
||||
&& *seq == self.seq
|
||||
{
|
||||
return Ok(bytes.clone());
|
||||
}
|
||||
let bytes = crate::delta_snapshot::encode_delta_snapshot(&self.state)?;
|
||||
if bytes.len() <= MAX_DELTA_CACHE_BYTES {
|
||||
self.delta_cache = Some((self.seq, bytes.clone()));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The document-level entries (styles, variables, collections, comments) a batch adds or
|
||||
/// removes, each with whether it is there afterwards. A new one is refused when its id lies in
|
||||
/// the space of another client this session gave an id to, or in a space at or above
|
||||
|
||||
@@ -417,15 +417,15 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() {
|
||||
let for_new = for_client(&out, capable.id());
|
||||
assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}");
|
||||
|
||||
// A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings.
|
||||
// A capable newcomer's catch-up (a fresh join, so a delta snapshot) carries the settings.
|
||||
let (_, out) = s.join(hello("tok")).unwrap();
|
||||
let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) =
|
||||
let Some(Outgoing::To(_, welcome @ ServerMsg::Welcome { .. })) =
|
||||
out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. })))
|
||||
else {
|
||||
panic!("no welcome");
|
||||
};
|
||||
let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") };
|
||||
assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}");
|
||||
let joined = Client::join(welcome).unwrap();
|
||||
assert!(!joined.document().design_review.is_default(), "capable newcomer carries design review settings");
|
||||
|
||||
// An old newcomer's catch-up carries none, and still has the rename.
|
||||
let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
|
||||
@@ -291,7 +291,9 @@ impl Sim {
|
||||
let ClientMsg::Hello(hello) = hello else { return Err(Error::Protocol("hello".into())) };
|
||||
let seen = self.clients.get(i).map_or(0, Client::seq);
|
||||
let (id, out) = self.server.join(hello).map_err(|m| Error::Protocol(format!("{m:?}")))?;
|
||||
if out.iter().any(|o| matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_), .. }) if *to == id)) {
|
||||
if out.iter().any(|o| {
|
||||
matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_) | crate::CatchUp::DeltaSnapshot(_), .. }) if *to == id)
|
||||
}) {
|
||||
self.snapshots += 1;
|
||||
if let Some(g) = self.gaps.get_mut(i) {
|
||||
g.push((seen, self.server.seq()));
|
||||
|
||||
@@ -256,6 +256,48 @@ fn text_style_json(cmd: &str, v: &Value) -> Result<TextStyle> {
|
||||
serde_json::from_value::<TextStyle>(v).map(|t| t.as_text_style()).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// A text style value from JSON: the character values from `style`, the paragraph values from
|
||||
/// `paragraph` (the same object for the flat `value` of `style.create`).
|
||||
fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result<StyleKind> {
|
||||
Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) })
|
||||
}
|
||||
|
||||
/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its
|
||||
/// variable bindings from the document, the new value and the style it replaces. The style
|
||||
/// redefined is the local text style of that name with the exported `id` (so a file re-importing
|
||||
/// its own export keeps each style's identity when two share a name), else the first of that
|
||||
/// name; never one in `touched`. True when one existed (with the style's id); the caller settles
|
||||
/// and propagates.
|
||||
pub(crate) fn upsert_text_style(
|
||||
doc: &mut Document,
|
||||
name: &str,
|
||||
id: Option<&str>,
|
||||
description: &str,
|
||||
style: &Value,
|
||||
paragraph: &Value,
|
||||
touched: &[StyleId],
|
||||
bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap<String, VariableId>,
|
||||
) -> Result<(StyleId, bool)> {
|
||||
let kind = text_kind("variable.import", style, paragraph)?;
|
||||
let eligible = |x: &Style| {
|
||||
x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id)
|
||||
};
|
||||
let same = id.and_then(|id| doc.styles.iter().position(|x| x.id == id && eligible(x))).or_else(|| doc.styles.iter().position(&eligible));
|
||||
let updated = same.is_some();
|
||||
let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i)));
|
||||
let mut st = match same.and_then(|i| doc.styles.get(i)) {
|
||||
Some(x) => Style { kind, bound, ..x.clone() },
|
||||
None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound },
|
||||
};
|
||||
crate::style_vars::prune(&mut st);
|
||||
let sid = st.id.clone();
|
||||
match same.and_then(|i| doc.styles.get_mut(i)) {
|
||||
Some(slot) => *slot = st,
|
||||
None => doc.styles.push(st),
|
||||
}
|
||||
Ok((sid, updated))
|
||||
}
|
||||
|
||||
/// The text style definition a layer's chars from `at` (None = its base style) show.
|
||||
fn text_style_of(n: &Node, at: Option<usize>) -> Option<TextStyle> {
|
||||
let t = n.kind.text()?;
|
||||
@@ -361,7 +403,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = if let Some(v) = get(p, "value") {
|
||||
match t.as_str() {
|
||||
"paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? },
|
||||
"text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) },
|
||||
"text" => text_kind(cmd, v, v)?,
|
||||
"effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
|
||||
"grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
|
||||
_ => return Err(bad(cmd, "type: paint|text|effect|grid")),
|
||||
@@ -567,7 +609,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint");
|
||||
Some(match cur {
|
||||
"paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? },
|
||||
"text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) },
|
||||
"text" => text_kind(cmd, v, v)?,
|
||||
"effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
|
||||
_ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, Variable, VariableId, VariableValue, Variables, trim_num};
|
||||
use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, StyleKind, Variable, VariableId, VariableValue, Variables, trim_num};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -18,14 +18,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"variable.export",
|
||||
"Export variables",
|
||||
"{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-<collection>=\"<mode>\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written",
|
||||
"{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-<collection>=\"<mode>\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written; the json format adds a top-level `textStyles` array (this file's text styles as style.list returns them, `bound` holding the ids `meta.variables` is keyed by), a FigCraft extension beside the REST-compatible `meta`",
|
||||
false,
|
||||
export
|
||||
),
|
||||
spec!(
|
||||
"variable.import",
|
||||
"Import variables",
|
||||
"{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}",
|
||||
"{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, styles {added, updated}, warnings (also when it holds no variables, or fewer than its collections list)}",
|
||||
true,
|
||||
import
|
||||
),
|
||||
@@ -44,8 +44,13 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(cmd, "collections: [collection ids or names]")),
|
||||
};
|
||||
let text = match string(p, "format").as_deref().unwrap_or("json") {
|
||||
"json" => serde_json::to_string_pretty(&figcraft_format::rest::export_variables(&doc.variables, &colls))
|
||||
.map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
"json" => {
|
||||
let mut out = figcraft_format::rest::export_variables(&doc.variables, &colls);
|
||||
if let Value::Object(m) = &mut out {
|
||||
m.insert("textStyles".into(), text_styles(doc));
|
||||
}
|
||||
serde_json::to_string_pretty(&out).map_err(|e| EngineError::Other(e.to_string()))?
|
||||
}
|
||||
"css" => css(doc, &colls, false),
|
||||
"tailwind" => css(doc, &colls, true),
|
||||
"dart" => dart(&doc.variables, &colls),
|
||||
@@ -60,6 +65,108 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// This file's own text styles as `style.list {type: "text"}` returns them (values and `bound`,
|
||||
/// the variable ids being those `meta.variables` is keyed by): the `textStyles` of the variables
|
||||
/// JSON, a FigCraft extension beside the REST-compatible `meta`.
|
||||
fn text_styles(doc: &Document) -> Value {
|
||||
let own = |st: &&figcraft_doc::Style| matches!(st.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &st.id);
|
||||
Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect())
|
||||
}
|
||||
|
||||
/// At most this many text styles are read from a variables JSON, this many bindings per style, and
|
||||
/// this many chars of a description.
|
||||
const MAX_TEXT_STYLES: usize = 10_000;
|
||||
const MAX_STYLE_BINDINGS: usize = 32;
|
||||
const MAX_STYLE_DESCRIPTION: usize = 10_000;
|
||||
|
||||
/// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's
|
||||
/// text style of the same name (the first one this import hasn't touched yet), others are added;
|
||||
/// bindings follow `ids` (imported variable id to this file's). Returns (added, updated); what
|
||||
/// can't be read is a warning.
|
||||
fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap<VariableId, VariableId>, warnings: &mut Vec<String>) -> (usize, usize) {
|
||||
let Value::Array(list) = entries else {
|
||||
warnings.push("`textStyles` should be an array of text styles: skipped".to_string());
|
||||
return (0, 0);
|
||||
};
|
||||
if list.len() > MAX_TEXT_STYLES {
|
||||
warnings.push(format!("`textStyles` holds {} entries: only the first {MAX_TEXT_STYLES} are read", list.len()));
|
||||
}
|
||||
let (mut added, mut updated) = (0, 0);
|
||||
let mut touched = Vec::new();
|
||||
for (i, e) in list.iter().take(MAX_TEXT_STYLES).enumerate() {
|
||||
let name = e.get("name").and_then(Value::as_str).and_then(super::variables::clean_name);
|
||||
let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else {
|
||||
warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped"));
|
||||
continue;
|
||||
};
|
||||
let description: String = e.get("description").and_then(Value::as_str).unwrap_or_default().chars().take(MAX_STYLE_DESCRIPTION).collect();
|
||||
let wanted = e.get("bound");
|
||||
let bind = |doc: &Document, kind: &StyleKind, current: Option<&figcraft_doc::Style>| {
|
||||
text_style_bindings(&name, wanted, ids, doc, kind, current, warnings)
|
||||
};
|
||||
let id = e.get("id").and_then(Value::as_str);
|
||||
match super::styles::upsert_text_style(doc, &name, id, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) {
|
||||
Ok((sid, was)) => {
|
||||
touched.push(sid);
|
||||
if was {
|
||||
updated += 1;
|
||||
} else {
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
Err(EngineError::BadParams { msg, .. }) => warnings.push(format!("text style `{name}`: {msg}")),
|
||||
Err(err) => warnings.push(format!("text style `{name}`: {err}")),
|
||||
}
|
||||
}
|
||||
crate::style_vars::settle(doc);
|
||||
for sid in touched {
|
||||
super::styles::propagate_style(doc, &sid);
|
||||
}
|
||||
(added, updated)
|
||||
}
|
||||
|
||||
/// The bindings an imported text style `name` keeps, as this file's variable ids: a variable
|
||||
/// follows `ids`, or stays when `current` (the style it replaces) already holds that same id for
|
||||
/// the field (a file's own export names variables the import doesn't carry); a field the style
|
||||
/// lacks or a variable of the wrong type is a warning, as are more than [`MAX_STYLE_BINDINGS`].
|
||||
fn text_style_bindings(
|
||||
name: &str,
|
||||
wanted: Option<&Value>,
|
||||
ids: &BTreeMap<VariableId, VariableId>,
|
||||
doc: &Document,
|
||||
kind: &StyleKind,
|
||||
current: Option<&figcraft_doc::Style>,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> BTreeMap<String, VariableId> {
|
||||
let mut bound = BTreeMap::new();
|
||||
let Some(Value::Object(m)) = wanted else { return bound };
|
||||
if m.len() > MAX_STYLE_BINDINGS {
|
||||
warnings.push(format!("text style `{name}`: {} bindings: only the first {MAX_STYLE_BINDINGS} are read", m.len()));
|
||||
}
|
||||
for (field, id) in m.iter().take(MAX_STYLE_BINDINGS) {
|
||||
let held = current.and_then(|c| c.bound.get(field)).filter(|h| id.as_str() == Some(h.as_str()));
|
||||
let local = id.as_str().and_then(|v| ids.get(v)).or(held);
|
||||
match checked_binding(doc, kind, field, local) {
|
||||
Ok(local) => {
|
||||
bound.insert(field.clone(), local.clone());
|
||||
}
|
||||
Err(why) => warnings.push(format!("text style `{name}`: {why}: left unbound")),
|
||||
}
|
||||
}
|
||||
bound
|
||||
}
|
||||
|
||||
/// `local` when it is a variable of this file of the type a text style's `field` takes.
|
||||
fn checked_binding<'a>(doc: &Document, kind: &StyleKind, field: &str, local: Option<&'a VariableId>) -> std::result::Result<&'a VariableId, String> {
|
||||
let local = local.ok_or_else(|| format!("`{field}` is bound to a variable the JSON doesn't hold"))?;
|
||||
let want = crate::style_vars::field_type(kind, field).ok_or_else(|| format!("no field `{field}` to bind"))?;
|
||||
match doc.variables.get_by_id(local).map(|v| v.kind) {
|
||||
Some(k) if k == want => Ok(local),
|
||||
Some(k) => Err(format!("`{field}` takes a {} variable, not a {} one", want.id(), k.id())),
|
||||
None => Err(format!("`{field}` is bound to a variable this file lacks")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a CSS comment or quoted string body.
|
||||
fn css_safe(text: &str) -> String {
|
||||
text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ")
|
||||
@@ -362,5 +469,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"collections": added_colls, "variables": added, "updated": updated, "warnings": warnings}))
|
||||
let (styles_added, styles_updated) = match v.get("textStyles") {
|
||||
Some(entries) => import_text_styles(doc, entries, &ids, &mut warnings),
|
||||
None => (0, 0),
|
||||
};
|
||||
Ok(json!({
|
||||
"collections": added_colls, "variables": added, "updated": updated,
|
||||
"styles": {"added": styles_added, "updated": styles_updated}, "warnings": warnings
|
||||
}))
|
||||
}
|
||||
@@ -304,6 +304,166 @@ fn variables_import_checks_what_it_reads() {
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_styles_in_a_variables_json_are_checked_and_capped() {
|
||||
let mut s = Session::new();
|
||||
let mode = json!([{"modeId": "m", "name": "Mode 1"}]);
|
||||
// Junk `textStyles` entries are skipped with a warning, never an internal error.
|
||||
let empty = json!({"variableCollections": {}, "variables": {}});
|
||||
for junk in
|
||||
[json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": "x", "style": {"font_size": "big"}}])]
|
||||
{
|
||||
let mut file = empty.clone();
|
||||
file["textStyles"] = junk.clone();
|
||||
match s.execute("variable.import", &json!({"variables": file})) {
|
||||
Ok(r) => assert!(r["warnings"].to_string().contains("text style") || r["warnings"].to_string().contains("textStyles"), "{junk}: {r}"),
|
||||
Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"),
|
||||
}
|
||||
}
|
||||
let mut file = empty.clone();
|
||||
file["textStyles"] = json!([{"name": "x", "style": {"font_size": "big"}}]);
|
||||
let r = ex(&mut s, "variable.import", json!({"variables": file}));
|
||||
assert!(r["warnings"].to_string().contains("text style `x`"), "{r}");
|
||||
assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in");
|
||||
// A name is cut to 500 chars, a description to 10,000, and only the first 10,000 entries are read.
|
||||
let mut file = empty.clone();
|
||||
file["textStyles"] = json!([{"name": "n".repeat(100_000), "description": "d".repeat(100_000), "style": {}}]);
|
||||
ex(&mut s, "variable.import", json!({"variables": file}));
|
||||
let styles = &s.doc().unwrap().styles;
|
||||
assert_eq!(styles.len(), 1);
|
||||
assert!(styles[0].name.chars().count() <= 500 && styles[0].description.chars().count() <= 10_000, "{}", styles[0].name.len());
|
||||
let mut file = empty.clone();
|
||||
file["textStyles"] = Value::Array((0..10_050).map(|i| json!({"name": format!("s{i}"), "style": {}})).collect());
|
||||
let r = ex(&mut s, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(r["styles"]["added"], 10_000, "{}", r["styles"]);
|
||||
assert!(r["warnings"].to_string().contains("10000") || r["warnings"].to_string().contains("10,000"), "{}", r["warnings"]);
|
||||
// A binding to a field the style lacks, or to a variable of another type, is dropped with a warning.
|
||||
let mut t = Session::new();
|
||||
let file = json!({
|
||||
"meta": {"variableCollections": {"c": {"id": "c", "name": "T", "modes": mode}},
|
||||
"variables": {"s": {"id": "s", "name": "s", "variableCollectionId": "c", "resolvedType": "STRING", "valuesByMode": {"m": "x"}}}},
|
||||
"textStyles": [{"name": "t", "style": {}, "bound": {"fontSize": "s", "nope": "s"}}]
|
||||
});
|
||||
let r = ex(&mut t, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(r["styles"]["added"], 1, "{r}");
|
||||
assert!(t.doc().unwrap().styles[0].bound.is_empty(), "{r}");
|
||||
let w = r["warnings"].as_array().unwrap().iter().filter_map(|x| x.as_str()).filter(|x| x.contains("text style `t`")).collect::<Vec<_>>();
|
||||
assert!(w.len() == 2 && w.iter().any(|x| x.contains("fontSize")) && w.iter().any(|x| x.contains("nope")), "{r}");
|
||||
}
|
||||
|
||||
/// A file with a "Body" text style whose size, line height and style name follow variables.
|
||||
fn body_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"}));
|
||||
ex(
|
||||
&mut s,
|
||||
"style.create",
|
||||
json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%", "paragraphSpacing": 8, "listStyle": "bulleted"}}),
|
||||
);
|
||||
for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] {
|
||||
ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_export_carries_text_styles_with_their_bindings() {
|
||||
let mut s = body_session();
|
||||
let out = ex(&mut s, "variable.export", json!({}));
|
||||
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
|
||||
let styles = file["textStyles"].as_array().unwrap();
|
||||
assert_eq!(styles.len(), 1, "{file}");
|
||||
assert_eq!(styles[0]["name"], "Body");
|
||||
assert_eq!(styles[0]["style"]["font_size"], 16.0);
|
||||
assert_eq!(styles[0]["style"]["font_style"], "Bold");
|
||||
assert_eq!(styles[0]["paragraph"]["paragraph_spacing"], 8.0, "{file}");
|
||||
assert_eq!(styles[0]["paragraph"]["list"], "bulleted", "{file}");
|
||||
let mut keys: Vec<&str> = styles[0].as_object().unwrap().keys().map(String::as_str).collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["bound", "description", "id", "name", "paragraph", "style", "type"], "the entry's shape is public: {file}");
|
||||
assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns");
|
||||
for field in ["fontSize", "lineHeight", "fontStyle"] {
|
||||
let id = styles[0]["bound"][field].as_str().unwrap();
|
||||
assert!(file["meta"]["variables"].get(id).is_some(), "{field} -> {id}");
|
||||
}
|
||||
let css = ex(&mut s, "variable.export", json!({"format": "css"}));
|
||||
assert!(!css["text"].as_str().unwrap().contains("Body"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_styles_round_trip_through_variables_import() {
|
||||
let mut s = body_session();
|
||||
let out = ex(&mut s, "variable.export", json!({}));
|
||||
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
|
||||
let mut t = Session::new();
|
||||
ex(&mut t, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]}));
|
||||
for (name, v) in [("gap", 4), ("pad", 6), ("lh", 30)] {
|
||||
ex(&mut t, "variable.create", json!({"collection": "Type", "name": name, "type": "number", "value": v}));
|
||||
}
|
||||
let r = ex(&mut t, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}");
|
||||
assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
|
||||
let doc = t.doc().unwrap();
|
||||
let body = doc.styles.iter().find(|x| x.name == "Body").unwrap();
|
||||
let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect();
|
||||
assert_eq!(body.bound.len(), 3, "{body:?}");
|
||||
assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables");
|
||||
for (field, name) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] {
|
||||
assert_eq!(doc.variables.get(&body.bound[field]).unwrap().name, name, "{field}");
|
||||
}
|
||||
let StyleKind::Text { paragraph, .. } = &body.kind else { panic!("{body:?}") };
|
||||
assert_eq!((paragraph.paragraph_spacing, paragraph.list), (8.0, ListStyle::Bulleted));
|
||||
let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") };
|
||||
assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0));
|
||||
// Again: the style is updated, not duplicated.
|
||||
let r = ex(&mut t, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}");
|
||||
assert_eq!(t.doc().unwrap().styles.len(), 1);
|
||||
assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
|
||||
assert_eq!(t.doc().unwrap().styles[0].bound.len(), 3);
|
||||
// A binding to a variable the JSON lacks is dropped with a warning naming the style.
|
||||
let mut u = Session::new();
|
||||
let mut lone = file.clone();
|
||||
lone["meta"] = json!({"variableCollections": {}, "variables": {}});
|
||||
let r = ex(&mut u, "variable.import", json!({"variables": lone}));
|
||||
assert_eq!(r["styles"]["added"], 1, "{r}");
|
||||
assert!(u.doc().unwrap().styles[0].bound.is_empty());
|
||||
assert!(r["warnings"].to_string().contains("Body"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_files_own_export_leaves_its_text_styles_alone() {
|
||||
let mut s = body_session();
|
||||
ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}}));
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Other", "modes": ["Base"]}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Other", "name": "o", "type": "number", "value": 1}));
|
||||
let out = ex(&mut s, "variable.export", json!({"collections": ["Other"]}));
|
||||
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
|
||||
let before = s.doc().unwrap().styles.clone();
|
||||
assert_eq!(before.len(), 2);
|
||||
let r = ex(&mut s, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(s.doc().unwrap().styles, before, "{r}");
|
||||
assert_eq!(r["styles"], json!({"added": 0, "updated": 2}), "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("left unbound"), "{r}");
|
||||
}
|
||||
|
||||
/// Two text styles share a name and are reordered after the export: re-importing it gives each
|
||||
/// style its own values back (matched by the exported id), not its namesake's.
|
||||
#[test]
|
||||
fn a_files_own_export_keeps_each_same_named_style_after_a_reorder() {
|
||||
let mut s = body_session();
|
||||
ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}}));
|
||||
let out = ex(&mut s, "variable.export", json!({}));
|
||||
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
|
||||
s.doc_mut().unwrap().styles.reverse();
|
||||
let before = s.doc().unwrap().styles.clone();
|
||||
let r = ex(&mut s, "variable.import", json!({"variables": file}));
|
||||
assert_eq!(s.doc().unwrap().styles, before, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_import_caps_the_file_it_reads() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id()));
|
||||
|
||||
@@ -226,6 +226,9 @@ impl FigApp {
|
||||
crate::control::drain(self, &ctx);
|
||||
windows::requests(self, &ctx);
|
||||
selection_spacing::sync(self, &ctx);
|
||||
let doc_uid = self.session.ds().ok().map(|d| d.uid);
|
||||
let cur_sel = self.session.selection().to_vec();
|
||||
widgets::update_selection_snapshot(&ctx, doc_uid, cur_sel);
|
||||
// Before any widget: the navigation keys (F6, Tab, arrows, Escape) move the keyboard.
|
||||
a11y::begin(self, &ctx, ui.scope_id());
|
||||
if self.ui.title_bar == TitleBar::Custom {
|
||||
@@ -360,6 +363,9 @@ impl FigApp {
|
||||
.show(ui, |ui| {
|
||||
let label = right_tab_label(self.ui.right_tab);
|
||||
a11y::region(&mut self.ui.nav, ui, a11y::Region::Properties, egui::accesskit::Role::Pane, label);
|
||||
let doc_uid = self.session.ds().ok().map(|d| d.uid);
|
||||
let cur_sel = self.session.selection().to_vec();
|
||||
widgets::update_selection_snapshot(ui.ctx(), doc_uid, cur_sel);
|
||||
right::right_panel(self, ui)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -548,8 +548,9 @@ pub fn background(app: &mut FigApp, ctx: &Context) {
|
||||
app.control_queue.push(r);
|
||||
continue;
|
||||
}
|
||||
if r.method == "ui.input" {
|
||||
// Keep one synthetic batch until a real UI pass consumes it.
|
||||
if r.method == "ui.input" || app.applied_frame == Some(crate::windows::viewport(target)) {
|
||||
// Keep one synthetic batch until a real UI pass consumes it, and what was queued behind
|
||||
// a batch already taken until the pass that applies it has presented.
|
||||
app.control_queue.push(r);
|
||||
continue;
|
||||
}
|
||||
@@ -777,6 +778,13 @@ fn route_queued(app: &mut FigApp, ctx: &Context, viewport: egui::ViewportId, now
|
||||
admit(app, r, target, now);
|
||||
return;
|
||||
}
|
||||
if app.applied_frame == Some(viewport) {
|
||||
// This pass applies an injected batch: what was queued behind it runs next frame, so a
|
||||
// file switch can't send the batch's keys or pointer into another document (#1503).
|
||||
ctx.request_repaint();
|
||||
app.control_queue.push(r);
|
||||
return;
|
||||
}
|
||||
if !r.begin() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -576,6 +576,54 @@ fn injected_input_is_acknowledged_only_after_the_pass_that_applies_it() {
|
||||
assert!(!u.app.control_synthetic, "the fence ends with the frame");
|
||||
}
|
||||
|
||||
/// Asserts a document switch that reaches the frame applying a batch waits for the next frame:
|
||||
/// the batch's Delete edits the file it was sent for, never the one switched to (#1503).
|
||||
#[test]
|
||||
fn a_switch_queued_behind_an_applied_batch_never_takes_its_input() {
|
||||
let mut s = Session::empty();
|
||||
let rect = |s: &mut Session, name: &str| {
|
||||
s.execute("file.new", &json!({"name": name})).unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("node.create", &json!({"type": "rectangle", "x": 0, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
};
|
||||
let (a, b) = (rect(&mut s, "A"), rect(&mut s, "B"));
|
||||
let index = |s: &Session, name: &str| s.docs.iter().position(|d| d.doc.name == name).expect("file");
|
||||
s.active = index(&s, "A");
|
||||
let mut u = Ui::new(s);
|
||||
let (tx, input) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(ControlRequest {
|
||||
id: json!(30),
|
||||
method: "ui.input".into(),
|
||||
params: json!({"events": [{"move": [700.0, 450.0]}, {"key": "Delete"}]}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
u.frame(vec![]);
|
||||
// The window takes A's batch; the switch to B arrives before that frame's control drain.
|
||||
let events = crate::windows::take_input(&mut u.app, egui::ViewportId::ROOT);
|
||||
assert!(!events.is_empty(), "A's batch is in the frame");
|
||||
let (tx, switch) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(ControlRequest {
|
||||
id: json!(31),
|
||||
method: "engine.execute".into(),
|
||||
params: json!({"command": "doc.switch", "params": {"index": index(&u.app.session, "B")}}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
u.frame(events);
|
||||
assert!(input.try_recv().expect("the batch is acknowledged").result.is_ok());
|
||||
assert!(switch.try_recv().is_err(), "the switch waits for the frame after the batch");
|
||||
u.frame(vec![]);
|
||||
assert!(switch.try_recv().expect("the switch runs next").result.is_ok());
|
||||
let file = |u: &Ui, name: &str| u.app.session.docs[index(&u.app.session, name)].doc.clone();
|
||||
assert_eq!(u.app.session.active, index(&u.app.session, "B"));
|
||||
assert!(!file(&u, "A").contains(a), "the batch edited the file it was sent for");
|
||||
assert!(file(&u, "B").contains(b), "and left the file switched to alone");
|
||||
}
|
||||
|
||||
/// Asserts a discarded pass neither acknowledges nor replays an injected batch; the presented
|
||||
/// pass acknowledges once.
|
||||
#[test]
|
||||
|
||||
@@ -1751,3 +1751,121 @@ fn a_boolean_groups_field_shows_the_radius_it_draws() {
|
||||
type_into(&mut u, "Corner radius", "+10", Key::Enter);
|
||||
assert_eq!(u.app.session.doc().unwrap().node(g).unwrap().corners.radii, [10.0; 4], "0 + 10, not 30 + 10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_is_dropped_when_the_selection_changes() {
|
||||
let (mut u, _a, b) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("23".into())]);
|
||||
|
||||
// Deselect (clear selection) while field is in editing state
|
||||
u.app.run("select.clear", json!({}));
|
||||
u.frame(vec![]);
|
||||
|
||||
// Now select b (which has height 20)
|
||||
u.app.run("select.set", json!({"ids": [b]}));
|
||||
u.frame(vec![]);
|
||||
|
||||
// Verify height field does NOT stay stuck in editing state
|
||||
let h_editing = u.ctx.data(|d| d.get_temp::<String>(Id::unique("lay_h").with("editing")));
|
||||
assert_eq!(h_editing, None, "Height field must not be stuck in editing state after deselect and reselect");
|
||||
assert_eq!(field(&mut u, "Height").1, "20", "Height field must show layer b's height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_canvas_while_editing_number_field_commits_value() {
|
||||
let (mut u, a, _) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("50".into())]);
|
||||
|
||||
// Click on empty canvas (outside the layers and panels)
|
||||
let canvas_click = pos2(500.0, 500.0);
|
||||
click(&mut u, canvas_click);
|
||||
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(a).unwrap().height, 50.0, "Clicking canvas must commit the edited field value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_draft_is_retained_when_window_loses_focus() {
|
||||
let (mut u, _a, _) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("55".into())]);
|
||||
|
||||
// Simulate window deactivation (e.g. user switching windows/applications)
|
||||
u.frame_raw(egui::RawInput { focused: false, ..Default::default() });
|
||||
|
||||
// Verify draft is still present
|
||||
let h_editing = u.ctx.data(|d| d.get_temp::<String>(Id::unique("lay_h").with("editing")));
|
||||
assert_eq!(h_editing.as_deref(), Some("55"), "field draft must be retained when window loses focus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_different_layer_in_layers_panel_drops_draft() {
|
||||
let (mut u, a, b) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("99".into())]);
|
||||
|
||||
// Click layer B in the Layers panel with press and release in the same frame
|
||||
let b_row = u.row_at(b);
|
||||
u.frame(vec![
|
||||
Event::PointerButton { pos: b_row, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::PointerButton { pos: b_row, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
u.frame(vec![]);
|
||||
|
||||
// Verify draft was dropped, A was not committed with 99, and B retains its height
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(a).unwrap().height, 30.0, "Layer A must retain its original height and not commit the draft");
|
||||
assert_eq!(doc.node(b).unwrap().height, 20.0, "Layer B must retain its original height");
|
||||
let h_editing = u.ctx.data(|d| d.get_temp::<String>(Id::unique("lay_h").with("editing")));
|
||||
assert_eq!(h_editing, None, "stale draft must not leak into newly selected layer");
|
||||
assert_eq!(field(&mut u, "Height").1, "20", "Height field must show layer b's height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_is_dropped_across_empty_selection_transition() {
|
||||
let (mut u, a, _) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("23".into())]);
|
||||
|
||||
// Clear selection for one frame (Design panel will not render Height during this frame)
|
||||
u.app.session.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
u.frame(vec![]);
|
||||
|
||||
// Update A's height externally while deselected
|
||||
u.app.session.execute("node.set", &json!({"id": a, "props": {"height": 60.0}})).unwrap();
|
||||
|
||||
// Reselect A
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
|
||||
// Draft must have been invalidated across the hidden selection transition
|
||||
let h_editing = u.ctx.data(|d| d.get_temp::<String>(Id::unique("lay_h").with("editing")));
|
||||
assert_eq!(h_editing, None, "draft must be invalidated across empty selection transition");
|
||||
assert_eq!(field(&mut u, "Height").1, "60", "Height field must display A's updated height");
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(a).unwrap().height, 60.0, "Layer A height must remain 60");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_is_dropped_when_layer_value_changes_externally() {
|
||||
let (mut u, a, _) = setup();
|
||||
let (h_pos, _) = field(&mut u, "Height");
|
||||
click(&mut u, h_pos);
|
||||
u.frame(vec![Event::Text("23".into())]);
|
||||
|
||||
// Change A's height externally through node.set while selection remains unchanged
|
||||
u.app.session.execute("node.set", &json!({"id": a, "props": {"height": 75.0}})).unwrap();
|
||||
u.frame(vec![]);
|
||||
|
||||
// Draft must be dropped and field must show the new size 75
|
||||
let h_editing = u.ctx.data(|d| d.get_temp::<String>(Id::unique("lay_h").with("editing")));
|
||||
assert_eq!(h_editing, None, "draft must be dropped when layer size changes");
|
||||
assert_eq!(field(&mut u, "Height").1, "75", "Height field must show the new layer size");
|
||||
}
|
||||
+145
-22
@@ -294,6 +294,123 @@ fn cancel_retargeted_field_save(ui: &mut Ui, id: Id) {
|
||||
ui.memory_mut(|m| m.surrender_focus(editor));
|
||||
}
|
||||
|
||||
/// A snapshot of the active document and selection generation.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub(crate) struct SelectionSnapshot {
|
||||
pub(crate) doc_uid: Option<u64>,
|
||||
pub(crate) selection: Vec<figcraft_doc::NodeId>,
|
||||
pub(crate) generation: u64,
|
||||
}
|
||||
|
||||
pub(crate) fn update_selection_snapshot(ctx: &egui::Context, doc_uid: Option<u64>, selection: Vec<figcraft_doc::NodeId>) {
|
||||
let sel_id = egui::Id::unique("app_current_selection");
|
||||
let prev: Option<SelectionSnapshot> = ctx.data(|d| d.get_temp(sel_id));
|
||||
let generation = match prev {
|
||||
Some(ref p) if p.doc_uid == doc_uid && p.selection == selection => p.generation,
|
||||
Some(ref p) => p.generation.wrapping_add(1),
|
||||
None => 1,
|
||||
};
|
||||
ctx.data_mut(|d| {
|
||||
d.insert_temp(sel_id, SelectionSnapshot { doc_uid, selection, generation });
|
||||
});
|
||||
}
|
||||
|
||||
/// Drop a field draft when the active selection, document, or layer value has changed since the edit began.
|
||||
fn sync_field_owner(ui: &mut Ui, id: Id, current_val: Option<f64>) -> (Option<String>, Option<SelectionSnapshot>) {
|
||||
let editing_id = id.with("editing");
|
||||
let owner_id = id.with("owner_sel");
|
||||
let owner_val_id = id.with("owner_val");
|
||||
let sel_id = egui::Id::unique("app_current_selection");
|
||||
let cur_snap: Option<SelectionSnapshot> = ui.data(|d| d.get_temp(sel_id));
|
||||
let owner_snap: Option<SelectionSnapshot> = ui.data(|d| d.get_temp(owner_id));
|
||||
let owner_val: Option<Option<f64>> = ui.data(|d| d.get_temp(owner_val_id));
|
||||
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
|
||||
|
||||
let selection_changed = editing.is_some()
|
||||
&& match (&cur_snap, &owner_snap) {
|
||||
(Some(cur), Some(owner)) => cur != owner,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
let value_changed = editing.is_some() && owner_val.is_some() && owner_val != Some(current_val);
|
||||
|
||||
if selection_changed || value_changed {
|
||||
ui.data_mut(|d| {
|
||||
d.remove::<String>(editing_id);
|
||||
d.remove::<String>(id.with("kept"));
|
||||
d.remove::<SelectionSnapshot>(owner_id);
|
||||
d.remove::<Option<f64>>(owner_val_id);
|
||||
d.remove::<bool>(id.with("selectall"));
|
||||
d.remove::<bool>(id.with("cmdstart"));
|
||||
d.remove::<bool>(id.with("edited"));
|
||||
});
|
||||
ui.memory_mut(|m| m.surrender_focus(id.with("te")));
|
||||
editing = None;
|
||||
}
|
||||
(editing, cur_snap)
|
||||
}
|
||||
|
||||
/// Drop a text field draft when the active selection, document, or string value has changed since the edit began.
|
||||
fn sync_text_field_owner(ui: &mut Ui, id: Id, current_val: &str) -> (Option<String>, Option<SelectionSnapshot>) {
|
||||
let editing_id = id.with("editing");
|
||||
let owner_id = id.with("owner_sel");
|
||||
let owner_text_id = id.with("owner_text");
|
||||
let sel_id = egui::Id::unique("app_current_selection");
|
||||
let cur_snap: Option<SelectionSnapshot> = ui.data(|d| d.get_temp(sel_id));
|
||||
let owner_snap: Option<SelectionSnapshot> = ui.data(|d| d.get_temp(owner_id));
|
||||
let owner_text: Option<String> = ui.data(|d| d.get_temp(owner_text_id));
|
||||
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
|
||||
|
||||
let selection_changed = editing.is_some()
|
||||
&& match (&cur_snap, &owner_snap) {
|
||||
(Some(cur), Some(owner)) => cur != owner,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
let value_changed = editing.is_some() && owner_text.as_deref().is_some_and(|t| t != current_val);
|
||||
|
||||
if selection_changed || value_changed {
|
||||
ui.data_mut(|d| {
|
||||
d.remove::<String>(editing_id);
|
||||
d.remove::<SelectionSnapshot>(owner_id);
|
||||
d.remove::<String>(owner_text_id);
|
||||
});
|
||||
ui.memory_mut(|m| m.surrender_focus(id.with("te")));
|
||||
editing = None;
|
||||
}
|
||||
(editing, cur_snap)
|
||||
}
|
||||
|
||||
/// Discard an editor's active draft and surrender focus.
|
||||
fn clear_field_editor(ui: &mut Ui, id: Id) {
|
||||
ui.data_mut(|d| {
|
||||
d.remove::<String>(id.with("editing"));
|
||||
d.remove::<SelectionSnapshot>(id.with("owner_sel"));
|
||||
d.remove::<Option<f64>>(id.with("owner_val"));
|
||||
d.remove::<String>(id.with("owner_text"));
|
||||
});
|
||||
ui.memory_mut(|m| m.surrender_focus(id.with("te")));
|
||||
}
|
||||
|
||||
/// Paint a lead label or icon for a number field.
|
||||
fn paint_number_field_lead(ui: &mut Ui, lead: &Lead, lead_rect: Rect, rect: Rect, lead_w: f32, lead_resp: &egui::Response, t: &Tokens) {
|
||||
match lead {
|
||||
Lead::Text(s) => {
|
||||
// Whole points: egui rounds wrap width to GUI_ROUNDING, which wraps a fractional label column.
|
||||
let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, (lead_w - 12.0).ceil());
|
||||
// A label cut short shows whole on hover.
|
||||
if galley.elided {
|
||||
lead_resp.clone().on_hover_text(*s);
|
||||
}
|
||||
ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary);
|
||||
}
|
||||
Lead::Icon(i, _) => {
|
||||
icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), *i, t.icon_secondary);
|
||||
}
|
||||
Lead::None | Lead::Named(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement the shared number field: label/icon lead, scrubbing, keyboard stepping and
|
||||
/// typing, select-all when a click starts editing, bindable values and deferred-save
|
||||
/// cancellation; returns an edit and/or bind event.
|
||||
@@ -323,7 +440,8 @@ fn number_field_impl(
|
||||
let lead_rect = Rect::from_min_size(rect.min, vec2(lead_w, FIELD_H));
|
||||
let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max);
|
||||
let editing_id = id.with("editing");
|
||||
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
|
||||
let owner_id = id.with("owner_sel");
|
||||
let (mut editing, cur_snap) = sync_field_owner(ui, id, value);
|
||||
// Alt held over the field scrubs it too, as the label always does: "hover the input field
|
||||
// itself and hold down the modifier key" (Adjust alignment, rotation, position, and
|
||||
// dimensions). The field senses drags only while Alt is held, or while a scrub begun that way
|
||||
@@ -349,21 +467,7 @@ fn number_field_impl(
|
||||
} else if hovered {
|
||||
ui.painter().rect_stroke(rect, CornerRadius::same(5), Stroke::new(1.0, t.field_hover_border), StrokeKind::Inside);
|
||||
}
|
||||
match lead {
|
||||
Lead::Text(s) => {
|
||||
// Whole points: egui rounds wrap width to GUI_ROUNDING, which wraps a fractional label column.
|
||||
let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, (lead_w - 12.0).ceil());
|
||||
// A label cut short shows whole on hover.
|
||||
if galley.elided {
|
||||
lead_resp.clone().on_hover_text(s);
|
||||
}
|
||||
ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary);
|
||||
}
|
||||
Lead::Icon(i, _) => {
|
||||
icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), i, t.icon_secondary)
|
||||
}
|
||||
Lead::None | Lead::Named(_) => {}
|
||||
}
|
||||
paint_number_field_lead(ui, &lead, lead_rect, rect, lead_w, &lead_resp, &t);
|
||||
if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
@@ -435,6 +539,10 @@ fn number_field_impl(
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(editing_id, editing.clone().unwrap_or_default());
|
||||
d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default());
|
||||
if let Some(ref s) = cur_snap {
|
||||
d.insert_temp(owner_id, s.clone());
|
||||
}
|
||||
d.insert_temp(id.with("owner_val"), value);
|
||||
d.insert_temp(id.with("selectall"), !typed_now);
|
||||
d.insert_temp(id.with("cmdstart"), with_command);
|
||||
d.remove::<bool>(id.with("edited"));
|
||||
@@ -486,6 +594,7 @@ fn number_field_impl(
|
||||
// The stepped value stays selected: typing replaces it.
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(kept_id, text.clone());
|
||||
d.insert_temp(id.with("owner_val"), Some(nv));
|
||||
d.insert_temp(id.with("selectall"), true);
|
||||
d.insert_temp(id.with("edited"), true);
|
||||
});
|
||||
@@ -497,8 +606,7 @@ fn number_field_impl(
|
||||
}
|
||||
if esc {
|
||||
// Back to what it was: nothing is committed.
|
||||
ui.data_mut(|d| d.remove::<String>(editing_id));
|
||||
ui.memory_mut(|m| m.surrender_focus(id.with("te")));
|
||||
clear_field_editor(ui, id);
|
||||
} else if r.lost_focus() || enter {
|
||||
// Enter, Tab or a click elsewhere commits what was typed (a field left as it was
|
||||
// commits nothing: no undo step, and a rounded display isn't written back).
|
||||
@@ -512,7 +620,9 @@ fn number_field_impl(
|
||||
{
|
||||
out = Some(e);
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<String>(editing_id));
|
||||
clear_field_editor(ui, id);
|
||||
} else if !r.ctx.memory(|m| m.has_focus(r.id)) && !started {
|
||||
clear_field_editor(ui, id);
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(editing_id, text));
|
||||
}
|
||||
@@ -683,7 +793,8 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str
|
||||
cancel_retargeted_field_save(ui, id);
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let editing_id = id.with("editing");
|
||||
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
|
||||
let owner_id = id.with("owner_sel");
|
||||
let (mut editing, cur_snap) = sync_text_field_owner(ui, id, value);
|
||||
let resp = ui.interact(rect, id.with("click"), field_sense(editing.is_some()));
|
||||
let shown = if secret { std::borrow::Cow::Owned("•".repeat(value.chars().count())) } else { std::borrow::Cow::Borrowed(value) };
|
||||
a11y::text(&resp, name, &shown);
|
||||
@@ -696,6 +807,12 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str
|
||||
let started = editing.is_none() && resp.clicked();
|
||||
if started {
|
||||
editing = Some(value.to_string());
|
||||
if let Some(ref s) = cur_snap {
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(owner_id, s.clone());
|
||||
d.insert_temp(id.with("owner_text"), value.to_string());
|
||||
});
|
||||
}
|
||||
ui.memory_mut(|m| m.request_focus(id.with("te")));
|
||||
select_all_next(ui, id.with("te"), value);
|
||||
}
|
||||
@@ -709,10 +826,12 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str
|
||||
let enter = !started && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
if esc {
|
||||
ui.data_mut(|d| d.remove::<String>(editing_id));
|
||||
clear_field_editor(ui, id);
|
||||
} else if r.lost_focus() || enter {
|
||||
out = Some(text);
|
||||
ui.data_mut(|d| d.remove::<String>(editing_id));
|
||||
clear_field_editor(ui, id);
|
||||
} else if !r.ctx.memory(|m| m.has_focus(r.id)) && !started {
|
||||
clear_field_editor(ui, id);
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(editing_id, text));
|
||||
}
|
||||
@@ -1457,6 +1576,10 @@ pub fn text_field_inline(ui: &mut Ui, id: Id, value: &str, rect: Rect, font: egu
|
||||
ui.data_mut(|d| d.remove::<String>(buf_id));
|
||||
ui.memory_mut(|m| m.surrender_focus(te_id));
|
||||
(text != value && !text.trim().is_empty()).then_some(text)
|
||||
} else if !r.ctx.memory(|m| m.has_focus(te_id)) && !started {
|
||||
ui.data_mut(|d| d.remove::<String>(buf_id));
|
||||
ui.memory_mut(|m| m.surrender_focus(te_id));
|
||||
None
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(buf_id, text));
|
||||
None
|
||||
|
||||
@@ -135,6 +135,15 @@ pub fn guard(app: &mut FigApp, ctx: &Context, f: impl FnOnce(&mut FigApp)) {
|
||||
let msg = e.downcast_ref::<&str>().map(ToString::to_string).or_else(|| e.downcast_ref::<String>().cloned()).unwrap_or_else(|| "panic".into());
|
||||
log::error!("UI panic: {msg}");
|
||||
app.toast(format!("Internal error (please report): {msg}"));
|
||||
// A pass that panicked never reached `end_input_frame`: its batch's replies say so, and
|
||||
// neither the control queue nor the clipboard fence waits for it.
|
||||
if app.applied_frame.take().is_some() {
|
||||
for ack in app.applied_acks.drain(..) {
|
||||
let _ = ack.tx.send(crate::ControlReply { id: ack.reply.id, result: Err(format!("the frame applying the input failed: {msg}")) });
|
||||
}
|
||||
app.applied_input = None;
|
||||
app.control_synthetic = false;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
app.services.emergency_save(&app.session);
|
||||
}
|
||||
|
||||
@@ -288,7 +288,7 @@ Server → client:
|
||||
|
||||
| Message | Meaning |
|
||||
|---|---|
|
||||
| `Welcome {session, client_id, seq, catch_up: Snapshot, Delta or Packed, processed, peers, access}` | Join accepted: the full document, or for a reconnecting client the batches it missed; `Packed` is the full document compressed (deflate of the snapshot's postcard bytes), sent only to clients whose hello announced `packed`, which read it back within the size an uncompressed welcome could have had; what the server did with that client's batches (`processed {last_batch, refused}`); `access` is `edit`, `view` (a view link: every batch is refused) or `comment` (a comment link: a batch is refused unless every change in it is to comment threads: a thread's `put` or `remove`, their order or the whole list). |
|
||||
| `Welcome {session, client_id, seq, catch_up: Snapshot, Delta, Packed or DeltaSnapshot, processed, peers, access}` | Join accepted: the full document, or for a reconnecting client the batches it missed; `Packed` is the full document compressed (deflate of the snapshot's postcard bytes), sent only to clients whose hello announced `packed`, which read it back within the size an uncompressed welcome could have had; `DeltaSnapshot` is a direct compressed mirror-delta and deduplicated-vector snapshot (`FCDS` header + version byte + exact inflated length + deflate), sent only to clients whose hello announced `delta-snapshot` (and `design-review`), enforcing inflated-byte, node-count and materialized-memory budgets during streaming decode; what the server did with that client's batches (`processed {last_batch, refused}`); `access` is `edit`, `view` (a view link: every batch is refused) or `comment` (a comment link: a batch is refused unless every change in it is to comment threads: a thread's `put` or `remove`, their order or the whole list). |
|
||||
| `Changes {seq, author, batch_id, changes}` | Accepted changes, in order, to everyone (the author gets its own back as confirmation). |
|
||||
| `Reject {batch_id, reason, fixes: [Change]}` | A batch (or part of it) was invalid: the current values to roll back to. |
|
||||
| `Presence {client_id, …}` / `PeerJoined` / `PeerLeft` | Other people's cursors, selections and arrivals. |
|
||||
@@ -958,10 +958,13 @@ Decisions, as built:
|
||||
10 000, `max_log_changes`, default 1 000 000, and `max_log_bytes`, default 64 MiB, which a
|
||||
desktop host uses as they are and `figcraft-server` takes from its `max_log_mb`). If every batch
|
||||
after the client's sequence number is still in it, the welcome carries them (`CatchUp::Delta`);
|
||||
otherwise the whole document (`CatchUp::Snapshot`), compressed for a client whose hello
|
||||
announced `packed` (`CatchUp::Packed`, `message::pack` / `unpack`: deflate at its fastest level
|
||||
on the hub's thread; a document's changes shrink about sevenfold, e.g. 397 KB to 53 KB for 4 040
|
||||
layers). Older clients, and servers from before, keep the uncompressed snapshot.
|
||||
otherwise the whole document: `CatchUp::DeltaSnapshot` for clients whose hello announced
|
||||
`delta-snapshot` and `design-review` (Kahn `(parent, source)` topological order, exact
|
||||
value-checked mirror deltas, deduplicated `VectorNetwork` table, cached per `seq` on the server
|
||||
up to 16 MiB compressed; breaking `FieldDelta` additions bump the version/capability word),
|
||||
`CatchUp::Packed` (`message::pack` / `unpack`: deflate at its fastest level on the hub's thread)
|
||||
for older clients that announced `packed`, and uncompressed `CatchUp::Snapshot` for the oldest
|
||||
clients.
|
||||
- **What happened to the batches in flight.** The server remembers per client the last batch id it
|
||||
processed and the latest refused ids (at most 1 024). Batches up to that id that the catch-up
|
||||
doesn't confirm were refused (the user is told); the others are sent again, in order, keeping
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Components, variants, styles and variables parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); 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 anotLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); 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; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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); 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
|
||||
@@ -71,6 +71,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
| 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 |
|
||||
| Text styles in the Variables JSON export and import (`textStyles`, a FigCraft extension: the REST `styles` metadata has no values) | done | `variable.export {format: "json"}` adds a top-level `textStyles` array (values and `bound`, ids matching `meta.variables`); `variable.import` merges it by style name and re-points bindings; CSS, Tailwind and Dart are variables only |
|
||||
| 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 |
|
||||
| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090); a scale that would take an instance past 0.001 to 1000 times is refused |
|
||||
| Explicit modes per frame and per page (Page section), library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there |
|
||||
@@ -102,6 +103,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. |
|
||||
| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. |
|
||||
| 2026-11-07 | patch | M3, #2090: an instance's own resizing follows its main's unless its size is overridden. Measured in Figma: a plain instance turns Fixed when its main's width does (a child set to Fill along it) and back to Hug with it; an instance whose width was typed keeps it; Fill in its own auto layout parent is kept. Tests: `components_behaviour_tests::a_plain_instances_resizing_follows_the_mains_root_both_ways` and the instance resizing tests beside it. |
|
||||
| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only |
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. |
|
||||
| 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. |
|
||||
| 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged |
|
||||
|
||||
@@ -340,7 +340,9 @@ controller button pressed in the prototype playing, the presenter's or else the
|
||||
short name, a key/gamepad trigger's name or a standard layout index 0–16; an error when no prototype
|
||||
plays); positions are window points. Events of one call
|
||||
arrive in the same frame, so send a press and its release (or a double-click's two clicks) as
|
||||
separate calls. Returns `{queued}`.
|
||||
separate calls. Returns `{queued}`. Requests sent after a batch that a frame has already taken run
|
||||
in the frame after it, so a `doc.switch` (or any other request) never sends the batch into another
|
||||
file; a batch whose file changed before a frame took it is not applied, and its reply is an error.
|
||||
|
||||
```json
|
||||
{"id":6,"method":"ui.input","params":{"events":[{"move":[1000,315]}]}}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master bacLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the texLine truncated
|
||||
|
||||
Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of
|
||||
`/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's
|
||||
@@ -22,7 +22,7 @@ and prototype interactions are still unchecked there.
|
||||
| `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcaseLine truncated
|
||||
| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — |
|
||||
| `.deck` (Slides) | native to other Figma products | no | no | out of scope | — |
|
||||
| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — |
|
||||
| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — |
|
||||
| `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/<key>`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — |
|
||||
| Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) |
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Where FigCraft falls short of Figma
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (gap 24: code blocks from the toolbar and the `` ` `` key, a language menu and width-only edge handles (#2237); gap 7: the browser uploads only what an edit changed of the canvas image; 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 Line truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; gap 24: code blocks from the toolbar and the `` ` `` key, a language menu and width-only edge handles (#2237); 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; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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; localiLine 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
|
||||
@@ -471,7 +471,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
- **Landed:** extended collections (`library.extendCollection`: a library collection's modes and
|
||||
variables in a collection of this file, values overridden per mode with reset, following library
|
||||
updates, variables of its own), variables import/export (`variable.export` / `variable.import`:
|
||||
the REST local variables JSON, merged by name; CSS custom properties), gradient stops and variant
|
||||
the REST local variables JSON, merged by name, with the file's text styles under `textStyles`; CSS custom properties), gradient stops and variant
|
||||
properties bound to variables.
|
||||
- **Landed (2026-10-12):** variables a library adds to a collection this file extends are a library
|
||||
update of their own (`library.updates` lists them by name, without an `id` until they have a
|
||||
|
||||
+2
-2
@@ -1413,13 +1413,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll
|
||||
default mode's named after the collection and the others after the collection and the mode, with a
|
||||
`static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart
|
||||
identifiers kept apart, aliases are resolved to their value in that mode), and
|
||||
returns `{text}` (or writes `path` and returns `{path}`). `variable.import {variables}` (an object,
|
||||
returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the ids `meta.variables` is keyed by, which it holds only for the variables of the exported local collections, so a file's own export with `collections` left out of it names variables its `meta` lacks, and an import keeps such a binding on the style it replaces; an entry's `style` keys are snake_case and its `bound` keys camelCase, `bound.fontSize` binding `style.font_size`); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object,
|
||||
JSON text or a path to a regular file of at most 256 MiB;
|
||||
`variableCollections` and `variables` under `meta` or at the top level) reads
|
||||
one back: a collection joins this file's collection of the same name
|
||||
(values matched by mode name, new modes and variables added, a same-named variable of another type
|
||||
skipped with a warning; library copies and extended collections are never targets), others are
|
||||
added; aliases are checked for loops; it returns `{collections, variables, updated, warnings}`,
|
||||
added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables; one to a variable the JSON lacks (unless the style it replaces already holds that id), to a field the style lacks or to a variable of another type is dropped with a warning; at most 10,000 styles and 32 bindings each are read); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`,
|
||||
with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`)
|
||||
or fewer than its collections list in `variableIds`. The
|
||||
Variables editor's Import… and Export… buttons do the same through file dialogs.
|
||||
|
||||
@@ -379,3 +379,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
|
||||
| 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code |
|
||||
| 2026-11-10 | minor | Boards (M12, #2226): Cmd/Ctrl+Enter pinned for a mind map node's child (`board.mindMapAdd`; live only on a mind map node: elsewhere the key is free on the canvas and still ends a text edit): 57 → 58 pinned |
|
||||
| 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). |
|
||||
| 2026-11-27 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields track document identity, selection generation, and layer value; drafts are dropped when the selection changes, across deselections, or when the underlying layer value changes, preventing stale values and green outlines from persisting; window blur retains field drafts while widget focus is kept (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`, `field_draft_is_retained_when_window_loses_focus`, `selecting_different_layer_in_layers_panel_drops_draft`, `draft_is_dropped_across_empty_selection_transition`, `draft_is_dropped_when_layer_value_changes_externally`) |
|
||||
Reference in new issue
Block a user