mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge upstream/main into feat/mind-maps-ui-2226
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Model-Effort: Opus 5.5 driver, no subagent
This commit is contained in:
commit
4a42da449d
55 files changed
+1746
-94
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-15 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
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
|
||||
@@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
|
||||
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged |
|
||||
|
||||
@@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result<usize, ValueError> {
|
||||
|
||||
/// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1.
|
||||
fn attach(s: &str) -> Result<String, ValueError> {
|
||||
if s.contains(':') {
|
||||
if let Some((host, port)) = s.rsplit_once(':') {
|
||||
if host.is_empty() || port.parse::<u16>().is_err() {
|
||||
return Err(ValueError::Attach);
|
||||
}
|
||||
return Ok(s.to_owned());
|
||||
}
|
||||
let port: u16 = s.parse().map_err(|_| ValueError::Attach)?;
|
||||
@@ -461,6 +464,12 @@ mod tests {
|
||||
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979"));
|
||||
let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") };
|
||||
assert_eq!(a.attach.as_deref(), Some("localhost:7979"));
|
||||
for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] {
|
||||
let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") };
|
||||
assert_eq!(a.attach.as_deref(), Some(address));
|
||||
}
|
||||
let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") };
|
||||
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0"));
|
||||
let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") };
|
||||
assert_eq!(a.timeout, Some(300));
|
||||
let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") };
|
||||
@@ -514,6 +523,11 @@ mod tests {
|
||||
(&["perf", "--layers", "10,x"], ValueValidation),
|
||||
(&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict),
|
||||
(&["mcp", "--attach", "notaport"], ValueValidation),
|
||||
(&["mcp", "--attach", ":7979"], ValueValidation),
|
||||
(&["mcp", "--attach", "localhost:"], ValueValidation),
|
||||
(&["mcp", "--attach", "localhost:notaport"], ValueValidation),
|
||||
(&["mcp", "--attach", "localhost:65536"], ValueValidation),
|
||||
(&["mcp", "--attach", "[::1]"], ValueValidation),
|
||||
(&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation),
|
||||
(&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation),
|
||||
(&["mcp", "--timeout", "300"], MissingRequiredArgument),
|
||||
@@ -543,6 +557,7 @@ mod tests {
|
||||
&["export", "x.figcraft", "-o", "out", "--help"],
|
||||
&["export", "-o", "--help"],
|
||||
&["mcp", "--attach", "notaport", "--help"],
|
||||
&["mcp", "--attach", "localhost:notaport", "--help"],
|
||||
&["mcp", "--bogus", "-h"],
|
||||
&["--no-system-fonts", "plugin", "publish", "--bogus", "--help"],
|
||||
] {
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::{CliError, CliResult};
|
||||
|
||||
/// A document's or plugin's text as a terminal should show it: control characters escaped, and
|
||||
/// everything else (quotes, backslashes in paths) left as it is.
|
||||
fn plain(text: &str) -> String {
|
||||
pub(crate) fn plain(text: &str) -> String {
|
||||
text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect()
|
||||
}
|
||||
|
||||
@@ -242,7 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult<ExitCode> {
|
||||
fn sanitize(name: &str) -> String {
|
||||
let s = figcraft_engine::cmd::file::safe_file_name(name);
|
||||
let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace());
|
||||
if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() }
|
||||
let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::<String>();
|
||||
// Truncation can expose a device name; its escape must still fit the limits.
|
||||
let s = figcraft_engine::file_access::escape_device_names(&cap(s));
|
||||
if s.is_empty() { "layer".into() } else { cap(&s) }
|
||||
}
|
||||
|
||||
/// What `export` exports and how.
|
||||
@@ -543,6 +546,10 @@ mod tests {
|
||||
assert_eq!(sanitize("Home / Hero"), "Home _ Hero");
|
||||
assert_eq!(sanitize("../.."), "_");
|
||||
assert_eq!(sanitize(""), "layer");
|
||||
assert_eq!(sanitize("CON"), "_CON");
|
||||
assert_eq!(sanitize(" .nul.txt. "), "_nul.txt");
|
||||
assert_eq!(sanitize("COM1"), "_COM1");
|
||||
assert_eq!(sanitize("HomeCON"), "HomeCON");
|
||||
// The same characters the app's export keeps (#1154): only what file systems refuse goes.
|
||||
assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)");
|
||||
assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é");
|
||||
@@ -553,6 +560,16 @@ mod tests {
|
||||
assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizes_names_that_become_devices_at_the_character_limit() {
|
||||
assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizes_names_that_become_devices_at_the_byte_limit() {
|
||||
assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_page_skips_leading_divider() {
|
||||
let mut doc = Document::new("divider");
|
||||
|
||||
@@ -38,14 +38,15 @@ fn main() -> ExitCode {
|
||||
return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2));
|
||||
}
|
||||
};
|
||||
// Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable.
|
||||
match run(cli) {
|
||||
Ok(code) => code,
|
||||
Err(CliError::Usage(msg)) => {
|
||||
eprintln!("error: {msg}\n\nFor more information, try '--help'.");
|
||||
eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg));
|
||||
ExitCode::from(2)
|
||||
}
|
||||
Err(CliError::Failed(msg)) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("error: {}", files::plain(&msg));
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() {
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_parse_errors_escape_terminal_controls() {
|
||||
let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id());
|
||||
let failed = ["info", missing.as_str()];
|
||||
let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"];
|
||||
for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] {
|
||||
let out = bin().arg("--no-system-fonts").args(args).output().unwrap();
|
||||
let error = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}");
|
||||
assert!(error.starts_with("error: "), "{args:?}: {error:?}");
|
||||
assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}");
|
||||
assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it
|
||||
/// does first (#1155), whatever else is on the line; nothing runs.
|
||||
#[test]
|
||||
|
||||
@@ -118,3 +118,6 @@ real_name = "Ashok Ram"
|
||||
|
||||
[people.GiovanniBot]
|
||||
sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
@@ -1355,6 +1355,8 @@ mod proto_overlay_anchor_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod vector_radius_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_regions_tests;
|
||||
#[cfg(test)]
|
||||
mod width_sides_tests;
|
||||
|
||||
+49
-11
@@ -145,6 +145,25 @@ struct Corner {
|
||||
cut2: f64,
|
||||
}
|
||||
|
||||
/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the
|
||||
/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from
|
||||
/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths.
|
||||
struct Turn {
|
||||
v: usize,
|
||||
r: f64,
|
||||
s1: usize,
|
||||
a1: bool,
|
||||
s2: usize,
|
||||
a2: bool,
|
||||
c1: CubicBez,
|
||||
c2: CubicBez,
|
||||
u1: Vec2,
|
||||
u2: Vec2,
|
||||
angle: f64,
|
||||
l1: f64,
|
||||
l2: f64,
|
||||
}
|
||||
|
||||
/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to
|
||||
/// those ends, and the point it ends at.
|
||||
struct CornerCurve {
|
||||
@@ -391,10 +410,11 @@ impl VectorNetwork {
|
||||
}
|
||||
|
||||
/// The network with its rounded points drawn in: each sharp point with a corner radius becomes
|
||||
/// an arc between its two segments (the radius shrinks so the arc fits in half of each
|
||||
/// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps
|
||||
/// the rest of its curve, the arc leaving along its direction there. `None` when no point is
|
||||
/// rounded.
|
||||
/// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other
|
||||
/// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose
|
||||
/// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where
|
||||
/// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there.
|
||||
/// `None` when no point is rounded.
|
||||
pub fn rounded(&self) -> Option<VectorNetwork> {
|
||||
self.rounded_smoothed(0.0)
|
||||
}
|
||||
@@ -424,7 +444,9 @@ impl VectorNetwork {
|
||||
*x = true;
|
||||
}
|
||||
}
|
||||
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
|
||||
let turns: Vec<Option<Turn>> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect();
|
||||
let rounds: Vec<bool> = turns.iter().map(Option::is_some).collect();
|
||||
let corners: Vec<Corner> = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect();
|
||||
let mut out = self.clone();
|
||||
for v in &mut out.vertices {
|
||||
v.radius = 0.0;
|
||||
@@ -558,10 +580,9 @@ impl VectorNetwork {
|
||||
joining.next().is_none().then_some(first)
|
||||
}
|
||||
|
||||
/// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments
|
||||
/// run on smoothly or fold back. With `smoothing`, a point between two straight segments that
|
||||
/// are both `on_loop` gets a smoothed corner.
|
||||
fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option<Corner> {
|
||||
/// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two
|
||||
/// segments that neither run on smoothly nor fold back there.
|
||||
fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option<Turn> {
|
||||
let r = self.vertices.get(v)?.radius;
|
||||
let [(s1, a1), (s2, a2)] = *incident else { return None };
|
||||
if !(r > 0.0 && r.is_finite()) || s1 == s2 {
|
||||
@@ -577,6 +598,23 @@ impl VectorNetwork {
|
||||
if !(l1 > 1e-9 && l2 > 1e-9) {
|
||||
return None;
|
||||
}
|
||||
Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 })
|
||||
}
|
||||
|
||||
/// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner
|
||||
/// there may reach: all of it when the other end stays sharp, half when that end is rounded
|
||||
/// too (`rounds`, by point) and takes the other half.
|
||||
fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 {
|
||||
let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a });
|
||||
if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l }
|
||||
}
|
||||
|
||||
/// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as
|
||||
/// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point
|
||||
/// between two straight segments that are both `on_loop` gets a smoothed corner.
|
||||
fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option<Corner> {
|
||||
let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p;
|
||||
let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds));
|
||||
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
|
||||
let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false);
|
||||
if smoothing > 0.0
|
||||
@@ -584,7 +622,7 @@ impl VectorNetwork {
|
||||
&& is_line(&c2)
|
||||
&& closed(s1)
|
||||
&& closed(s2)
|
||||
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing)
|
||||
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing)
|
||||
&& let (Some(first), Some(last)) = (curves.first(), curves.last())
|
||||
{
|
||||
let (a, b) = (first.p0, last.p3);
|
||||
@@ -595,7 +633,7 @@ impl VectorNetwork {
|
||||
let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2);
|
||||
return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) });
|
||||
}
|
||||
let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0);
|
||||
let t = (r / (angle / 2.0).tan()).min(reach);
|
||||
let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2));
|
||||
// A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between
|
||||
// them and ρ the radius of the circle through both ends (the corner radius between lines).
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the
|
||||
//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single
|
||||
//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other.
|
||||
|
||||
use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg};
|
||||
use figcraft_geom::{BezPath, Point};
|
||||
|
||||
use crate::vector::VectorNetwork;
|
||||
|
||||
/// A 100 × 100 square's points: top left, top right, bottom right, bottom left.
|
||||
const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
|
||||
|
||||
/// A network through `pts` (closed or open) whose points have radii `radii`.
|
||||
fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork {
|
||||
let mut n = VectorNetwork::from_points(pts, closed);
|
||||
for (v, r) in n.vertices.iter_mut().zip(radii) {
|
||||
v.radius = *r;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight).
|
||||
fn curves(path: &BezPath) -> Vec<CubicBez> {
|
||||
path.segments()
|
||||
.filter_map(|s| match s {
|
||||
PathSeg::Cubic(c) => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same point to within rounding.
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
(a - b).hypot() < 1e-9
|
||||
}
|
||||
|
||||
/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc
|
||||
/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the
|
||||
/// circle's radius is `t`), and no other curve.
|
||||
fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) {
|
||||
let got = curves(path);
|
||||
assert_eq!(got.len(), want.len(), "{why}: {got:?}");
|
||||
for &(corner, prev, next, t) in want {
|
||||
let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t;
|
||||
let (a, b) = (toward(prev), toward(next));
|
||||
let center = a + (b - corner);
|
||||
let mid = center + (corner - center) / (corner - center).hypot() * t;
|
||||
// Two arcs can share both ends (opposite corners of a square), so the middle picks one.
|
||||
let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a));
|
||||
let passing: Vec<Point> = got.iter().filter(ends).map(|c| c.eval(0.5)).collect();
|
||||
assert!(
|
||||
passing.iter().any(|&m| near(m, mid)),
|
||||
"{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() {
|
||||
let [tl, tr, br, bl] = SQUARE;
|
||||
// (radii of [top left, top right, bottom right, bottom left], each arc as (point, its
|
||||
// neighbours, how far it reaches along both), derivation)
|
||||
#[allow(clippy::type_complexity)]
|
||||
let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![
|
||||
([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"),
|
||||
([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"),
|
||||
([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"),
|
||||
([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"),
|
||||
(
|
||||
[0.0, 10.0, 100.0, 0.0],
|
||||
vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)],
|
||||
"the segment to the rounded top right is shared, half each, and the shorter room wins",
|
||||
),
|
||||
(
|
||||
[100.0, 0.0, 100.0, 0.0],
|
||||
vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)],
|
||||
"opposite points share no segment: each reaches its sharp neighbours (a lens)",
|
||||
),
|
||||
(
|
||||
[100.0; 4],
|
||||
vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)],
|
||||
"every point rounded: a circle, as before",
|
||||
),
|
||||
];
|
||||
for (radii, want, why) in rows {
|
||||
let net = network(&SQUARE, true, &radii);
|
||||
assert_arcs(&net.fill_path(), &want, why);
|
||||
assert_arcs(&net.stroke_path(), &want, why);
|
||||
// The stored radii stay as they were set.
|
||||
assert_eq!(net.vertices.iter().map(|p| p.radius).collect::<Vec<_>>(), radii.to_vec(), "{why}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() {
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)];
|
||||
// (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no
|
||||
// room from the middle point.
|
||||
let rows: Vec<([f64; 3], &str)> =
|
||||
vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")];
|
||||
for (radii, why) in rows {
|
||||
let net = network(&pts, false, &radii);
|
||||
assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() {
|
||||
// Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100
|
||||
// side (50) would cut smoothing down; the whole side next to sharp points leaves all of it.
|
||||
let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]);
|
||||
let path = net.rounded_smoothed(0.6).unwrap().fill_path();
|
||||
let ends: Vec<Point> = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect();
|
||||
for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] {
|
||||
assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}");
|
||||
}
|
||||
assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}");
|
||||
}
|
||||
@@ -1158,10 +1158,12 @@ pub fn prune(doc: &mut Document, library: &str) -> Result<()> {
|
||||
doc.styles.retain(|s| !unused.contains(&s.id));
|
||||
doc.libraries_mut().styles.retain(|r| !unused.contains(&r.local));
|
||||
}
|
||||
// Variables layers bind or set, local variables alias or extend (with what those alias).
|
||||
// Variables layers bind or set, styles bind, local variables alias or extend (with what those
|
||||
// alias).
|
||||
let seeds = doc
|
||||
.nodes()
|
||||
.flat_map(|n| n.bound.values().map(String::as_str).chain(action_variables(n)))
|
||||
.chain(doc.styles.iter().flat_map(|s| s.bound.values().map(String::as_str)))
|
||||
.chain(doc.variables.variables.iter().filter_map(|v| v.extends.as_deref()))
|
||||
.map(str::to_string)
|
||||
.chain(
|
||||
|
||||
@@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40;
|
||||
/// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute
|
||||
/// is refused as well, rather than left to what comes next.
|
||||
fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option<Unresolved> {
|
||||
// Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given.
|
||||
if has_trimmed_name(path) {
|
||||
return Some(Unresolved::Linked);
|
||||
}
|
||||
// Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a
|
||||
// bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes
|
||||
// `..` by name, so `link\..\x` is `x` and never goes through the link.
|
||||
@@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool {
|
||||
/// the way is opened in turn while the path is resolved, and the device behind a name such as
|
||||
/// `LPT1` can be a printer on another computer.
|
||||
fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option<Refused> {
|
||||
// A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names.
|
||||
if is_native_name(Path::new(p)) {
|
||||
return Some(Refused::Device);
|
||||
}
|
||||
match craft_docpath::resolve(p, None) {
|
||||
// With a root passed as the document path (what a link would be relative to), a path on
|
||||
// that root's share is allowed.
|
||||
@@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool {
|
||||
let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else {
|
||||
return false;
|
||||
};
|
||||
volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}')
|
||||
let bytes = volume.as_bytes();
|
||||
bytes.len() == 44
|
||||
&& volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{"))
|
||||
&& volume.ends_with('}')
|
||||
&& bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() })
|
||||
}
|
||||
|
||||
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
|
||||
@@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
|
||||
Entry::Link(target) => target,
|
||||
};
|
||||
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true };
|
||||
// Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive,
|
||||
// and Win32 trims a trailing period or space that the kernel follows as it is.
|
||||
if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) {
|
||||
return true;
|
||||
}
|
||||
// A relative target is relative to the link's folder; an absolute one replaces it.
|
||||
let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path()));
|
||||
return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look);
|
||||
@@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link
|
||||
/// may hold: no prefix for `std`, yet the system follows it to wherever it names.
|
||||
fn is_native_name(path: &Path) -> bool {
|
||||
let bytes = path.as_os_str().as_encoded_bytes();
|
||||
[&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| {
|
||||
bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no
|
||||
/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names.
|
||||
fn is_rooted_without_drive(path: &Path) -> bool {
|
||||
matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\'))
|
||||
}
|
||||
|
||||
/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up.
|
||||
fn has_trimmed_name(path: &Path) -> bool {
|
||||
path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' '))))
|
||||
}
|
||||
|
||||
/// `p` with its `.` and `..` taken by name, as Windows takes them.
|
||||
fn lexical(p: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
@@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool {
|
||||
matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a
|
||||
/// path that resolving would not be allowed to open (on another computer, or a device: see
|
||||
/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the
|
||||
/// callers guard against overwriting a file through another name for it, so it counts as the same:
|
||||
/// the guard keeps asking (a path like that can't be written anyway). A local path outside the
|
||||
/// roots is compared.
|
||||
pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
|
||||
let (a, b) = (a.as_ref(), b.as_ref());
|
||||
a == b || same_file::is_same_file(a, b).unwrap_or(false)
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if let Some(scope) = current() {
|
||||
let roots = [scope.read.as_slice(), scope.write.as_slice()].concat();
|
||||
if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
same_file::is_same_file(a, b).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `p` without Windows' `\\?\` prefix, for messages.
|
||||
@@ -345,6 +397,12 @@ fn device_name(n: &str) -> bool {
|
||||
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
|
||||
}
|
||||
|
||||
/// Prefix Windows device-name components of a generated export path with `_`.
|
||||
/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged.
|
||||
pub fn escape_device_names(path: &str) -> String {
|
||||
path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,27 @@ use serde_json::json;
|
||||
use super::{Access, Roots, allow, confined, current};
|
||||
use crate::Session;
|
||||
|
||||
#[test]
|
||||
fn generated_export_paths_escape_device_components_and_preserve_other_names() {
|
||||
for (path, expected) in [
|
||||
("CON", "_CON"),
|
||||
("CoN.txt", "_CoN.txt"),
|
||||
("nul.txt", "_nul.txt"),
|
||||
("PRN/icon", "_PRN/icon"),
|
||||
("folder/COM1", "folder/_COM1"),
|
||||
("LPT9.png", "_LPT9.png"),
|
||||
("COM¹", "_COM¹"),
|
||||
("LPT²/icon", "_LPT²/icon"),
|
||||
("CONIN$", "_CONIN$"),
|
||||
("HomeCON", "HomeCON"),
|
||||
("COM10", "COM10"),
|
||||
("CON@2x", "CON@2x"),
|
||||
("folder/.NUL", "folder/.NUL"),
|
||||
] {
|
||||
assert_eq!(super::escape_device_names(path), expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test: `<tmp>/figcraft-roots-<name>-<pid>`, holding `root/`, `root2/`
|
||||
/// (a sibling whose name starts like the root's) and `outside/`.
|
||||
struct Fixture(PathBuf);
|
||||
@@ -229,6 +250,8 @@ fn spellings_of_other_computers_and_devices_are_refused() {
|
||||
r"C:\work\LPT³\x.png",
|
||||
r"C:\work\conout$",
|
||||
r"C:\work\aux:stream",
|
||||
// A volume name that is not a GUID could be an alias of anything.
|
||||
r"\\?\Volume{remote}\x.png",
|
||||
// After a name `craft_docpath` refuses for another reason.
|
||||
r"C:\work\a:b\prn.png",
|
||||
];
|
||||
@@ -402,6 +425,34 @@ fn a_parent_after_a_link_is_taken_by_name() {
|
||||
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
|
||||
}
|
||||
|
||||
/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the
|
||||
/// same file as one inside, even when it is another name for it (a hard link outside the roots).
|
||||
#[test]
|
||||
fn same_file_does_not_open_a_path_outside_the_roots() {
|
||||
let f = Fixture::new("same-file");
|
||||
let inside = f.p("root/in.txt");
|
||||
let outside = f.p("outside/linked.txt");
|
||||
if std::fs::hard_link(&inside, &outside).is_err() {
|
||||
eprintln!("skipped: hard links can't be made here");
|
||||
return;
|
||||
}
|
||||
assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file");
|
||||
let roots = Arc::new(f.rw());
|
||||
confined(Some(&roots), || {
|
||||
assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file");
|
||||
if cfg!(windows) {
|
||||
assert!(
|
||||
super::same_file(&inside, r"\\192.0.2.1\share\x"),
|
||||
"a path on another computer is never opened, and counts as the same so that the guard keeps asking"
|
||||
);
|
||||
}
|
||||
assert!(super::same_file(&inside, &inside), "a path is the same file as itself");
|
||||
let other = f.p("root/sub/other.txt");
|
||||
std::fs::write(&other, b"other").unwrap();
|
||||
assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ");
|
||||
});
|
||||
}
|
||||
|
||||
/// A path on another computer and a device path are refused before anything is opened: resolving
|
||||
/// them made Windows contact the server, which may send it the signed-in user's credentials
|
||||
/// (#1094). Each is refused with a message that only the check before resolving gives: had the
|
||||
@@ -468,6 +519,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() {
|
||||
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
|
||||
}
|
||||
|
||||
/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the
|
||||
/// rest of the path after it, reaches `\Device\Mup\...`.
|
||||
#[test]
|
||||
fn native_names_are_told_with_or_without_the_closing_separator() {
|
||||
for p in
|
||||
[r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"]
|
||||
{
|
||||
assert!(super::is_native_name(Path::new(p)), "{p}");
|
||||
}
|
||||
for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] {
|
||||
assert!(!super::is_native_name(Path::new(p)), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the
|
||||
/// link's drive, whichever directory it names.
|
||||
#[test]
|
||||
fn rooted_link_targets_without_a_drive_are_refused() {
|
||||
for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] {
|
||||
assert!(super::is_rooted_without_drive(Path::new(p)), "{p}");
|
||||
}
|
||||
for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] {
|
||||
assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a
|
||||
/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the
|
||||
/// others where it looks a name up but not where the kernel follows a link.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn native_names_and_names_windows_trims_are_refused_as_written() {
|
||||
let f = Fixture::new("native-trimmed");
|
||||
let r = f.rw();
|
||||
if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native"))
|
||||
|| !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed"))
|
||||
{
|
||||
eprintln!("skipped: this system doesn't let tests make symbolic links");
|
||||
return;
|
||||
}
|
||||
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
|
||||
// However the system stores the native name, the link is refused.
|
||||
let native = f.p("root/native/x.png");
|
||||
assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}");
|
||||
let p = f.p("root/trimmed/x.png");
|
||||
let e = r.check(Path::new(&p), Access::Read).expect_err(&p);
|
||||
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
|
||||
let p = f.p("root/remote /x.png");
|
||||
let e = r.check(Path::new(&p), Access::Write).expect_err(&p);
|
||||
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
|
||||
assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_confines_the_thread_and_ends_with_it() {
|
||||
let f = Fixture::new("scope");
|
||||
|
||||
@@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() {
|
||||
assert_eq!(results[6]["ok"], true);
|
||||
assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_step_names_its_step_and_keeps_its_kind() {
|
||||
let mut s = Session::new();
|
||||
let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap());
|
||||
let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap());
|
||||
let before = s.doc().unwrap().clone();
|
||||
let undo = s.undo_depth();
|
||||
let result = s.execute(
|
||||
"command.batch",
|
||||
&json!({"commands": [
|
||||
{"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}}
|
||||
]}),
|
||||
);
|
||||
match result {
|
||||
Err(EngineError::Disabled(cmd, msg)) => {
|
||||
assert_eq!(cmd, "node.create");
|
||||
assert!(msg.starts_with("step 0: "), "{msg}");
|
||||
assert!(msg.contains("can't be added"), "{msg}");
|
||||
}
|
||||
other => panic!("expected Disabled, got {other:?}"),
|
||||
}
|
||||
assert_eq!(s.doc().unwrap(), &before, "the batch rolled back");
|
||||
assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch");
|
||||
// Outside a batch the same refusal keeps its kind and says no step.
|
||||
match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) {
|
||||
Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"),
|
||||
other => panic!("expected Disabled, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_internal_step_says_which_step_without_changing_kind() {
|
||||
use crate::derived;
|
||||
let mut s = Session::new();
|
||||
let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap());
|
||||
let before = s.doc().unwrap().clone();
|
||||
derived::PANIC.with(|p| p.set(true));
|
||||
let result = s.execute(
|
||||
"command.batch",
|
||||
&json!({"commands": [
|
||||
{"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}}
|
||||
]}),
|
||||
);
|
||||
derived::PANIC.with(|p| p.set(false));
|
||||
match result {
|
||||
Err(EngineError::Internal { cmd, msg }) => {
|
||||
assert_eq!(cmd, "node.set");
|
||||
assert!(msg.starts_with("step 0: "), "{msg}");
|
||||
}
|
||||
other => panic!("expected Internal, got {other:?}"),
|
||||
}
|
||||
assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back");
|
||||
// Kinds without a message are left as they are.
|
||||
assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_)));
|
||||
assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting));
|
||||
}
|
||||
@@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator<Item = (NodeId, Vec<ExportSetting>)>, d
|
||||
if out.len() >= MAX_EXPORT_FILES {
|
||||
return out;
|
||||
}
|
||||
let stem = format!("{base}{}", safe_file_name(&e.file_suffix()));
|
||||
let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix())));
|
||||
let ext = e.format.ext();
|
||||
let file =
|
||||
(1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase()));
|
||||
@@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod filename_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() {
|
||||
let mut doc = Document::new("Export names");
|
||||
let page = doc.first_page().unwrap();
|
||||
let cases = [
|
||||
("C", "ON", "_CON.png"),
|
||||
("_con", "", "_con 2.png"),
|
||||
("CON/icon", "", "_CON/icon.png"),
|
||||
("Home", "CON", "HomeCON.png"),
|
||||
("COM", "1", "_COM1.png"),
|
||||
("COM1", "@2x", "COM1@2x.png"),
|
||||
];
|
||||
let items: Vec<_> = cases
|
||||
.iter()
|
||||
.map(|(name, suffix, _)| {
|
||||
let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
(id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }])
|
||||
})
|
||||
.collect();
|
||||
let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect();
|
||||
assert_eq!(files, cases.map(|(_, _, expected)| expected));
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
return Ok(json!({"id": id, "divider": true}));
|
||||
}
|
||||
let ds = s.ds_mut()?;
|
||||
ds.page = id;
|
||||
ds.open_page(id);
|
||||
ds.selection.clear();
|
||||
ds.zoom_to_fit();
|
||||
Ok(json!({"id": id}))
|
||||
}),
|
||||
spec!("page.select", "Go to page", "{id | index}", false, |s, p| {
|
||||
@@ -74,10 +73,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
return Err(bad("page.select", "a divider isn't a page to open"));
|
||||
}
|
||||
let ds = s.ds_mut()?;
|
||||
ds.page = id;
|
||||
ds.open_page(id);
|
||||
ds.selection.clear();
|
||||
ds.text_edit = None;
|
||||
ds.zoom_to_fit();
|
||||
ok()
|
||||
}),
|
||||
spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| {
|
||||
|
||||
@@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let ds = s.ds_mut()?;
|
||||
ds.page = pg;
|
||||
ds.open_page(pg);
|
||||
ds.selection.clear();
|
||||
ds.zoom_to_fit();
|
||||
Ok(json!({"page": pg}))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::view_state::ViewState;
|
||||
use super::{Arc, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit};
|
||||
use super::{
|
||||
Arc, BTreeMap, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit,
|
||||
};
|
||||
|
||||
/// One undo step.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -114,6 +116,9 @@ pub struct DocState {
|
||||
/// The file on disk as this tab last read or wrote it: a save refuses to replace what another
|
||||
/// app (figcraft-cli, say) wrote to it since (#1330).
|
||||
pub(crate) on_disk: Option<library::Stamp>,
|
||||
/// Where each page's view was left in this session (its centre and zoom; see
|
||||
/// [`Self::open_page`]; not saved).
|
||||
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
|
||||
}
|
||||
|
||||
/// A version shown on the canvas in place of the document: read-only until it's restored or the
|
||||
@@ -178,6 +183,7 @@ impl DocState {
|
||||
last_duplicate: None,
|
||||
images_left_in_file: None,
|
||||
on_disk: None,
|
||||
page_views: BTreeMap::new(),
|
||||
};
|
||||
st.zoom_to_fit();
|
||||
st
|
||||
@@ -311,6 +317,21 @@ impl DocState {
|
||||
}
|
||||
|
||||
/// Fit the current page's content (or centre on the origin when empty).
|
||||
/// Show `page` at the view it was left at in this session, or one that fits its content the
|
||||
/// first time; the page shown till now keeps its view for when it comes back. The page shown
|
||||
/// already keeps its view.
|
||||
pub fn open_page(&mut self, page: NodeId) {
|
||||
if page == self.page {
|
||||
return;
|
||||
}
|
||||
self.page_views.insert(self.page, (self.view.cx, self.view.cy, self.view.zoom));
|
||||
self.page = page;
|
||||
match self.page_views.get(&page) {
|
||||
Some(&(cx, cy, zoom)) => (self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom),
|
||||
None => self.zoom_to_fit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn zoom_to_fit(&mut self) {
|
||||
match self.doc.page_content_bounds(self.page) {
|
||||
Some(b) => self.view.fit(b, 1.0),
|
||||
|
||||
@@ -43,6 +43,8 @@ impl EngineError {
|
||||
match self {
|
||||
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: format!("step {step}: {msg}") },
|
||||
EngineError::Other(msg) => EngineError::Other(format!("step {step}: {msg}")),
|
||||
EngineError::Disabled(cmd, msg) => EngineError::Disabled(cmd, format!("step {step}: {msg}")),
|
||||
EngineError::Internal { cmd, msg } => EngineError::Internal { cmd, msg: format!("step {step}: {msg}") },
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -668,6 +668,8 @@ mod widget_shapes_tests;
|
||||
#[cfg(test)]
|
||||
mod widgets_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod page_view_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_reorder_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -550,3 +550,55 @@ fn stored_variable_ids_keep_library_alias_dependencies() {
|
||||
assert!(copy.values.values().all(|v| *v == VariableValue::Alias(map.variables[target].clone())));
|
||||
assert!(dest.variables.collections.iter().any(|c| c.name == "Base"));
|
||||
}
|
||||
|
||||
/// A library with collection `coll` (Main/Alt), a colour variable `var` and a paint style `var`
|
||||
/// bound to it, published to `path`; returns (the library session, its id).
|
||||
fn styled_library(path: &str, coll: &str, var: &str, main: &str, alt: &str) -> (Session, String) {
|
||||
let mut lib = Session::new();
|
||||
ex(&mut lib, "variable.createCollection", json!({"name": coll, "modes": ["Main", "Alt"]}));
|
||||
let v = ex(&mut lib, "variable.create", json!({"collection": coll, "name": var, "type": "color", "values": {"Main": main, "Alt": alt}}))["id"]
|
||||
.clone();
|
||||
let style = ex(&mut lib, "style.create", json!({"type": "paint", "name": var, "value": main}))["id"].clone();
|
||||
ex(&mut lib, "style.bind", json!({"style": style, "field": "fill", "variable": v}));
|
||||
let lid = publish_to(&mut lib, path);
|
||||
(lib, lid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_updates_keeps_variables_only_library_styles_use() {
|
||||
let d = dir("accept-style-vars");
|
||||
let (pa, pb) = (path_str(&d.join("a.figcraft")), path_str(&d.join("b.figcraft")));
|
||||
let (mut a, la) = styled_library(&pa, "TokensA", "accent", "#1565c0", "#2e7d32");
|
||||
let (_b, lb) = styled_library(&pb, "TokensB", "primary", "#7b1fa2", "#00838f");
|
||||
|
||||
let mut s = Session::new();
|
||||
let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200})));
|
||||
let ra = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20, "parent": frame})));
|
||||
let rb = idv(&ex(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 20, "height": 20, "parent": frame})));
|
||||
ex(&mut s, "library.add", json!({"path": pa}));
|
||||
ex(&mut s, "library.add", json!({"path": pb}));
|
||||
ex(&mut s, "library.applyStyle", json!({"library": la, "style": "accent", "id": ra}));
|
||||
ex(&mut s, "library.applyStyle", json!({"library": lb, "style": "primary", "id": rb}));
|
||||
ex(&mut s, "library.setVariableMode", json!({"library": la, "collection": "TokensA", "mode": "Alt", "ids": [frame]}));
|
||||
ex(&mut s, "library.setVariableMode", json!({"library": lb, "collection": "TokensB", "mode": "Alt", "ids": [frame]}));
|
||||
assert_eq!(fill(&s, ra), "2E7D32");
|
||||
assert_eq!(fill(&s, rb), "00838F");
|
||||
healthy(&s);
|
||||
|
||||
ex(&mut a, "variable.set", json!({"variable": "accent", "mode": "Alt", "value": "#ef6c00"}));
|
||||
republish(&mut a);
|
||||
let r = ex(&mut s, "library.acceptUpdates", json!({}));
|
||||
assert_eq!(r["variables"], 1, "{r}");
|
||||
|
||||
let doc = s.doc().unwrap();
|
||||
for name in ["accent", "primary"] {
|
||||
let v = doc.variables.variables.iter().find(|v| v.name == name && is_remote_variable(doc, &v.id));
|
||||
assert!(v.is_some(), "library variable copy `{name}` was deleted");
|
||||
let id = &v.unwrap().id;
|
||||
assert!(doc.libraries.variables.iter().any(|r| &r.local == id), "record of `{name}` was deleted");
|
||||
}
|
||||
assert_eq!(fill(&s, ra), "EF6C00");
|
||||
assert_eq!(fill(&s, rb), "00838F");
|
||||
healthy(&s);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Each page keeps its view in a session: going back to a page shows it where it was left, not
|
||||
//! fitted again (a new page is still fitted); going to the page shown changes nothing.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn view(s: &mut Session) -> (f64, f64, f64) {
|
||||
let v: Value = s.execute("view.get", &json!({})).unwrap();
|
||||
(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap(), v["zoom"].as_f64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_back_to_a_page_shows_it_where_it_was_left() {
|
||||
let mut s = Session::new();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap();
|
||||
let first = s.page().unwrap();
|
||||
s.execute("view.set", &json!({"zoom": 2.5, "cx": 1000, "cy": 500})).unwrap();
|
||||
let second = crate::params::id_of(&s.execute("page.add", &json!({})).unwrap()["id"]).unwrap();
|
||||
assert_ne!(view(&mut s), (1000.0, 500.0, 2.5), "a new page is fitted, not shown at the last page's view");
|
||||
s.execute("shape.ellipse", &json!({"x": 5000, "y": 5000, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("view.set", &json!({"zoom": 0.5, "cx": -200, "cy": 40})).unwrap();
|
||||
|
||||
s.execute("page.select", &json!({"id": first})).unwrap();
|
||||
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5), "the first page as it was left");
|
||||
s.execute("view.nextPage", &json!({})).unwrap();
|
||||
assert_eq!(s.page().unwrap(), second);
|
||||
assert_eq!(view(&mut s), (-200.0, 40.0, 0.5), "the second page as it was left");
|
||||
// The page shown: nothing moves.
|
||||
s.execute("view.set", &json!({"zoom": 3.0, "cx": 7, "cy": 8})).unwrap();
|
||||
s.execute("page.select", &json!({"id": second})).unwrap();
|
||||
assert_eq!(view(&mut s), (7.0, 8.0, 3.0));
|
||||
s.execute("view.prevPage", &json!({})).unwrap();
|
||||
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5));
|
||||
}
|
||||
@@ -187,4 +187,30 @@ mod tests {
|
||||
assert!(out.contains(&bomb));
|
||||
assert!(out.len() < 3 * bomb.len(), "{}", out.len());
|
||||
}
|
||||
|
||||
/// Every command the server's instructions and the prompts name exists: an agent told to run a
|
||||
/// renamed or misspelt one gets an error instead of the workflow.
|
||||
#[test]
|
||||
fn the_commands_the_instructions_and_prompts_name_exist() {
|
||||
let ids: Vec<&str> = figcraft_engine::all_commands().iter().map(|c| c.id).collect();
|
||||
let namespaces: Vec<&str> = ids.iter().filter_map(|id| id.split('.').next()).collect();
|
||||
let texts = std::iter::once(crate::INSTRUCTIONS).chain(PROMPTS.iter().map(|p| p.template));
|
||||
let mut named = 0;
|
||||
for text in texts {
|
||||
for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '.')).map(|w| w.trim_end_matches('.')) {
|
||||
let Some((ns, rest)) = word.split_once('.') else { continue };
|
||||
// wait_for_changes events, which the prompts name too.
|
||||
let event = matches!(word, "comment.added" | "comment.replied");
|
||||
if event || rest.is_empty() || !rest.starts_with(|c: char| c.is_ascii_lowercase()) || !namespaces.contains(&ns) {
|
||||
continue;
|
||||
}
|
||||
named += 1;
|
||||
assert!(ids.contains(&word), "`{word}` is not a command");
|
||||
}
|
||||
}
|
||||
assert!(named > 10, "the check found the command ids ({named})");
|
||||
for id in ["component.create", "instance.create", "component.addProperty", "instance.setProperties", "component.combineVariants"] {
|
||||
assert!(crate::INSTRUCTIONS.contains(id), "the instructions name {id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,16 @@ reports both x/y relative to the parent frame (groups don't count) and absoluteB
|
||||
positioned by the layout (set layout, gap, padding, mainAlign, crossAlign, sizingH/sizingV instead). \
|
||||
Every menu item, panel action and shortcut is a command: find ids and params with list_commands (use a filter) \
|
||||
and run them with run_command, or several as one undo step with batch. Commands act on `ids` when given, else \
|
||||
on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". Verify your work: \
|
||||
on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". \
|
||||
Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component: build it once, make it one with \
|
||||
component.create (or create_node type component), then place every other copy with \
|
||||
instance.create {component, parent?, x?, y?} instead of duplicating layers, so every copy follows its main component. \
|
||||
States and sizes are variants of one set: name the mains Property=value (State=Default, State=Hover) and run \
|
||||
component.combineVariants on them; component.addVariant {id} adds one more. What changes from copy to copy is a \
|
||||
component property: component.addProperty {id, name, type: text|boolean|instanceSwap, layer} on the component (on the \
|
||||
set once its variants are combined, then component.bindProperty {layer, property} for each other variant's layer), and \
|
||||
instance.setProperties {ids, properties} sets it on each copy. get_node shows whether a layer is an instance and of \
|
||||
which main. Verify your work: \
|
||||
inspect_document / get_node return the layer tree as JSON (check sizes, fills, layout, overrides), and \
|
||||
screenshot returns a PNG of the page or of given layers to look at. undo/redo step through history. \
|
||||
Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \
|
||||
|
||||
@@ -163,3 +163,75 @@ fn huge_backdrop_blur_renders_in_one_piece() {
|
||||
assert!(render_bands(&d, p, &view(1.0), &Options::default(), 4).is_none());
|
||||
assert!(render_view(&d, p, &view(1.0), &Options::default()).is_some());
|
||||
}
|
||||
|
||||
/// [`row_diffs`] down the columns: an artifact of column bands runs down a whole column.
|
||||
fn col_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> {
|
||||
let (w, h) = (a.width() as usize, a.height() as usize);
|
||||
let column = |p: &Pixmap, x: usize| -> Vec<u8> { (0..h).flat_map(|y| p.data()[(y * w + x) * 4..(y * w + x) * 4 + 4].to_vec()).collect() };
|
||||
(0..w).map(|x| row_stats(&column(a, x), &column(b, x))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_match_one_piece_rendering() {
|
||||
let (d, p) = scene(true, true);
|
||||
for scale in [1.0, 2.0] {
|
||||
let v = view(scale);
|
||||
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
|
||||
for bands in [2, 3, 7] {
|
||||
let banded = render_columns(&d, p, &v, &Options::default(), bands).unwrap();
|
||||
assert_eq!((banded.width(), banded.height()), (one.width(), one.height()));
|
||||
for (x, (mean, off)) in col_diffs(&one, &banded).into_iter().enumerate() {
|
||||
assert!(
|
||||
row_ok(mean, off, v.height as usize),
|
||||
"scale {scale}, {bands} columns: column {x} differs ({off} pixels, {mean:.2} on average)"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut d, p) = scene(true, true);
|
||||
let g = d.find_by_name("Glass", None)[0];
|
||||
d.get_mut(g).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(1e6)), visible: true }];
|
||||
assert!(render_columns(&d, p, &view(1.0), &Options::default(), 4).is_none(), "a blur past a whole column: in one piece");
|
||||
}
|
||||
|
||||
/// The strips a pan uncovers render in bands along their longer side, and match one piece: no row
|
||||
/// or column where a band's edge shows (a seam differs along all of it). A strip is too narrow for
|
||||
/// [`row_ok`]'s mean: the edge antialiasing every band render has (a few pixels along a curve)
|
||||
/// outweighs it there, so this counts the pixels that differ at all.
|
||||
#[test]
|
||||
fn a_tall_or_wide_part_of_a_view_matches_one_piece_rendering() {
|
||||
let (d, p) = scene(true, true);
|
||||
for (w, h) in [(60, 480), (880, 60), (200, 200)] {
|
||||
let v = View { origin: (35.0, -10.0), scale: 2.0, width: w, height: h };
|
||||
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
|
||||
let part = render_part(&d, p, &v, &Options::default()).unwrap();
|
||||
assert_eq!((part.width(), part.height()), (w, h));
|
||||
for (y, (_, off)) in row_diffs(&one, &part).into_iter().enumerate() {
|
||||
assert!(off * 20 <= w as usize, "{w} x {h}: row {y} differs in {off} pixels");
|
||||
}
|
||||
for (x, (_, off)) in col_diffs(&one, &part).into_iter().enumerate() {
|
||||
assert!(off * 20 <= h as usize, "{w} x {h}: column {x} differs in {off} pixels");
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A textured layer scatters its pixels up to the texture's radius, past where a band cuts the
|
||||
/// view; it is drawn off screen whole before it is cut, so column and row bands show it exactly as
|
||||
/// one piece does, clipped to its shape or not.
|
||||
#[test]
|
||||
fn a_textured_layer_renders_the_same_in_bands() {
|
||||
for clip_to_shape in [false, true] {
|
||||
let mut d = Document::new("texture");
|
||||
let p = d.first_page().unwrap();
|
||||
let r = d.create(p, NodeKind::Rectangle, "T", 20.0, 20.0, 400.0, 200.0).unwrap();
|
||||
let n = d.get_mut(r).unwrap();
|
||||
n.fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
|
||||
let texture = figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() };
|
||||
n.effects = vec![Effect { kind: EffectKind::Texture(texture), visible: true }];
|
||||
let v = View { origin: (0.0, 0.0), scale: 1.7, width: 760, height: 400 };
|
||||
let one = render_view_single(&d, p, &v, &Options::default()).unwrap();
|
||||
for bands in [2, 3, 7] {
|
||||
assert!(render_columns(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} columns");
|
||||
assert!(render_bands(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} rows");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,58 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) ->
|
||||
render_one(doc, page, view, opts)
|
||||
}
|
||||
|
||||
/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the
|
||||
/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a
|
||||
/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is
|
||||
/// drawn whole for a sliver of it), not its pixels.
|
||||
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
|
||||
start_render();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(pool) = band_pool() {
|
||||
let threads = pool.current_num_threads().clamp(1, 16) as u32;
|
||||
let rendered = if view.height >= view.width {
|
||||
let bands = threads.min(view.height / 96);
|
||||
(bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten()
|
||||
} else {
|
||||
let bands = threads.min(view.width / 96);
|
||||
(bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten()
|
||||
};
|
||||
if rendered.is_some() {
|
||||
return rendered;
|
||||
}
|
||||
}
|
||||
render_one(doc, page, view, opts)
|
||||
}
|
||||
|
||||
/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
|
||||
use rayon::prelude::*;
|
||||
let band_w = view.width.div_ceil(bands.max(1));
|
||||
let overlap = band_overlap(doc, view, band_w)?;
|
||||
let s = view.scale.max(1e-9);
|
||||
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let x0 = i * band_w;
|
||||
let w = band_w.min(view.width.saturating_sub(x0)).max(1);
|
||||
let left = x0.saturating_sub(overlap);
|
||||
let right = (x0 + w + overlap).min(view.width).max(x0 + w);
|
||||
let v =
|
||||
View { origin: (view.origin.0 + f64::from(left) / s, view.origin.1), scale: view.scale, width: right - left, height: view.height };
|
||||
let own = tiny_skia::IntRect::from_xywh((x0 - left) as i32, 0, w, view.height.clamp(1, 16_384));
|
||||
(x0, render_one(doc, page, &v, opts).zip(own).and_then(|(p, r)| p.clone_rect(r)))
|
||||
})
|
||||
.collect();
|
||||
let mut out = new_pixmap(view.width, view.height)?;
|
||||
let copy = tiny_skia::PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() };
|
||||
for (x0, part) in parts {
|
||||
let part = part?;
|
||||
out.draw_pixmap(x0 as i32, 0, part.as_ref(), ©, tiny_skia::Transform::identity(), None);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The stack a thread that renders needs (#1082). A level of the layer tree takes about 6.5 KB of
|
||||
/// stack in a render (6.8 KB in a debug build), so the deepest render [`MAX_EXPORT_DEPTH`] allows,
|
||||
/// pattern sources included, needs about 1.7 MB: more than the 2 MiB threads get by default once
|
||||
@@ -590,6 +642,8 @@ mod mask_bounds_tests;
|
||||
#[cfg(test)]
|
||||
mod paint_behaviour_tests;
|
||||
#[cfg(test)]
|
||||
mod pan_bench_tests;
|
||||
#[cfg(test)]
|
||||
mod progressive_tests;
|
||||
#[cfg(test)]
|
||||
mod render_depth_tests;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Pan render timings: a page of 60 × 60 cards, each with a drop shadow and an inner shadow, seen
|
||||
//! at 100% through a 1600 × 1100 device-pixel view. Run in release:
|
||||
//! `cargo test --release -p figcraft-render --lib pan_render_timings -- --ignored --nocapture`.
|
||||
//!
|
||||
//! "full" renders the whole view; "pan" rows go through `Retained` as the canvas does, each step
|
||||
//! moving the view by `step` device pixels and redrawing only the strips it uncovers.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow};
|
||||
|
||||
use crate::{Options, Retained, View, render_view};
|
||||
|
||||
const STEPS: u32 = 12;
|
||||
|
||||
/// The cards: (document, page).
|
||||
fn cards() -> (Arc<Document>, NodeId) {
|
||||
let mut d = Document::new("pan bench");
|
||||
let p = d.first_page().unwrap();
|
||||
for y in 0..60u32 {
|
||||
for x in 0..60u32 {
|
||||
let c = d.create(p, NodeKind::Rectangle, "Card", f64::from(x) * 140.0, f64::from(y) * 110.0, 120.0, 90.0).unwrap();
|
||||
let n = d.get_mut(c).unwrap();
|
||||
n.fills = vec![Paint::solid(Color::new(x as f32 / 60.0, y as f32 / 60.0, 0.7, 1.0))];
|
||||
n.corners.radii = [12.0; 4];
|
||||
n.effects = vec![
|
||||
Effect { kind: EffectKind::DropShadow(Shadow { radius: 18.0, offset: (0.0, 6.0), ..Shadow::default() }), visible: true },
|
||||
Effect { kind: EffectKind::InnerShadow(Shadow { radius: 8.0, ..Shadow::default() }), visible: true },
|
||||
];
|
||||
}
|
||||
}
|
||||
(Arc::new(d), p)
|
||||
}
|
||||
|
||||
fn view(origin: (f64, f64)) -> View {
|
||||
View { origin, scale: 1.0, width: 1600, height: 1100 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "timing; run in release with --ignored --nocapture"]
|
||||
fn pan_render_timings() {
|
||||
let (d, p) = cards();
|
||||
let opts = Options { lod: true, ..Options::default() };
|
||||
let t0 = Instant::now();
|
||||
for _ in 0..4 {
|
||||
render_view(&d, p, &view((1000.0, 1000.0)), &opts).unwrap();
|
||||
}
|
||||
println!("full: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 4.0);
|
||||
for (name, step) in [("pan right", (60.0, 0.0)), ("pan down", (0.0, 60.0)), ("pan diagonally", (60.0, 24.0)), ("pan right fast", (240.0, 0.0))] {
|
||||
let mut r = Retained::default();
|
||||
let mut at = (1000.0, 1000.0);
|
||||
r.render(&d, p, &view(at), &opts).unwrap();
|
||||
let t0 = Instant::now();
|
||||
for _ in 0..STEPS {
|
||||
at = (at.0 + step.0, at.1 + step.1);
|
||||
r.render(&d, p, &view(at), &opts).unwrap();
|
||||
}
|
||||
println!("{name} ({:?} px a step): {:.1} ms a step", step, t0.elapsed().as_secs_f64() * 1000.0 / f64::from(STEPS));
|
||||
}
|
||||
}
|
||||
@@ -553,7 +553,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) ->
|
||||
let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?);
|
||||
// The same pixel grid as the frame: origin (px + offset) / scale.
|
||||
let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh };
|
||||
let part = render_view(doc, page, &sub, opts)?;
|
||||
let part = crate::render_part(doc, page, &sub, opts)?;
|
||||
let inner = IntRect::from_xywh(
|
||||
i32::try_from(d.x0 - ox).ok()?,
|
||||
i32::try_from(d.y0 - oy).ok()?,
|
||||
|
||||
@@ -555,7 +555,7 @@ fn names(f: &skrifa::FontRef) -> (Option<String>, Option<String>) {
|
||||
/// document: the browser has no other fonts. The symbol fonts come last: Apple Symbols (macOS),
|
||||
/// Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for signs such as ⌖ and ⤒
|
||||
/// that no text face has.
|
||||
const FALLBACK_FAMILIES: [&str; 32] = [
|
||||
const FALLBACK_FAMILIES: [&str; 33] = [
|
||||
"Inter",
|
||||
"Helvetica Neue",
|
||||
"Arial",
|
||||
@@ -563,6 +563,7 @@ const FALLBACK_FAMILIES: [&str; 32] = [
|
||||
"DejaVu Sans",
|
||||
"Noto Sans",
|
||||
"BIZ UDPGothic",
|
||||
"Noto Sans JP",
|
||||
"Hiragino Sans",
|
||||
"PingFang SC",
|
||||
"Hiragino Sans GB",
|
||||
|
||||
@@ -604,6 +604,7 @@ fn every_embeddable_script_face_is_a_document_fallback() {
|
||||
"Noto Sans Hebrew",
|
||||
"Noto Sans Devanagari",
|
||||
"Noto Sans Georgian",
|
||||
"Noto Sans JP",
|
||||
"Noto Sans Symbols",
|
||||
"Noto Sans Symbols 2",
|
||||
] {
|
||||
|
||||
@@ -22,6 +22,7 @@ name = "Svenska"
|
||||
"A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "En samling i den här filen med dessa lägen och variabler: ange overrides för deras värden per läge och lägg till egna variabler"
|
||||
"A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "Det finns redan en .figcraft-fil med det här namnet. Välj dess fullständiga namn för att bekräfta att den ersätts."
|
||||
"A later vote" = "En senare omröstning"
|
||||
"A layer in an auto layout frame is placed by its frame" = "Ett lager i en auto layout-frame placeras av framen"
|
||||
"A layer on its own aligns to its frame: select more layers, or one in a frame" = "Ett ensamt lager justeras mot sin frame: markera fler lager, eller ett lager i en frame"
|
||||
"A responsive product page: hero, features, figures, a quote and a footer" = "En responsiv produktsida: toppsektion, funktioner, figurer, ett citat och en sidfot"
|
||||
"A spring plays until it settles: its mass, stiffness and damping set how long" = "En fjäder spelas tills den stannar: dess massa, styvhet och dämpning avgör hur länge"
|
||||
@@ -123,6 +124,7 @@ name = "Svenska"
|
||||
"Android Vector Drawable" = "Android Vector Drawable"
|
||||
"Angular" = "Vinkelmått"
|
||||
"Animation" = "Animering"
|
||||
"Annotation" = "Anteckning"
|
||||
"Annotations" = "Annoteringar"
|
||||
"Annotations shown on the canvas" = "Annoteringar som visas på arbetsytan"
|
||||
"Another server, or one that needs its key. The usual server is set in Preferences." = "En annan server, eller en som kräver sin nyckel. Standardservern anges i Inställningar."
|
||||
@@ -522,6 +524,7 @@ name = "Svenska"
|
||||
"Duo" = "Duo"
|
||||
"Duplicate" = "Duplicera"
|
||||
"Duplicate by dragging" = "Duplicera genom att dra"
|
||||
"Duplicate group" = "Duplicera grupp"
|
||||
"Duplicate mode" = "Duplicera läge"
|
||||
"Duplicate page" = "Duplicera sida"
|
||||
"Edit" = "Redigera"
|
||||
@@ -534,6 +537,9 @@ name = "Svenska"
|
||||
"Edit padding on all sides" = "Redigera padding på alla sidor"
|
||||
"Edit style" = "Redigera stil"
|
||||
"Edit variable" = "Redigera variabel"
|
||||
"Edit variables" = "Redigera variabler"
|
||||
"Scope" = "Omfång"
|
||||
"No scope is shared by all the selected variables" = "Inget omfång delas av alla markerade variabler"
|
||||
"Edit with the builder" = "Redigera med byggaren"
|
||||
"Edited {when}" = "Ändrat {when}"
|
||||
"Effect settings" = "Effektinställningar"
|
||||
@@ -883,6 +889,7 @@ name = "Svenska"
|
||||
"Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Designlager inklistrade; urklippet innehöll inte bilderna för: {layers}"
|
||||
"Remove these results from the file" = "Ta bort de här resultaten från filen"
|
||||
"Scroll wheel zoom" = "Zooma med scrollhjulet"
|
||||
"Invert zoom direction" = "Invertera zoomriktning"
|
||||
"Shared by your team on {server}" = "Delat av ditt team på {server}"
|
||||
"Slot name" = "Platsens namn"
|
||||
"Mar" = "Mar"
|
||||
@@ -1399,6 +1406,7 @@ name = "Svenska"
|
||||
"Server for online sharing" = "Server för delning online"
|
||||
"Server key" = "Servernyckel"
|
||||
"Set as default" = "Ange som standard"
|
||||
"Set as opening page" = "Ange som startsida"
|
||||
"Set corner smoothing to 60%" = "Ställ in hörnutjämning på 60 %"
|
||||
"Set variable" = "Ange variabel"
|
||||
"Set variable mode" = "Ange variabelläge"
|
||||
@@ -1574,6 +1582,11 @@ name = "Svenska"
|
||||
"Text content" = "Textinnehåll"
|
||||
"Text on a path" = "Text längs en bana"
|
||||
"Text size" = "Textstorlek"
|
||||
"Small" = "Liten"
|
||||
"Medium" = "Medel"
|
||||
"Large" = "Stor"
|
||||
"Extra large" = "Extra stor"
|
||||
"Huge" = "Enorm"
|
||||
"Text style" = "Textstil"
|
||||
"Text styles" = "Textstilar"
|
||||
"Texts" = "Texter"
|
||||
@@ -1618,6 +1631,7 @@ name = "Svenska"
|
||||
"This version can't be read." = "Den här versionen kan inte läsas."
|
||||
"This version doesn't have it: all of it is new." = "Den här versionen saknar det: allt är nytt."
|
||||
"Tidy up" = "Snygga till"
|
||||
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Markera en rad, en kolumn eller ett helt rutnät med tre eller fler lager, utanför ett auto layout-flöde"
|
||||
"Tile" = "Sida vid sida"
|
||||
"Tile type" = "Upprepningstyp"
|
||||
"Timer" = "Timer"
|
||||
@@ -1886,7 +1900,9 @@ name = "Svenska"
|
||||
"some vector segments refer to style settings missing from the file; they use the layer's stroke" = "vissa vektorsegment hänvisar till stilinställningar som saknas i filen; de använder lagrets kontur"
|
||||
"stale or invalid grid track sizing entries were ignored" = "inaktuella eller ogiltiga storleksposter för rutnätsspår ignorerades"
|
||||
"stars and polygons without point counts or geometry use the default point count" = "stjärnor och polygoner utan antal punkter eller geometri använder standardantalet punkter"
|
||||
"sticky layers import as frames with their text" = "fästlappslager importeras som frames med sin text"
|
||||
"style settings of some vector segments aren't supported; those segments use the layer's stroke" = "stilinställningar för vissa vektorsegment stöds inte; de segmenten använder lagrets kontur"
|
||||
"swapped instances whose previous component isn't in the file took the new component's look" = "utbytta instanser vars tidigare komponent inte finns i filen fick den nya komponentens utseende"
|
||||
"text path underline or strikethrough decoration is not rendered" = "understrykning eller genomstrykning av text på bana ritas inte"
|
||||
"text style overrides refer to missing table entries" = "overrides av textstilar hänvisar till tabellposter som saknas"
|
||||
"the file has no pages" = "filen har inga sidor"
|
||||
@@ -2351,6 +2367,7 @@ name = "Svenska"
|
||||
"plugins.runLast" = "Kör senaste plugin"
|
||||
"pref.autoSave" = "Spara filer automatiskt"
|
||||
"pref.highlightHover" = "Framhäv lager vid hovring"
|
||||
"pref.invertZoom" = "Invertera zoomriktning"
|
||||
"pref.keepTool" = "Behåll verktyget markerat efter användning"
|
||||
"pref.language" = "Gränssnittsspråk"
|
||||
"pref.nudge" = "Steglängd"
|
||||
@@ -2508,6 +2525,7 @@ name = "Svenska"
|
||||
"text.weightDown" = "Minska teckenvikten"
|
||||
"text.weightUp" = "Öka teckenvikten"
|
||||
"text.wrapStyle" = "Radbrytningsstil"
|
||||
"tool.annotation" = "Anteckning"
|
||||
"tool.arrow" = "Pil"
|
||||
"tool.comment" = "Kommentar"
|
||||
"tool.connector" = "Koppling"
|
||||
@@ -2696,6 +2714,9 @@ name = "Svenska"
|
||||
"text.alignJustify" = "Marginaljustera text"
|
||||
"text.alignLeft" = "Vänsterjustera text"
|
||||
"text.alignRight" = "Högerjustera text"
|
||||
"text.directionAuto" = "Auto"
|
||||
"text.directionLtr" = "Vänster till höger"
|
||||
"text.directionRtl" = "Höger till vänster"
|
||||
"view.assets" = "Resurser"
|
||||
"view.design" = "Design"
|
||||
"view.layers" = "Lager"
|
||||
|
||||
@@ -90,6 +90,8 @@ impl FigApp {
|
||||
"quality": if self.canvas.tex_coarse { "preview" } else { "refined" },
|
||||
"previewLatencyMs": self.canvas.preview_latency_ms,
|
||||
"refineLatencyMs": self.canvas.refine_latency_ms,
|
||||
// The share of the canvas only the page colour covered last frame (no render reached it).
|
||||
"uncovered": self.canvas.uncovered,
|
||||
},
|
||||
"live": live::inspect(self),
|
||||
"window": self.windows.current,
|
||||
|
||||
@@ -62,6 +62,9 @@ pub struct CanvasState {
|
||||
/// shows its image at once while it renders again, instead of a blank canvas (and, where
|
||||
/// renders are slow, a coarse preview).
|
||||
kept: Vec<Kept>,
|
||||
/// The coarse image of the area around the view ([`render_worker::Surround`]), shown where
|
||||
/// the texture doesn't reach, and the file and page it is of.
|
||||
surround: Option<(egui::TextureHandle, figcraft_render::View, (u64, NodeId))>,
|
||||
submitted: Option<JobKey>,
|
||||
/// The view of the last render asked for.
|
||||
want_view: Option<figcraft_render::View>,
|
||||
@@ -71,6 +74,8 @@ pub struct CanvasState {
|
||||
/// canvas texture (ms; the texture is uploaded when that frame is painted).
|
||||
pub preview_latency_ms: Option<f64>,
|
||||
pub refine_latency_ms: Option<f64>,
|
||||
/// The share of the canvas no render covered last frame: the page background showed there.
|
||||
pub uncovered: f32,
|
||||
dragging: bool,
|
||||
space_pan: bool,
|
||||
middle_pan: Option<(Pos2, f64, f64)>,
|
||||
@@ -104,11 +109,13 @@ impl Default for CanvasState {
|
||||
tex_coarse: false,
|
||||
tex_seq: 0,
|
||||
kept: Vec::new(),
|
||||
surround: None,
|
||||
submitted: None,
|
||||
want_view: None,
|
||||
render_work: None,
|
||||
preview_latency_ms: None,
|
||||
refine_latency_ms: None,
|
||||
uncovered: 0.0,
|
||||
dragging: false,
|
||||
space_pan: false,
|
||||
middle_pan: None,
|
||||
@@ -339,6 +346,21 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
app.canvas.tex_coarse = done.coarse;
|
||||
app.canvas.tex_seq = done.seq;
|
||||
}
|
||||
if let Some(around) = worker.surround()
|
||||
&& shown == Some((around.uid, around.page))
|
||||
{
|
||||
let of = (around.uid, around.page);
|
||||
match &mut app.canvas.surround {
|
||||
Some((t, view, at)) => {
|
||||
t.set(around.image, egui::TextureOptions::LINEAR);
|
||||
(*view, *at) = (around.view, of);
|
||||
}
|
||||
None => {
|
||||
let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR);
|
||||
app.canvas.surround = Some((t, around.view, of));
|
||||
}
|
||||
}
|
||||
}
|
||||
let painter = ui.painter_at(rect);
|
||||
crate::theme::set_canvas_page(&ctx, bg);
|
||||
let image = if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) {
|
||||
@@ -351,7 +373,16 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
background::paint(&painter, rect, bg, image.map(|(_, r)| r));
|
||||
// Not in pixel preview: its pixels are the point, and it keeps no image around the view.
|
||||
let pixel_preview = app.session.ds().ok().and_then(|ds| ds.view.pixel_preview_scale()).is_some();
|
||||
let surround = match (&app.canvas.surround, pixel_preview) {
|
||||
(Some((tex, v, of)), false) if shown == Some(*of) => {
|
||||
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0);
|
||||
Some((tex.id(), presented_image_rect(app.to_screen(v.origin.0, v.origin.1), v, zoom, ppp, false)))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
app.canvas.uncovered = background::paint(&painter, rect, bg, image.map(|(_, r)| r), surround);
|
||||
if let Some((texture, image_rect)) = image {
|
||||
painter.image(texture, image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
@@ -461,5 +492,8 @@ mod wheel_zoom_tests;
|
||||
#[cfg(test)]
|
||||
mod zoom_preview_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod surround_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tab_switch_tests;
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The transparency grid behind the page; rendered pixels already contain the page colour.
|
||||
|
||||
use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, pos2};
|
||||
use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, TextureId, pos2};
|
||||
|
||||
/// Reuse the checkerboard texture, updating its pixels when the active theme changes.
|
||||
fn grid_texture(ctx: &egui::Context) -> TextureHandle {
|
||||
@@ -25,18 +25,40 @@ fn grid_texture(ctx: &egui::Context) -> TextureHandle {
|
||||
texture
|
||||
}
|
||||
|
||||
/// Draw the transparency grid and apply page colour only outside the rendered image.
|
||||
pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option<Rect>) {
|
||||
/// Draw the transparency grid, and where the rendered image doesn't reach the coarse image around
|
||||
/// the view (`surround`: its texture and screen rect), and the page colour past that. Returns the
|
||||
/// share of `rect` that only the page colour covers.
|
||||
pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option<Rect>, surround: Option<(TextureId, Rect)>) -> f32 {
|
||||
if background.a() < 255 {
|
||||
// Repeat four pixels instead of allocating one shape per square on a large canvas.
|
||||
let texture = grid_texture(painter.ctx());
|
||||
let uv = Rect::from_min_size(egui::Pos2::ZERO, rect.size() / 16.0);
|
||||
painter.image(texture.id(), rect, uv, Color32::WHITE);
|
||||
}
|
||||
// The render contains the page colour and its alpha. Painting that colour beneath it
|
||||
// applies alpha twice (50% becomes 75%). Only uncovered areas need the fallback colour.
|
||||
let covered = rendered.map(|r| r.intersect(rect)).filter(|r| r.is_positive());
|
||||
let areas = match covered {
|
||||
// Renders contain the page colour and its alpha. Painting that colour (or the coarse image)
|
||||
// beneath one applies alpha twice (50% becomes 75%): each area gets exactly one of them.
|
||||
let mut bare = 0.0;
|
||||
for area in outside(rect, rendered) {
|
||||
let rest = match surround {
|
||||
Some((texture, at)) => {
|
||||
if area.intersect(at).is_positive() {
|
||||
painter.with_clip_rect(area).image(texture, at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
outside(area, Some(at))
|
||||
}
|
||||
None => outside(area, None),
|
||||
};
|
||||
for r in rest {
|
||||
painter.rect_filled(r, CornerRadius::ZERO, background);
|
||||
bare += r.area();
|
||||
}
|
||||
}
|
||||
if rect.area() > 0.0 { (bare / rect.area()).clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The parts of `rect` outside `covered`: at most four strips that don't overlap.
|
||||
fn outside(rect: Rect, covered: Option<Rect>) -> impl Iterator<Item = Rect> {
|
||||
let areas = match covered.map(|r| r.intersect(rect)).filter(|r| r.is_positive()) {
|
||||
Some(r) => [
|
||||
Rect::from_min_max(rect.min, pos2(rect.right(), r.top())),
|
||||
Rect::from_min_max(pos2(rect.left(), r.bottom()), rect.max),
|
||||
@@ -45,9 +67,7 @@ pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered
|
||||
],
|
||||
None => [rect, Rect::NOTHING, Rect::NOTHING, Rect::NOTHING],
|
||||
};
|
||||
for area in areas.into_iter().filter(|r| r.is_positive()) {
|
||||
painter.rect_filled(area, CornerRadius::ZERO, background);
|
||||
}
|
||||
areas.into_iter().filter(|r| r.is_positive())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -59,7 +79,7 @@ mod tests {
|
||||
fn shapes(alpha: u8, rendered: Option<Rect>) -> egui::FullOutput {
|
||||
let ctx = egui::Context::default();
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered);
|
||||
paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered, None);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
@@ -169,7 +189,9 @@ mod tests {
|
||||
let mut previous_id = None;
|
||||
for tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark(), crate::theme::Tokens::light()] {
|
||||
crate::theme::apply(&ctx, tokens);
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| paint(ui.painter(), canvas(), Color32::TRANSPARENT, None));
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
paint(ui.painter(), canvas(), Color32::TRANSPARENT, None, None);
|
||||
});
|
||||
let (tile, _) =
|
||||
ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("drawn checkerboard");
|
||||
let grid_index = assert_grid(&out, tile.id(), canvas());
|
||||
@@ -227,4 +249,47 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the rendered image the coarse image around the view shows, clipped to outside the
|
||||
/// image, and the page colour only past both: nothing is painted twice, and what is left bare
|
||||
/// is what the call returns.
|
||||
#[test]
|
||||
fn the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest() {
|
||||
let ctx = egui::Context::default();
|
||||
let around = TextureId::User(7);
|
||||
// The render covers the left half; the coarse image reaches 80 to the right.
|
||||
let rendered = Rect::from_min_max(pos2(0.0, 0.0), pos2(50.0, 100.0));
|
||||
let at = Rect::from_min_max(pos2(-100.0, -100.0), pos2(80.0, 200.0));
|
||||
let mut bare = -1.0;
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, at)));
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let coarse: Vec<_> = out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == around)).collect();
|
||||
assert_eq!(coarse.len(), 1, "one strip of the canvas lies past the render");
|
||||
assert_eq!(coarse[0].clip_rect, Rect::from_min_max(pos2(50.0, 0.0), pos2(100.0, 100.0)), "clipped to past the render");
|
||||
let fills: Vec<Rect> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Rect(r) => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(fills, [Rect::from_min_max(pos2(80.0, 0.0), pos2(100.0, 100.0))], "the page colour only past both");
|
||||
assert!((bare - 0.2).abs() < 1e-6, "a fifth of the canvas is bare: {bare}");
|
||||
// Without one the page colour fills all of it; with one reaching everywhere nothing.
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), None);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert!((bare - 0.5).abs() < 1e-6, "{bare}");
|
||||
let everywhere = Rect::from_min_max(pos2(-100.0, -100.0), pos2(200.0, 200.0));
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, everywhere)));
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(bare, 0.0);
|
||||
assert!(!out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(_))), "no page colour under the coarse image");
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@
|
||||
//! ([`figcraft_render::Steps`]), at least a band a frame and more while they fit in [`STEP_MS`],
|
||||
//! so input is handled while it draws (on a page whose render takes seconds, a band is a
|
||||
//! fraction of that: eight at most).
|
||||
//! On the desktop a third thread keeps a coarse image of the area around the view
|
||||
//! ([`Surround`]): where the canvas image doesn't reach (a pan past its edge before the strips are
|
||||
//! drawn, a zoom out) the canvas shows that, blurred, instead of the bare page colour.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -145,6 +148,78 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool)
|
||||
Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 }
|
||||
}
|
||||
|
||||
/// The coarse image around the view is this many views wide and tall, centred on it.
|
||||
const SURROUND_SPAN: f64 = 3.0;
|
||||
|
||||
/// The area [`SURROUND_SPAN`] times as wide and tall as `view`, centred on it, with
|
||||
/// [`PREVIEW_FACTOR`] times fewer pixels per page unit (`view` is at most as large as a texture,
|
||||
/// so this is too).
|
||||
pub fn surround_view(view: &View) -> View {
|
||||
let c = coarse_view(view);
|
||||
let s = c.scale.max(1e-9);
|
||||
let (w, h) = (f64::from(c.width), f64::from(c.height));
|
||||
let pad = (SURROUND_SPAN - 1.0) / 2.0;
|
||||
let side = |n: f64| (n * SURROUND_SPAN).ceil().max(1.0) as u32;
|
||||
View { origin: (view.origin.0 - pad * w / s, view.origin.1 - pad * h / s), scale: c.scale, width: side(w), height: side(h) }
|
||||
}
|
||||
|
||||
/// Whether `around` reaches a third of `view`'s size past each of its sides: a pan that far shows
|
||||
/// no edge.
|
||||
fn reaches(around: &View, view: &View) -> bool {
|
||||
let (a, v) = (around.page_rect(), view.page_rect());
|
||||
let (mx, my) = (v.width() / 3.0, v.height() / 3.0);
|
||||
a.x0 <= v.x0 - mx && a.y0 <= v.y0 - my && a.x1 >= v.x1 + mx && a.y1 >= v.y1 + my
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same view, bit for bit.
|
||||
fn same_view(a: &View, b: &View) -> bool {
|
||||
(a.origin.0.to_bits(), a.origin.1.to_bits(), a.scale.to_bits(), a.width, a.height)
|
||||
== (b.origin.0.to_bits(), b.origin.1.to_bits(), b.scale.to_bits(), b.width, b.height)
|
||||
}
|
||||
|
||||
/// The coarse image of the area around the view ([`surround_view`]), kept between requests.
|
||||
#[derive(Default)]
|
||||
pub struct Surround {
|
||||
retained: Retained,
|
||||
/// The file, page and view of the image handed over last, and whether it was soft-proofed
|
||||
/// (marked after the render, so the kept image can't tell).
|
||||
of: Option<(u64, NodeId, View, bool)>,
|
||||
}
|
||||
|
||||
impl Surround {
|
||||
/// The image around `job`'s view when the one handed over last no longer stands for it (of
|
||||
/// another file, page or zoom, short of a third of a view past an edge, or the document
|
||||
/// changed), drawn on the kept one: a pan shifts it and redraws the strips, an edit the areas
|
||||
/// that changed. `None` in pixel preview, whose pixels are the point.
|
||||
pub fn render(&mut self, job: &Job) -> Option<Done> {
|
||||
if !job.zoom_preview {
|
||||
return None;
|
||||
}
|
||||
let want = surround_view(&job.view);
|
||||
let view = match &self.of {
|
||||
Some((uid, page, have, _))
|
||||
if *uid == job.uid && *page == job.page && have.scale.to_bits() == want.scale.to_bits() && reaches(have, &job.view) =>
|
||||
{
|
||||
have.clone()
|
||||
}
|
||||
_ => want,
|
||||
};
|
||||
let same = self
|
||||
.of
|
||||
.as_ref()
|
||||
.is_some_and(|(uid, page, have, proof)| *uid == job.uid && *page == job.page && *proof == job.proof && same_view(have, &view));
|
||||
let t0 = Instant::now();
|
||||
let d = guarded(&mut self.retained, |r| {
|
||||
let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?;
|
||||
(!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true))
|
||||
});
|
||||
if d.is_some() {
|
||||
self.of = Some((job.uid, job.page, view, job.proof));
|
||||
}
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
/// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area.
|
||||
pub fn coarse_view(view: &View) -> View {
|
||||
let shrink = |n: u32| (f64::from(n) / PREVIEW_FACTOR).ceil().max(1.0) as u32;
|
||||
@@ -413,6 +488,12 @@ pub struct Worker {
|
||||
finished: Arc<std::sync::atomic::AtomicU64>,
|
||||
/// The watchdog is drawing a late preview, or has one to hand over and wake the UI for.
|
||||
previewing: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// The images around the view ([`Surround`]) from their thread.
|
||||
surround_rx: std::sync::mpsc::Receiver<Done>,
|
||||
/// The newest request handed to the surround thread, and the newest it is done with (its image
|
||||
/// handed over and the UI woken, or none needed).
|
||||
surround_asked: Arc<std::sync::atomic::AtomicU64>,
|
||||
surround_done: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -467,6 +548,33 @@ impl Worker {
|
||||
if let Err(e) = watchdog {
|
||||
log::error!("render preview thread: {e}");
|
||||
}
|
||||
// The image around the view, on a thread of its own so it never holds up the canvas image:
|
||||
// the render thread hands it each request it has refined, the newest queued one wins.
|
||||
let (around_tx, around) = std::sync::mpsc::channel::<(u64, Job)>();
|
||||
let (surround_tx, surround_rx) = std::sync::mpsc::channel::<Done>();
|
||||
let surround_ctx = ctx.clone();
|
||||
let surround_asked = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
let surround_done = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
let (asked, surrounded) = (surround_asked.clone(), surround_done.clone());
|
||||
let surrounding =
|
||||
std::thread::Builder::new().name("figcraft-render-surround".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || {
|
||||
let mut surround = Surround::default();
|
||||
while let Ok((mut seq, mut job)) = around.recv() {
|
||||
while let Ok(newer) = around.try_recv() {
|
||||
(seq, job) = newer;
|
||||
}
|
||||
if let Some(d) = surround.render(&job) {
|
||||
if surround_tx.send(d).is_err() {
|
||||
break;
|
||||
}
|
||||
surround_ctx.request_repaint_of(viewport);
|
||||
}
|
||||
surrounded.store(seq, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
if let Err(e) = surrounding {
|
||||
log::error!("render surround thread: {e}");
|
||||
}
|
||||
let spawned = std::thread::Builder::new().name("figcraft-render".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || {
|
||||
let mut renders = Renders::default();
|
||||
let mut next = None;
|
||||
@@ -502,11 +610,21 @@ impl Worker {
|
||||
}
|
||||
let done = renders.refine(&job);
|
||||
refined.store(seq, std::sync::atomic::Ordering::SeqCst);
|
||||
let refined_job = done.is_some();
|
||||
if let Some(d) = done
|
||||
&& done_tx.send(answering(d, seq)).is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
if refined_job {
|
||||
// Asked before the send (and before this request counts as done), so `in_flight`
|
||||
// holds until the surround thread is done with it. Without that thread (it failed
|
||||
// to start) the page colour shows past the edge.
|
||||
asked.store(seq, std::sync::atomic::Ordering::SeqCst);
|
||||
if around_tx.send((seq, job)).is_err() {
|
||||
asked.store(0, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
ctx.request_repaint_of(viewport);
|
||||
done_with.store(seq, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
@@ -514,7 +632,7 @@ impl Worker {
|
||||
if let Err(e) = spawned {
|
||||
log::error!("render thread: {e}");
|
||||
}
|
||||
Self { tx, rx, submitted: 0, finished, previewing }
|
||||
Self { tx, rx, submitted: 0, finished, previewing, surround_rx, surround_asked, surround_done }
|
||||
}
|
||||
|
||||
pub fn submit(&mut self, job: Job) {
|
||||
@@ -524,9 +642,13 @@ impl Worker {
|
||||
}
|
||||
|
||||
/// Whether a submitted job is still rendering or hasn't woken the UI yet, the watchdog's late
|
||||
/// preview included (a finished image may still wait for [`Self::poll`]).
|
||||
/// preview and the image around the view included (a finished image may still wait for
|
||||
/// [`Self::poll`] or [`Self::surround`]).
|
||||
pub fn in_flight(&self) -> bool {
|
||||
self.finished.load(std::sync::atomic::Ordering::SeqCst) < self.submitted || self.previewing.load(std::sync::atomic::Ordering::SeqCst)
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
self.finished.load(SeqCst) < self.submitted
|
||||
|| self.previewing.load(SeqCst)
|
||||
|| self.surround_done.load(SeqCst) < self.surround_asked.load(SeqCst)
|
||||
}
|
||||
|
||||
/// The best of the renders finished since the last poll ([`better`]).
|
||||
@@ -537,6 +659,11 @@ impl Worker {
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// The newest image around the view ([`Surround`]) finished since the last call.
|
||||
pub fn surround(&mut self) -> Option<Done> {
|
||||
self.surround_rx.try_iter().last()
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser's worker: renders inline, one image a frame: a preview first when one is due, the
|
||||
@@ -599,6 +726,11 @@ impl Inline {
|
||||
pub fn in_flight(&self) -> bool {
|
||||
self.pending.is_some()
|
||||
}
|
||||
/// shortcut: the browser renders on the page's own thread, so it keeps no image around the view
|
||||
/// (one would hold the page up); draw one there once the canvas renders on a wasm thread (#1500).
|
||||
pub fn surround(&mut self) -> Option<Done> {
|
||||
None
|
||||
}
|
||||
pub fn poll(&mut self) -> Option<Done> {
|
||||
self.poll_at(Instant::now())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The coarse image around the view ([`Surround`]): three views wide and tall at a quarter of the
|
||||
//! pixels each way, kept while the view stays a third of a view inside it, moved (a shift and the
|
||||
//! strips) when a pan goes further, patched after an edit, none in pixel preview; and the desktop
|
||||
//! worker hands one over after each refined render, so a pan past the canvas image shows that
|
||||
//! instead of the bare page colour.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use figcraft_render::{View, Work};
|
||||
use serde_json::json;
|
||||
|
||||
use super::zoom_preview_tests::{document, job, view_at};
|
||||
use crate::render_worker::{Job, PREVIEW_FACTOR, Surround, Worker, surround_view};
|
||||
|
||||
/// Whether `outer` shows all of the page `inner` does, give or take the snapping to whole pixels.
|
||||
fn contains(outer: &View, inner: &View) -> bool {
|
||||
let (o, i) = (outer.page_rect(), inner.page_rect());
|
||||
let eps = 2.0 / outer.scale;
|
||||
o.x0 <= i.x0 + eps && o.y0 <= i.y0 + eps && o.x1 >= i.x1 - eps && o.y1 >= i.y1 - eps
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_area_around_a_view_is_three_views_wide_at_a_quarter_of_the_pixels() {
|
||||
let v = view_at((400.0, 300.0), 2.0, 800, 600);
|
||||
let a = surround_view(&v);
|
||||
assert_eq!(a.scale, v.scale / PREVIEW_FACTOR);
|
||||
assert_eq!((a.width, a.height), (600, 450), "3 × 800 / 4 by 3 × 600 / 4");
|
||||
let (pa, pv) = (a.page_rect(), v.page_rect());
|
||||
assert!((pa.center().x - pv.center().x).abs() < 1e-9 && (pa.center().y - pv.center().y).abs() < 1e-9, "centred on the view");
|
||||
assert!((pa.width() - 3.0 * pv.width()).abs() < 1e-9 && (pa.height() - 3.0 * pv.height()).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_around_the_view_is_kept_for_small_pans_and_moved_for_far_ones() {
|
||||
let (s, rect) = document();
|
||||
let ds = s.ds().unwrap();
|
||||
let at = |c: (f64, f64)| job(&ds.doc, ds.page, ds.uid, view_at(c, 1.0, 400, 300));
|
||||
let mut around = Surround::default();
|
||||
let first = around.render(&at((250.0, 150.0))).expect("the first one");
|
||||
assert_eq!(first.work, Work::Full);
|
||||
assert!(first.coarse && contains(&first.view, &surround_view(&at((250.0, 150.0)).view)));
|
||||
assert!(around.render(&at((250.0, 150.0))).is_none(), "the same request: nothing new");
|
||||
// A quarter of a view: it still reaches more than a third of a view past every side.
|
||||
assert!(around.render(&at((350.0, 225.0))).is_none(), "kept for a small pan");
|
||||
// Most of a view: moved to centre on the view again, built on the kept image.
|
||||
let moved = around.render(&at((570.0, 150.0))).expect("moved for a far pan");
|
||||
assert!(matches!(moved.work, Work::Partial { .. }), "a shift and the strips: {:?}", moved.work);
|
||||
assert!(contains(&moved.view, &surround_view(&at((570.0, 150.0)).view)));
|
||||
// An edit redraws its area.
|
||||
let mut s = s;
|
||||
s.execute("node.set", &json!({"id": rect, "props": {"x": 140}})).unwrap();
|
||||
let ds = s.ds().unwrap();
|
||||
let edited = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 1.0, 400, 300));
|
||||
assert!(matches!(around.render(&edited).expect("after an edit").work, Work::Partial { .. }));
|
||||
// Soft proof marks the image after it renders: turning it on or off hands over a new one.
|
||||
assert!(around.render(&Job { proof: true, ..edited.clone() }).is_some(), "proof on");
|
||||
assert!(around.render(&Job { proof: true, ..edited.clone() }).is_none());
|
||||
assert!(around.render(&edited).is_some(), "proof off");
|
||||
// Another zoom starts over; pixel preview has none.
|
||||
let zoomed = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 2.0, 400, 300));
|
||||
assert_eq!(around.render(&zoomed).expect("another zoom").work, Work::Full);
|
||||
assert!(around.render(&Job { zoom_preview: false, ..job(&ds.doc, ds.page, ds.uid, view_at((0.0, 0.0), 8.0, 400, 300)) }).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_worker_hands_over_the_image_around_each_refined_view() {
|
||||
let (s, _) = document();
|
||||
let ds = s.ds().unwrap();
|
||||
let j = job(&ds.doc, ds.page, ds.uid, view_at((250.0, 150.0), 1.0, 400, 300));
|
||||
let mut w = Worker::new(egui::Context::default());
|
||||
w.submit(j.clone());
|
||||
let start = std::time::Instant::now();
|
||||
let around = loop {
|
||||
assert!(start.elapsed() < Duration::from_secs(60), "no image around the view came");
|
||||
if let Some(d) = w.surround() {
|
||||
break d;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
};
|
||||
assert_eq!((around.uid, around.page), (ds.uid, ds.page));
|
||||
assert!(contains(&around.view, &surround_view(&j.view)), "it reaches a view past every side");
|
||||
assert!(w.poll().is_some_and(|d| !d.coarse), "the refined image came through as before");
|
||||
}
|
||||
@@ -27,7 +27,7 @@ use crate::render_worker::{
|
||||
/// scanned first (once per process, and a concurrent caller waits for it): the scan another test
|
||||
/// starts bumps the global font generation, and a render kept from before it is stale, so a pan
|
||||
/// or an edit meanwhile would redraw in full instead of patching.
|
||||
fn document() -> (Session, NodeId) {
|
||||
pub(super) fn document() -> (Session, NodeId) {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
for k in 0..12 {
|
||||
@@ -69,11 +69,11 @@ fn slow_scene(views: &[View], ms: f64) -> Session {
|
||||
}
|
||||
|
||||
/// A `w` × `h` device-pixel view at `scale` centred on page point `c`.
|
||||
fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View {
|
||||
pub(super) fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View {
|
||||
View { origin: (c.0 - f64::from(w) / scale / 2.0, c.1 - f64::from(h) / scale / 2.0), scale, width: w, height: h }
|
||||
}
|
||||
|
||||
fn job(doc: &Arc<Document>, page: NodeId, uid: u64, view: View) -> Job {
|
||||
pub(super) fn job(doc: &Arc<Document>, page: NodeId, uid: u64, view: View) -> Job {
|
||||
Job {
|
||||
doc: doc.clone(),
|
||||
page,
|
||||
|
||||
@@ -302,6 +302,8 @@ mod vector_keys_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_panel_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_point_radius_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_point_xy_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_tail_ui_tests;
|
||||
|
||||
@@ -248,6 +248,12 @@ struct Snapshot {
|
||||
overlays: Vec<OverlayState>,
|
||||
history: Vec<Visit>,
|
||||
scroll: HashMap<NodeId, (f64, f64)>,
|
||||
/// When each instance last changed variant: a temporary change that reverts restores it, so
|
||||
/// the variant shown again keeps its After delay deadline.
|
||||
swapped: HashMap<NodeId, f64>,
|
||||
/// The After delays that had fired: a temporary variant change clears the swapped instance's,
|
||||
/// and the revert puts them back so a delay that already ran doesn't run again.
|
||||
delays_fired: HashSet<(NodeId, usize)>,
|
||||
}
|
||||
|
||||
/// A "while hovering / while pressing" state that reverts when the pointer leaves / lifts.
|
||||
@@ -290,6 +296,8 @@ pub struct Presenter {
|
||||
bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>,
|
||||
arrived: f64,
|
||||
delays_fired: HashSet<(NodeId, usize)>,
|
||||
/// When each instance last changed variant (Change to): its After delay timers count from then.
|
||||
swapped: HashMap<NodeId, f64>,
|
||||
/// Mouse triggers waiting out their delay.
|
||||
waiting: Vec<Waiting>,
|
||||
hovered: Vec<NodeId>,
|
||||
@@ -370,6 +378,7 @@ impl Presenter {
|
||||
bar_thumb: None,
|
||||
arrived: -1.0,
|
||||
delays_fired: HashSet::new(),
|
||||
swapped: HashMap::new(),
|
||||
waiting: Vec::new(),
|
||||
hovered: Vec::new(),
|
||||
press: None,
|
||||
@@ -460,6 +469,9 @@ mod tail_tests;
|
||||
#[cfg(test)]
|
||||
mod delay_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod afterdelay_chain_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod overlay_anchor_tests;
|
||||
|
||||
|
||||
@@ -218,6 +218,9 @@ impl Presenter {
|
||||
}
|
||||
figcraft_engine::components::sync_instance(d, inst);
|
||||
self.settle(&before);
|
||||
// The new variant's After delay interactions are fresh: they count from now.
|
||||
self.delays_fired.retain(|(id, _)| !doc.is_ancestor(inst, *id));
|
||||
self.swapped.insert(inst, now);
|
||||
true
|
||||
}
|
||||
Action::SetVariable { variable, value, expr } => {
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
//! A chain of variant After delay steps (Change to) plays to the end, each step's delay counted
|
||||
//! from when its variant appeared (#2352). Driven through egui headless on the harness's clock.
|
||||
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::present_tests::{Ui as Harness, id};
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// Variants A to D of one set, an instance on A in a screen, each step an After delay of `ms`
|
||||
/// changing to the next variant. (harness presenting the screen, the instance, the variants)
|
||||
fn chain(ms: u32) -> (Harness, NodeId, Vec<NodeId>) {
|
||||
let mut s = Session::new();
|
||||
let variants: Vec<NodeId> = ["A", "B", "C", "D"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, state)| {
|
||||
let f = id(&ex(
|
||||
&mut s,
|
||||
"frame.create",
|
||||
json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}),
|
||||
));
|
||||
id(&ex(&mut s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
for pair in variants.windows(2) {
|
||||
let it = json!({"id": pair[0], "trigger": {"type": "afterDelay", "ms": ms}, "action": {"type": "changeTo", "dest": pair[1]}, "transition": {"type": "instant"}, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", it);
|
||||
}
|
||||
let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap();
|
||||
let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen})));
|
||||
ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]}));
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": screen}));
|
||||
(u, inst, variants)
|
||||
}
|
||||
|
||||
/// The variant (index) the instance shows in the presenter.
|
||||
fn shown(u: &Harness, inst: NodeId, variants: &[NodeId]) -> Option<usize> {
|
||||
let p = crate::tabs::shown_or_paused(&u.app)?;
|
||||
let d = p.doc.as_ref()?;
|
||||
match d.node(inst)?.kind {
|
||||
NodeKind::Instance { component, .. } => variants.iter().position(|v| *v == component),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_of_variant_after_delays_plays_to_the_end() {
|
||||
let (mut u, inst, variants) = chain(0);
|
||||
u.frames(30, Vec::new);
|
||||
assert_eq!(shown(&u, inst, &variants), Some(3), "A -> B -> C -> D");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_step_waits_its_own_delay_from_when_its_variant_appeared() {
|
||||
let (mut u, inst, variants) = chain(500);
|
||||
// Step until the instance shows B, then note the time.
|
||||
let mut guard = 0;
|
||||
while shown(&u, inst, &variants) != Some(1) {
|
||||
u.frame(Vec::new());
|
||||
guard += 1;
|
||||
assert!(guard < 120, "A never changed to B");
|
||||
}
|
||||
let appeared = u.time;
|
||||
while u.time < appeared + 0.4 {
|
||||
u.frame(Vec::new());
|
||||
}
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "400 ms after B appeared: still B");
|
||||
while u.time < appeared + 0.6 {
|
||||
u.frame(Vec::new());
|
||||
}
|
||||
assert_eq!(shown(&u, inst, &variants), Some(2), "600 ms after B appeared: C");
|
||||
}
|
||||
|
||||
/// A hover that changes the variant and reverts leaves the variant shown again on its own After
|
||||
/// delay deadline (counted from the screen's arrival), not from the hover.
|
||||
#[test]
|
||||
fn a_hover_variant_that_reverts_keeps_the_after_delay_deadline() {
|
||||
let mut s = Session::new();
|
||||
let variants: Vec<NodeId> = ["A", "Hover", "Next"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, state)| {
|
||||
let f = id(&ex(
|
||||
&mut s,
|
||||
"frame.create",
|
||||
json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}),
|
||||
));
|
||||
id(&ex(&mut s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let instant = json!({"type": "instant"});
|
||||
let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "changeTo", "dest": variants[2]}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", delay);
|
||||
let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", hover);
|
||||
let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap();
|
||||
let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen})));
|
||||
ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]}));
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": screen}));
|
||||
u.frame(Vec::new());
|
||||
let start = u.time;
|
||||
let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default();
|
||||
let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}"));
|
||||
let r: Vec<f32> = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect();
|
||||
let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0));
|
||||
while u.time < start + 0.8 {
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
}
|
||||
u.frame(vec![egui::Event::PointerMoved(on)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant");
|
||||
while u.time < start + 0.9 {
|
||||
u.frame(vec![egui::Event::PointerMoved(on)]);
|
||||
}
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again");
|
||||
while u.time < start + 1.3 {
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
}
|
||||
assert_eq!(shown(&u, inst, &variants), Some(2), "A's 1,000 ms delay from the arrival fired, not 1,000 ms after the hover");
|
||||
}
|
||||
|
||||
/// A delay that already ran on a variant stays run after a hover changes the variant and reverts:
|
||||
/// the keys the temporary change cleared come back with the revert.
|
||||
#[test]
|
||||
fn a_hover_variant_that_reverts_does_not_rerun_a_fired_delay() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Run", "name": "count", "type": "number", "value": 0}));
|
||||
let count = s.doc().unwrap().variables.get("count").map(|v| v.id.clone()).unwrap();
|
||||
let variants: Vec<NodeId> = ["A", "Hover"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, state)| {
|
||||
let f = id(&ex(
|
||||
&mut s,
|
||||
"frame.create",
|
||||
json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}),
|
||||
));
|
||||
id(&ex(&mut s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let instant = json!({"type": "instant"});
|
||||
// A's delay leaves A on screen: it counts its runs (count = count + 1).
|
||||
let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": count}}, {"value": {"type": "number", "value": 1}}]}});
|
||||
let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "setVariable", "variable": count, "value": null, "expr": inc}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", delay);
|
||||
let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", hover);
|
||||
let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap();
|
||||
let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen})));
|
||||
ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]}));
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": screen}));
|
||||
u.frame(Vec::new());
|
||||
let start = u.time;
|
||||
let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default();
|
||||
let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}"));
|
||||
let r: Vec<f32> = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect();
|
||||
let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0));
|
||||
while u.time < start + 0.3 {
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
}
|
||||
let fired: Vec<(NodeId, usize)> = crate::tabs::shown_or_paused(&u.app).map(|p| p.delays_fired.iter().copied().collect()).unwrap_or_default();
|
||||
assert!(!fired.is_empty(), "A's delay ran before the hover");
|
||||
u.frame(vec![egui::Event::PointerMoved(on)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant");
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again");
|
||||
u.frames(5, Vec::new);
|
||||
let p = crate::tabs::shown_or_paused(&u.app).expect("presenting");
|
||||
assert!(fired.iter().all(|k| p.delays_fired.contains(k)), "the delay that ran before the hover is still marked as run: {:?}", p.delays_fired);
|
||||
let runs = p.design.as_ref().and_then(|d| d.variables.resolve(&count, &Default::default()));
|
||||
assert_eq!(runs, Some(figcraft_doc::VariableValue::Number(1.0)), "A's delay ran once, not again after the hover");
|
||||
}
|
||||
|
||||
/// A delay that fires on the hover variant names that variant's interaction: after the revert it
|
||||
/// doesn't count as A's delay at the same index, which still runs on its own deadline.
|
||||
#[test]
|
||||
fn a_delay_fired_on_a_hover_variant_does_not_block_the_restored_variants_delay() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Run", "name": "a_runs", "type": "number", "value": 0}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Run", "name": "hover_runs", "type": "number", "value": 0}));
|
||||
let var = |s: &Session, name: &str| s.doc().unwrap().variables.get(name).map(|v| v.id.clone()).unwrap();
|
||||
let (a_runs, hover_runs) = (var(&s, "a_runs"), var(&s, "hover_runs"));
|
||||
let inc = |v: &str| json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": v}}, {"value": {"type": "number", "value": 1}}]}});
|
||||
let variants: Vec<NodeId> = ["A", "Hover"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, state)| {
|
||||
let f = id(&ex(
|
||||
&mut s,
|
||||
"frame.create",
|
||||
json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}),
|
||||
));
|
||||
id(&ex(&mut s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let instant = json!({"type": "instant"});
|
||||
// A: index 0 a 1,000 ms delay counting its runs, index 1 the hover. Hover: index 0 a delay due at once.
|
||||
let a_delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "setVariable", "variable": a_runs, "value": null, "expr": inc(&a_runs)}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", a_delay);
|
||||
let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", hover);
|
||||
let h_delay = json!({"id": variants[1], "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": hover_runs, "value": null, "expr": inc(&hover_runs)}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", h_delay);
|
||||
let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap();
|
||||
let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen})));
|
||||
ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]}));
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": screen}));
|
||||
u.frame(Vec::new());
|
||||
let start = u.time;
|
||||
let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default();
|
||||
let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}"));
|
||||
let r: Vec<f32> = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect();
|
||||
let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0));
|
||||
let value = |u: &Harness, v: &str| {
|
||||
crate::tabs::shown_or_paused(&u.app).and_then(|p| p.design.as_ref().and_then(|d| d.variables.resolve(v, &Default::default())))
|
||||
};
|
||||
while u.time < start + 0.2 {
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
}
|
||||
while u.time < start + 0.4 {
|
||||
u.frame(vec![egui::Event::PointerMoved(on)]);
|
||||
}
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant");
|
||||
assert_eq!(value(&u, &hover_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's delay ran");
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again");
|
||||
while u.time < start + 1.3 {
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
}
|
||||
assert_eq!(value(&u, &a_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "A's own delay at index 0 ran on its deadline");
|
||||
}
|
||||
|
||||
/// A layer that only the hover variant has, with its own After delay that ran during the hover,
|
||||
/// leaves no fired key behind after the revert (its id may be issued again by the next hover).
|
||||
#[test]
|
||||
fn a_hover_variants_own_layer_leaves_no_fired_key_after_the_revert() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "Run", "name": "runs", "type": "number", "value": 0}));
|
||||
let runs = s.doc().unwrap().variables.get("runs").map(|v| v.id.clone()).unwrap();
|
||||
let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": runs}}, {"value": {"type": "number", "value": 1}}]}});
|
||||
let frames: Vec<NodeId> = ["A", "Hover"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, state)| {
|
||||
id(&ex(&mut s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")})))
|
||||
})
|
||||
.collect();
|
||||
// Only the hover state has this layer, with a delay due at once.
|
||||
let dot = id(&ex(&mut s, "shape.rectangle", json!({"x": 160, "y": 610, "width": 10, "height": 10, "parent": frames[1]})));
|
||||
let instant = json!({"type": "instant"});
|
||||
let dot_delay = json!({"id": dot, "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": runs, "value": null, "expr": inc}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", dot_delay);
|
||||
let variants: Vec<NodeId> = frames.iter().map(|f| id(&ex(&mut s, "component.create", json!({"ids": [f]})))).collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", hover);
|
||||
let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap();
|
||||
let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen})));
|
||||
ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]}));
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": screen}));
|
||||
u.frame(Vec::new());
|
||||
let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default();
|
||||
let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}"));
|
||||
let r: Vec<f32> = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect();
|
||||
let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0));
|
||||
for _ in 0..6 {
|
||||
u.frame(vec![egui::Event::PointerMoved(on)]);
|
||||
}
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant");
|
||||
let p = crate::tabs::shown_or_paused(&u.app).expect("presenting");
|
||||
let ran = p.design.as_ref().and_then(|d| d.variables.resolve(&runs, &Default::default()));
|
||||
assert_eq!(ran, Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's own layer ran its delay");
|
||||
u.frame(vec![egui::Event::PointerMoved(away)]);
|
||||
u.frame(Vec::new());
|
||||
assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again");
|
||||
let p = crate::tabs::shown_or_paused(&u.app).expect("presenting");
|
||||
let d = p.design.as_ref().expect("a document");
|
||||
let stale: Vec<_> = p.delays_fired.iter().filter(|(id, _)| !d.contains(*id)).collect();
|
||||
assert!(stale.is_empty(), "no fired key names a layer the restored document lacks: {stale:?}");
|
||||
}
|
||||
|
||||
/// An edit in the editor while presenting brings back the editor's variants, so the swap times of
|
||||
/// the variants changed at run time no longer delay them.
|
||||
#[test]
|
||||
fn an_edit_while_presenting_drops_the_swap_times() {
|
||||
let (mut u, inst, variants) = chain(500);
|
||||
let start = u.time;
|
||||
let mut guard = 0;
|
||||
while shown(&u, inst, &variants) != Some(1) {
|
||||
u.frame(Vec::new());
|
||||
guard += 1;
|
||||
assert!(guard < 120, "A never changed to B");
|
||||
}
|
||||
// An edit: the presenter shows the editor's document again, the instance on A.
|
||||
u.run("page.rename", json!({"name": "Renamed"}));
|
||||
u.frame(Vec::new());
|
||||
let edited = u.time;
|
||||
// A's 500 ms delay counts from the screen's arrival, long past: it fires at once, not 500 ms
|
||||
// after the run-time change to B.
|
||||
while u.time < edited + 0.2 {
|
||||
u.frame(Vec::new());
|
||||
}
|
||||
assert!(edited < start + 0.9, "the edit came before B's own delay was due");
|
||||
assert_eq!(shown(&u, inst, &variants), Some(1), "A changed to B again right after the edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_after_delay_still_fires_once() {
|
||||
let mut s = Session::new();
|
||||
let a = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": "A"})));
|
||||
let b = id(&ex(&mut s, "frame.create", json!({"x": 400, "y": 0, "width": 300, "height": 400, "name": "B"})));
|
||||
let it = json!({"id": a, "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "navigate", "dest": b}, "transition": {"type": "instant"}, "durationMs": 0});
|
||||
ex(&mut s, "proto.interaction.add", it);
|
||||
let mut u = Harness::new(s);
|
||||
u.run("proto.present", json!({"start": a}));
|
||||
u.frames(3, Vec::new);
|
||||
let name = |u: &Harness| u.app.inspect()["presenter"]["name"].as_str().unwrap_or_default().to_string();
|
||||
assert_eq!(name(&u), "A", "not before the delay");
|
||||
u.frames(30, Vec::new);
|
||||
assert_eq!(name(&u), "B", "once the delay is over");
|
||||
u.frames(60, Vec::new);
|
||||
assert_eq!(name(&u), "B", "and not again");
|
||||
}
|
||||
@@ -42,6 +42,8 @@ impl Presenter {
|
||||
self.closing.retain(|(_, o)| doc.contains(o.id));
|
||||
// These hold states of the document before the edit.
|
||||
self.temp = None;
|
||||
// The edit's variants replace the runtime ones: their swap times no longer apply.
|
||||
self.swapped.clear();
|
||||
self.anim = None;
|
||||
self.scroll_anim = None;
|
||||
self.stop_scrolling();
|
||||
@@ -150,6 +152,8 @@ impl Presenter {
|
||||
overlays: self.overlays.clone(),
|
||||
history: self.history.clone(),
|
||||
scroll: self.scroll.clone(),
|
||||
swapped: self.swapped.clone(),
|
||||
delays_fired: self.delays_fired.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -170,6 +174,7 @@ impl Presenter {
|
||||
}
|
||||
self.arrived = now;
|
||||
self.delays_fired.clear();
|
||||
self.swapped.clear();
|
||||
self.waiting.clear();
|
||||
self.hovered.clear();
|
||||
self.rev += 1;
|
||||
@@ -220,6 +225,16 @@ impl Presenter {
|
||||
|
||||
pub(super) fn revert(&mut self, now: f64) {
|
||||
let Some(t) = self.temp.take() else { return };
|
||||
// The delays fired during the temporary change: inside an instance it changed the variant
|
||||
// of, a key names the temporary variant's interaction, not the restored one's, so drop it;
|
||||
// keep the others, and put back the ones the change cleared.
|
||||
let changed: Vec<NodeId> = self.swapped.iter().filter(|(i, at)| t.snap.swapped.get(*i) != Some(*at)).map(|(i, _)| *i).collect();
|
||||
let restored = &t.snap.doc;
|
||||
let during: Vec<(NodeId, usize)> = self.delays_fired.difference(&t.snap.delays_fired).copied().collect();
|
||||
let mut fired = t.snap.delays_fired.clone();
|
||||
fired.extend(during.into_iter().filter(|(id, _)| !changed.iter().any(|i| i == id || restored.is_ancestor(*i, *id))));
|
||||
// A layer the temporary change added is gone again (and its id may be issued anew).
|
||||
fired.retain(|(id, _)| restored.contains(*id));
|
||||
self.begin(t.transition.reversed(), t.dur, t.easing, now);
|
||||
self.current = t.snap.current;
|
||||
self.design = Some(t.snap.doc);
|
||||
@@ -227,6 +242,8 @@ impl Presenter {
|
||||
self.overlays = t.snap.overlays;
|
||||
self.history = t.snap.history;
|
||||
self.scroll = t.snap.scroll;
|
||||
self.swapped = t.snap.swapped;
|
||||
self.delays_fired = fired;
|
||||
self.stop_scrolling();
|
||||
self.hovered.clear();
|
||||
self.rev += 1;
|
||||
@@ -245,7 +262,9 @@ pub(crate) fn next_delay(p: &Presenter, doc: &Document, root: NodeId, now: f64)
|
||||
if let Trigger::AfterDelay { ms } = it.trigger
|
||||
&& !p.delays_fired.contains(&(id, k))
|
||||
{
|
||||
let due = since + f64::from(ms) / 1000.0 - now;
|
||||
// Inside an instance that changed variant, the timer starts when it did.
|
||||
let from = p.swapped.iter().filter(|(inst, _)| doc.is_ancestor(**inst, id)).fold(since, |a, (_, t)| a.max(*t));
|
||||
let due = from + f64::from(ms) / 1000.0 - now;
|
||||
if next.is_none_or(|(_, d)| due < d) {
|
||||
next = Some(((id, k), due));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The vector edit panel's Corner radius for a point (#2334): a typed radius larger than half the
|
||||
//! point's segments is kept and shown as typed, and the point is drawn rounded across the whole of
|
||||
//! the segments whose other ends stay sharp, as Figma draws it.
|
||||
|
||||
use egui::Key;
|
||||
use figcraft_geom::Point;
|
||||
use figcraft_geom::kurbo::{ParamCurve, PathSeg};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::field_tests::{field, type_into};
|
||||
use crate::vector_point_xy_tests::setup;
|
||||
|
||||
#[test]
|
||||
fn a_typed_radius_is_kept_shown_and_drawn_across_the_sharp_neighbours_segments() {
|
||||
// The 100 × 60 rectangle in vector edit mode; point 2 is its bottom right corner.
|
||||
let (mut u, id) = setup();
|
||||
u.app.session.execute("vector.edit.select", &json!({"vertices": [2]})).unwrap();
|
||||
type_into(&mut u, "Corner radius", "100", Key::Enter);
|
||||
assert_eq!(field(&mut u, "Corner radius").1, "100", "the field shows the radius as typed");
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let net = figcraft_engine::vectoredit::network(doc, id).unwrap();
|
||||
assert_eq!(net.vertices.iter().map(|v| v.radius).collect::<Vec<_>>(), vec![0.0, 0.0, 100.0, 0.0], "only point 2 stores it, unclamped");
|
||||
assert_eq!(net.vertices[2].point(), Point::new(100.0, 60.0));
|
||||
// Both neighbours are sharp, so the arc reaches the whole 60 of the shorter side: from the top
|
||||
// right corner to 60 along the bottom, on a circle of radius 60 centred at (40, 0).
|
||||
let arcs: Vec<_> = net
|
||||
.fill_path()
|
||||
.segments()
|
||||
.filter_map(|s| match s {
|
||||
PathSeg::Cubic(c) => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(arcs.len(), 1, "{arcs:?}");
|
||||
let ends = [arcs[0].p0, arcs[0].p3];
|
||||
let close = |a: Point, b: Point| (a - b).hypot() < 1e-9;
|
||||
assert!(ends.iter().any(|e| close(*e, Point::new(100.0, 0.0))) && ends.iter().any(|e| close(*e, Point::new(40.0, 60.0))), "{ends:?}");
|
||||
let h = 60.0 / 2f64.sqrt();
|
||||
assert!(close(arcs[0].eval(0.5), Point::new(40.0 + h, h)), "{:?}", arcs[0].eval(0.5));
|
||||
}
|
||||
@@ -9,7 +9,9 @@ use serde_json::json;
|
||||
use crate::field_tests::{field, scrub, type_into, undo_steps};
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
fn setup() -> (Ui, NodeId) {
|
||||
/// A 100 × 60 rectangle at the origin, selected and in vector edit mode (points clockwise from
|
||||
/// the top left), and its id.
|
||||
pub(crate) fn setup() -> (Ui, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
|
||||
@@ -32,15 +32,11 @@ all end with the same geometry.
|
||||
| Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why |
|
||||
| Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 16 by default (FigJam's "Small", read twice from its size field, 2026-11-12) and fixed as it fills: the note grows taller and never shrinks its text (2026-11-09, #2157); a size menu in the contextual bar (Small 16, Medium 24, Large 40, Extra large 64, Huge 96; a number when the size matches none) sets every selected sticky, the note grows taller when Huge no longer fits and shrinks back to square at Large, and the sticky tool remembers the last size for new stickies, all measured in FigJam's web app, 2026-11-12; stickies saved with another size keep it, the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it |
|
||||
| Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; size presets done (the bar's menu, `board.setStyle {fontSize}`, `board.sticky {fontSize}`); no stacks |
|
||||
| Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was |
|
||||
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile (`board_connect_tests`, #1919) |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before |
|
||||
| Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) |
|
||||
| A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side |
|
||||
| Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. Dragging a run moves it, and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none |
|
||||
@@ -73,6 +69,7 @@ all end with the same geometry.
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. |
|
||||
| 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` |
|
||||
| 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). |
|
||||
| 2026-11-09 | patch | M12, #2157: a sticky's text is 18 and stays 18 (measured in FigJam's web app: ten lines, then a long paragraph, never changed it; the note kept its width and grew taller). The normalize pass no longer resets a sticky's text to a size by its length (24 down to 11 before), so stickies in saved files keep their size. Size presets (Small to Huge) are still missing. Tests: `a_new_sticky_starts_at_18`, `a_sticky_keeps_its_text_size_as_text_is_added`, `a_sticky_saved_with_another_text_size_keeps_it` |
|
||||
|
||||
+2
-1
@@ -118,7 +118,8 @@ page 1 "Screens": 380 nodes, 4 top-level
|
||||
after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer.
|
||||
The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |`
|
||||
and control characters), which become `_`, and leading or trailing spaces and dots, which are
|
||||
dropped. A name is cut at 100 characters. The app's export replaces the same characters (there a
|
||||
dropped. Reserved Windows device names such as `CON` get a leading `_`.
|
||||
A name is cut at 100 characters. The app's export replaces the same characters (there a
|
||||
`/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`…
|
||||
- `<out>` has an image extension: one file with the given `--node`, or the whole page composited.
|
||||
- `--node` takes a layer id (`12` or `0:12`) or a layer name.
|
||||
|
||||
@@ -13,7 +13,6 @@ accounts).
|
||||
| Feature | Status | Notes |
|
||||
|---|---|---|
|
||||
| 2026-11-11 | minor | M3, #2022: an instance lists only the properties its variant's layers use (its variant properties, slots, and the boolean, text and instance swap properties a layer of its current variant reads), as measured in Figma's web app: an instance of variant A lists `State` and `A label`, never `B label` or a property no layer reads. The set and its variants still list every definition, so unused ones can be deleted there. A long property name in the panel is cut to one line with an ellipsis, the full name on hover, instead of wrapping over the rows around it. Tests: `prop_order_tests::an_instance_lists_only_the_properties_its_variant_uses`, `component_props_reorder_tests::a_long_property_name_stays_on_one_line`, `prop_value_tests::a_set_keeps_each_named_text_definition_and_layers_read_their_own`. Grade unchanged. |
|
||||
| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main |
|
||||
| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=<layer name>` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) |
|
||||
| Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances |
|
||||
| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push |
|
||||
@@ -81,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
| 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged |
|
||||
|
||||
@@ -236,7 +236,9 @@ zoom preview or the refined image (`canvas.quality`: `preview` or `refined`) and
|
||||
asking for a render to its preview and its refined image being handed to egui as the canvas
|
||||
texture (`canvas.previewLatencyMs`, `canvas.refineLatencyMs`, on a monotonic clock, rendering
|
||||
included in the browser too; the GPU upload and presenting the frame come after; `null` until
|
||||
there was one). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`,
|
||||
there was one), and the share of the canvas only the page colour covered last frame, no render
|
||||
reaching it (`canvas.uncovered`, 0 to 1: past the canvas image the desktop shows a coarse image of the
|
||||
area around the view). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`,
|
||||
`null` while none is open). The window opens only for a file the user opened or imported in the app
|
||||
(File ▸ Open or Import, Open recent, a recent file on the home screen, a drop, a paste, the system's open event).
|
||||
Emulated user input counts as the user's action: `ui.input` and `ui.key` (for example a Cmd+V paste or a click
|
||||
|
||||
@@ -14,8 +14,7 @@ repository, third-party integrations. Remaining: 1–2 h.
|
||||
| 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name |
|
||||
| Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why |
|
||||
| Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) |
|
||||
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) |
|
||||
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) |
|
||||
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) |
|
||||
| Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours |
|
||||
| Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
|
||||
| Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) |
|
||||
@@ -31,6 +30,7 @@ repository, third-party integrations. Remaining: 1–2 h.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. |
|
||||
| 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged |
|
||||
| 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
|
||||
| 2026-10-30 | minor | Gap 16: `figcraft-cli connect publish <file.figcraft> [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file (as the incumbent's Code Connect CLI publishes a repository's mappings): it links each entry's component or set by name, warns about and skips links that don't fit, saves the file in place through the engine's save (or not, with `--dry-run`) and fails when nothing links. Dev Mode breadth (~98%) and ready (~78%) unchanged at this rounding; hours unchanged |
|
||||
|
||||
@@ -39,8 +39,7 @@ and prototype interactions are still unchecked there.
|
||||
| BMP | — | yes | | — |
|
||||
| MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 |
|
||||
| Images over 4096 px | downscaled to 4096 | kept | | — |
|
||||
| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` |
|
||||
| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` |
|
||||
| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` |
|
||||
|
||||
## Export
|
||||
|
||||
@@ -53,9 +52,8 @@ export limit, not a native document nesting limit.
|
||||
|
||||
| Format | Figma | FigCraft | Notes | Hours |
|
||||
|---|---|---|---|---|
|
||||
| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels | — |
|
||||
| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — |
|
||||
| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels; a color profile per setting (Same as file, the default, sRGB or Display P3: `colorProfile`), the pixels converted and the file tagged (`sRGB` chunk, or ICC and `cICP`) | — |
|
||||
| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — |
|
||||
| SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `<text>` with one `<tspan>` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — |
|
||||
| PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 |
|
||||
| WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — |
|
||||
@@ -198,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. |
|
||||
| 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software |
|
||||
| 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software |
|
||||
| 2026-11-12 | minor | M6, #2297: the `.fig` exporter writes an image paint's adjustments as `paintFilter` (seven fields: exposure, contrast, vibrance from saturation, temperature, tint, highlights, shadows; the tint's sign is flipped, as the importer reads it), and no longer warns about them; the importer already read them. Not checked in other software |
|
||||
|
||||
+19
-1
@@ -1,6 +1,6 @@
|
||||
# Where FigCraft falls short of Figma
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 24: mind maps from the toolbar and the keyboard (#2226); gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 24: mind maps from the toolbar and the keyboard (#2226); gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from
|
||||
doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The
|
||||
@@ -312,6 +312,22 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x
|
||||
display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are
|
||||
refined at once, as before.
|
||||
- **Landed (2026-11-17):** the desktop keeps a coarse image of the area around the view, three
|
||||
views wide and tall at a quarter of the pixels each way (`render_worker::Surround`, on a thread of
|
||||
its own after each refined render, built on the last one: a pan shifts it, an edit patches it).
|
||||
Where the canvas image doesn't reach, a pan past its edge before the strips are drawn or a zoom
|
||||
out, the canvas shows that, blurred, then sharp, instead of the bare page colour. On a page of
|
||||
3,600 cards with shadows panned at 60 pt a step (debug build), the canvas was 36% bare on
|
||||
average and at 77 of 80 steps; now none of it is. `ui.inspect` reports the bare share
|
||||
(`canvas.uncovered`). The browser keeps none (it renders on the page's thread).
|
||||
- **Landed (2026-11-17):** the strips a pan uncovers, and the areas an edit redraws, render in
|
||||
parallel bands as full renders do (`render_part`): rows of a tall strip, columns of a wide one,
|
||||
however few pixels they have. A strip costs the layers it crosses, not its pixels (a card's
|
||||
shadow is drawn whole for a sliver of it), and was drawn on one thread: on a page of 3,600 cards
|
||||
with a drop and an inner shadow each, a 60 px pan took 33 ms right and 47 ms down where the
|
||||
whole view took 80 ms; now 9 and 11 ms (`pan_bench_tests`, release, a 32-thread desktop; bands stop at 16). In the app
|
||||
(release) a pan step on that page went from 150–170 ms to 17–27 ms. The browser renders on one
|
||||
thread and is unchanged.
|
||||
- **Landed (2026-10-28):** the browser refines a zoom's preview only once no newer request has
|
||||
come for 120 ms (`SETTLE_MS`), or for as long as its last full render took when that is shorter:
|
||||
its full renders run on the UI thread, and one between every two wheel steps held the page up
|
||||
@@ -602,6 +618,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | Gap 24: mind maps in the UI (step 2): Shapes ▸ Mind map in the toolbar, Cmd/Ctrl+Enter and Shift+Cmd/Ctrl+Enter for a child and a sibling, Tab between siblings, the bar over a node and a branch (#2226); the "+" handles, drag to re-parent and `.jam` import are what is missing of them. |
|
||||
| 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` |
|
||||
| 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` |
|
||||
| 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` |
|
||||
| 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them |
|
||||
| 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list |
|
||||
|
||||
@@ -110,11 +110,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v
|
||||
| Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build) | no | draft | 1–2 (after native review) |
|
||||
| Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 (100%: 1,975 UI strings, 641 command labels, 31 menu wordings; draft, counted 2026-11-03) | yes | CJK text and IME in documents; UI text in an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC or Heiti TC (web: only with a built-in TC face); zh-TW, zh-HK, zh-MO and zh-Hant read it, an explicit Hans stays Simplified | no | draft | 1–2 (after native review) |
|
||||
| Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab`, or with `FIGCRAFT_WEB_FONTS` naming Noto Sans Arabic, embeds it (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) |
|
||||
| French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) |
|
||||
| Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) |
|
||||
| Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) |
|
||||
@@ -149,6 +146,7 @@ Hindi and Arabic.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Hindi, Arabic. |
|
||||
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source and marked as a draft awaiting native review. `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it; an explicit Hans still reads Simplified Chinese. The desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled. No plural forms. Localization grade and estimates unchanged |
|
||||
| 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. |
|
||||
| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). |
|
||||
|
||||
+20
-2
@@ -94,8 +94,14 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`:
|
||||
(writing through it would create its target, wherever that is). A path outside the roots gets
|
||||
the same refusal whatever exists there, so a refusal doesn't tell what is outside. Folders are
|
||||
compared by whole names: `/work2/x` is not inside `/work`. On Windows the case comes from the disk (`C:\WORK\x` is
|
||||
inside `C:\work`), `\\?\` and UNC (`\\server\share\…`) paths are resolved like drive-letter ones,
|
||||
and new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused.
|
||||
inside `C:\work`), `\\?\C:\…` paths are resolved like drive-letter ones, and
|
||||
new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused.
|
||||
A path on another computer (`\\server\share\…`, `\\?\UNC\…`, WebDAV's `\\host@SSL\share\…`) or a device
|
||||
path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`) is refused by its spelling before anything looks it up, since looking
|
||||
it up would contact that host, unless a root is on the same share; a link whose target is one of those is
|
||||
refused too. A local volume's `\\?\Volume{…}\` path is let through. A link whose text is a native NT name
|
||||
(`\Device\…`, `\??\…`, `\GLOBAL??\…`) is refused as a device path, and so is a name that ends in a period or a space, in a
|
||||
path or as a link's target, since Windows trims it where it looks a name up.
|
||||
- **The network:** a confined call reaches no FigCraft or plugin server, so it can't send a
|
||||
document anywhere through one. Hosting, joining, publishing and sharing a file (`collab.host`,
|
||||
`collab.join`, `collab.publish`, `collab.share` …), team libraries on a server (`library.check`
|
||||
@@ -182,6 +188,18 @@ Or in a project's `.mcp.json`:
|
||||
leaves its contents where they are, and so does resizing a frame with `cmd` held (constraints
|
||||
ignored); a layer a mask hides can't be clicked there, and a mask group's box and exports are
|
||||
the mask's (plus any layers under the mask).
|
||||
- Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component and its copies
|
||||
are instances: make it once with `component.create` (or `create_node` type `component`) and place
|
||||
each other copy with `instance.create {component, parent?, x?, y?}` rather than duplicating the
|
||||
layers, so every copy follows the main. States and sizes are variants of one set: name the mains
|
||||
`Property=value` (`State=Default`, `State=Hover`) and run `component.combineVariants` on them;
|
||||
`component.addVariant {id}` adds one more. What changes per copy is a component property:
|
||||
`component.addProperty {id, name, type: text|boolean|instanceSwap, layer}` on the component, or
|
||||
on the set once its variants are combined, then `component.bindProperty {layer, property}` for
|
||||
each other variant's layer (a property added to one variant before combining stays that
|
||||
variant's, so an instance switched to another variant loses it); `instance.setProperties {ids,
|
||||
properties}` sets it on each copy. The server's `initialize` instructions say this too, since
|
||||
agents otherwise tend to copy layers.
|
||||
- Children of an auto-layout frame are positioned by the layout: set `layout`, `gap`, `padding`,
|
||||
`mainAlign`, `crossAlign`, `sizingH`/`sizingV` instead of x/y. In one call, `layout` applies
|
||||
before the keys that tune it, so `{"layout": {"mode": "vertical"}, "gap": 8}` keeps the gap;
|
||||
|
||||
@@ -39,7 +39,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr
|
||||
| Key/gamepad on a controller: the trigger takes a controller button in place of a key, pressed anywhere on the screen | **added** | `Gamepad A` … `Gamepad Home` (the standard layout's 17 buttons, face buttons by position) as the trigger's key, picked from the Controller menu beside the key field; the player polls controllers only while the prototype has such a trigger and the window has the focus, and plays each press once (held buttons don't repeat); Windows reads Xbox-compatible controllers, the browser its Gamepad API's standard-mapped ones; `controller_buttons_fire_key_gamepad_triggers`, `controller_buttons_play_key_gamepad_triggers` |
|
||||
| A controller button is not the keyboard key of the same name; the d-pad is not the arrow keys; a keyboard modifier held makes a button press another input | silent | pinned as stated |
|
||||
| REST files: controller triggers (`device` other than `KEYBOARD`) | **added** | they were skipped; their code reads as the standard layout's button index (silent: the schema doesn't say what the codes count); two buttons at once or an unknown code is skipped with a warning; `controller_triggers_import_as_their_button` |
|
||||
| After delay: timed from when the screen shows | pass | `triggers_fire_on_their_gesture` |
|
||||
| After delay: timed from when the screen shows; a chain of variant changes on After delay plays to the end, each step's delay counted from when its variant appears (#2352) | pass | `triggers_fire_on_their_gesture`, `a_chain_of_variant_after_delays_plays_to_the_end` |
|
||||
| After delay on an overlay: timed from when the overlay opens, again each time it opens | **fixed** | timed from when the screen under it arrived (a toast opened late closed at once) and fired only the first time; `an_overlays_after_delay_counts_from_when_it_opens` |
|
||||
| Nested layers with the same trigger: the top-most layer's interaction wins; a layer without that trigger lets it through to the one under it | pass | `nested_hotspots_and_click_through`, `hotspots_priority_and_click_through` |
|
||||
| A layer without interactions over a hotspot | silent | it doesn't block it: clicks reach the hotspot under it |
|
||||
@@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged |
|
||||
| 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to |
|
||||
| 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` |
|
||||
| 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. |
|
||||
|
||||
+11
-17
@@ -1,6 +1,6 @@
|
||||
# UI and interaction parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the Line truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_andLine truncated
|
||||
|
||||
Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys,
|
||||
drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status:
|
||||
@@ -16,9 +16,7 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Item | Status | Notes |
|
||||
|---|---|---|
|
||||
| Light and dark themes | done | colours from `theme::Tokens`; component, variant and instance rows in the Layers panel take the theme's component tint, at AA on the panel and on their selected row (hidden ones in the faded text colour, at least 3:1 on the panel, a hovered row and their selected row), and the rows inside a selected component a tone of its row (`layers_component_rows_tests`, #1903); a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) |
|
||||
| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) |
|
||||
| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) |
|
||||
| Light and dark themes | done | colours from `theme::Tokens`; a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) |
|
||||
| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) |
|
||||
| Minimize UI (Shift+Cmd/Ctrl+\\, the Minimize button by the file name) and Show/Hide UI (Cmd/Ctrl+\\) | done | Minimize collapses the navigation bar and both sidebars and keeps the toolbar and the panel widths; "If you select an object while the panels are minimized, the left sidebar remains minimized while the right sidebar expands [...] Once all objects are deselected, the right panel minimizes again" (Explore the navigation bar and left sidebar); a small Expand button at the top left of the canvas puts them back (FigCraft's own, the article names no control for it). Hide UI takes the toolbar too (`panel_width_tests`, `shortcuts_tests`; #1835) |
|
||||
| Resizable panels | done | each panel's edge drags its width (left 240–450, right 240–500, 240 by default, as measured in Figma's web app on 2026-11-08; a double-click on the edge or View ▸ Panels ▸ Reset panel widths puts the default back); the widths are each window's own, the main window's are kept in the preferences when a drag ends and come back at the next start (a width saved under other limits is clamped to the current ones on load, and one that isn't a number, NaN or infinite, falls back to 240), a new window opens with those of the window it comes from; Minimize UI hides the panels and brings them back as they were; the view keeps its centre and zoom while a panel is resized; in a window too small for them the panels give way so the canvas keeps 160 px (the left one first), down to the smallest window (800×500) (`panel_width_tests`). The double-click reset to 240 matches Figma's; no snap points |
|
||||
| Design panel's sections on one grid | done | every section lays its rows out on the same grid: the panel is 240 pt, its content 16 pt in from the left and 8 pt from the right, two 88 pt columns at that width with 8 pt gutters and a 24 pt column for the buttons at a row's end (the columns are flex, so they share the panel when it is dragged wider); rows 24 pt in a 32 pt track, 10 pt captions over them; section titles 11 pt semibold and a row's values 11 pt, their buttons 24 pt and 4 pt apart. The panel's edge is drawn inside it: a frame stroke counts as margin and took 1 pt off each side, putting every right margin 1–2 pt out (checked in the app on Windows over the control channel) |
|
||||
@@ -51,7 +49,7 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) |
|
||||
| Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned; Tab on the last row wraps to the first row's rename, measured in Figma's web app on 2026-11-12 (`tab_on_the_last_row_commits_and_wraps_to_the_first`); Shift+Tab on the first row ends the rename (not measured); Tab and Shift+Tab move only the rename, the selection stays on the layer first renamed, measured in Figma's web app on 2026-11-12 (`tab_while_renaming_leaves_the_selection_on_the_first_layer`); a double-click on a row's icon zooms to the layer (selecting it first) and renames nothing, while a double-click on the name or elsewhere on the row still renames, measured in Figma's web app on 2026-11-12 (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`) |
|
||||
| Find layers (filter by name) | done | not covered by the documentation |
|
||||
| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`) |
|
||||
| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`); going back to a page shows it where it was left in the session, only a page not shown yet is fitted to its content (`page.select`, Previous/Next page; `page_view_tests`) |
|
||||
| Assets panel: folders from page, frames and slash names (fold away), search, thumbnails, drag onto the canvas or into frames and auto layout, Alt-drop swap, enabled libraries | done | Shift+I (Quick insert), Alt+2 and View ▸ Panels ▸ Assets open it; the toolbar's Resources button was removed (the left rail's Assets tab and those shortcuts are the ways in) |
|
||||
| Hide when publishing from the Assets panel's context menu | done | a right-click on one of this file's components (also Libraries ▸ Hide when publishing for the selection, `component.hideWhenPublishing {ids?, on?}`): the model's sign of it is the name, so hiding puts a `.` before the name and showing takes the leading `.` and `_` away (one undo step, saved and synced like a rename; a variant or a layer inside hides its whole component or set); a hidden component shows a crossed eye on its tile and a dimmer name, the menu item its check mark; the next publish leaves it out and brings it back when shown again (`hide_publishing_tests`). Library components (read-only here) have no such menu |
|
||||
|
||||
@@ -65,8 +63,7 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) |
|
||||
| Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming |
|
||||
| Resize handles: Shift keeps proportions, Alt from centre, constraints-aware | done | Alt shrinks too; past an edge flips (several layers mirror); groups and mixed rotations scale each layer along its own axes, keeping rotation and flip (no skew: children turned off a right angle are approximate); Cmd/Ctrl ignores a frame's constraints (`transform_behaviour_tests`); Shift keeps the ratio (a corner by the axis dragged most, an edge scaling the other axis about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, each read afresh on every move (`handle_drags_resize_by_the_documented_rules`; measured in Figma's web app, 2026-11-08; Ctrl/Cmd while dragging not measurable) |
|
||||
| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` |
|
||||
| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0 |
|
||||
| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` |
|
||||
| Flip, rotate 90° | done | |
|
||||
| Rotation origin (Alt+R) | done | a handle at the selection's centre to drag (snaps to the box's corners, edge middles and centre), double-click puts it back, Escape or Alt+R hides it; the corner handles, the rotation field, Rotate 90°/180° and `transform.rotate` turn about it; it follows the layers and lasts as long as the selection, not saved (the documentation doesn't say; pinned) |
|
||||
| Align and Distribute (Design panel and shortcuts) | done | single and multi-layer Align and Distribute were measured in Figma's web app on 2026-11-12 and match: one layer aligns to its frame, several to their combined bounds, Distribute spaces three or more. Align is disabled for a child in an auto layout frame's flow (Alt+A and Alt+S do nothing, the frame is untouched), as measured; the panel's tip says the frame places the layer, and an absolutely positioned child still aligns to its frame (not measured, so today's behaviour is kept). Tidy up was measured to differ (Figma keeps the order and sizes and evens one gap per axis): not yet. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` |
|
||||
@@ -85,10 +82,8 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session |
|
||||
| Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) |
|
||||
| Tidy up | partial | measured in Figma's web app on 2026-11-12 (a row, a column, a 2 x 3 grid of unequal sizes and its transpose, and many runs on the gap, the unavailable cases among them): the order and the sizes are kept; in a row or a column the first layer also stays and the other axis is untouched (a grid can move a layer on both axes, as below). A row (one group of layers whose Y ranges overlap, side by side) evens its horizontal gaps and a column its vertical gaps to one gap: the most common existing gap (the smaller of two equally common ones), else the mean rounded to a whole number, half up (30, 40, 30 gives 30; 80, 20, 45 gives 48; 10, 10, 50, 90 gives 10; 10, 25 gives 18; 10, 25, 30 gives 22). Layers of a row may overlap along X, and overlapping layers in a chain count as a row (the first and third needn't touch): the negative gap counts in the mean (50 px squares at X 0, 60, 105, 170, gaps 10, -5, 15, give X 0, 57, 114, 171; squares at X 0, 40, 80, 150 give 0, 40, 80, 120). Measured in Figma's web app on 2026-11-13: a negative gap is raised so no layer reaches the one two places before it, floor(-w / 2) + 1 for the narrowest interior layer's width w, so 10, 20 and 30 wide interior layers among 100s give -4, -9 and -14 (X 0, 96, 102, 198, 294, 390 for widths 100, 10, 100 x4), while six layers 100 wide keep the most common gap, -40; only those widths were measured, and an explicit `spacing` is not raised. A grid (two or more rows and columns, one layer in every cell) is packed along the axis with more groups: a column is as wide as its widest layer around the middle of where its layers were, the first column stays, each layer is centred in its column to a whole pixel with Snap to pixel grid on, and every column is stacked from the selection's top; a grid with more rows than columns is the mirror image (centred rows, laid out left to right). The vertical gap reads 51 or 52 in Figma's own runs (mean 51.67), so FigCraft's positions along a stack can differ by a pixel there. Unavailable, as measured, for fewer than three layers, for layers that all overlap each other (one row and one column), for a diagonal and for an irregular layout: a greyed-out row with a tip in the Design panel's menu, the command moving nothing and adding no undo step. Not measured, FigCraft's choices: a 2 x 2 grid packed as columns; layers in an auto layout flow being unavailable (the frame places them; the measurement could not tell this from an irregular layout); the 2,000 layer cap; rotated layers counting by their box; gaps a pixel apart being different gaps; an explicit `spacing` setting the gap and taking two layers; no rounding with Snap to pixel grid off. Tests: tidy_tests |
|
||||
| Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also offers enabled libraries' published color styles and Create style (`selection.createColorStyle`); no library variables and no new variable from a row (#403) |
|
||||
| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) |
|
||||
| Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance; a layer without children shows it only with two paint groups, such as a red fill and a blue stroke; one paint group, however many layers share it, hides it), counting the selected layers' own fills and strokes and their descendants' (measured in Figma's web app, 2026-11-09, #2188, on frames, groups and rectangles only; the rule for components and instances is not measured), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also lists each enabled library's published color styles under the library's name (a library that can't be read offers none), and a linked row's menu switches it to another style; a library style is copied in, linked and read-only, in the same undo step (`selection.applyColorStyle` with `library`). Create style on an ordinary row asks for a name (the next free "Color n" first) and makes a style of the row's whole paint, gradients, opacity, blend mode and variables bound to gradient stops included, linked to every fill and stroke the row stands for in one undo step; a name in use keeps the window open (`selection.createColorStyle`). Text ranges with fills of their own take the style's value, without a link. No library variables from there, and no new variable from a row (#403) |
|
||||
| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes |
|
||||
| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) |
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -99,13 +94,10 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) |
|
||||
| Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; a Count handle sits on a polygon's first vertex or a star's first outer point clockwise from the top, and the count follows the pointer's angle about the centre, `round(360 / angle)` clockwise from the top point, clamped to 3 to 60, in one undo step (measured in Figma's web app, 2026-11-12; a polygon's maximum wasn't read and is clamped at 60 like the star's, the help center's range); corner smoothing rounds rectangles and frames only |
|
||||
| Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) |
|
||||
| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers |
|
||||
| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn, an arc reaching along the whole of a segment whose other end is sharp and half of one whose other end is rounded too, so one rounded corner of a 100 × 100 square with radius 100 runs from one neighbour to the other, while the radius field keeps what was typed (#2334, `vector_radius_tests`, `vector_point_radius_tests`); Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers |
|
||||
| Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | |
|
||||
| Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003) |
|
||||
| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check |
|
||||
| Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. Not yet included: per-paragraph settings, text-style support and the `.fig` import/export mapping (#1827). Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` |
|
||||
| Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003); a boolean group takes a corner radius from the Design panel and from `node.set cornerRadius`: every sharp corner of its result rounds, convex and concave, layers inside keep their own radius and do not stack with it, a radius larger than the edges allow shrinks to fit while the field keeps the value typed, Flatten bakes the arcs and a mixed selection reads Mixed; measured in Figma's web app on 2026-11-10 (#2222; `crates/pathops/src/round_tests.rs`, `crates/render/src/boolean_radius_tests.rs`, `crates/engine/src/boolean_radius_tests.rs`, the boolean group test in `crates/ui-egui/src/field_tests.rs`). Pinned and not yet compared with Figma: corner smoothing on a boolean group draws the polygon profile between straight edges, a corner beside a curve stays within the curve piece next to it, and there is no radius handle on the canvas |
|
||||
| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; no spell check |
|
||||
| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check |
|
||||
| Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. At three levels (the text layer, a paragraph and a text style, per Explore text properties): the paragraph level is the caret's or the selection's paragraphs while editing (`text.wrapStyle`; the control follows them), or `start`/`end` on `node.set wrapStyle` (a paragraph's own style beats the layer's; setting the layer sets every paragraph again; Enter carries it to the new paragraph; inspect reports `lineWrapStyles` when paragraphs differ and CSS `text-wrap` only when they agree); the text-style level is a style's `wrapStyle` (shown read-only in the style editor, applied with the style, moved by `style.update`, unlinking when edited). The `.fig` import/export mapping stays open (#1827): a `.fig` export leaves the wrap styles out and a `.fig` import reads every text as Auto, so the wrap styles are lost through a `.fig` round trip. Test: `text_behaviour_tests::wrap_style_per_paragraph_overrides_the_layers`, `styles_behaviour_tests::text_styles_carry_the_wrap_style`, `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` |
|
||||
| Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Developer Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way (with `text-align: left` beside `rtl`, as Left is absolute on the canvas); `.fig` import and export carry each line's `sourceDirectionality`, read up to the paragraph count. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` |
|
||||
| Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them` |
|
||||
@@ -120,7 +112,7 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
|
||||
| Item | Status | Notes |
|
||||
|---|---|---|
|
||||
| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testsPreferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testszoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) |
|
||||
| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) |
|
||||
| Rulers and guides (drag out, move, remove; rotated frames; frame guides) | done | guides belong to the page or a top-level frame (a frame moved into another keeps its guides but they stop applying); a click selects one for Delete, the arrows or the context menu's Remove guide; Alt-drag drops a copy; Alt while dragging measures to the layers in the frame it crosses; ruler numbering checked by eye only |
|
||||
| Frame labels (rotated, right-to-left), size badge | done | |
|
||||
| Outline mode | done | Outlines, outlines for the selection, mask outlines, frame outlines; shapes are clicked on their outlines, reaching layers behind; View ▸ Outlines ▸ Include hidden layers (`view.outlinesHiddenLayers`) outlines hidden layers too and Include object bounds (`view.outlinesObjectBounds`) draws the box of every layer whose outline isn't its box (groups, text, ellipses, vectors); what either draws can be clicked there (a hidden layer on its outline, a group on its box) and nothing else can; both are view settings like the other outline flags (per file, off in a new one, checked in the menu); the lines are light on a dark page (`outline_options_tests`). The main menu now shows a check mark beside every View toggle that is on |
|
||||
@@ -149,7 +141,6 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look
|
||||
| | Count | Notes |
|
||||
|---|---|---|
|
||||
| Documented shortcuts (rows) | 137 | each with macOS and Windows/Linux keys |
|
||||
| Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys |
|
||||
| Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 16 held keys, gestures and presentation keys, 6 vector edit tool keys |
|
||||
| Bound on other keys (documented conflict) | 1 | Run last plugin: the documentation also gives Ctrl+Alt+P to pixel preview on Windows; the plugin takes Ctrl+Alt+Shift+P there |
|
||||
| Missing | 0 | moving the rotation origin (Alt+R, `transform.rotationOrigin`) and placing an object with Enter after choosing its tool (`tool.place`) were the last two |
|
||||
@@ -216,11 +207,14 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) |
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. |
|
||||
| 2026-11-12 | patch | M8: a double-click on a layer's icon in the Layers panel selects the layer and zooms the canvas to it (`view.zoomSelection`) and starts no rename, as measured in Figma's web app on 2026-11-12; a double-click on the name or elsewhere on the row still renames; the icon's hit area is the rect the row paints the icon in (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`), Rename row |
|
||||
| 2026-11-12 | minor | M8: Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12. A row or column evens one gap (the most common one, the smaller of a tie, else the mean rounded half up) and keeps the other axis, layers of a row may overlap along X (also in a chain, and a negative gap is raised so no layer reaches the one two before it, measured in Figma's web app on 2026-11-13), and a grid is packed along the axis with more groups; fewer than three layers, layers that all overlap, a diagonal and an irregular layout grey the row out and move nothing. Measured: those rules and the unavailable cases; FigCraft's choices: a 2 x 2 grid as columns, auto layout flow children, the 2,000 layer cap, rotated layers by their box, `spacing` with two layers, and no rounding with pixel snapping off. Tests: tidy_tests (a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps, gaps_that_all_differ_take_their_mean_taken_down, a_mean_is_rounded_half_up, two_equally_common_gaps_give_the_smaller, an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts, a_grid_is_tidied_by_columns, a_transposed_grid_is_tidied_by_rows, layers_on_a_diagonal_are_unavailable, an_irregular_selection_is_unavailable and the rest). |
|
||||
| 2026-11-13 | patch | M8, #2307: with Crop chosen in an image fill's colour picker, a press and drag on the image moved the whole layer: the press closed the picker, which committed the crop as a plain move. The picker now treats a crop drag as its own control (as it does the open gradient's handles, #1852), so the drag moves the picture inside the layer. A drag whose gesture something else committed under the held button no longer shows the engine's internal "no gesture in progress" as a message (`EngineError::NoGesture`, dropped by the canvas). Tests: `crop_image_tests::crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_layer`, `a_drag_whose_gesture_was_committed_under_the_button_shows_no_message`. |
|
||||
| 2026-11-12 | minor | M8: Align is unavailable for the one selected layer of an auto layout frame that takes part in its flow, as in Figma (measured in Figma's web app on 2026-11-12: the Design panel's Align buttons are greyed out, Alt+A and Alt+S do nothing and the frame's alignment doesn't change). `align_target` returns none for it, so `can_align` is false and the `align.*` commands leave the layout alone; the disabled tip reads "A layer in an auto layout frame is placed by its frame" (`align_blocked_by_auto_layout`). An absolutely positioned child still aligns to its frame and multi-layer selections are unchanged (neither measured). Single and multi-layer Align and Distribute otherwise matched Figma; Tidy up differs (Figma keeps the order and sizes and evens one gap per axis) and is not yet changed. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` |
|
||||
| 2026-11-12 | patch | M5, #1560: the context menu's Select layer lists locked layers with a padlock in the leading column (the Layers panel's padlock icon; a row both selected and locked shows the check) and picking one selects it, as Lock and unlock layers' note says and as measured in Figma's web app, 2026-11-10; the submenu shows only with more than one layer under the pointer (measured on a single locked layer only: the least certain rule). Left clicks, hover and marquee still never reach a locked layer. `select.layersAt` lists locked layers too and its rows gain `locked`. Tests: `layers_at_a_point_list_locked_layers_with_a_flag_and_select_set_takes_them`, `select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`. Counts unchanged |
|
||||
| 2026-11-13 | patch | M4, #2334: a vector point's corner radius was cut to half of its shorter segment, so radius 100 on one corner of a 100 × 100 square drew a radius-50 arc. Figma (the issue's screenshot) draws it from one neighbour to the other. Now each arc may reach along the whole of a segment whose other end stays sharp, and along half of one whose other end is rounded too (as before; Figma's plugin docs clamp each end of such an edge to half its length); the shorter room of the two segments wins, and a smoothed corner uses the same room before losing smoothing. The stored radius and the Point section's field were already as typed. Not measured: how Figma splits a segment between two rounded ends with different radii. Tests: `vector_radius_tests` (doc), `vector_point_radius_tests` (UI) |
|
||||
| 2026-11-09 | patch | Zoom to selection: the selection is fitted with a 40 pt margin into the canvas above the floating bottom toolbar (`ViewState::bottom_inset`, set by the UI each frame, never saved; `view.set` takes `bottomInset`) and centred in that area, as measured in Figma's web app on 2026-11-09. Zoom to fit is unchanged (margin not measured yet). Numbers unchanged. |
|
||||
| 2026-11-13 | patch | M1: Shift+Cmd/Ctrl+V (Paste over selection) puts the pasted layers just above the selected layer, in its parent and in the copied order, at its position; they went to the top of the parent's layers, so in an auto layout frame they ended the flow instead of following the selected layer. |
|
||||
| 2026-11-12 | patch | Drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis with no 45° snap, Alt copies, Shift keeps a resize's ratio (an edge scales about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, and a modifier changed mid-drag is read fresh on each move; FigCraft matches in all six, Ctrl/Cmd while dragging could not be measured; no code change | this page |
|
||||
|
||||
+68
-3
@@ -266,6 +266,27 @@ fn parity() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Cargo versions require a numeric core and nonempty, ASCII prerelease/build identifiers.
|
||||
fn valid_version(v: &str) -> bool {
|
||||
let (without_build, build) = v.split_once('+').map_or((v, None), |(version, build)| (version, Some(build)));
|
||||
let (core, pre) = without_build.split_once('-').map_or((without_build, None), |(core, pre)| (core, Some(pre)));
|
||||
let mut numbers = core.split('.');
|
||||
if !(0..3).all(|_| {
|
||||
numbers.next().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()) && (n.len() == 1 || !n.starts_with('0')) && n.parse::<u64>().is_ok())
|
||||
}) || numbers.next().is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let identifiers = |s: &str, allow_numeric_leading_zeroes: bool| {
|
||||
s.split('.').all(|id| {
|
||||
!id.is_empty()
|
||||
&& id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
&& (allow_numeric_leading_zeroes || id.len() == 1 || !id.starts_with('0') || !id.bytes().all(|b| b.is_ascii_digit()))
|
||||
})
|
||||
};
|
||||
pre.is_none_or(|p| identifiers(p, false)) && build.is_none_or(|b| identifiers(b, true))
|
||||
}
|
||||
|
||||
fn version(sub: Option<&str>, value: Option<&str>) -> bool {
|
||||
let path = root().join("Cargo.toml");
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { return false };
|
||||
@@ -277,9 +298,7 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool {
|
||||
.to_string();
|
||||
match (sub, value) {
|
||||
(Some("set"), Some(v)) => {
|
||||
let valid =
|
||||
v.split(['-', '+']).next().is_some_and(|core| core.split('.').count() == 3 && core.split('.').all(|p| p.parse::<u64>().is_ok()));
|
||||
if !valid {
|
||||
if !valid_version(v) {
|
||||
eprintln!("version must look like 1.2.3 or 1.2.3-rc.1");
|
||||
return false;
|
||||
}
|
||||
@@ -296,3 +315,49 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod version_tests {
|
||||
use super::valid_version;
|
||||
|
||||
#[test]
|
||||
fn accepts_cargo_versions_including_prerelease_and_build_metadata() {
|
||||
for v in [
|
||||
"0.0.0",
|
||||
"1.2.3",
|
||||
"18446744073709551615.0.0",
|
||||
"1.2.3-0",
|
||||
"1.2.3-01a",
|
||||
"1.2.3-alpha-beta.1",
|
||||
"1.2.3-18446744073709551616",
|
||||
"1.2.3+001",
|
||||
"1.2.3-rc.1+build.7",
|
||||
] {
|
||||
assert!(valid_version(v), "{v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_versions_that_would_leave_the_manifest_invalid() {
|
||||
for v in [
|
||||
"",
|
||||
"1.2",
|
||||
"1.2.3.4",
|
||||
"01.2.3",
|
||||
"1.02.3",
|
||||
"1.2.03",
|
||||
"18446744073709551616.0.0",
|
||||
"1.2.3-",
|
||||
"1.2.3-01",
|
||||
"1.2.3-rc.01",
|
||||
"1.2.3-a..b",
|
||||
"1.2.3-a_b",
|
||||
"1.2.3+",
|
||||
"1.2.3+meta+again",
|
||||
"1.2.3-alpha\"",
|
||||
"1.2.3-alpha\n",
|
||||
] {
|
||||
assert!(!valid_version(v), "{v:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user