mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-15 23:02:36 +00:00
Release: FigCraft v0.19.0 (main bad07e4433)
This commit is contained in:
commit
80c8d38712
325 files changed
+19643
-1087
No files matched your search
@@ -16,6 +16,11 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
# Pin the coverage setup that provisions test data and fetches locked dependencies before offline metadata tests.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@5008f8cd1b011b35eed223a7d058d7a8e9075ef6
|
||||
with:
|
||||
# The shared coverage archive's shards omit the CLI executable used by integration tests.
|
||||
# Run this repository's suite in one instrumented job and provide its pinned test data.
|
||||
shards: 1
|
||||
fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
secrets: inherit
|
||||
Generated
+24
-23
@@ -1134,7 +1134,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1785,7 +1785,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "figcraft"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"craft-menu",
|
||||
@@ -1812,12 +1812,13 @@ dependencies = [
|
||||
"windows",
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-cli"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
@@ -1835,7 +1836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-collab"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -1853,7 +1854,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-collab-net"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"figcraft-collab",
|
||||
@@ -1876,7 +1877,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-color"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
@@ -1885,7 +1886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-doc"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-color",
|
||||
"figcraft-geom",
|
||||
@@ -1898,7 +1899,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-engine"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-docpath",
|
||||
@@ -1932,7 +1933,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-format"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-doc",
|
||||
"figcraft-layout",
|
||||
@@ -1949,7 +1950,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-geom"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
@@ -1957,7 +1958,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-layout"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-doc",
|
||||
"figcraft-geom",
|
||||
@@ -1965,7 +1966,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-mcp"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"figcraft-collab-net",
|
||||
@@ -1981,7 +1982,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-pathops"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-doc",
|
||||
"figcraft-geom",
|
||||
@@ -1990,7 +1991,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-pdf"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-color",
|
||||
"figcraft-doc",
|
||||
@@ -2007,7 +2008,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-plugin"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-color",
|
||||
"serde",
|
||||
@@ -2020,7 +2021,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-render"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"figcraft-color",
|
||||
@@ -2039,7 +2040,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-server"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"crc32fast",
|
||||
@@ -2064,7 +2065,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-svg"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"figcraft-color",
|
||||
@@ -2080,7 +2081,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-text"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"core-text",
|
||||
"craft-font-catalog",
|
||||
@@ -2098,7 +2099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-ui-egui"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2126,7 +2127,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-vectordrawable"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-color",
|
||||
"figcraft-doc",
|
||||
@@ -2140,7 +2141,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-web"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-web-api",
|
||||
@@ -6763,7 +6764,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"figcraft-engine",
|
||||
"serde_json",
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@ exclude = ["plugins"]
|
||||
# default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -43,7 +43,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
|
||||
# pull a second egui family version).
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto
|
||||
# indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library Line truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server cLine truncated
|
||||
|
||||
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
|
||||
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
|
||||
@@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | 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 |
|
||||
| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged |
|
||||
|
||||
@@ -464,7 +464,7 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliRe
|
||||
refuse_dropping_images_from_script(input.map(|input| (input, input_images_left_out)), ds, out)?;
|
||||
if ext(out) == "figcraft" {
|
||||
// Through the engine, so the version history is kept.
|
||||
write(out, &figcraft_engine::cmd::file::file_bytes(ds).map_err(|e| CliError::Failed(e.to_string()))?)?;
|
||||
write(out, &figcraft_engine::cmd::file::file_bytes_at(ds, out).map_err(|e| CliError::Failed(e.to_string()))?)?;
|
||||
} else {
|
||||
write_doc(&ds.doc, ds.page, out)?;
|
||||
}
|
||||
@@ -670,7 +670,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap();
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::SUCCESS);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -700,7 +700,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap();
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::SUCCESS);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -737,7 +737,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
// The failure is the script's, not the call's: the CLI reports it and exits non-zero.
|
||||
run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap();
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::from(1));
|
||||
assert!(!out.exists(), "a script that failed writes nothing");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -508,7 +508,13 @@ fn measure_components(table: &mut Table, col: usize, instances: usize) -> CliRes
|
||||
let lib = figcraft_engine::library::Cache::default().load(&path).map_err(failed)?;
|
||||
let mut doc = Document::new("Consumer");
|
||||
let m = &lib.manifest;
|
||||
doc.libraries_mut().enabled.push(figcraft_doc::LibraryLink { id: m.id.clone(), name: m.name.clone(), path: path.clone(), version: m.version });
|
||||
doc.libraries_mut().enabled.push(figcraft_doc::LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.clone(),
|
||||
version: m.version,
|
||||
..Default::default()
|
||||
});
|
||||
let map = figcraft_engine::library::import(&mut doc, &lib, &lib_ds.assets(), false).map_err(failed)?;
|
||||
let mut local = lib_ds.remap(&map);
|
||||
local.theme = doc.libraries.collections.iter().find(|r| r.key == lib_ds.theme).map(|r| r.local.clone()).unwrap_or_default();
|
||||
|
||||
@@ -2,15 +2,21 @@
|
||||
//! `--no-system-fonts` or `FIGCRAFT_NO_SYSTEM_FONTS=1` opts out.
|
||||
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The result of one `figcraft-cli run` step (script file `name`); `opt_out` sets the environment
|
||||
/// variable.
|
||||
fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value {
|
||||
static NEXT_SCRIPT: AtomicU64 = AtomicU64::new(0);
|
||||
let d = std::env::temp_dir().join(format!("figcraft-cli-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let script = d.join(format!("{name}.json"));
|
||||
// Tests in this binary run concurrently. `sketch_imports_keep_to_no_system_fonts` also calls
|
||||
// `families`, so a shared `families.json` could be truncated while another child reads it;
|
||||
// an empty script is valid and makes the CLI exit successfully without printing result JSON.
|
||||
let sequence = NEXT_SCRIPT.fetch_add(1, Ordering::Relaxed);
|
||||
let script = d.join(format!("{name}-{sequence}.json"));
|
||||
std::fs::write(&script, json!([step]).to_string()).unwrap();
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_figcraft-cli"));
|
||||
cmd.arg("run").arg(&script).args(args);
|
||||
@@ -20,8 +26,21 @@ fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value {
|
||||
cmd.env_remove("FIGCRAFT_NO_SYSTEM_FONTS");
|
||||
}
|
||||
let out = cmd.output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let line: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{name}: CLI status {:?}; stdout={:?}; stderr={}",
|
||||
out.status.code(),
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
);
|
||||
let line: Value = serde_json::from_slice(&out.stdout).unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"{name} {:?}: CLI returned success without JSON: {error}; stdout={:?}; stderr={}",
|
||||
args,
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
)
|
||||
});
|
||||
line["result"].clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::{JsFuture, future_to_promise};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::saved_files::SavedFiles;
|
||||
|
||||
@@ -150,15 +150,6 @@ async fn sleep(ms: i32) {
|
||||
let _ = JsFuture::from(promise).await;
|
||||
}
|
||||
|
||||
/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`.
|
||||
fn outcome(reply: &Value) -> Result<JsValue, JsValue> {
|
||||
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(to_js(reply.get("result").unwrap_or(&Value::Null)))
|
||||
} else {
|
||||
Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into())
|
||||
}
|
||||
}
|
||||
|
||||
fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> {
|
||||
js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ())
|
||||
}
|
||||
@@ -169,20 +160,20 @@ pub fn install() -> Result<(), JsValue> {
|
||||
Rc::new(PageApi::new(APP, Methods::default(), request)).install()?;
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let obj: js_sys::Object = js_sys::Reflect::get(&window, &APP.into())?.unchecked_into();
|
||||
set_fn(
|
||||
&obj,
|
||||
"inspect",
|
||||
Closure::<dyn Fn() -> js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("document.inspect", json!({})).await) }))
|
||||
.into_js_value(),
|
||||
)?;
|
||||
// `inspect` is `docInspect` under its earlier name: the crate's function, so it times out too.
|
||||
let doc_inspect = js_sys::Reflect::get(&obj, &"docInspect".into())?;
|
||||
js_sys::Reflect::set(&obj, &"inspect".into(), &doc_inspect)?;
|
||||
// `openFile` runs `file.open` through the crate's `execute`, so a call the app does not answer times out and is cancelled.
|
||||
let execute: js_sys::Function = js_sys::Reflect::get(&obj, &"execute".into())?.unchecked_into();
|
||||
let this = obj.clone();
|
||||
set_fn(
|
||||
&obj,
|
||||
"openFile",
|
||||
Closure::<dyn Fn(String, js_sys::Uint8Array) -> js_sys::Promise>::new(|name: String, bytes: js_sys::Uint8Array| {
|
||||
Closure::<dyn Fn(String, js_sys::Uint8Array) -> JsValue>::new(move |name: String, bytes: js_sys::Uint8Array| {
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(bytes.to_vec());
|
||||
future_to_promise(async move {
|
||||
outcome(&send("engine.execute", json!({"command": "file.open", "params": {"name": name, "data": data}})).await)
|
||||
})
|
||||
execute
|
||||
.call2(&this, &"file.open".into(), &to_js(&json!({"name": name, "data": data})))
|
||||
.unwrap_or_else(|e| js_sys::Promise::reject(&e).into())
|
||||
})
|
||||
.into_js_value(),
|
||||
)?;
|
||||
|
||||
@@ -39,6 +39,9 @@ env_logger = { version = "0.11", default-features = false, features = ["auto-col
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] }
|
||||
# The custom title bar's window styles (src/window_frame.rs): safe Win32 wrappers (MIT); the `user`
|
||||
# feature is User32.dll only. Same version as DesignCraft and PhotoCraft.
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
|
||||
|
||||
# The system colour scheme (org.freedesktop.portal.Settings): winit reports no theme on Linux and
|
||||
# the BSDs, so the interface's "system" mode follows the portal's instead. zbus comes in through
|
||||
|
||||
@@ -29,6 +29,7 @@ mod graphics;
|
||||
mod recovery;
|
||||
mod services;
|
||||
mod startup;
|
||||
mod window_frame;
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
mod apple_events_tests;
|
||||
@@ -63,6 +64,8 @@ struct App {
|
||||
title: String,
|
||||
/// Shared with the services, which write the copies after a panic.
|
||||
recovery: recovery::Shared,
|
||||
/// Keeps the custom title bar's undecorated windows borderless (Windows, #1343).
|
||||
window_frame: window_frame::WindowFrame,
|
||||
/// Documents and quit requests from Finder, the Dock and Open With.
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
@@ -111,6 +114,9 @@ impl eframe::App for App {
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
// winit gives an undecorated window its caption back when it changes the window's flags
|
||||
// (maximize, restore, ...): take it off again before the frame is laid out (#1343).
|
||||
self.window_frame.run();
|
||||
// Pointer and key events sent over the control channel (`ui.input`), for the window
|
||||
// about to draw.
|
||||
if let Some(events) = with_app(|fig| figcraft_ui_egui::windows::take_input(fig, raw_input.viewport_id)) {
|
||||
@@ -268,6 +274,7 @@ fn main() -> eframe::Result {
|
||||
// the old bespoke xdg-decoration probe that always drew FigCraft's custom title bar on KDE.
|
||||
fig.ui.title_bar = desktop_title_bar();
|
||||
viewport = window_chrome(viewport, fig.ui.title_bar);
|
||||
let custom_titlebar = fig.ui.title_bar == figcraft_ui_egui::TitleBar::Custom;
|
||||
if let Some(icon) = icon {
|
||||
viewport = viewport.with_icon(icon);
|
||||
}
|
||||
@@ -304,6 +311,9 @@ fn main() -> eframe::Result {
|
||||
ctx_slot,
|
||||
title: String::new(),
|
||||
recovery,
|
||||
// The custom title bar's undecorated window must stay borderless, or its caption
|
||||
// and border offset the content and the pointer on some Windows systems (#1343).
|
||||
window_frame: window_frame::WindowFrame::new(custom_titlebar),
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: apple_events.connect(&cc.egui_ctx),
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Keeps the custom (undecorated) title bar windows truly borderless on Windows (#1343).
|
||||
//!
|
||||
//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the
|
||||
//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems the
|
||||
//! desktop compositor still reserves that frame for the window surface: the content is drawn about
|
||||
//! 30 px low (a black band above it) while the pointer keeps the un-offset client coordinates, so
|
||||
//! clicks land on something other than what is drawn under them.
|
||||
//!
|
||||
//! winit 0.27 omitted those styles for undecorated windows and had no offset. [`WindowFrame`]
|
||||
//! restores that: it strips `WS_CAPTION` and `WS_BORDER` from every window of this process that
|
||||
//! draws its own title bar, and has Windows recalculate the frame. winit puts the styles back
|
||||
//! whenever it changes the window flags (maximize, restore, ...), so the step runs every frame; it
|
||||
//! reads each style and writes only when it differs, so it costs next to nothing.
|
||||
//!
|
||||
//! The same fix is in DesignCraft (#2139) and PhotoCraft (#2401). The long-term fix is in winit
|
||||
//! (storytold/winit#17); this module goes when the pinned winit has it.
|
||||
//!
|
||||
//! The Windows calls go through safe `winsafe` wrappers (the workspace forbids `unsafe`). Which
|
||||
//! windows are ours is found by enumerating this process's top-level windows of winit's window
|
||||
//! class, so the main window and every other window opened later are covered alike, and a file
|
||||
//! dialog or message box of the same process is left alone.
|
||||
|
||||
/// `WS_BORDER`.
|
||||
#[cfg(any(windows, test))]
|
||||
const WS_BORDER: u32 = 0x0080_0000;
|
||||
/// `WS_CAPTION`, which already includes `WS_BORDER`.
|
||||
#[cfg(any(windows, test))]
|
||||
const WS_CAPTION: u32 = 0x00C0_0000;
|
||||
|
||||
/// `style` without the OS title bar and frame (`WS_CAPTION`, `WS_BORDER`). The sizing border
|
||||
/// (`WS_THICKFRAME`) and the window buttons stay, so edge resizing, Aero snap and the system menu
|
||||
/// keep working, as they did with winit 0.27's undecorated windows.
|
||||
#[cfg(any(windows, test))]
|
||||
pub fn borderless_style(style: u32) -> u32 {
|
||||
style & !(WS_CAPTION | WS_BORDER)
|
||||
}
|
||||
|
||||
/// The per-frame step that keeps the windows borderless; a no-op where the OS draws the frame
|
||||
/// (macOS, Linux, the BSDs), where the app uses the system title bar, and in the browser.
|
||||
pub struct WindowFrame {
|
||||
step: Option<Box<dyn FnMut()>>,
|
||||
}
|
||||
|
||||
impl WindowFrame {
|
||||
/// The step for an app whose windows draw their own title bar when `custom_titlebar`.
|
||||
pub fn new(custom_titlebar: bool) -> Self {
|
||||
Self { step: platform::step(custom_titlebar) }
|
||||
}
|
||||
|
||||
/// Run the step; call it once per frame, before the frame is laid out.
|
||||
pub fn run(&mut self) {
|
||||
if let Some(step) = self.step.as_mut() {
|
||||
step();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn with_step(step: Box<dyn FnMut()>) -> Self {
|
||||
Self { step: Some(step) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod platform {
|
||||
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
|
||||
|
||||
/// winit's window class (`WindowAttributes`' default `class_name`).
|
||||
const WINIT_CLASS: &str = "Window Class";
|
||||
|
||||
/// A step that strips the frame styles from this process's windows each call, or `None` when
|
||||
/// the app uses the system title bar (the windows are decorated).
|
||||
pub fn step(custom_titlebar: bool) -> Option<Box<dyn FnMut()>> {
|
||||
if !custom_titlebar {
|
||||
return None;
|
||||
}
|
||||
let pid = std::process::id();
|
||||
Some(Box::new(move || {
|
||||
// The windows are handed over as real `HWND`s; nothing is wrapped from a raw handle.
|
||||
let _ = winsafe::EnumWindows(|hwnd| {
|
||||
strip_if_ours(&hwnd, pid);
|
||||
true
|
||||
});
|
||||
}))
|
||||
}
|
||||
|
||||
/// Strip `hwnd` when it is one of this process's winit windows.
|
||||
fn strip_if_ours(hwnd: &HWND, pid: u32) {
|
||||
if hwnd.GetWindowThreadProcessId().1 != pid || !matches!(hwnd.GetClassName().as_deref(), Ok(WINIT_CLASS)) {
|
||||
return;
|
||||
}
|
||||
strip(hwnd);
|
||||
}
|
||||
|
||||
/// Removes `WS_CAPTION`/`WS_BORDER` and has Windows recalculate the frame; a no-op once they
|
||||
/// are gone.
|
||||
fn strip(hwnd: &HWND) {
|
||||
let style = hwnd.style();
|
||||
// The decision is the tested arithmetic; the write uses the same bits as winsafe's flags.
|
||||
if super::borderless_style(style.raw()) == style.raw() {
|
||||
return;
|
||||
}
|
||||
hwnd.set_style(style & !(co::WS::CAPTION | co::WS::BORDER));
|
||||
let _ = hwnd.SetWindowPos(
|
||||
HwndPlace::None,
|
||||
POINT::new(),
|
||||
SIZE::new(),
|
||||
co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod platform {
|
||||
pub fn step(_custom_titlebar: bool) -> Option<Box<dyn FnMut()>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod window_frame_tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::{WS_BORDER, WS_CAPTION, WindowFrame, borderless_style};
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_style_bits_match_winsafes() {
|
||||
use winsafe::co;
|
||||
assert_eq!(co::WS::CAPTION.raw(), WS_CAPTION);
|
||||
assert_eq!(co::WS::BORDER.raw(), WS_BORDER);
|
||||
}
|
||||
|
||||
const WS_SYSMENU: u32 = 0x0008_0000;
|
||||
const WS_THICKFRAME: u32 = 0x0004_0000;
|
||||
const WS_MINIMIZEBOX: u32 = 0x0002_0000;
|
||||
const WS_MAXIMIZEBOX: u32 = 0x0001_0000;
|
||||
const WS_VISIBLE: u32 = 0x1000_0000;
|
||||
|
||||
#[test]
|
||||
fn the_borderless_style_drops_the_caption_and_border_only() {
|
||||
let decorated = WS_CAPTION | WS_BORDER | WS_SYSMENU | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_VISIBLE;
|
||||
let bare = borderless_style(decorated);
|
||||
assert_eq!(bare & WS_CAPTION, 0, "caption gone");
|
||||
assert_eq!(bare & WS_BORDER, 0, "border gone");
|
||||
assert_eq!(bare & WS_THICKFRAME, WS_THICKFRAME, "edge resizing kept");
|
||||
assert_eq!(bare & (WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU), WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU, "window buttons kept");
|
||||
assert_eq!(bare & WS_VISIBLE, WS_VISIBLE, "unrelated bits kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_borderless_style_is_unchanged_so_no_frame_change_is_made() {
|
||||
let bare = WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_VISIBLE;
|
||||
assert_eq!(borderless_style(bare), bare);
|
||||
assert_eq!(borderless_style(borderless_style(bare | WS_CAPTION)), bare);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_step_runs_each_time_the_frame_runs_it() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let n = calls.clone();
|
||||
let mut frame = WindowFrame::with_step(Box::new(move || {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
}));
|
||||
for _ in 0..3 {
|
||||
frame.run();
|
||||
}
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_step_is_fine() {
|
||||
// Decorated windows and other platforms have no step; running must do nothing.
|
||||
let mut frame = WindowFrame::new(false);
|
||||
frame.run();
|
||||
}
|
||||
}
|
||||
@@ -115,3 +115,6 @@ display_name = "Hamza0101"
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
[people.GiovanniBot]
|
||||
sync_github_name = true
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use figcraft_collab::message::{Peer, Presence, ServerMsg};
|
||||
use figcraft_collab::message::{Access, CatchUp, Peer, Presence, Processed, ServerMsg};
|
||||
use figcraft_engine::live::{Event, MAX_PEERS};
|
||||
|
||||
use crate::guest::GuestConfig;
|
||||
@@ -59,3 +59,39 @@ fn joins_past_the_cap_are_left_out_until_someone_leaves() {
|
||||
send(joined(over));
|
||||
assert!(matches!(inbox.drain().as_slice(), [Event::PeerLeft(7), Event::PeerJoined(p)] if p.client_id == over));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hosts_long_names_and_colours_are_cut_where_they_are_kept() {
|
||||
let inbox = inbox();
|
||||
let cfg = GuestConfig::new(Invite::new("127.0.0.1:47900", "0123456789abcdef", "AbCdEfGhIjKlMnOpQrStUv"), "Ada".into());
|
||||
let resume = Mutex::new(None);
|
||||
let mut seen = Seen::default();
|
||||
let long = "x".repeat(100_000);
|
||||
take(ServerMsg::PeerJoined(Peer { client_id: 1, name: long.clone(), color: long }), &cfg, &inbox, &mut seen, &resume, &|| {});
|
||||
match inbox.drain().as_slice() {
|
||||
[Event::PeerJoined(p)] => assert_eq!((p.name.as_str(), p.color.as_str()), ("x".repeat(256).as_str(), "x".repeat(32).as_str())),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_welcome_handed_to_the_sync_client_carries_the_bounded_roster() {
|
||||
let inbox = inbox();
|
||||
let cfg = GuestConfig::new(Invite::new("127.0.0.1:47900", "0123456789abcdef", "AbCdEfGhIjKlMnOpQrStUv"), "Ada".into());
|
||||
let resume = Mutex::new(None);
|
||||
let long = "y".repeat(100_000);
|
||||
let welcome = ServerMsg::Welcome {
|
||||
session: 1,
|
||||
client_id: 9,
|
||||
seq: 0,
|
||||
catch_up: CatchUp::Snapshot(Vec::new()),
|
||||
processed: Processed::default(),
|
||||
peers: vec![Peer { client_id: 1, name: long.clone(), color: long }],
|
||||
access: Access::default(),
|
||||
secret: 0,
|
||||
};
|
||||
take(welcome, &cfg, &inbox, &mut Seen::default(), &resume, &|| {});
|
||||
let events = inbox.drain();
|
||||
let Some(Event::Sync(ServerMsg::Welcome { peers, .. })) = events.iter().find(|e| matches!(e, Event::Sync(_))) else { panic!("{events:?}") };
|
||||
assert_eq!(peers.first().map(|p| (p.name.chars().count(), p.color.chars().count())), Some((256, 32)));
|
||||
}
|
||||
@@ -226,6 +226,19 @@ pub(crate) struct Seen {
|
||||
peers: Vec<Peer>,
|
||||
}
|
||||
|
||||
/// `p` with its name and colour cut to what the UI shows: the host is untrusted, and the roster is
|
||||
/// copied whenever someone's identity is updated.
|
||||
fn bounded(mut p: Peer) -> Peer {
|
||||
p.name = p.name.chars().take(MAX_PEER_NAME).collect();
|
||||
p.color = p.color.chars().take(MAX_COLOR).collect();
|
||||
p
|
||||
}
|
||||
|
||||
/// The most characters of a colour (`#rrggbb` and a few spellings more) kept for someone.
|
||||
const MAX_COLOR: usize = 32;
|
||||
/// The most characters of a name kept for someone.
|
||||
const MAX_PEER_NAME: usize = 256;
|
||||
|
||||
/// What taking in one message from the host means for the connection.
|
||||
pub(crate) enum Taken {
|
||||
Continue,
|
||||
@@ -251,7 +264,7 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
|
||||
*r = Some(Resume { session, client_id, seq, secret });
|
||||
}
|
||||
// The sync client opens the document (and fills in its name and pages).
|
||||
let peers: Vec<Peer> = peers.iter().take(MAX_PEERS).cloned().collect();
|
||||
let peers: Vec<Peer> = peers.iter().take(MAX_PEERS).cloned().map(bounded).collect();
|
||||
let inv = &cfg.invite;
|
||||
let info = SessionInfo {
|
||||
role: Role::Guest,
|
||||
@@ -268,20 +281,24 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
|
||||
view: None,
|
||||
};
|
||||
seen.peers = peers.clone();
|
||||
// The sync client keeps the roster of the welcome it is handed: the bounded one.
|
||||
if let ServerMsg::Welcome { peers: sent, .. } = &mut m {
|
||||
sent.clone_from(&peers);
|
||||
}
|
||||
seen.info = Some(info.clone());
|
||||
welcomed();
|
||||
inbox.push(Event::Welcome { info, peers });
|
||||
inbox.push(Event::Sync(m));
|
||||
return Taken::Welcomed;
|
||||
}
|
||||
ServerMsg::PeerJoined(p) => match seen.info.as_mut() {
|
||||
ServerMsg::PeerJoined(p) => match (seen.info.as_mut(), bounded(p)) {
|
||||
// The host tells you how you are shown.
|
||||
Some(info) if p.client_id == info.me => {
|
||||
(Some(info), p) if p.client_id == info.me => {
|
||||
info.name = p.name;
|
||||
info.color = p.color;
|
||||
inbox.push(Event::Welcome { info: info.clone(), peers: seen.peers.clone() });
|
||||
}
|
||||
_ => {
|
||||
(_, p) => {
|
||||
match seen.peers.iter().position(|q| q.client_id == p.client_id) {
|
||||
Some(i) => {
|
||||
seen.peers.remove(i);
|
||||
|
||||
@@ -37,8 +37,8 @@ impl FileKind {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum BoardItem {
|
||||
/// A sticky note: a frame whose first text layer is the note (its size shrinks as the note
|
||||
/// grows) and, below it, who wrote it.
|
||||
/// A sticky note: a frame whose first text layer is the note (its size stays fixed, the note
|
||||
/// grows taller) and, below it, who wrote it.
|
||||
Sticky {
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
author: String,
|
||||
|
||||
+166
-34
@@ -152,7 +152,7 @@ fn near_path(path: &BezPath, p: Point, dist: f64) -> bool {
|
||||
/// boolean groups are hit where their `result` is.
|
||||
pub fn hit_leaf(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
|
||||
let p = doc.node(page)?;
|
||||
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None).filter(|_| !masked_out(doc, p, *c, pt)))
|
||||
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, HitOpts::default()).filter(|_| !masked_out(doc, p, *c, pt)))
|
||||
}
|
||||
|
||||
/// Whether child `c` of `parent` is masked at `pt`: a visible mask below it (the nearest mask
|
||||
@@ -175,7 +175,7 @@ fn covers(doc: &Document, id: NodeId, n: &Node, pt: Point, depth: usize) -> bool
|
||||
|
||||
/// Like [`hit_leaf`], but only within layer `root` (it included).
|
||||
pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
|
||||
hit_rec(doc, root, pt, tol, 0, result, None)
|
||||
hit_rec(doc, root, pt, tol, 0, result, None, HitOpts::default())
|
||||
}
|
||||
|
||||
/// [`hit_leaf`] (or [`hit_in`] for a `root` that isn't a page) in outline mode: shapes are hit
|
||||
@@ -185,8 +185,8 @@ pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolRes
|
||||
/// when it shows them, and every layer on the edge of its box when it shows object bounds.
|
||||
pub fn hit_outlines(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, also: OutlineHits) -> Option<NodeId> {
|
||||
match doc.node(root) {
|
||||
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also))),
|
||||
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also)),
|
||||
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also), HitOpts::default())),
|
||||
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also), HitOpts::default()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,13 +204,30 @@ fn on_box_edge(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64) -> boo
|
||||
r.inflate(tol, tol).contains(lp) && !(r.width() > 2.0 * tol && r.height() > 2.0 * tol && r.inflate(-tol, -tol).contains(lp))
|
||||
}
|
||||
|
||||
fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, also: Option<OutlineHits>) -> Option<NodeId> {
|
||||
/// Options for the hit tests that the plain pick never sets.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HitOpts {
|
||||
/// Reach locked layers (and what a locked frame holds) too. A click, hover or marquee never
|
||||
/// does; the Select layer list does.
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
fn hit_rec(
|
||||
doc: &Document,
|
||||
id: NodeId,
|
||||
pt: Point,
|
||||
tol: f64,
|
||||
depth: usize,
|
||||
result: BoolResult,
|
||||
also: Option<OutlineHits>,
|
||||
opts: HitOpts,
|
||||
) -> Option<NodeId> {
|
||||
if depth > 512 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(id)?;
|
||||
let outline = also.is_some();
|
||||
if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked {
|
||||
if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked && !opts.locked {
|
||||
return None;
|
||||
}
|
||||
if let NodeKind::Section { contents_hidden: true } = n.kind {
|
||||
@@ -228,7 +245,7 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result
|
||||
return None;
|
||||
}
|
||||
for c in n.paint_order().rev() {
|
||||
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also).filter(|_| !masked_out(doc, n, c, pt)) {
|
||||
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also, opts).filter(|_| !masked_out(doc, n, c, pt)) {
|
||||
return Some(h);
|
||||
}
|
||||
}
|
||||
@@ -239,14 +256,20 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result
|
||||
None
|
||||
}
|
||||
|
||||
/// Every visible, unlocked layer under `pt` (page coordinates) with its depth below the page, in
|
||||
/// layer-tree order (each layer before what it contains, the front-most first): what
|
||||
/// "Select layer" in the context menu lists. Clip content is honoured; boolean groups (hit where
|
||||
/// their `result` is) and sections with hidden contents count as one layer.
|
||||
/// Every visible, unlocked layer under `pt`: [`layers_at_opts`] with the default options.
|
||||
pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Vec<(NodeId, usize)> {
|
||||
fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, out: &mut Vec<(NodeId, usize)>) {
|
||||
layers_at_opts(doc, page, pt, tol, result, HitOpts::default())
|
||||
}
|
||||
|
||||
/// Every visible layer under `pt` (page coordinates) with its depth below the page, in
|
||||
/// layer-tree order (each layer before what it contains, the front-most first): what
|
||||
/// "Select layer" in the context menu lists. Locked layers are left out unless `opts.locked`.
|
||||
/// Clip content is honoured; boolean groups (hit where their `result` is) and sections with
|
||||
/// hidden contents count as one layer.
|
||||
pub fn layers_at_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Vec<(NodeId, usize)> {
|
||||
fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, opts: HitOpts, out: &mut Vec<(NodeId, usize)>) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
if !n.visible || n.locked || depth > 512 {
|
||||
if !n.visible || n.locked && !opts.locked || depth > 512 {
|
||||
return;
|
||||
}
|
||||
let clips = n.clip && n.kind.is_frame_like();
|
||||
@@ -256,14 +279,14 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool
|
||||
let at = out.len();
|
||||
let whole = matches!(n.kind, NodeKind::BooleanOp { .. } | NodeKind::Section { contents_hidden: true });
|
||||
if whole {
|
||||
if hit_rec(doc, id, pt, tol, depth, result, None).is_some() {
|
||||
if hit_rec(doc, id, pt, tol, depth, result, None, opts).is_some() {
|
||||
out.push((id, depth));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.paint_order().rev() {
|
||||
let before = out.len();
|
||||
rec(doc, c, pt, tol, depth + 1, result, out);
|
||||
rec(doc, c, pt, tol, depth + 1, result, opts, out);
|
||||
if out.len() > before && masked_out(doc, n, c, pt) {
|
||||
out.truncate(before);
|
||||
}
|
||||
@@ -276,7 +299,7 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool
|
||||
if let Some(p) = doc.node(page) {
|
||||
for c in p.children.iter().rev() {
|
||||
let before = out.len();
|
||||
rec(doc, *c, pt, tol, 0, result, &mut out);
|
||||
rec(doc, *c, pt, tol, 0, result, opts, &mut out);
|
||||
if out.len() > before && masked_out(doc, p, *c, pt) {
|
||||
out.truncate(before);
|
||||
}
|
||||
@@ -355,14 +378,15 @@ pub fn enter_target(doc: &Document, leaf: NodeId, selection: &[NodeId]) -> NodeI
|
||||
inner.unwrap_or_else(|| select_target(doc, leaf, selection, false))
|
||||
}
|
||||
|
||||
/// Nodes on `page` whose world bounds intersect `rect` (marquee): top-level children, or the
|
||||
/// children of top-level frames when the marquee starts inside a frame (`within`).
|
||||
/// Nodes a marquee over `rect` touches, one level only: the children of `within` (a focus view's
|
||||
/// frame), or the top-level layers of `page`. Frames are not opened or enclosed here; see
|
||||
/// [`marquee_select`] for a plain marquee.
|
||||
pub fn marquee(doc: &Document, page: NodeId, rect: Rect, within: Option<NodeId>) -> Vec<NodeId> {
|
||||
let parent = within.unwrap_or(page);
|
||||
doc.node(parent).map(|p| marquee_children(doc, p, rect)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Nodes on `page` a Cmd/Ctrl marquee selects: the innermost layers whose bounds touch `rect`
|
||||
/// Nodes on `page` a Cmd/Ctrl marquee selects: the innermost layers the marquee touches
|
||||
/// (frames, groups and instances are looked into; a container none of whose children are touched
|
||||
/// counts itself; boolean groups count as one shape).
|
||||
pub fn marquee_deep(doc: &Document, page: NodeId, rect: Rect) -> Vec<NodeId> {
|
||||
@@ -384,25 +408,133 @@ pub fn marquee_deep(doc: &Document, page: NodeId, rect: Rect) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The visible, unlocked children of `p` whose world bounds touch `rect` (on both axes: lines and
|
||||
/// other flat layers too).
|
||||
/// The visible, unlocked children of `p` the marquee touches (see [`marquee_touches`]).
|
||||
fn marquee_children(doc: &Document, p: &Node, rect: Rect) -> Vec<NodeId> {
|
||||
p.children
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|c| doc.node(*c).is_some_and(|n| n.visible && !n.locked))
|
||||
.filter(|c| doc.world_bounds(*c).is_some_and(|b| b.x0 <= rect.x1 && b.x1 >= rect.x0 && b.y0 <= rect.y1 && b.y1 >= rect.y0))
|
||||
.collect()
|
||||
p.children.iter().copied().filter(|c| doc.node(*c).is_some_and(|n| n.visible && !n.locked && marquee_touches(doc, *c, n, rect))).collect()
|
||||
}
|
||||
|
||||
/// Figma marquee rule: a marquee that fully contains a top-level frame selects the frame; one
|
||||
/// starting on empty canvas selects top-level objects it touches.
|
||||
pub fn marquee_select(doc: &Document, page: NodeId, rect: Rect, start_inside: Option<NodeId>) -> Vec<NodeId> {
|
||||
if let Some(frame) = start_inside {
|
||||
let inside = marquee(doc, page, rect, Some(frame));
|
||||
return inside;
|
||||
/// The outline a rotated shape is touched by. One line: return the turned box instead
|
||||
/// (`figcraft_geom::rounded_rect(n.width, n.height, [0.0; 4], 0.0)`) if Figma proves to test that.
|
||||
fn marquee_outline(n: &Node) -> Option<BezPath> {
|
||||
shape_path(n)
|
||||
}
|
||||
|
||||
/// Whether the marquee touches layer `id`: its world box overlaps `rect` (inclusive, so lines and
|
||||
/// zero-size marquees count) and, for a rotated shape, its outline in page space does too.
|
||||
fn marquee_touches(doc: &Document, id: NodeId, n: &Node, rect: Rect) -> bool {
|
||||
let box_hit = doc.world_bounds(id).is_some_and(|b| b.x0 <= rect.x1 && b.x1 >= rect.x0 && b.y0 <= rect.y1 && b.y1 >= rect.y0);
|
||||
if !box_hit
|
||||
|| !matches!(
|
||||
n.kind,
|
||||
NodeKind::Rectangle
|
||||
| NodeKind::Ellipse { .. }
|
||||
| NodeKind::Polygon { .. }
|
||||
| NodeKind::Star { .. }
|
||||
| NodeKind::Line
|
||||
| NodeKind::Vector { .. }
|
||||
)
|
||||
{
|
||||
return box_hit;
|
||||
}
|
||||
marquee(doc, page, rect, None)
|
||||
let xf = doc.world_transform(id);
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
const EPS: f64 = 1e-9;
|
||||
let rotated = !((b.abs() < EPS && c.abs() < EPS) || (a.abs() < EPS && d.abs() < EPS));
|
||||
if !rotated {
|
||||
return true;
|
||||
}
|
||||
let det = a * d - b * c;
|
||||
if ![a, b, c, d, e, f, det].iter().all(|v| v.is_finite()) || det.abs() < EPS {
|
||||
return true;
|
||||
}
|
||||
marquee_outline(n).is_none_or(|path| path_touches_rect(n, &path, xf, rect))
|
||||
}
|
||||
|
||||
/// Whether the marquee and the shape drawn as local `path` under `xf` share a point: a path end
|
||||
/// inside the marquee, a path segment crossing a marquee edge, or the marquee inside the filled shape.
|
||||
fn path_touches_rect(n: &Node, path: &BezPath, xf: figcraft_geom::Affine, rect: Rect) -> bool {
|
||||
use figcraft_geom::kurbo::{Line, ParamCurve, PathSeg};
|
||||
let inside = |p: Point| p.x >= rect.x0 && p.x <= rect.x1 && p.y >= rect.y0 && p.y <= rect.y1;
|
||||
let mut world = path.clone();
|
||||
world.apply_affine(xf);
|
||||
if world.segments().any(|s| inside(s.start()) || inside(s.end())) {
|
||||
return true;
|
||||
}
|
||||
let (tl, tr, br, bl) = (Point::new(rect.x0, rect.y0), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1));
|
||||
let edges = [(tl, tr), (tr, br), (br, bl), (bl, tl)];
|
||||
for (p, q) in edges {
|
||||
if (q - p).hypot() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let line = Line::new(p, q);
|
||||
if world.segments().any(|s: PathSeg| s.intersect_line(line).iter().any(|h| (0.0..=1.0).contains(&h.line_t))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
is_closed(n) && fills_point(n, path, xf.inverse() * tl)
|
||||
}
|
||||
|
||||
/// Whether a marquee takes a touched top-level layer whole, opens it for the layers in it, or skips it.
|
||||
enum Touch {
|
||||
Whole,
|
||||
/// The frame the drag started in: the layers in it the marquee touches, or the frame itself
|
||||
/// (whole) once the marquee is at the top level.
|
||||
Open,
|
||||
/// A partly covered frame or section: the layers in it, or the frame itself once the marquee is at the top level.
|
||||
Partial,
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Figma's marquee rule (measured in the web app, 2026-11-11): each top-level layer the marquee
|
||||
/// touches is selected whole, except a frame with children or a section with its contents shown:
|
||||
/// enclosed by the marquee it is selected itself, otherwise the marquee takes the layers in it that
|
||||
/// it touches. The frame the drag started in (`start_inside`) is selected only when the marquee also
|
||||
/// takes another top-level frame (then whole); otherwise only the layers in it the marquee touches.
|
||||
/// Selecting a frame or section whole keeps the marquee at the top level: no frame opens then, and a
|
||||
/// partly covered one is selected whole. Components, instances, board items and sections with hidden
|
||||
/// contents are selected only when enclosed.
|
||||
pub fn marquee_select(doc: &Document, page: NodeId, rect: Rect, start_inside: Option<NodeId>) -> Vec<NodeId> {
|
||||
let Some(page_node) = doc.node(page) else { return Vec::new() };
|
||||
let touched = marquee_children(doc, page_node, rect);
|
||||
let classified: Vec<(NodeId, Touch, bool)> = touched
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let n = doc.node(*t)?;
|
||||
let enclosed = doc.world_bounds(*t).is_some_and(|b| rect.contains(b.origin()) && rect.contains(Point::new(b.x1, b.y1)));
|
||||
let container = n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. });
|
||||
let opens = match &n.kind {
|
||||
NodeKind::Frame | NodeKind::Section { .. } => !n.is_board_atom() && !n.hides_contents() && !n.children.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
let plain_empty_frame = matches!(n.kind, NodeKind::Frame) && n.children.is_empty() && !n.is_board_atom();
|
||||
let act = if start_inside == Some(*t) {
|
||||
Touch::Open
|
||||
} else if opens {
|
||||
if enclosed { Touch::Whole } else { Touch::Partial }
|
||||
} else if plain_empty_frame || !(container || n.is_board_atom()) || enclosed {
|
||||
Touch::Whole
|
||||
} else {
|
||||
Touch::Skip
|
||||
};
|
||||
let whole_container = container && matches!(act, Touch::Whole);
|
||||
Some((*t, act, whole_container))
|
||||
})
|
||||
.collect();
|
||||
let top_level_mode = classified.iter().any(|(_, _, whole_container)| *whole_container);
|
||||
let mut out = Vec::new();
|
||||
for (t, act, _) in &classified {
|
||||
match act {
|
||||
Touch::Whole => out.push(*t),
|
||||
Touch::Open | Touch::Partial if top_level_mode => out.push(*t),
|
||||
Touch::Open | Touch::Partial => {
|
||||
if let Some(n) = doc.node(*t) {
|
||||
out.extend(marquee_children(doc, n, rect));
|
||||
}
|
||||
}
|
||||
Touch::Skip => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bounds of a node's outline in page coordinates for snapping (the box corners and centre).
|
||||
|
||||
@@ -152,6 +152,11 @@ pub struct LibraryLink {
|
||||
pub name: String,
|
||||
/// Where the library file is.
|
||||
pub path: String,
|
||||
/// Where the library file is from the folder of the document that links it ('/'-separated;
|
||||
/// written on save): followed first when the document is opened, so the link survives moving
|
||||
/// or cloning the folder that holds both. Empty for server links and older files.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub relative: String,
|
||||
/// The library version this document last saw (when it was added or its updates accepted).
|
||||
pub version: u64,
|
||||
}
|
||||
|
||||
@@ -395,7 +395,8 @@ impl NodeKind {
|
||||
)
|
||||
}
|
||||
|
||||
/// Kinds whose corners can be rounded from the panel.
|
||||
/// Kinds whose corners can be rounded from the panel. A boolean group has one radius for every
|
||||
/// sharp corner of its result.
|
||||
pub fn has_corner_radius(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
@@ -408,16 +409,19 @@ impl NodeKind {
|
||||
| NodeKind::Star { .. }
|
||||
| NodeKind::Vector { .. }
|
||||
| NodeKind::Section { .. }
|
||||
| NodeKind::BooleanOp { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Kinds with a radius per corner (the others round every corner alike).
|
||||
/// Kinds with a radius per corner (the others, boolean groups included, round every corner alike).
|
||||
pub fn has_independent_corners(&self) -> bool {
|
||||
self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. })
|
||||
self.has_corner_radius()
|
||||
&& !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. } | NodeKind::BooleanOp { .. })
|
||||
}
|
||||
|
||||
/// Kinds whose rounded corners are drawn with corner smoothing: a vector only when its network
|
||||
/// has a closed region (an open path's rounded points are drawn without it).
|
||||
/// has a closed region (an open path's rounded points are drawn without it). A boolean group's
|
||||
/// smoothing applies to its result's corners between straight edges.
|
||||
pub fn has_corner_smoothing(&self) -> bool {
|
||||
match self {
|
||||
NodeKind::Vector { network } => !network.regions.is_empty(),
|
||||
|
||||
@@ -1399,6 +1399,10 @@ impl ExportSize {
|
||||
Some((i, c)) if c.is_ascii_alphabetic() => (s.get(..i)?.trim(), Some(c)),
|
||||
_ => (s.as_str(), None),
|
||||
};
|
||||
// Plain decimal only: no sign, exponent, "inf" or "nan".
|
||||
if !num.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
|
||||
return None;
|
||||
}
|
||||
let value: f64 = num.parse().ok()?;
|
||||
match unit {
|
||||
None | Some('x') => ExportSize::Scale { value },
|
||||
@@ -1449,8 +1453,10 @@ pub struct PrintSettings {
|
||||
/// is printed this far out, to be trimmed off.
|
||||
pub bleed: f64,
|
||||
/// Crop marks outside the bleed, at the trim's corners.
|
||||
#[serde(alias = "crop_marks")]
|
||||
pub crop_marks: bool,
|
||||
/// Bleed marks outside the bleed, at the bleed's corners.
|
||||
#[serde(alias = "bleed_marks")]
|
||||
pub bleed_marks: bool,
|
||||
/// CMYK colour (converted from RGB) instead of RGB.
|
||||
pub cmyk: bool,
|
||||
@@ -1519,25 +1525,32 @@ pub struct ExportSetting {
|
||||
pub print: PrintSettings,
|
||||
/// Only the layer itself (on), or every layer that shows in its area (off).
|
||||
#[serde(skip_serializing_if = "is_true")]
|
||||
#[serde(alias = "contents_only")]
|
||||
pub contents_only: bool,
|
||||
/// The layer's own box, cutting off what it paints outside it (shadows, outside strokes).
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
#[serde(alias = "include_bounding_box")]
|
||||
pub include_bounding_box: bool,
|
||||
/// SVG: text as outlines (on) or as `<text>` elements (off).
|
||||
#[serde(skip_serializing_if = "is_true")]
|
||||
#[serde(alias = "svg_outline_text")]
|
||||
pub svg_outline_text: bool,
|
||||
/// SVG: layer names as `id` attributes.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
#[serde(alias = "svg_id_attribute")]
|
||||
pub svg_id_attribute: bool,
|
||||
/// SVG: strokes as `stroke` attributes where that's exact (on), else as outlines.
|
||||
#[serde(skip_serializing_if = "is_true")]
|
||||
#[serde(alias = "svg_simplify_stroke")]
|
||||
pub svg_simplify_stroke: bool,
|
||||
/// Android Vector Drawable: what to do with what a drawable can't hold exactly.
|
||||
#[serde(skip_serializing_if = "VdCompat::is_default")]
|
||||
#[serde(alias = "vd_compat")]
|
||||
pub vd_compat: VdCompat,
|
||||
/// PNG, JPG and WebP: the color profile the file is written in. SVG, PDF and XML are always
|
||||
/// sRGB, whatever this says.
|
||||
#[serde(skip_serializing_if = "ExportColorProfile::is_default")]
|
||||
#[serde(alias = "color_profile")]
|
||||
pub color_profile: ExportColorProfile,
|
||||
/// JPG: the encoder's quality, 1 (smallest file) to 100 (see [`ExportSetting::quality`]).
|
||||
#[serde(skip_serializing_if = "is_default_quality")]
|
||||
|
||||
@@ -902,6 +902,46 @@ fn a_chamfered_rectangles_rounded_fill_is_cut_at_every_point() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reporter's network (#1951): a corner cut off by a segment drawn before the corner point was
|
||||
/// deleted, so the region's loop is the open chain of the other four segments and the cutting
|
||||
/// segment, joining the chain's two ends, is in no loop. Rounded, the fill and the region trace
|
||||
/// the stroke's outline, cut by an arc at the chain's ends as at every other point.
|
||||
#[test]
|
||||
fn a_rounded_loop_left_open_where_a_segment_joins_its_ends_follows_that_segment() {
|
||||
open_loop_follows_the_segment_joining_its_ends([(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)], vec![3, 1, 2, 0]);
|
||||
}
|
||||
|
||||
/// The same network with the joining segment listed first, and with the loop walked the other way.
|
||||
#[test]
|
||||
fn an_open_loop_follows_the_segment_joining_its_ends_listed_first_or_walked_backwards() {
|
||||
open_loop_follows_the_segment_joining_its_ends([(3, 4), (0, 3), (1, 2), (2, 0), (4, 1)], vec![4, 2, 3, 1]);
|
||||
open_loop_follows_the_segment_joining_its_ends([(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)], vec![0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
fn open_loop_follows_the_segment_joining_its_ends(segments: [(usize, usize); 5], open_loop: Vec<usize>) {
|
||||
use figcraft_geom::BezPath;
|
||||
use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(525.0, 525.0), Point::new(0.0, 525.0), Point::new(333.0, 0.0), Point::new(525.0, 183.0)];
|
||||
let mut net = VectorNetwork::from_points(&corners, false);
|
||||
net.segments = segments.iter().map(|&(a, b)| Segment::line(a, b)).collect();
|
||||
net.regions.push(Region { loops: vec![open_loop], winding: WindingRule::NonZero, fills: None, paint_space: None });
|
||||
for v in &mut net.vertices {
|
||||
v.radius = 125.0;
|
||||
}
|
||||
let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min);
|
||||
let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::<f64>();
|
||||
let stroke = net.stroke_path();
|
||||
let fill = net.fill_path();
|
||||
let region = net.rounded().unwrap().region_path(0).unwrap();
|
||||
for (i, p) in corners.iter().enumerate() {
|
||||
assert!(keeps_off(&stroke, *p) > 2.0, "the stroke is cut at point {i}");
|
||||
assert!(keeps_off(&fill, *p) > 2.0, "the fill runs into point {i} ({:.2} from it)", keeps_off(&fill, *p));
|
||||
assert!(keeps_off(®ion, *p) > 2.0, "the region runs into point {i} ({:.2} from it)", keeps_off(®ion, *p));
|
||||
}
|
||||
assert!((length(&fill) - length(&stroke)).abs() < 1e-6, "fill {} and stroke {} trace the same outline", length(&fill), length(&stroke));
|
||||
assert!((length(®ion) - length(&stroke)).abs() < 1e-6, "region {} and stroke {} trace the same outline", length(®ion), length(&stroke));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_variable_ids_resolve_only_their_exact_collection() {
|
||||
let mut vars = crate::proto_expr_tests::vars();
|
||||
|
||||
+238
-1
@@ -276,6 +276,31 @@ pub enum TextDirection {
|
||||
/// Deepest list nesting (levels 0..=MAX_LIST_INDENT).
|
||||
pub const MAX_LIST_INDENT: u8 = 8;
|
||||
|
||||
/// For each paragraph, whether it is an item where a list starts counting. Numbers count the items
|
||||
/// of one list at one level and restart after a plain paragraph, a shallower item or the other
|
||||
/// kind of list; the first item of such a run starts counting (and takes its own start number).
|
||||
/// The layout numbers by this rule.
|
||||
pub fn list_item_starts_counting(lists: &[ParaList]) -> Vec<bool> {
|
||||
let mut run = [ListStyle::None; MAX_LIST_INDENT as usize + 1];
|
||||
lists
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
if pl.list == ListStyle::None {
|
||||
run.fill(ListStyle::None);
|
||||
return false;
|
||||
}
|
||||
let d = usize::from(pl.indent).min(run.len() - 1);
|
||||
for c in run.iter_mut().skip(d + 1) {
|
||||
*c = ListStyle::None;
|
||||
}
|
||||
let Some(c) = run.get_mut(d) else { return false };
|
||||
let starts = *c != pl.list;
|
||||
*c = pl.list;
|
||||
starts
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One paragraph's list settings and base direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
@@ -293,6 +318,10 @@ pub struct ParaList {
|
||||
/// The paragraph's base direction (Text ▸ Text direction); `Auto` follows its letters.
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub direction: TextDirection,
|
||||
/// The paragraph's own wrap style (a wrap style can be set on the text layer, a paragraph or a
|
||||
/// text style); `None` follows the layer's [`TextData::wrap_style`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub wrap: Option<WrapStyle>,
|
||||
}
|
||||
|
||||
/// Character style. In runs, every field is an override; `None` means "inherit the base".
|
||||
@@ -337,6 +366,9 @@ pub struct ParagraphStyle {
|
||||
pub paragraph_indent: f64,
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub list: ListStyle,
|
||||
/// The wrap style (Auto asks nothing).
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub wrap_style: WrapStyle,
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub features: std::collections::BTreeMap<String, bool>,
|
||||
}
|
||||
@@ -838,6 +870,33 @@ impl TextData {
|
||||
self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() })
|
||||
}
|
||||
|
||||
/// Paragraph `p`'s wrap style: its own, else the layer's.
|
||||
pub fn para_wrap_style(&self, p: usize) -> WrapStyle {
|
||||
self.paragraphs.get(p).and_then(|pl| pl.wrap).unwrap_or(self.wrap_style)
|
||||
}
|
||||
|
||||
/// The layer level: every paragraph takes wrap style `w` (their own overrides go).
|
||||
pub fn set_wrap_style(&mut self, w: WrapStyle) {
|
||||
self.wrap_style = w;
|
||||
// Every paragraph by index: `para_span` leaves out an empty one after a final newline.
|
||||
let last = self.paragraph_count() - 1;
|
||||
self.set_para_lists_between(0, last, false, |pl| pl.wrap = None);
|
||||
}
|
||||
|
||||
/// The paragraph level: the paragraphs chars `start..end` touch take wrap style `w`; one equal
|
||||
/// to the layer's is no override.
|
||||
pub fn set_para_wrap_styles(&mut self, start: usize, end: usize, w: WrapStyle) {
|
||||
let layer = self.wrap_style;
|
||||
self.set_para_lists(start, end, |pl| pl.wrap = (w != layer).then_some(w));
|
||||
}
|
||||
|
||||
/// The effective wrap style the paragraphs chars `start..end` touch share, or None when they differ.
|
||||
pub fn common_wrap_style(&self, start: usize, end: usize) -> Option<WrapStyle> {
|
||||
let (a, b) = self.para_span(start, end);
|
||||
let first = self.para_wrap_style(a);
|
||||
(a..=b).all(|p| self.para_wrap_style(p) == first).then_some(first)
|
||||
}
|
||||
|
||||
/// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries).
|
||||
fn fill_paragraphs(&mut self) {
|
||||
let n = self.paragraph_count();
|
||||
@@ -886,6 +945,43 @@ impl TextData {
|
||||
}
|
||||
pl.indent = pl.indent.min(MAX_LIST_INDENT);
|
||||
}
|
||||
self.fold_paragraph_lists();
|
||||
}
|
||||
|
||||
/// Give paragraphs `a..=b` (by index) no start number of their own, as an item made by Enter
|
||||
/// has none. Touches nothing else: a plain paragraph keeps its level, a bullet its settings.
|
||||
/// One pass over the range, and nothing at all when no paragraph carries a start.
|
||||
pub fn clear_list_starts(&mut self, a: usize, b: usize) {
|
||||
if self.paragraphs.iter().all(|p| p.start_offset == 0) {
|
||||
return;
|
||||
}
|
||||
self.fill_paragraphs();
|
||||
for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) {
|
||||
pl.start_offset = 0;
|
||||
}
|
||||
self.fold_paragraph_lists();
|
||||
}
|
||||
|
||||
/// Keep a start number only on the item where a numbered list starts counting, and give every
|
||||
/// item that goes on counting 0 (the rule the layout numbers by, [`list_item_starts_counting`]).
|
||||
/// An imported file may carry the list's start on every line; once the list is split, the
|
||||
/// items after the split must restart at 1, not at the old start.
|
||||
pub fn keep_list_starts_where_counting_starts(&mut self) {
|
||||
if self.paragraphs.iter().all(|p| p.start_offset == 0) {
|
||||
return;
|
||||
}
|
||||
self.fill_paragraphs();
|
||||
let starts = list_item_starts_counting(&self.paragraphs);
|
||||
for (pl, starts) in self.paragraphs.iter_mut().zip(starts) {
|
||||
if !starts {
|
||||
pl.start_offset = 0;
|
||||
}
|
||||
}
|
||||
self.fold_paragraph_lists();
|
||||
}
|
||||
|
||||
/// One style for all paragraphs with no nesting or start folds back into `list`.
|
||||
fn fold_paragraph_lists(&mut self) {
|
||||
if let Some(first) = self.paragraphs.first().copied()
|
||||
&& first == (ParaList { list: first.list, ..ParaList::default() })
|
||||
&& self.paragraphs.iter().all(|p| *p == first)
|
||||
@@ -911,7 +1007,16 @@ impl TextData {
|
||||
Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list,
|
||||
_ => self.list,
|
||||
};
|
||||
ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() }
|
||||
// Every paragraph by index: `para_span` leaves out an empty one after a final newline.
|
||||
let first = self.para_wrap_style(0);
|
||||
let wrap_style = if (1..self.paragraph_count()).all(|p| self.para_wrap_style(p) == first) { first } else { self.wrap_style };
|
||||
ParagraphStyle {
|
||||
paragraph_spacing: self.paragraph_spacing,
|
||||
paragraph_indent: self.paragraph_indent,
|
||||
list,
|
||||
wrap_style,
|
||||
features: self.features.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and
|
||||
@@ -923,6 +1028,7 @@ impl TextData {
|
||||
// Every paragraph by index: `para_span` leaves out an empty one after a final newline.
|
||||
let last = self.paragraph_count() - 1;
|
||||
self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list);
|
||||
self.set_wrap_style(ps.wrap_style);
|
||||
}
|
||||
|
||||
/// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the
|
||||
@@ -933,6 +1039,7 @@ impl TextData {
|
||||
self.paragraph_indent = ps.paragraph_indent;
|
||||
self.features.clone_from(&ps.features);
|
||||
self.set_para_lists(start, end, |pl| pl.list = ps.list);
|
||||
self.set_para_wrap_styles(start, end, ps.wrap_style);
|
||||
}
|
||||
|
||||
/// Follow text style `id`'s paragraph-level definition wherever chars link to it.
|
||||
@@ -951,6 +1058,7 @@ impl TextData {
|
||||
&& self.paragraph_indent == ps.paragraph_indent
|
||||
&& self.features == ps.features
|
||||
&& self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list)
|
||||
&& self.common_wrap_style(start, end) == Some(ps.wrap_style)
|
||||
}
|
||||
|
||||
/// Whether the whole text shows what text style `ps` sets at the paragraph and layer level.
|
||||
@@ -1104,6 +1212,123 @@ mod case_tests {
|
||||
t.set_para_lists(0, 0, |p| p.list = P);
|
||||
assert_eq!(t.para_list(0), ParaList::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_style_per_paragraph_loads_from_old_files_and_folds() {
|
||||
use WrapStyle::{Auto, Balance, Pretty};
|
||||
let old = r#"{"list":"numbered","indent":1}"#;
|
||||
assert_eq!(serde_json::from_str::<ParaList>(old).unwrap().wrap, None);
|
||||
let mut t = TextData::new("a\nb");
|
||||
let key = t.layout_key();
|
||||
t.set_para_wrap_styles(0, 0, Balance);
|
||||
assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Balance, Auto));
|
||||
assert_ne!(t.layout_key(), key);
|
||||
let back: TextData = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
|
||||
assert_eq!(back, t);
|
||||
t.set_para_wrap_styles(0, 0, Auto);
|
||||
assert!(t.paragraphs.is_empty());
|
||||
t.set_para_wrap_styles(0, 0, Balance);
|
||||
t.set_wrap_style(Pretty);
|
||||
assert!(t.paragraphs.is_empty());
|
||||
assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Pretty, Pretty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_style_loads_from_old_paragraph_styles_and_texts() {
|
||||
use WrapStyle::Auto;
|
||||
// A paragraph style saved before it carried a wrap style.
|
||||
let old = r#"{"paragraph_spacing":4.0,"list":"bulleted"}"#;
|
||||
let ps: ParagraphStyle = serde_json::from_str(old).unwrap();
|
||||
assert_eq!((ps.wrap_style, ps.paragraph_spacing, ps.list), (Auto, 4.0, ListStyle::Bulleted));
|
||||
assert!(!serde_json::to_string(&ParagraphStyle::default()).unwrap().contains("wrap_style"), "Auto is not saved");
|
||||
// A text saved before its paragraphs carried a wrap style.
|
||||
let mut t = TextData::new("a\nb");
|
||||
t.set_para_lists(0, 0, |p| p.list = ListStyle::Bulleted);
|
||||
let mut v = serde_json::to_value(&t).unwrap();
|
||||
for p in v["paragraphs"].as_array_mut().unwrap() {
|
||||
assert!(p.as_object_mut().unwrap().remove("wrap").is_none(), "Auto is not saved");
|
||||
}
|
||||
v.as_object_mut().unwrap().remove("wrap_style");
|
||||
let old: TextData = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(old.wrap_style, Auto);
|
||||
assert_eq!(old.paragraphs.len(), 2);
|
||||
assert!(old.paragraphs.iter().all(|p| p.wrap.is_none()));
|
||||
assert_eq!((old.para_wrap_style(0), old.para_wrap_style(1)), (Auto, Auto));
|
||||
assert_eq!(old, t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_wrap_style_clears_an_override_on_the_empty_last_paragraph() {
|
||||
use WrapStyle::{Auto, Balance, Pretty};
|
||||
let mut t = TextData::new("ab\n");
|
||||
assert_eq!(t.paragraph_count(), 2);
|
||||
// The empty paragraph after the final newline: a caret there reaches it.
|
||||
t.set_para_wrap_styles(3, 3, Balance);
|
||||
assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Auto, Balance));
|
||||
t.set_wrap_style(Pretty);
|
||||
assert!(t.paragraphs.is_empty(), "{:?}", t.paragraphs);
|
||||
assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Pretty, Pretty));
|
||||
// Back to the layer's own style: no override is left on either paragraph.
|
||||
t.set_para_wrap_styles(3, 3, Auto);
|
||||
assert_eq!(t.para_wrap_style(1), Auto);
|
||||
t.set_wrap_style(Auto);
|
||||
assert!(t.paragraphs.is_empty());
|
||||
assert_eq!(t.common_wrap_style(0, t.char_count()), Some(Auto));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_list_starts_touches_only_starts() {
|
||||
use ListStyle::{None as P, Numbered as N};
|
||||
let mut t = TextData { characters: "a\nb\nc".into(), ..Default::default() };
|
||||
t.paragraphs = vec![
|
||||
ParaList { list: N, start_offset: 4, ..ParaList::default() },
|
||||
ParaList { list: P, indent: 1, ..ParaList::default() },
|
||||
ParaList { list: N, indent: 2, start_offset: 7, ..ParaList::default() },
|
||||
];
|
||||
t.clear_list_starts(1, 2);
|
||||
assert_eq!(t.para_list(0).start_offset, 4, "outside the range");
|
||||
assert_eq!(t.para_list(1), ParaList { list: P, indent: 1, ..ParaList::default() }, "a plain paragraph keeps its level");
|
||||
assert_eq!(t.para_list(2), ParaList { list: N, indent: 2, start_offset: 0, ..ParaList::default() });
|
||||
// Out of range and no-start cases leave it alone.
|
||||
t.clear_list_starts(5, 9);
|
||||
t.clear_list_starts(0, 0);
|
||||
assert_eq!(t.para_list(0).start_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_starts_stay_only_where_counting_starts() {
|
||||
use ListStyle::{Bulleted as B, None as P, Numbered as N};
|
||||
let pl = |list, indent, start_offset| ParaList { list, indent, start_offset, ..ParaList::default() };
|
||||
// (paragraphs, the starts kept, derivation)
|
||||
let cases: Vec<(Vec<ParaList>, Vec<u32>, &str)> = vec![
|
||||
(vec![pl(N, 0, 4), pl(N, 0, 4), pl(N, 0, 4)], vec![4, 0, 0], "items that go on counting lose theirs"),
|
||||
(vec![pl(N, 0, 4), pl(P, 0, 0), pl(N, 0, 6)], vec![4, 0, 6], "a list after a plain paragraph keeps its own"),
|
||||
(vec![pl(N, 0, 4), pl(B, 0, 0), pl(N, 0, 6)], vec![4, 0, 6], "and one after a bullet item"),
|
||||
(
|
||||
vec![pl(N, 0, 4), pl(N, 1, 2), pl(N, 1, 2), pl(N, 0, 4)],
|
||||
vec![4, 2, 0, 0],
|
||||
"a nested level keeps its first item's; the outer count goes on",
|
||||
),
|
||||
(vec![pl(N, 0, 1), pl(N, 1, 2), pl(N, 0, 9), pl(N, 1, 3)], vec![1, 2, 0, 3], "a shallower item starts the deeper count again"),
|
||||
(vec![pl(N, 255, 4), pl(N, 9, 4), pl(N, 8, 4)], vec![4, 0, 0], "levels past the deepest count as the deepest"),
|
||||
];
|
||||
for (paragraphs, want, why) in cases {
|
||||
let characters = vec!["x"; paragraphs.len()].join("\n");
|
||||
let mut t = TextData { characters, paragraphs, ..TextData::new("") };
|
||||
t.keep_list_starts_where_counting_starts();
|
||||
let got: Vec<u32> = (0..t.paragraph_count()).map(|p| t.para_list(p).start_offset).collect();
|
||||
assert_eq!(got, want, "{why}");
|
||||
}
|
||||
// No start anywhere: nothing is spelled out.
|
||||
let mut t = TextData { list: N, ..TextData::new("a\nb") };
|
||||
t.keep_list_starts_where_counting_starts();
|
||||
assert!(t.paragraphs.is_empty());
|
||||
// More entries than paragraphs, and an empty last paragraph.
|
||||
let mut t = TextData { paragraphs: vec![pl(N, 0, 4); 5], ..TextData::new("a\n") };
|
||||
t.keep_list_starts_where_counting_starts();
|
||||
assert_eq!((t.para_list(0).start_offset, t.para_list(1).start_offset), (4, 0));
|
||||
assert!(list_item_starts_counting(&[]).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1152,4 +1377,16 @@ mod whole_text_paragraph_style_tests {
|
||||
plain.take_paragraph_style(&ps);
|
||||
assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_made_from_the_whole_layer_counts_a_trailing_empty_paragraphs_wrap_style() {
|
||||
// The first two paragraphs are Balance, the empty one after the final newline keeps the
|
||||
// layer's Auto: they differ, so the style takes the layer's wrap style, not Balance.
|
||||
let mut t = TextData::new("a\nb\n");
|
||||
t.set_para_wrap_styles(0, 3, WrapStyle::Balance);
|
||||
assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1), t.para_wrap_style(2)), (WrapStyle::Balance, WrapStyle::Balance, WrapStyle::Auto));
|
||||
assert_eq!(t.paragraph_style().wrap_style, WrapStyle::Auto);
|
||||
t.set_para_wrap_styles(4, 4, WrapStyle::Balance);
|
||||
assert_eq!(t.paragraph_style().wrap_style, WrapStyle::Balance, "all three Balance");
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,13 @@ fn redirect_last_segment(net: &mut VectorNetwork, loop_segs: &[usize], from: usi
|
||||
}
|
||||
}
|
||||
|
||||
/// Which segments are in a loop, and which segments join each pair of points: the lookups
|
||||
/// [`VectorNetwork::closing_segment`] reads, built once per pass by [`VectorNetwork::loop_index`].
|
||||
pub struct LoopIndex {
|
||||
in_loop: Vec<bool>,
|
||||
by_ends: std::collections::BTreeMap<(usize, usize), Vec<usize>>,
|
||||
}
|
||||
|
||||
impl VectorNetwork {
|
||||
/// A network from a polyline / polygon.
|
||||
pub fn from_points(points: &[Point], closed: bool) -> Self {
|
||||
@@ -471,16 +478,16 @@ impl VectorNetwork {
|
||||
// The curves go between the two segments wherever a loop walks through the point, in the
|
||||
// order the loop meets them. Each loop is rebuilt in one pass, so a polygon with many
|
||||
// rounded corners isn't quadratic.
|
||||
let index = self.loop_index();
|
||||
for lp in out.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) {
|
||||
let Some(&first_idx) = lp.first() else { continue };
|
||||
let start_v = match (self.segments.get(first_idx), lp.get(1).and_then(|&i| self.segments.get(i))) {
|
||||
(Some(first), Some(second)) if first.a == second.a || first.a == second.b => first.b,
|
||||
(Some(first), _) => first.a,
|
||||
_ => 0,
|
||||
};
|
||||
let mut rebuilt = Vec::with_capacity(lp.len() + by_vertex.len().min(lp.len()));
|
||||
if lp.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let start_v = self.loop_start(lp).unwrap_or(0);
|
||||
let mut rebuilt = Vec::with_capacity(lp.len() + by_vertex.len().min(lp.len()) + 1);
|
||||
let mut cur = start_v;
|
||||
for &x in lp.iter() {
|
||||
let closing = self.closing_segment(lp, &index);
|
||||
for &x in lp.iter().chain(closing.iter()) {
|
||||
rebuilt.push(x);
|
||||
let Some(s) = self.segments.get(x) else { continue };
|
||||
cur = if s.a == cur { s.b } else { s.a };
|
||||
@@ -497,6 +504,60 @@ impl VectorNetwork {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The point loop `lp` is walked from: the end of its first segment that its second does not
|
||||
/// share.
|
||||
fn loop_start(&self, lp: &[usize]) -> Option<usize> {
|
||||
let first = self.segments.get(*lp.first()?)?;
|
||||
match lp.get(1).and_then(|&i| self.segments.get(i)) {
|
||||
Some(second) if first.a == second.a || first.a == second.b => Some(first.b),
|
||||
_ => Some(first.a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookups [`Self::closing_segment`] needs, built once for a pass over every loop.
|
||||
pub fn loop_index(&self) -> LoopIndex {
|
||||
let mut in_loop = vec![false; self.segments.len()];
|
||||
for &x in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) {
|
||||
if let Some(f) = in_loop.get_mut(x) {
|
||||
*f = true;
|
||||
}
|
||||
}
|
||||
let mut by_ends: std::collections::BTreeMap<(usize, usize), Vec<usize>> = std::collections::BTreeMap::new();
|
||||
for (i, s) in self.segments.iter().enumerate() {
|
||||
by_ends.entry((s.a.min(s.b), s.a.max(s.b))).or_default().push(i);
|
||||
}
|
||||
LoopIndex { in_loop, by_ends }
|
||||
}
|
||||
|
||||
/// The segment that joins the two ends of an open loop `lp` when it is in no loop of its own
|
||||
/// (and the only such segment): a corner cut off by a segment drawn before the corner point was
|
||||
/// deleted leaves the loop open there, and the stroke follows that segment. Only a loop that
|
||||
/// walks in order as one continuous chain has one. Rounding walks it as the loop's last
|
||||
/// segment, so the points at the loop's ends are cut by arcs as the stroke's are, and deleting
|
||||
/// points or segments puts it into the loop (#1951). `index` is this network's [`Self::loop_index`],
|
||||
/// shared by every loop of one pass.
|
||||
pub fn closing_segment(&self, lp: &[usize], index: &LoopIndex) -> Option<usize> {
|
||||
let start_v = self.loop_start(lp)?;
|
||||
let mut cur = start_v;
|
||||
for &x in lp {
|
||||
let s = self.segments.get(x)?;
|
||||
cur = if s.a == cur {
|
||||
s.b
|
||||
} else if s.b == cur {
|
||||
s.a
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
}
|
||||
if cur == start_v {
|
||||
return None;
|
||||
}
|
||||
let mut joining =
|
||||
index.by_ends.get(&(cur.min(start_v), cur.max(start_v)))?.iter().copied().filter(|&i| !index.in_loop.get(i).copied().unwrap_or(false));
|
||||
let first = joining.next()?;
|
||||
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.
|
||||
|
||||
@@ -103,3 +103,24 @@ fn a_settings_file_without_or_with_a_wrong_interface_size_reads_as_the_systems_s
|
||||
let p: crate::Prefs = serde_json::from_value(json!({"ui_scale": 99, "theme": "dark"})).unwrap();
|
||||
assert_eq!((p.ui_scale, p.theme.as_str()), (crate::UI_SCALE_MAX, "dark"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_invert_zoom_preference_toggles_and_is_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(!s.prefs.invert_zoom, "off by default");
|
||||
assert_eq!(s.execute("pref.invertZoom", &json!({})).unwrap()["on"], true);
|
||||
assert!(s.prefs.invert_zoom);
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert_eq!(saved["invert_zoom"], true);
|
||||
let loaded: crate::Prefs = serde_json::from_value(saved).unwrap();
|
||||
assert!(loaded.invert_zoom);
|
||||
assert_eq!(s.execute("pref.invertZoom", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert!(!s.prefs.invert_zoom);
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert_eq!(saved["invert_zoom"], false);
|
||||
let loaded: crate::Prefs = serde_json::from_value(saved).unwrap();
|
||||
assert!(!loaded.invert_zoom, "off persists after being on");
|
||||
// Preferences saved before the setting existed read it as off.
|
||||
let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap();
|
||||
assert!(!old.invert_zoom);
|
||||
}
|
||||
@@ -336,3 +336,36 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() {
|
||||
set(&mut s, f, json!({"layout": null, "name": "Plain"}));
|
||||
assert!(s.doc().unwrap().node(f).unwrap().layout.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() {
|
||||
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
|
||||
let mut s = Session::new();
|
||||
let f = al_frame(&mut s, json!({"gap": 10}));
|
||||
let a = rect(&mut s, f, 20.0, 20.0, "#ff0000");
|
||||
let b = rect(&mut s, f, 20.0, 20.0, "#00ff00");
|
||||
let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
|
||||
let (before_a, before_b) = (at(&s, a), at(&s, b));
|
||||
assert_eq!(before_b.x0, 30.0, "the layout placed the second one after the first");
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(!can_align(doc, &[b]), "Align is greyed out for one child of the frame");
|
||||
assert!(align_blocked_by_auto_layout(doc, &[b]), "because its frame places it");
|
||||
for cmd in ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"] {
|
||||
s.execute(cmd, &json!({"ids": [b]})).unwrap();
|
||||
assert_eq!((at(&s, a), at(&s, b)), (before_a, before_b), "{cmd} leaves the layout alone");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it() {
|
||||
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
|
||||
let mut s = Session::new();
|
||||
let f = al_frame(&mut s, json!({}));
|
||||
let kid = rect(&mut s, f, 20.0, 20.0, "#ff0000");
|
||||
set(&mut s, kid, json!({"absolute": true}));
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(can_align(doc, &[kid]));
|
||||
assert!(!align_blocked_by_auto_layout(doc, &[kid]));
|
||||
s.execute("align.right", &json!({"ids": [kid]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().world_bounds(kid).unwrap().x1, 200.0);
|
||||
}
|
||||
@@ -69,3 +69,100 @@ fn grid_drag_takes_the_cell_under_the_pointer() {
|
||||
let cl = s.doc().unwrap().node(kids[0]).unwrap().child_layout.clone();
|
||||
assert_eq!((cl.grid_column, cl.grid_row), (None, None), "one undo step");
|
||||
}
|
||||
|
||||
/// Three 60 x 60 rectangles in a row (or column), gap 20, at 0, 80 and 160 along the flow.
|
||||
fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) {
|
||||
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap());
|
||||
let kids: Vec<NodeId> =
|
||||
(0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect();
|
||||
s.execute("layout.add", &json!({"ids": [f]})).unwrap();
|
||||
s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(f, [kids[0], kids[1], kids[2]])
|
||||
}
|
||||
|
||||
/// The order after dragging kid `which` by `by` along the flow, grabbed `grab` from its start edge.
|
||||
fn dragged_order(mode: &str, which: usize, grab: f64, by: f64) -> Vec<usize> {
|
||||
let mut s = Session::new();
|
||||
let (f, kids) = three(&mut s, mode);
|
||||
let vertical = mode == "vertical";
|
||||
let b = s.doc().unwrap().world_bounds(kids[which]).unwrap();
|
||||
let from = if vertical { (b.center().x, b.y0 + grab) } else { (b.x0 + grab, b.center().y) };
|
||||
let to = if vertical { (from.0, from.1 + by) } else { (from.0 + by, from.1) };
|
||||
drag(&mut s, from, to);
|
||||
let order = s.doc().unwrap().node(f).unwrap().children.clone();
|
||||
order.iter().map(|c| kids.iter().position(|k| k == c).unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_dragged_right_passes_a_sibling_when_its_leading_edge_reaches_the_siblings_middle() {
|
||||
assert_eq!(dragged_order("horizontal", 0, 30.0, 49.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 30.0, 50.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 30.0, 129.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 30.0, 130.0), vec![1, 2, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn where_the_child_is_grabbed_does_not_change_its_slot() {
|
||||
assert_eq!(dragged_order("horizontal", 0, 10.0, 49.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 10.0, 50.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 10.0, 129.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 0, 10.0, 130.0), vec![1, 2, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_dragged_left_passes_a_sibling_by_its_left_edge() {
|
||||
assert_eq!(dragged_order("horizontal", 2, 30.0, -49.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("horizontal", 2, 30.0, -50.0), vec![0, 2, 1]);
|
||||
assert_eq!(dragged_order("horizontal", 2, 30.0, -130.0), vec![2, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_reorders_by_the_bottom_edge() {
|
||||
assert_eq!(dragged_order("vertical", 0, 30.0, 50.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("vertical", 0, 30.0, 130.0), vec![1, 2, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_dragged_left_passes_the_second_sibling_one_pixel_later() {
|
||||
assert_eq!(dragged_order("horizontal", 2, 30.0, -129.0), vec![0, 2, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_reorders_at_the_boundaries_both_ways() {
|
||||
assert_eq!(dragged_order("vertical", 0, 30.0, 49.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("vertical", 0, 30.0, 129.0), vec![1, 0, 2]);
|
||||
assert_eq!(dragged_order("vertical", 2, 30.0, -49.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("vertical", 2, 30.0, -50.0), vec![0, 2, 1]);
|
||||
assert_eq!(dragged_order("vertical", 2, 30.0, -129.0), vec![0, 2, 1]);
|
||||
assert_eq!(dragged_order("vertical", 2, 30.0, -130.0), vec![2, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_with_no_move_along_the_flow_keeps_the_slot() {
|
||||
// Back at the start, and a drag across the flow only, with snapping on (the default).
|
||||
assert_eq!(dragged_order("horizontal", 1, 30.0, 0.0), vec![0, 1, 2]);
|
||||
assert_eq!(dragged_order("vertical", 1, 30.0, 0.0), vec![0, 1, 2]);
|
||||
let mut s = Session::new();
|
||||
let (f, kids) = three(&mut s, "horizontal");
|
||||
let b = s.doc().unwrap().world_bounds(kids[1]).unwrap();
|
||||
let from = (b.center().x, b.center().y);
|
||||
drag(&mut s, from, (from.0, from.1 + 40.0));
|
||||
let order = s.doc().unwrap().node(f).unwrap().children.clone();
|
||||
assert_eq!(order, kids.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_dragged_children_use_their_combined_box() {
|
||||
// Kids 0 and 1 together span 0..140; moved right by 49 the leading edge is at 189, just short of the middle of kid 2 (190).
|
||||
for (by, expected) in [(49.0, vec![0, 1, 2]), (50.0, vec![2, 0, 1])] {
|
||||
let mut s = Session::new();
|
||||
let (f, kids) = three(&mut s, "horizontal");
|
||||
s.execute("select.set", &json!({"ids": [kids[0], kids[1]]})).unwrap();
|
||||
let b = s.doc().unwrap().world_bounds(kids[0]).unwrap();
|
||||
let from = (b.center().x, b.center().y);
|
||||
drag(&mut s, from, (from.0 + by, from.1));
|
||||
let order: Vec<usize> = s.doc().unwrap().node(f).unwrap().children.iter().map(|c| kids.iter().position(|k| k == c).unwrap()).collect();
|
||||
assert_eq!(order, expected, "by {by}");
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ pub use patch::sync_after_edit;
|
||||
pub(crate) use patch::{FULL_REBUILD, PATCHED};
|
||||
#[cfg(test)]
|
||||
use rebase::RebaseSources;
|
||||
pub use rebase::rebase_instance;
|
||||
pub use rebase::{MainPaths, rebase_instance, rebase_instance_with};
|
||||
pub use sync::keep_text_overrides;
|
||||
pub use variants::{default_variant, exposed_copies, find_variant, mirror_issues, variant_conflicts, variant_name, variant_options, variant_props};
|
||||
|
||||
@@ -298,6 +298,30 @@ pub fn prop_list(doc: &Document, c: NodeId) -> Vec<(String, PropDef)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The properties an instance of `component` lists: [`prop_list`] without the boolean, text and
|
||||
/// instance swap properties that no layer of the component reads. A set's variants share its
|
||||
/// definitions, so one a variant's layers don't bind (another variant's text, a leftover of a
|
||||
/// deleted variant) stays defined, and shows on the set, but not on this variant's instances
|
||||
/// (#2022). Slots stay. Walks as [`slots_of`] does: a nested instance counts, its own layers and
|
||||
/// the content put into slots are not entered.
|
||||
pub fn instance_prop_list(doc: &Document, component: NodeId) -> Vec<(String, PropDef)> {
|
||||
let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
let mut stack = vec![component];
|
||||
let mut seen = 0usize;
|
||||
while let Some(c) = stack.pop() {
|
||||
seen += 1;
|
||||
if seen > 1_000_000 {
|
||||
break;
|
||||
}
|
||||
let Some(n) = doc.node(c) else { continue };
|
||||
used.extend(n.prop_refs.values().cloned());
|
||||
if c == component || (!is_instance(doc, c) && !holds_content(n)) {
|
||||
stack.extend(n.children.iter().rev().copied());
|
||||
}
|
||||
}
|
||||
prop_list(doc, component).into_iter().filter(|(k, d)| !takes_value(d) || used.contains(k)).collect()
|
||||
}
|
||||
|
||||
/// Whether instances store a value for the property (every kind but slots).
|
||||
pub fn takes_value(d: &PropDef) -> bool {
|
||||
!matches!(d, PropDef::Slot { .. })
|
||||
|
||||
@@ -165,10 +165,28 @@ impl<'a> RebaseSources<'a> {
|
||||
/// values (after detaching an outer instance, restoring a main, or copying a nested instance out):
|
||||
/// the look is kept exactly. Values a component property sets aren't overrides.
|
||||
pub fn rebase_instance(doc: &mut Document, inst: NodeId) {
|
||||
rebase_instance_with(doc, inst, &mut MainPaths::new());
|
||||
}
|
||||
|
||||
/// The layers of mains by path, kept across several [`rebase_instance_with`] calls. Rebasing only
|
||||
/// writes instances' `source` and `overrides`, never a main's layers or names, so a main's paths
|
||||
/// stay right for as long as the caller changes nothing else.
|
||||
pub type MainPaths = BTreeMap<NodeId, std::rc::Rc<BTreeMap<String, NodeId>>>;
|
||||
|
||||
/// [`rebase_instance`], taking each main's path map from `mains` (and adding it there).
|
||||
pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPaths) {
|
||||
let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|n| n.kind.clone()) else { return };
|
||||
let mine = path_map(doc, inst, true);
|
||||
let theirs: BTreeMap<String, NodeId> =
|
||||
if doc.contains(component) { path_map(doc, component, false).into_iter().map(|(k, v)| (v, k)).collect() } else { BTreeMap::new() };
|
||||
let theirs = mains
|
||||
.entry(component)
|
||||
.or_insert_with(|| {
|
||||
std::rc::Rc::new(if doc.contains(component) {
|
||||
path_map(doc, component, false).into_iter().map(|(k, v)| (v, k)).collect()
|
||||
} else {
|
||||
BTreeMap::new()
|
||||
})
|
||||
})
|
||||
.clone();
|
||||
let value_groups = |a: &Node, b: &Node| -> Vec<String> {
|
||||
diff_groups(a, b).into_iter().filter(|g| !matches!(*g, "size" | "position")).map(str::to_string).collect()
|
||||
};
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn sync_instance_depth(doc: &mut Document, inst: NodeId, depth: usize
|
||||
let nid = doc.alloc_id();
|
||||
map.insert(s, nid);
|
||||
}
|
||||
let Copies { nodes: new_nodes, nested, mut remeasure } = copy_layers(doc, inst, &src, &map, &old, &edited, eff_props);
|
||||
let Copies { nodes: new_nodes, nested, mut remeasure } = copy_layers(doc, inst, component, &src, &map, &old, &edited, eff_props);
|
||||
for n in new_nodes {
|
||||
let (id, parent) = (n.id, n.parent);
|
||||
if insert_linked(doc, n).is_err()
|
||||
@@ -132,6 +132,7 @@ struct Copies {
|
||||
fn copy_layers(
|
||||
doc: &Document,
|
||||
inst: NodeId,
|
||||
component: NodeId,
|
||||
src: &[NodeId],
|
||||
map: &BTreeMap<NodeId, NodeId>,
|
||||
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
|
||||
@@ -139,7 +140,7 @@ fn copy_layers(
|
||||
props: BTreeMap<String, Value>,
|
||||
) -> Copies {
|
||||
let mut enclosing: BTreeMap<NodeId, Vec<NodeId>> = BTreeMap::from([(inst, vec![inst])]);
|
||||
let mut inst_props: BTreeMap<NodeId, BTreeMap<String, Value>> = BTreeMap::from([(inst, props)]);
|
||||
let mut inst_props: BTreeMap<NodeId, (NodeId, BTreeMap<String, Value>)> = BTreeMap::from([(inst, (component, props))]);
|
||||
let mut out = Copies { nodes: Vec::new(), nested: Vec::new(), remeasure: Vec::new() };
|
||||
for s in src {
|
||||
let Some(orig) = doc.node(*s) else { continue };
|
||||
@@ -164,12 +165,12 @@ fn copy_layers(
|
||||
// No longer a slot in the main: it mirrors the main again.
|
||||
n.overrides.remove(SLOT);
|
||||
}
|
||||
// Component properties: the main layer's bindings use this instance's values; layers of
|
||||
// nested instances use the nested instance's values (one level per source hop).
|
||||
// Bindings use the enclosing instance of their defining component, even when slot
|
||||
// content has fewer source hops than enclosing instances.
|
||||
let enc = enclosing.get(&parent).cloned().unwrap_or_default();
|
||||
apply_enclosing_props(doc, &mut n, orig, &enc, &inst_props);
|
||||
if let NodeKind::Instance { component: c, props } = &n.kind {
|
||||
inst_props.insert(nid, props.clone());
|
||||
inst_props.insert(nid, (*c, props.clone()));
|
||||
let mut e = enc;
|
||||
e.push(nid);
|
||||
enclosing.insert(nid, e);
|
||||
@@ -253,14 +254,28 @@ fn rebuild_nested(doc: &mut Document, nested: Vec<NodeId>, old: &BTreeMap<NodeId
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_enclosing_props(doc: &Document, n: &mut Node, orig: &Node, enc: &[NodeId], inst_props: &BTreeMap<NodeId, BTreeMap<String, Value>>) {
|
||||
/// Apply bindings from their defining components, preserving explicit overrides and letting
|
||||
/// nearer source layers take precedence. Slot content need not have one source hop per instance.
|
||||
fn apply_enclosing_props(
|
||||
doc: &Document,
|
||||
n: &mut Node,
|
||||
orig: &Node,
|
||||
enc: &[NodeId],
|
||||
inst_props: &BTreeMap<NodeId, (NodeId, BTreeMap<String, Value>)>,
|
||||
) {
|
||||
let mut chain: Vec<&Node> = vec![orig];
|
||||
while chain.len() < enc.len() {
|
||||
let Some(next) = chain.last().and_then(|c| c.source).and_then(|x| doc.node(x)) else { break };
|
||||
chain.push(next);
|
||||
}
|
||||
for (j, level) in chain.iter().enumerate().rev() {
|
||||
let Some(props) = enc.get(j).and_then(|e| inst_props.get(e)) else { continue };
|
||||
if level.prop_refs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(owner) = owning_component(doc, level.id) else { continue };
|
||||
// Instance-owned slot content skips a source hop through the slot's component. Match
|
||||
// the binding's defining component, not the position in the enclosing instance chain.
|
||||
let Some((_, props)) = enc.iter().rev().filter_map(|e| inst_props.get(e)).find(|(component, _)| *component == owner) else { continue };
|
||||
for (field, prop) in &level.prop_refs {
|
||||
let g = field_group(field);
|
||||
if n.overrides.contains(g) || (j > 0 && orig.overrides.contains(g)) {
|
||||
|
||||
@@ -395,8 +395,11 @@ fn unbind_delete_and_vary(s: &mut Session, c: NodeId, i: NodeId, title: NodeId,
|
||||
ex(s, "component.deleteProperty", json!({"id": c, "name": "Heading"}));
|
||||
assert!(node(s, title).prop_refs.is_empty());
|
||||
assert!(matches!(&node(s, i).kind, NodeKind::Instance { props, .. } if !props.contains_key("Heading")));
|
||||
let desc = ex(s, "component.properties", json!({"id": i}));
|
||||
// "Show dot" is still defined but no layer reads it any more: the main lists it, the instance doesn't (#2022).
|
||||
let desc = ex(s, "component.properties", json!({"id": c}));
|
||||
assert_eq!(desc["properties"].as_array().unwrap().len(), 1);
|
||||
let desc = ex(s, "component.properties", json!({"id": i}));
|
||||
assert!(desc["properties"].as_array().unwrap().is_empty());
|
||||
// A variant property on a lone component makes it a component set.
|
||||
let set = idv(&ex(s, "component.addProperty", json!({"id": c, "name": "Theme", "type": "variant", "default": "Light"})));
|
||||
assert!(matches!(node(s, set).kind, NodeKind::ComponentSet { .. }));
|
||||
|
||||
@@ -628,6 +628,90 @@ pub fn absolute_path(path: &str) -> String {
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
/// `path` with `.` and `..` taken out without asking the file system (`..` at the root stays there).
|
||||
fn lexical(path: &std::path::Path) -> std::path::PathBuf {
|
||||
use std::path::Component;
|
||||
let mut out = std::path::PathBuf::new();
|
||||
for c in path.components() {
|
||||
match c {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir if matches!(out.components().next_back(), Some(Component::Normal(_))) => {
|
||||
out.pop();
|
||||
}
|
||||
Component::ParentDir if out.has_root() => {}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The folder of the document saved at `doc_path`, absolute.
|
||||
fn doc_folder(doc_path: &str) -> Option<std::path::PathBuf> {
|
||||
lexical(std::path::Path::new(&absolute_path(doc_path))).parent().map(std::path::Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// Library file `lib` from the folder of the document at `doc_path`, '/'-separated; `None` when
|
||||
/// there is no such path (another drive, say).
|
||||
fn relative_to(doc_path: &str, lib: &str) -> Option<String> {
|
||||
use std::path::Component;
|
||||
let folder = doc_folder(doc_path)?;
|
||||
let lib = lexical(std::path::Path::new(&absolute_path(lib)));
|
||||
let (from, to): (Vec<_>, Vec<_>) = (folder.components().collect(), lib.components().collect());
|
||||
let same = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
|
||||
// Not even the root in common: no relative path leads there.
|
||||
if same == 0 || !matches!(to.get(same..), Some([_, ..])) {
|
||||
return None;
|
||||
}
|
||||
let up = from.get(same..).unwrap_or_default().iter().map(|_| Some(".."));
|
||||
let down = to.get(same..).unwrap_or_default().iter().map(|c| match c {
|
||||
Component::Normal(s) => s.to_str(),
|
||||
_ => None,
|
||||
});
|
||||
up.chain(down).collect::<Option<Vec<_>>>().map(|parts| parts.join("/"))
|
||||
}
|
||||
|
||||
/// Before saving the document to `doc_path`: each library file link also says where the file is
|
||||
/// from the document's folder ([`LibraryLink::relative`]).
|
||||
pub fn relate_links(doc: &mut Document, doc_path: &str) {
|
||||
if doc.libraries.enabled.is_empty() {
|
||||
return;
|
||||
}
|
||||
for l in &mut doc.libraries_mut().enabled {
|
||||
l.relative = if crate::library_server::is_server_link(&l.path) { None } else { relative_to(doc_path, &l.path) }.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
/// After opening the document at `doc_path`: library file links go by its folder. A library
|
||||
/// found at its [relative](LibraryLink::relative) place is followed (the folder was moved or
|
||||
/// cloned), and a relative `path` is taken from the document's folder, not the working directory.
|
||||
/// The open document keeps only the absolute `path`.
|
||||
pub fn resolve_links(doc: &mut Document, doc_path: &str) {
|
||||
if doc.libraries.enabled.iter().all(|l| crate::library_server::is_server_link(&l.path) && l.relative.is_empty()) {
|
||||
return;
|
||||
}
|
||||
let Some(folder) = doc_folder(doc_path) else { return };
|
||||
for l in &mut doc.libraries_mut().enabled {
|
||||
if crate::library_server::is_server_link(&l.path) {
|
||||
l.relative.clear();
|
||||
continue;
|
||||
}
|
||||
let moved = Some(l.relative.as_str()).filter(|r| !r.is_empty()).map(|r| lexical(&folder.join(r)));
|
||||
// Only a place on this computer is looked at (see `Session::fetch_library`).
|
||||
if let Some(p) =
|
||||
moved.filter(|p| p.to_str().is_some_and(craft_docpath::is_local) && crate::file_access::metadata(p).is_ok_and(|m| m.is_file()))
|
||||
{
|
||||
l.path = p.to_string_lossy().into_owned();
|
||||
} else if !l.path.is_empty()
|
||||
&& std::path::Path::new(&l.path).is_relative()
|
||||
&& let Some(p) = lexical(&folder.join(&l.path)).to_str().filter(|p| craft_docpath::is_local(p))
|
||||
{
|
||||
l.path = p.to_string();
|
||||
}
|
||||
// Written again on each save, from `path`.
|
||||
l.relative.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The enabled library `key` (its id, name or path).
|
||||
pub fn find_link<'a>(doc: &'a Document, key: &str) -> Option<&'a LibraryLink> {
|
||||
let l = &doc.libraries.enabled;
|
||||
@@ -1257,7 +1341,13 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
|
||||
if doc.libraries.link(&m.id).is_none()
|
||||
&& let Some(path) = src_path
|
||||
{
|
||||
doc.libraries_mut().enabled.push(LibraryLink { id: m.id.clone(), name: m.name.clone(), path: path.to_string(), version: m.version });
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,3 +641,57 @@ fn a_file_stamp_from_the_moment_it_was_read_does_not_prove_it_unchanged() {
|
||||
assert!(entry(old).still_valid(&Stamp { len: 10, modified: Some(old) }));
|
||||
assert!(!entry(old).still_valid(&Stamp { len: 11, modified: Some(old) }));
|
||||
}
|
||||
|
||||
/// Library `lid` is listed without an error, and `library.updates` reports no errors.
|
||||
fn link_found(s: &mut Session, lid: &str) {
|
||||
let list = ex(s, "library.list", json!({}));
|
||||
let l = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == lid).unwrap_or_else(|| panic!("{list}"));
|
||||
assert!(l.get("error").is_none_or(Value::is_null), "{l}");
|
||||
let u = ex(s, "library.updates", json!({}));
|
||||
assert_eq!(u["errors"], json!([]), "{u}");
|
||||
}
|
||||
|
||||
/// A library next to the documents that use it stays linked when their folder is moved or cloned;
|
||||
/// files from before relative links, and relative paths written by hand, keep working too.
|
||||
#[test]
|
||||
fn library_links_follow_a_moved_folder() {
|
||||
let d = dir("moved-folder");
|
||||
let (a, b) = (d.join("a"), d.join("b"));
|
||||
std::fs::create_dir_all(a.join("lib")).unwrap();
|
||||
std::fs::create_dir_all(a.join("pages")).unwrap();
|
||||
let mut lib = Session::new();
|
||||
kit(&mut lib);
|
||||
let lid = publish_to(&mut lib, &path_str(&a.join("lib").join("kit.figcraft")));
|
||||
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.saveAs", json!({"path": path_str(&a.join("pages").join("Page.figcraft"))}));
|
||||
ex(&mut s, "library.add", json!({"path": path_str(&a.join("lib").join("kit.figcraft"))}));
|
||||
ex(&mut s, "library.place", json!({"library": lid, "component": "Card", "x": 0, "y": 0}));
|
||||
ex(&mut s, "file.save", json!({}));
|
||||
// The folder moves (or is cloned elsewhere): the library keeps its place next to the page.
|
||||
std::fs::rename(&a, &b).unwrap();
|
||||
let mut moved = Session::empty();
|
||||
ex(&mut moved, "file.open", json!({"path": path_str(&b.join("pages").join("Page.figcraft"))}));
|
||||
link_found(&mut moved, &lid);
|
||||
|
||||
// A file from before relative links: the absolute path is followed.
|
||||
let old = d.join("old");
|
||||
std::fs::create_dir_all(&old).unwrap();
|
||||
let mut doc = Document::new("Old");
|
||||
let abs = path_str(&b.join("lib").join("kit.figcraft"));
|
||||
doc.libraries_mut().enabled.push(LibraryLink { id: lid.clone(), name: "Kit".into(), path: abs, version: 1, ..Default::default() });
|
||||
std::fs::write(old.join("Old.figcraft"), figcraft_format::save_bytes(&doc, None).unwrap()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
ex(&mut s, "file.open", json!({"path": path_str(&old.join("Old.figcraft"))}));
|
||||
link_found(&mut s, &lid);
|
||||
|
||||
// A relative path written by hand goes by the document's folder, not the working directory.
|
||||
let mut doc = Document::new("Hand");
|
||||
let rel = "../lib/kit.figcraft".to_string();
|
||||
doc.libraries_mut().enabled.push(LibraryLink { id: lid.clone(), name: "Kit".into(), path: rel, version: 1, ..Default::default() });
|
||||
std::fs::write(b.join("pages").join("Hand.figcraft"), figcraft_format::save_bytes(&doc, None).unwrap()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
ex(&mut s, "file.open", json!({"path": path_str(&b.join("pages").join("Hand.figcraft"))}));
|
||||
link_found(&mut s, &lid);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Variables bound inside shared styles. A style's `bound` map names fields of its own value in
|
||||
//! the keys a layer's bindings use (`fills/<i>/color`, `fills/<i>/stops/<j>/color`,
|
||||
//! `effects/<i>/<field>`, `layoutGrids/<i>/<field>`, a text style's `fontSize`, `lineHeight`,
|
||||
//! `letterSpacing`, `fontFamily`, `fontStyle`). Each layer using the style sees those fields
|
||||
//! `letterSpacing`, `fontWeight`, `fontFamily`, `fontStyle`; a number weight and a style name set the
|
||||
//! same property, the weight wins). Each layer using the style sees those fields
|
||||
//! resolved in its own modes; the style itself stores them resolved in the default modes.
|
||||
|
||||
use std::borrow::Cow;
|
||||
@@ -32,7 +33,7 @@ pub fn field_type(kind: &StyleKind, key: &str) -> Option<VariableType> {
|
||||
(StyleKind::Effect { effects }, Some((BoundList::Effects, i, field))) => effect_field_type(&effects.get(i)?.kind, field),
|
||||
(StyleKind::Grid { grids }, Some((BoundList::Grids, i, "size" | "count" | "gutter" | "offset"))) => grids.get(i).map(|_| Number),
|
||||
(StyleKind::Text { .. }, None) => match key {
|
||||
"fontSize" | "lineHeight" | "letterSpacing" => Some(Number),
|
||||
"fontSize" | "lineHeight" | "letterSpacing" | "fontWeight" => Some(Number),
|
||||
"fontFamily" | "fontStyle" => Some(String),
|
||||
_ => None,
|
||||
},
|
||||
@@ -70,6 +71,7 @@ pub fn field_scopes(kind: &StyleKind, key: &str) -> Option<&'static [&'static st
|
||||
"letterSpacing" => &["LETTER_SPACING"],
|
||||
"fontFamily" => &["FONT_FAMILY"],
|
||||
"fontStyle" => &["FONT_STYLE"],
|
||||
"fontWeight" => &["FONT_WEIGHT"],
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
@@ -111,6 +113,8 @@ pub fn from_layer(n: &Node, field: &str, kind: &StyleKind) -> BTreeMap<String, V
|
||||
/// `st`'s value with its bound fields resolved in `modes`.
|
||||
fn resolved(vars: &Variables, st: &Style, modes: &Modes) -> StyleKind {
|
||||
let mut kind = st.kind.clone();
|
||||
// `bound` is a BTreeMap, so `fontStyle` applies before `fontWeight` and a weight wins when a file carries both
|
||||
// (pinned by `font_weight_wins_over_font_style_when_a_file_carries_both`).
|
||||
for (key, var) in &st.bound {
|
||||
let Some(val) = vars.resolve(var, modes) else { continue };
|
||||
match (&mut kind, list_binding(key), &val) {
|
||||
@@ -134,7 +138,14 @@ fn set_text_field(style: &mut TextStyle, key: &str, val: &VariableValue) {
|
||||
("lineHeight", VariableValue::Number(x)) if x.is_finite() => style.line_height = LineHeight::Pixels(x.clamp(0.0, 100_000.0)),
|
||||
("letterSpacing", VariableValue::Number(x)) if x.is_finite() => style.letter_spacing = LetterSpacing::Pixels(x.clamp(-10_000.0, 10_000.0)),
|
||||
("fontFamily", VariableValue::String(f)) if !f.trim().is_empty() => style.font_family = f.clone(),
|
||||
("fontStyle", VariableValue::String(f)) if !f.trim().is_empty() => style.font_style = f.clone(),
|
||||
("fontStyle", VariableValue::String(f)) if !f.trim().is_empty() => style.set_font_style(f.clone()),
|
||||
("fontWeight", VariableValue::Number(x)) if x.is_finite() => {
|
||||
// The face nearest the number (a static family) and the `wght` axis (a variable font).
|
||||
let w = x.clamp(1.0, 1000.0);
|
||||
let italic = style.italic();
|
||||
style.set_font_style(crate::cmd::props::styled_name(crate::cmd::props::weight_name(w as u16), italic));
|
||||
style.variations.insert("wght".to_string(), w);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! What a file's number variables measure, so exported tokens carry the right unit: a radius,
|
||||
//! font size, spacing or other length is in pixels, opacity and font weight are bare numbers.
|
||||
//! A number's role comes from the layer fields bound to it, else its scopes, and an alias target
|
||||
//! A number's role comes from the layer fields bound to it (and a text style's weight), else its scopes, and an alias target
|
||||
//! with no role of its own takes the role of the variables that read it (the target of an opacity
|
||||
//! alias stays unitless). A number nothing tells about is a length: design tokens mostly are.
|
||||
|
||||
@@ -60,6 +60,13 @@ impl Roles {
|
||||
}
|
||||
}
|
||||
}
|
||||
for st in &doc.styles {
|
||||
for (field, id) in &st.bound {
|
||||
if field == "fontWeight" {
|
||||
roles.entry(id.clone()).or_insert(NumberRole::Unitless);
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in vars.iter().filter(|v| v.kind == VariableType::Number) {
|
||||
if let Some(r) = v.scopes.as_ref().and_then(|s| s.iter().find_map(|s| role_of_scope(s))) {
|
||||
roles.entry(v.id.clone()).or_insert(r);
|
||||
|
||||
@@ -12,6 +12,11 @@
|
||||
//! existing folder is resolved and the rest must be plain names. The comparison is by whole
|
||||
//! components (`/work2` is not inside `/work`), and the I/O uses the resolved path, so what was
|
||||
//! checked is what is opened.
|
||||
//!
|
||||
//! On Windows, resolving a path opens it, and opening a path on another computer contacts that
|
||||
//! computer and may send it the signed-in user's credentials. So on Windows, before anything is
|
||||
//! resolved, a path on another computer whose share no root is on, a device path, or one reached
|
||||
//! through a link that leads to them is refused by how it is spelled (#1094).
|
||||
#![allow(clippy::disallowed_methods)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -19,6 +24,8 @@ use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_docpath::Refused;
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// What a command does with a file.
|
||||
@@ -58,6 +65,19 @@ impl Roots {
|
||||
Access::Read => ([self.read.as_slice(), self.write.as_slice()].concat(), "read"),
|
||||
Access::Write => (self.write.clone(), "written"),
|
||||
};
|
||||
if cfg!(windows) {
|
||||
match refused_unresolved(path, &roots) {
|
||||
Some(Unresolved::Spelled(Refused::Network)) => {
|
||||
return Err(format!(
|
||||
"automation path rejected: {asked} is on another computer, and no folder that may be {what} is on its share"
|
||||
));
|
||||
}
|
||||
Some(Unresolved::Spelled(_)) => return Err(format!("automation path rejected: {asked} names a device, not a file")),
|
||||
// Where a link leads is only told by the usual message: it would say what is there.
|
||||
Some(Unresolved::Linked) => return Err(outside(asked, &roots, what)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
match resolve(path) {
|
||||
Ok(resolved) if roots.iter().any(|r| resolved.starts_with(r)) => return Ok(resolved),
|
||||
Ok(_) => {}
|
||||
@@ -65,11 +85,7 @@ impl Roots {
|
||||
Err(why) if inside_as_far_as_it_exists(path, &roots) => return Err(format!("automation path rejected: {asked}: {why}")),
|
||||
Err(_) => {}
|
||||
}
|
||||
if roots.is_empty() {
|
||||
return Err(format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}"));
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
|
||||
Err(format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", ")))
|
||||
Err(outside(asked, &roots, what))
|
||||
}
|
||||
|
||||
/// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`.
|
||||
@@ -79,23 +95,165 @@ impl Roots {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `asked` is refused: it is outside every one of `roots`, the folders that may be `what`
|
||||
/// ("read" or "written"). The message lists those folders, or says that no folder may be `what`
|
||||
/// when `roots` is empty.
|
||||
fn outside(asked: std::path::Display<'_>, roots: &[PathBuf], what: &str) -> String {
|
||||
if roots.is_empty() {
|
||||
return format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}");
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
|
||||
format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", "))
|
||||
}
|
||||
|
||||
/// Why a path is refused before it is resolved (#1094).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Unresolved {
|
||||
/// Its spelling leads to another computer ([`Refused::Network`]) or a device ([`Refused::Device`]).
|
||||
Spelled(Refused),
|
||||
/// A link on the way leads there, or the way there can't be looked at: a link or folder on it
|
||||
/// can't be read, it has more than [`MAX_LINKS`] links, or the path can't be made absolute.
|
||||
Linked,
|
||||
}
|
||||
|
||||
/// How many links are followed on the way to a path before it is given up on, as on Linux.
|
||||
const MAX_LINKS: u8 = 40;
|
||||
|
||||
/// Why `path` is refused before anything on the way to it is opened, if it is: resolving it would
|
||||
/// open a path on another computer, which on Windows contacts that computer and may send it the
|
||||
/// signed-in user's credentials, or open a device (#1094). That is the case when the path as
|
||||
/// given or made absolute is refused by its spelling ([`refused_spelling`]), or when a link on
|
||||
/// the way, or on the way on from where one leads, leads to such a path ([`link_refused`]). A path
|
||||
/// 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> {
|
||||
// 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.
|
||||
let Ok(abs) = std::path::absolute(path) else { return Some(Unresolved::Linked) };
|
||||
if let Some(why) = [path, abs.as_path()].into_iter().find_map(|p| refused_spelling(&p.to_string_lossy(), roots)) {
|
||||
return Some(Unresolved::Spelled(why));
|
||||
}
|
||||
link_refused(&abs, roots, MAX_LINKS, &on_disk).then_some(Unresolved::Linked)
|
||||
}
|
||||
|
||||
/// What is at a path, looked at without following a link there.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Entry {
|
||||
/// Nothing ([`nothing_there`]): resolving the path meets the same there and goes no further.
|
||||
Missing,
|
||||
/// Something that can't be looked at (no permission, for one). It may be a link that resolving
|
||||
/// the path would still follow, so the path is refused.
|
||||
Unreadable,
|
||||
/// A file or a folder.
|
||||
Plain,
|
||||
/// A link, with where it leads (`None` when that can't be read).
|
||||
Link(Option<PathBuf>),
|
||||
}
|
||||
|
||||
/// What is at `p` on disk (see [`Entry`]), looked at with [`std::fs::symlink_metadata`], which
|
||||
/// doesn't follow a link there; a link's target is read with [`std::fs::read_link`].
|
||||
fn on_disk(p: &Path) -> Entry {
|
||||
match std::fs::symlink_metadata(p) {
|
||||
Ok(m) if m.is_symlink() => Entry::Link(std::fs::read_link(p).ok()),
|
||||
Ok(_) => Entry::Plain,
|
||||
Err(e) if nothing_there(&e) => Entry::Missing,
|
||||
Err(_) => Entry::Unreadable,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether looking at a path failed with `e` because nothing is there: no such name, a file where
|
||||
/// a folder was expected, or a name no file can have. Any other failure says nothing about what is
|
||||
/// there.
|
||||
fn nothing_there(e: &std::io::Error) -> bool {
|
||||
use std::io::ErrorKind::{InvalidFilename, NotADirectory, NotFound};
|
||||
matches!(e.kind(), NotFound | NotADirectory | InvalidFilename)
|
||||
}
|
||||
|
||||
/// Why path `p` is refused by its spelling alone, if it is (see [`craft_docpath::resolve`], which
|
||||
/// reads both `/` and `\` as separators and compares names ignoring case):
|
||||
/// - on another computer (`\\server\share`, `//server/share`, `\\?\UNC\…`, `\\.\UNC\…`, or a
|
||||
/// server without a share) and on no root's share;
|
||||
/// - a device path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`, `\\.\C:\…`), other than a local volume's
|
||||
/// `\\?\Volume{…}\` or `\\.\Volume{…}\`, which a folder can be mounted as;
|
||||
/// - or with a device name (`CON`, `NUL`, `COM1.png`, `lpt1 `…) as any of its names: each folder on
|
||||
/// 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> {
|
||||
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.
|
||||
Err(Refused::Network) if !roots.iter().any(|r| craft_docpath::resolve(p, Some(r)) != Err(Refused::Network)) => {
|
||||
return Some(Refused::Network);
|
||||
}
|
||||
Err(Refused::Device) if !is_volume(p) => return Some(Refused::Device),
|
||||
_ => {}
|
||||
}
|
||||
// `craft_docpath` stops at the first name it refuses, which may not be the device's.
|
||||
p.split(['\\', '/']).any(device_name).then_some(Refused::Device)
|
||||
}
|
||||
|
||||
/// Whether `p` is in a local volume by its `\\?\Volume{…}` (or `\\.\Volume{…}`) name.
|
||||
fn is_volume(p: &str) -> bool {
|
||||
let mut names = p.split(['\\', '/']);
|
||||
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('}')
|
||||
}
|
||||
|
||||
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
|
||||
/// refuses, following at most `links` links: one that leads to another, or on through further
|
||||
/// links, is followed too, as resolving the path would. A link that can't be read, a name on the
|
||||
/// way that can't be looked at ([`Entry::Unreadable`]), or more links than that, are refused as
|
||||
/// well. Each name on the way is looked at with `look` ([`on_disk`]), which doesn't follow a
|
||||
/// link: where a link leads is looked at only once its spelling is known not to be refused.
|
||||
fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -> Entry) -> bool {
|
||||
let mut at = PathBuf::new();
|
||||
let mut rest = abs.components();
|
||||
while let Some(c) = rest.next() {
|
||||
at.push(c);
|
||||
if !matches!(c, Component::Normal(_)) {
|
||||
continue;
|
||||
}
|
||||
let target = match look(&at) {
|
||||
Entry::Plain => continue,
|
||||
// Nothing is below what isn't there, so no link either.
|
||||
Entry::Missing => return false,
|
||||
Entry::Unreadable => return true,
|
||||
Entry::Link(target) => target,
|
||||
};
|
||||
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { 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);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `p` with its `.` and `..` taken by name, as Windows takes them.
|
||||
fn lexical(p: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for c in p.components() {
|
||||
match c {
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
Component::CurDir => {}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `path` lies in one of `roots` once made absolute with its `.` and `..` taken by name and
|
||||
/// its longest leading part that exists resolved, so links on the way are followed as the roots'
|
||||
/// were (`/tmp/work/x` is inside root `/private/tmp/work`, a link out of a root leads out of it).
|
||||
fn inside_as_far_as_it_exists(path: &Path, roots: &[PathBuf]) -> bool {
|
||||
let Ok(abs) = std::path::absolute(path) else { return false };
|
||||
let mut lexical = PathBuf::new();
|
||||
for c in abs.components() {
|
||||
match c {
|
||||
Component::ParentDir => {
|
||||
lexical.pop();
|
||||
}
|
||||
Component::CurDir => {}
|
||||
c => lexical.push(c),
|
||||
}
|
||||
}
|
||||
let folded = lexical(&abs);
|
||||
let mut rest: Vec<&OsStr> = Vec::new();
|
||||
let mut at = lexical.as_path();
|
||||
let mut at = folded.as_path();
|
||||
let resolved = loop {
|
||||
if let Ok(mut base) = std::fs::canonicalize(at) {
|
||||
base.extend(rest.iter().rev());
|
||||
@@ -169,18 +327,24 @@ fn resolve(path: &Path) -> std::result::Result<PathBuf, String> {
|
||||
fn plain_name(name: &OsStr) -> std::result::Result<(), String> {
|
||||
if cfg!(windows) {
|
||||
let n = name.to_string_lossy();
|
||||
let stem = n.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
|
||||
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|
||||
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
|
||||
&& stem.chars().count() == 4
|
||||
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')));
|
||||
if device || n.contains(':') {
|
||||
if device_name(&n) || n.contains(':') {
|
||||
return Err(format!("`{n}` is a device or stream name, not a file"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether Windows opens a device for file or folder name `n`: `CON`, `PRN`, `AUX`, `NUL`,
|
||||
/// `CONIN$`, `CONOUT$`, `COM1`…`COM9` and `LPT1`…`LPT9` (also with `¹`, `²` or `³`), in any case,
|
||||
/// and with anything after a dot or a colon or trailing spaces (`nul.txt`, `COM1 .png`, `con:x`).
|
||||
fn device_name(n: &str) -> bool {
|
||||
let stem = n.split(['.', ':']).next().unwrap_or_default().trim_end().to_ascii_uppercase();
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|
||||
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
|
||||
&& stem.chars().count() == 4
|
||||
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
@@ -191,6 +191,283 @@ fn windows_case_devices_and_streams() {
|
||||
assert!(!e.contains(r"\\?\"), "{e}");
|
||||
}
|
||||
|
||||
/// How each spelling of a path on another computer or of a device is told apart from a local path
|
||||
/// (#1094), on every system: only Windows checks them, but they are spelled the same everywhere.
|
||||
#[test]
|
||||
fn spellings_of_other_computers_and_devices_are_refused() {
|
||||
use super::refused_spelling;
|
||||
use craft_docpath::Refused::{Device, Network};
|
||||
let local = [PathBuf::from(r"C:\work")];
|
||||
// On `\\192.0.2.1\share`.
|
||||
let on_the_share = [
|
||||
r"\\192.0.2.1\share\x.png",
|
||||
"//192.0.2.1/share/x.png",
|
||||
r"\/192.0.2.1/share\x.png",
|
||||
r"\\?\UNC\192.0.2.1\share\x.png",
|
||||
r"\\?\unc\192.0.2.1\share\x.png",
|
||||
"//?/UNC/192.0.2.1/share/x.png",
|
||||
r"\\.\UNC\192.0.2.1\share\x.png",
|
||||
];
|
||||
let elsewhere = [
|
||||
// A server without a share is contacted too.
|
||||
r"\\192.0.2.1",
|
||||
r"\\192.0.2.1\",
|
||||
r"\\SERVER.\share \x.png",
|
||||
];
|
||||
let network = [&on_the_share[..], &elsewhere[..]].concat();
|
||||
let device = [
|
||||
r"\\.\pipe\figcraft",
|
||||
r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png",
|
||||
r"\\.\C:\work\x.png",
|
||||
r"\\.\COM1",
|
||||
r"\??\UNC\192.0.2.1\share\x.png",
|
||||
// A device name anywhere: each folder on the way is opened as the path is resolved.
|
||||
r"C:\work\COM1",
|
||||
r"C:\work\nul.txt",
|
||||
r"C:\work\Com1 .png",
|
||||
r"C:\work\lpt1.\x.png",
|
||||
r"C:\work\LPT³\x.png",
|
||||
r"C:\work\conout$",
|
||||
r"C:\work\aux:stream",
|
||||
// After a name `craft_docpath` refuses for another reason.
|
||||
r"C:\work\a:b\prn.png",
|
||||
];
|
||||
let fine = [
|
||||
r"C:\work\x.png",
|
||||
r"\\?\C:\work\x.png",
|
||||
r"C:\work\console.png",
|
||||
r"C:\work\com10.png",
|
||||
r"C:\work\lpt.png",
|
||||
r"C:\work\nul-ish.txt",
|
||||
r"\\?\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
|
||||
r"\\.\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
|
||||
"/home/u/work/x.png",
|
||||
"x.png",
|
||||
r"..\x.png",
|
||||
];
|
||||
for (paths, want) in [(&network[..], Some(Network)), (&device[..], Some(Device)), (&fine[..], None)] {
|
||||
for p in paths {
|
||||
assert_eq!(refused_spelling(p, &[]), want, "{p}");
|
||||
assert_eq!(refused_spelling(p, &local), want, "{p} with a local root");
|
||||
}
|
||||
}
|
||||
// A root on a share lets the paths on that share through, in any case and spelling, and only them:
|
||||
// every spelling above of a path on `\\192.0.2.1\share`, but not the server without a share
|
||||
// or another server.
|
||||
for root in [r"\\?\UNC\192.0.2.1\share", r"\\192.0.2.1\share\work"] {
|
||||
let on_share = [PathBuf::from(root)];
|
||||
for p in on_the_share {
|
||||
assert_eq!(refused_spelling(p, &on_share), None, "{p} with root {root}");
|
||||
}
|
||||
for p in elsewhere {
|
||||
assert_eq!(refused_spelling(p, &on_share), Some(Network), "{p} with root {root}");
|
||||
}
|
||||
}
|
||||
let shared = [PathBuf::from(r"\\?\UNC\Server\Share\work")];
|
||||
for p in [r"\\server\SHARE\work\x.png", r"\\?\UNC\SERVER\share\elsewhere\x.png", "//Server/Share/work/x.png"] {
|
||||
assert_eq!(refused_spelling(p, &shared), None, "{p}");
|
||||
}
|
||||
for p in [r"\\server\other\x.png", r"\\other\share\x.png", r"\\server", r"\\server.\share\x.png"] {
|
||||
assert_eq!(refused_spelling(p, &shared), Some(Network), "{p}");
|
||||
}
|
||||
assert_eq!(refused_spelling(r"\\server\share\work\COM1", &shared), Some(Device));
|
||||
}
|
||||
|
||||
/// The links on the way to a path are followed by their spelling before anything they lead to is
|
||||
/// opened (#1094). The links are made up here, so this runs where tests may not make links.
|
||||
#[test]
|
||||
fn links_on_the_way_are_followed_by_their_spelling_first() {
|
||||
use super::{Entry, MAX_LINKS, link_refused};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
let base = std::env::temp_dir().join("figcraft-links");
|
||||
let at = |rel: &str| base.join(rel);
|
||||
let mut links: HashMap<PathBuf, Option<PathBuf>> = HashMap::from([
|
||||
// Relative to the link's folder, to a device name.
|
||||
(at("root/dev"), Some(PathBuf::from("../outside/nul"))),
|
||||
// To another link.
|
||||
(at("root/hop"), Some(at("root/dev"))),
|
||||
// Within the root.
|
||||
(at("root/alias"), Some(PathBuf::from("sub"))),
|
||||
(at("root/loop"), Some(at("root/loop"))),
|
||||
(at("root/unreadable"), None),
|
||||
// Below a name that isn't there: never looked at.
|
||||
(at("missing/dev"), Some(PathBuf::from("nul"))),
|
||||
]);
|
||||
if cfg!(windows) {
|
||||
links.insert(at("root/remote"), Some(PathBuf::from(r"\\192.0.2.1\share")));
|
||||
links.insert(at("root/far"), Some(at("root/remote/work")));
|
||||
}
|
||||
// Chains of `n` links, `root/<n>-1` to `root/<n>-2` and so on, the last one to `root/sub`.
|
||||
for n in [MAX_LINKS - 1, MAX_LINKS, MAX_LINKS + 1] {
|
||||
for i in 1..=n {
|
||||
let next = if i == n { at("root/sub") } else { at(&format!("root/{n}-{}", i + 1)) };
|
||||
links.insert(at(&format!("root/{n}-{i}")), Some(next));
|
||||
}
|
||||
}
|
||||
let plain = [at("root"), at("root/sub"), at("outside")];
|
||||
// What can't be looked at (no permission, say) may be a link, so it isn't taken for nothing.
|
||||
let unreadable = at("root/locked");
|
||||
let looked = RefCell::new(Vec::new());
|
||||
let look = |p: &Path| {
|
||||
looked.borrow_mut().push(p.to_path_buf());
|
||||
match links.get(p) {
|
||||
Some(target) => Entry::Link(target.clone()),
|
||||
None if base.starts_with(p) || plain.iter().any(|q| q == p) => Entry::Plain,
|
||||
None if p == unreadable => Entry::Unreadable,
|
||||
None => Entry::Missing,
|
||||
}
|
||||
};
|
||||
let refused = |rel: &str, roots: &[PathBuf]| link_refused(&at(rel), roots, MAX_LINKS, &look);
|
||||
for rel in ["root/dev/x.png", "root/hop/x.png", "root/loop/x.png", "root/unreadable/x.png", "root/locked/x.png", "root/locked"] {
|
||||
assert!(refused(rel, &[]), "{rel}");
|
||||
}
|
||||
for rel in ["root/alias/x.png", "root/sub/x.png", "root/x.png", "missing/dev/x.png"] {
|
||||
assert!(!refused(rel, &[]), "{rel}");
|
||||
}
|
||||
// As many links as are followed lead on; one more is refused.
|
||||
assert!(!refused(&format!("root/{}-1/x.png", MAX_LINKS - 1), &[]));
|
||||
assert!(!refused(&format!("root/{MAX_LINKS}-1/x.png"), &[]));
|
||||
assert!(refused(&format!("root/{}-1/x.png", MAX_LINKS + 1), &[]));
|
||||
// A refused target isn't looked at, nor is anything below what isn't there.
|
||||
let looked = looked.take();
|
||||
assert!(!looked.contains(&at("outside/nul")) && !looked.contains(&at("missing/dev")), "{looked:?}");
|
||||
if cfg!(windows) {
|
||||
for rel in ["root/remote/x.png", "root/far/x.png"] {
|
||||
assert!(refused(rel, &[]), "{rel}");
|
||||
// Unless a root is on that share.
|
||||
assert!(!refused(rel, &[PathBuf::from(r"\\?\UNC\192.0.2.1\share")]), "{rel}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that can't be looked at is refused rather than taken for one with nothing there (#1094):
|
||||
/// only a failure that says nothing is there lets the walk stop, and a path that can't even be
|
||||
/// made absolute isn't left to the checks after it.
|
||||
#[test]
|
||||
fn what_cannot_be_looked_at_is_refused() {
|
||||
use super::{Unresolved, nothing_there, refused_unresolved};
|
||||
use std::io::{Error, ErrorKind};
|
||||
for kind in [ErrorKind::NotFound, ErrorKind::NotADirectory, ErrorKind::InvalidFilename] {
|
||||
assert!(nothing_there(&Error::from(kind)), "{kind:?}");
|
||||
}
|
||||
for kind in [ErrorKind::PermissionDenied, ErrorKind::ResourceBusy, ErrorKind::Interrupted, ErrorKind::Other] {
|
||||
assert!(!nothing_there(&Error::from(kind)), "{kind:?}");
|
||||
}
|
||||
assert_eq!(refused_unresolved(Path::new(""), &[]), Some(Unresolved::Linked));
|
||||
}
|
||||
|
||||
/// On Windows a path is classified as Windows opens it (#1094): with `..` taken by name before
|
||||
/// anything is opened (so a link followed by `..` is never gone through), and with names that
|
||||
/// aren't Unicode (a lone surrogate) still read for the parts that are spelled in ASCII.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn paths_are_classified_as_windows_opens_them() {
|
||||
use super::{Unresolved, refused_unresolved};
|
||||
use craft_docpath::Refused::{Device, Network};
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
assert_eq!(std::path::absolute(r"C:\work\remote\..\x.png").unwrap(), PathBuf::from(r"C:\work\x.png"));
|
||||
// `before`, a lone surrogate, then `after`.
|
||||
let odd = |before: &str, after: &str| {
|
||||
let wide: Vec<u16> = before.encode_utf16().chain([0xD800]).chain(after.encode_utf16()).collect();
|
||||
PathBuf::from(OsString::from_wide(&wide))
|
||||
};
|
||||
assert_eq!(refused_unresolved(&odd(r"\\192.0.2.1\share\", ".png"), &[]), Some(Unresolved::Spelled(Network)));
|
||||
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", r"\nul"), &[]), Some(Unresolved::Spelled(Device)));
|
||||
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", ".png"), &[]), None);
|
||||
// A NUL can't be passed to Windows at all, so the path can't be made absolute.
|
||||
assert_eq!(refused_unresolved(Path::new("C:\\work\\a\0b.png"), &[]), Some(Unresolved::Linked));
|
||||
}
|
||||
|
||||
/// `..` after a link is taken by name, by the check and by Windows when it opens the path, so
|
||||
/// `root\j\..\in.txt` is `root\in.txt` and the link `j` is never gone through (#1094). Shown with
|
||||
/// a junction, a link any account can make: `j` leads out of the root to `outside`, and beside
|
||||
/// `outside` is another `in.txt`, which is what `..` would reach through the link.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_parent_after_a_link_is_taken_by_name() {
|
||||
use super::{Entry, on_disk};
|
||||
let f = Fixture::new("parent");
|
||||
let r = f.rw();
|
||||
std::fs::write(f.0.join("in.txt"), b"beside").unwrap();
|
||||
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(f.0.join(r"root\j")).arg(f.0.join("outside")).output();
|
||||
assert!(made.is_ok_and(|o| o.status.success()), "a junction can be made");
|
||||
// The junction is a link to the check, and what is through it is outside.
|
||||
assert!(matches!(on_disk(&f.0.join(r"root\j")), Entry::Link(Some(_))));
|
||||
assert!(r.check(Path::new(&f.p(r"root\j\secret.txt")), Access::Read).is_err());
|
||||
let through = f.p(r"root\j\..\in.txt");
|
||||
assert_eq!(r.check(Path::new(&through), Access::Read), r.check(Path::new(&f.p(r"root\in.txt")), Access::Read));
|
||||
assert!(r.check(Path::new(&through), Access::Read).is_ok());
|
||||
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// path been resolved, 192.0.2.1 (an address for documentation, where nothing answers) would have
|
||||
/// been contacted and the message would be the one for a path that can't be resolved.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_computers_and_devices_are_refused_before_anything_is_opened() {
|
||||
let f = Fixture::new("network");
|
||||
let r = f.rw();
|
||||
let read_only = Roots::new(&[f.p("root")], &[]).unwrap();
|
||||
let refused = |roots: &Roots, p: &str, access: Access| roots.check(Path::new(p), access).expect_err(p);
|
||||
for p in
|
||||
[r"\\192.0.2.1\share\x.png", "//192.0.2.1/share/x.png", r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\UNC\192.0.2.1\share\x.png", r"\\192.0.2.1"]
|
||||
{
|
||||
for access in [Access::Read, Access::Write] {
|
||||
let e = refused(&r, p, access);
|
||||
assert!(e.contains("is on another computer, and no folder that may be"), "{p}: {e}");
|
||||
}
|
||||
let e = refused(&read_only, p, Access::Write);
|
||||
assert!(e.ends_with("is on another computer, and no folder that may be written is on its share"), "{p}: {e}");
|
||||
}
|
||||
for p in [r"\\.\pipe\figcraft-roots", r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png", &f.p(r"root\COM1\x.png"), "nul"] {
|
||||
for access in [Access::Read, Access::Write] {
|
||||
let e = refused(&r, p, access);
|
||||
assert!(e.ends_with("names a device, not a file"), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
// Local paths, in either spelling, are checked as before.
|
||||
let inside = std::fs::canonicalize(f.p("root")).unwrap().join("in.txt");
|
||||
assert!(r.check(&inside, Access::Read).is_ok());
|
||||
assert!(r.check(Path::new(&f.p(r"root\in.txt")), Access::Read).is_ok());
|
||||
}
|
||||
|
||||
/// A link in a root to another computer is refused before it is followed (#1094), also through
|
||||
/// another link, and with the message any path outside gets: it doesn't tell where the link
|
||||
/// leads. Had the link been followed, the message would be the one for a path that can't be
|
||||
/// resolved. This needs real links, which Windows lets only some accounts make: elsewhere it
|
||||
/// says so and checks nothing (`links_on_the_way_are_followed_by_their_spelling_first` covers the
|
||||
/// same walk with made-up links on every system).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn links_to_other_computers_are_refused_before_they_are_followed() {
|
||||
let f = Fixture::new("network-links");
|
||||
let r = f.rw();
|
||||
if !symlink_dir(Path::new(r"\\192.0.2.1\share"), &f.0.join("root/remote")) || !symlink_dir(&f.0.join("root/remote/work"), &f.0.join("root/hop")) {
|
||||
eprintln!("skipped: this system doesn't let tests make symbolic links");
|
||||
return;
|
||||
}
|
||||
// Relative to the link's folder.
|
||||
assert!(symlink_dir(Path::new(r"..\remote"), &f.0.join("root/sub/up")));
|
||||
assert!(symlink_file(Path::new(r"\\.\pipe\figcraft-roots"), &f.0.join("root/pipe")));
|
||||
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
|
||||
for p in [f.p("root/remote/x.png"), f.p("root/hop/x.png"), f.p("root/sub/up/x.png"), f.p("root/pipe")] {
|
||||
for access in [Access::Read, Access::Write] {
|
||||
let e = r.check(Path::new(&p), access).expect_err(&p);
|
||||
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
// `..` after the link is taken by name, so the link isn't gone through.
|
||||
assert!(r.check(Path::new(&f.p(r"root\remote\..\in.txt")), Access::Read).is_ok());
|
||||
// A link to a folder in the root still leads there.
|
||||
assert!(symlink_dir(&f.0.join("root/sub"), &f.0.join("root/alias")));
|
||||
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_confines_the_thread_and_ends_with_it() {
|
||||
let f = Fixture::new("scope");
|
||||
|
||||
@@ -57,6 +57,7 @@ pub const NODE_KEYS: &[&str] = &[
|
||||
"lineHeight",
|
||||
"lineIndentations",
|
||||
"lineTypes",
|
||||
"lineWrapStyles",
|
||||
"listSpacing",
|
||||
"listStartOffsets",
|
||||
"listStyle",
|
||||
@@ -466,8 +467,14 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
|
||||
if t.leading_trim != figcraft_doc::LeadingTrim::None {
|
||||
insert_prop(o, options, "leadingTrim", || json!(t.leading_trim));
|
||||
}
|
||||
if t.wrap_style != figcraft_doc::WrapStyle::Auto {
|
||||
insert_prop(o, options, "wrapStyle", || json!(t.wrap_style));
|
||||
// The paragraphs' effective wrap styles: one for the layer when they agree, else each one's.
|
||||
let wraps: Vec<figcraft_doc::WrapStyle> = (0..t.paragraph_count()).map(|p| t.para_wrap_style(p)).collect();
|
||||
if let Some(first) = wraps.first().copied().filter(|w| *w != figcraft_doc::WrapStyle::Auto)
|
||||
&& wraps.iter().all(|w| *w == first)
|
||||
{
|
||||
insert_prop(o, options, "wrapStyle", || json!(first));
|
||||
} else if wraps.iter().any(|w| *w != figcraft_doc::WrapStyle::Auto) {
|
||||
insert_prop(o, options, "lineWrapStyles", || wraps.iter().map(|w| json!(w)).collect());
|
||||
}
|
||||
if !t.runs.is_empty() {
|
||||
insert_prop(o, options, "styledRuns", || serde_json::to_value(&t.runs).unwrap_or(Value::Null));
|
||||
|
||||
@@ -383,3 +383,41 @@ fn the_caps_refuse_what_is_too_far_and_cut_what_is_too_long() {
|
||||
assert_eq!(text_data(&s, id(&out, "id")).characters.chars().count(), 500);
|
||||
assert_eq!(text_data(&s, id(&out["children"][0], "id")).characters.chars().count(), 500);
|
||||
}
|
||||
|
||||
/// Where a node's own origin (the place `x`/`y` name) is on the page.
|
||||
fn origin(s: &Session, n: NodeId) -> Point {
|
||||
s.doc().unwrap().world_transform(n) * Point::new(0.0, 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mind_map_in_a_section_without_a_place_is_centred_on_the_view() {
|
||||
let mut s = board();
|
||||
let (vx, vy) = {
|
||||
let v = &s.ds().unwrap().view;
|
||||
(v.cx, v.cy)
|
||||
};
|
||||
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id");
|
||||
let out = s.execute("board.mindMap", &json!({"parent": sec})).unwrap();
|
||||
let c = origin(&s, id(&out, "id"));
|
||||
assert!(same(c.x, vx) && same(c.y, vy), "the root's place {c:?} is the view's centre ({vx}, {vy})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mind_map_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() {
|
||||
let mut s = board();
|
||||
let (vx, vy) = {
|
||||
let v = &s.ds().unwrap().view;
|
||||
(v.cx, v.cy)
|
||||
};
|
||||
let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": 200, "width": 2000, "height": 2000})).unwrap(), "id");
|
||||
s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap();
|
||||
let out = s.execute("board.mindMap", &json!({"parent": fr})).unwrap();
|
||||
let c = origin(&s, id(&out, "id"));
|
||||
assert!(same(c.x, vx) && same(c.y, vy), "the root's place {c:?} is the view's centre ({vx}, {vy})");
|
||||
|
||||
// A given place is the frame's own, as on the page: (10, 20) of the frame, carried through it.
|
||||
let given = id(&s.execute("board.mindMap", &json!({"parent": fr, "x": 10, "y": 20})).unwrap(), "id");
|
||||
let want = s.doc().unwrap().world_transform(fr) * Point::new(10.0, 20.0);
|
||||
let got = origin(&s, given);
|
||||
assert!(same(got.x, want.x) && same(got.y, want.y), "{got:?} against {want:?}");
|
||||
}
|
||||
@@ -258,3 +258,187 @@ fn template_and_table_commands_survive_junk() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Resizing a table (#2172): a height change goes into its rows, never into blank space.
|
||||
|
||||
fn drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) {
|
||||
s.pointer(&PointerEvent::at(PointerKind::Down, from.0, from.1, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, (from.0 + to.0) / 2.0, (from.1 + to.1) / 2.0, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, to.0, to.1, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, to.0, to.1, 1.0)).unwrap();
|
||||
}
|
||||
|
||||
/// A selected 3 x 3 table at 0,0 (480 x 122: a line under all but the last row adds 1 to each), with `texts` in the first row.
|
||||
fn table_3x3(texts: [&str; 3]) -> (Session, NodeId) {
|
||||
let mut s = board();
|
||||
let r = s.execute("board.table", &json!({"x": 0, "y": 0, "cells": [texts, ["", "", ""], ["", "", ""]]})).unwrap();
|
||||
(s, id(&r, "id"))
|
||||
}
|
||||
|
||||
fn rows_of(s: &Session, t: NodeId) -> Vec<NodeId> {
|
||||
let doc = s.doc().unwrap();
|
||||
doc.node(t).unwrap().children.iter().copied().filter(|c| !node(s, *c).child_layout.absolute).collect()
|
||||
}
|
||||
|
||||
fn row_heights(s: &Session, t: NodeId) -> Vec<f64> {
|
||||
rows_of(s, t).into_iter().map(|r| node(s, r).height).collect()
|
||||
}
|
||||
|
||||
fn column_widths(s: &Session, t: NodeId) -> Vec<f64> {
|
||||
let r = rows_of(s, t)[0];
|
||||
node(s, r).children.iter().map(|c| node(s, *c).width).collect()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 0.6
|
||||
}
|
||||
|
||||
fn all_near(got: &[f64], want: &[f64]) -> bool {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(*a, *b))
|
||||
}
|
||||
|
||||
fn is_hug(s: &Session, t: NodeId) -> bool {
|
||||
node(s, t).child_layout.sizing_v == figcraft_doc::Sizing::Hug
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bottom_drag_grows_only_the_last_row() {
|
||||
// The programmatic route.
|
||||
let (mut s, t) = table_3x3(["Alpha", "", ""]);
|
||||
s.execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap();
|
||||
assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 190.0]), "{:?}", row_heights(&s, t));
|
||||
let n = node(&s, t);
|
||||
assert!(near(n.width, 480.0) && near(n.height, 272.0), "{}x{}", n.width, n.height);
|
||||
assert!(is_hug(&s, t), "still hugging its rows");
|
||||
assert!(all_near(&column_widths(&s, t), &[160.0; 3]));
|
||||
assert!(lines(&s, t).iter().all(|(_, h)| near(*h, 272.0)), "{:?}", lines(&s, t));
|
||||
// The pointer route: the bottom edge dragged down by 150.
|
||||
let (mut s, t) = table_3x3(["Alpha", "", ""]);
|
||||
drag(&mut s, (240.0, 122.0), (240.0, 272.0));
|
||||
assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 190.0]), "{:?}", row_heights(&s, t));
|
||||
assert!(near(node(&s, t).height, 272.0) && near(node(&s, t).width, 480.0));
|
||||
assert!(is_hug(&s, t));
|
||||
assert!(all_near(&column_widths(&s, t), &[160.0; 3]));
|
||||
assert!(lines(&s, t).iter().all(|(_, h)| near(*h, 272.0)), "{:?}", lines(&s, t));
|
||||
// The text keeps its size.
|
||||
let row0 = rows_of(&s, t)[0];
|
||||
let cell = node(&s, node(&s, row0).children[0]);
|
||||
let NodeKind::Text(td) = &node(&s, cell.children[0]).kind else { panic!("text") };
|
||||
assert_eq!(td.style.font_size, 14.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corner_drag_shares_the_change_over_every_row_and_column() {
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
drag(&mut s, (480.0, 122.0), (570.0, 182.0));
|
||||
let n = node(&s, t);
|
||||
assert!(near(n.width, 570.0) && near(n.height, 182.0), "{}x{}", n.width, n.height);
|
||||
assert!(all_near(&row_heights(&s, t), &[61.0, 61.0, 60.0]), "{:?}", row_heights(&s, t));
|
||||
assert!(all_near(&column_widths(&s, t), &[190.0; 3]), "{:?}", column_widths(&s, t));
|
||||
let xs: Vec<f64> = lines(&s, t).iter().map(|l| l.0).collect();
|
||||
assert!(all_near(&xs, &[189.5, 379.5]), "{xs:?}");
|
||||
assert!(is_hug(&s, t));
|
||||
// The same through `transform.resize`.
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
s.execute("transform.resize", &json!({"ids": [t], "width": 570, "height": 182})).unwrap();
|
||||
assert!(all_near(&row_heights(&s, t), &[61.0, 61.0, 60.0]), "{:?}", row_heights(&s, t));
|
||||
assert!(all_near(&column_widths(&s, t), &[190.0; 3]), "{:?}", column_widths(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_side_drag_changes_no_row() {
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
s.execute("node.set", &json!({"id": t, "props": {"width": 680}})).unwrap();
|
||||
assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t));
|
||||
assert!(near(node(&s, t).height, 122.0) && near(node(&s, t).width, 680.0));
|
||||
assert!(is_hug(&s, t));
|
||||
// A pointer drag of the right edge.
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
drag(&mut s, (480.0, 60.0), (680.0, 60.0));
|
||||
assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t));
|
||||
assert!(near(node(&s, t).height, 122.0) && near(node(&s, t).width, 680.0));
|
||||
assert!(is_hug(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_never_shrinks_below_its_cells() {
|
||||
let (mut s, t) = table_3x3(["Alpha", "Bravo longer text", "Charlie"]);
|
||||
drag(&mut s, (480.0, 122.0), (50.0, 32.0));
|
||||
let n = node(&s, t);
|
||||
assert!(near(n.width, 120.0), "width {}", n.width);
|
||||
assert!(all_near(&column_widths(&s, t), &[40.0; 3]), "{:?}", column_widths(&s, t));
|
||||
let rows = row_heights(&s, t);
|
||||
assert!(rows[0] > 40.0, "row 1 holds its wrapped text: {rows:?}");
|
||||
assert!(near(rows[1], 41.0) && near(rows[2], 40.0), "{rows:?}");
|
||||
assert!(near(n.height, rows.iter().sum::<f64>()), "{} vs {rows:?}", n.height);
|
||||
assert!(is_hug(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resized_table_still_grows_with_its_text_and_undoes_in_one_step() {
|
||||
// Text measures only once system fonts are scanned (without craft-fonts), so scan them here
|
||||
// without depending on another test having scanned them first.
|
||||
figcraft_text::scan_system_fonts();
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
drag(&mut s, (240.0, 122.0), (240.0, 272.0));
|
||||
assert!(near(node(&s, t).height, 272.0));
|
||||
// Typing in a last-row cell: the table grows once the text needs more than 190.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::DoubleClick, 80.0, 200.0, 1.0)).unwrap();
|
||||
assert!(s.ds().unwrap().text_edit.is_some(), "typing in the last row's cell");
|
||||
let long = (0..12).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
|
||||
crate::textedit::insert(&mut s, &long).unwrap();
|
||||
crate::textedit::end(&mut s).unwrap();
|
||||
assert!(node(&s, t).height > 272.0, "grew with its text: {}", node(&s, t).height);
|
||||
assert!(is_hug(&s, t));
|
||||
// Undo: the typing, then the resize, to the table as made.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(node(&s, t).height, 272.0), "{}", node(&s, t).height);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let n = node(&s, t);
|
||||
assert!(near(n.width, 480.0) && near(n.height, 122.0), "{}x{}", n.width, n.height);
|
||||
assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_resizes_sync_in_live_sessions() {
|
||||
let s = board();
|
||||
let mut room = Room::new(s.doc().unwrap().clone(), 2, 12);
|
||||
let t = id(&room.s(0).execute("board.table", &json!({"x": 0, "y": 0})).unwrap(), "id");
|
||||
room.settle();
|
||||
room.check();
|
||||
room.s(0).execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap();
|
||||
room.settle();
|
||||
room.check();
|
||||
let doc = room.server.document();
|
||||
let heights: Vec<f64> =
|
||||
doc.node(t).unwrap().children.iter().map(|c| doc.node(*c).unwrap()).filter(|n| !n.child_layout.absolute).map(|n| n.height).collect();
|
||||
assert!(all_near(&heights, &[41.0, 41.0, 190.0]), "{heights:?}");
|
||||
assert!(near(doc.node(t).unwrap().height, 272.0));
|
||||
assert_eq!(doc.node(t).unwrap().child_layout.sizing_v, figcraft_doc::Sizing::Hug);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_table_survives_junk_and_saves_the_rows() {
|
||||
for h in [json!(1e308), json!(-5), json!("NaN"), json!(null), json!(0)] {
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
if let Err(EngineError::Internal { cmd, msg }) = s.execute("node.set", &json!({"id": t, "props": {"height": h}})) {
|
||||
panic!("{cmd} panicked on {h}: {msg}");
|
||||
}
|
||||
for p in [json!({"ids": [t], "width": h, "height": h}), json!({"ids": [t], "height": h}), json!({"ids": [t], "width": h})] {
|
||||
if let Err(EngineError::Internal { cmd, msg }) = s.execute("transform.resize", &p) {
|
||||
panic!("{cmd} panicked on {p}: {msg}");
|
||||
}
|
||||
}
|
||||
let n = node(&s, t);
|
||||
assert!(n.width.is_finite() && n.height.is_finite(), "{h}: {}x{}", n.width, n.height);
|
||||
}
|
||||
let (mut s, t) = table_3x3(["", "", ""]);
|
||||
s.execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap();
|
||||
let heights: Vec<f64> =
|
||||
back.node(t).unwrap().children.iter().map(|c| back.node(*c).unwrap()).filter(|n| !n.child_layout.absolute).map(|n| n.height).collect();
|
||||
assert!(all_near(&heights, &[41.0, 41.0, 190.0]), "{heights:?}");
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use figcraft_doc::{
|
||||
use figcraft_geom::Point;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::board::{route, sticky_font_size};
|
||||
use crate::board::{STICKY_TEXT_SIZE, route};
|
||||
use crate::collab_live_tests::Room;
|
||||
use crate::tools::{PointerEvent, PointerKind, ToolId};
|
||||
use crate::{EngineError, Session};
|
||||
@@ -77,7 +77,7 @@ fn board_commands_refuse_on_design_files_and_prototyping_refuses_on_boards() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sticky_is_a_square_frame_whose_note_shrinks_as_it_grows() {
|
||||
fn a_sticky_is_a_square_frame_whose_note_grows_taller_as_it_fills() {
|
||||
let mut s = board();
|
||||
s.prefs.user_name = "Ada".into();
|
||||
let r = s.execute("board.sticky", &json!({"x": 10, "y": 20, "text": "Hi", "color": "blue"})).unwrap();
|
||||
@@ -88,19 +88,125 @@ fn a_sticky_is_a_square_frame_whose_note_shrinks_as_it_grows() {
|
||||
assert_eq!(n.fills[0].solid_color(), board_color("blue"));
|
||||
assert!(n.layout.is_some() && !n.effects.is_empty());
|
||||
assert_eq!(n.children.len(), 2, "the note and its author");
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 24.0);
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0);
|
||||
// A click on the note picks the sticky whole.
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(figcraft_doc::geometry::select_target(doc, note, &[], false), st);
|
||||
// A long note takes a smaller size; a very long one grows the sticky past its square.
|
||||
// A long note keeps the size; a very long one grows the sticky past its square.
|
||||
let long = "word ".repeat(120);
|
||||
s.execute("node.set", &json!({"id": note, "props": {"characters": long}})).unwrap();
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, sticky_font_size(&long));
|
||||
assert!(sticky_font_size(&long) < 16.0);
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, STICKY_TEXT_SIZE);
|
||||
assert!(node(&s, st).width == 200.0 && node(&s, st).height >= 200.0);
|
||||
// Undo puts the short note and its size back.
|
||||
// Undo puts the short note back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 24.0);
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_sticky_is_small_16() {
|
||||
let mut s = board();
|
||||
for (cmd, p) in [("board.sticky", json!({"x": 0, "y": 0, "text": "Hi"})), ("board.sticky", json!({"x": 300, "y": 0}))] {
|
||||
let note = id(&s.execute(cmd, &p).unwrap(), "text");
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0);
|
||||
}
|
||||
let next = id(&s.execute("board.nextSticky", &json!({})).unwrap(), "text");
|
||||
assert_eq!(node(&s, next).kind.text().unwrap().style.font_size, 16.0);
|
||||
assert_eq!(STICKY_TEXT_SIZE, 16.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sticky_sizes_are_figjams() {
|
||||
let table = [("Small", 16.0), ("Medium", 24.0), ("Large", 40.0), ("Extra large", 64.0), ("Huge", 96.0)];
|
||||
assert_eq!(crate::board::STICKY_SIZES, table);
|
||||
}
|
||||
|
||||
fn note_size(s: &Session, note: NodeId) -> f64 {
|
||||
node(s, note).kind.text().unwrap().style.font_size
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_style_font_size_sizes_every_selected_sticky() {
|
||||
let mut s = board();
|
||||
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "A"})).unwrap();
|
||||
let b = s.execute("board.sticky", &json!({"x": 400, "y": 0, "text": "B"})).unwrap();
|
||||
let ids = json!([id(&a, "id").0, id(&b, "id").0]);
|
||||
s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 24})).unwrap();
|
||||
assert_eq!(note_size(&s, id(&a, "text")), 24.0);
|
||||
assert_eq!(note_size(&s, id(&b, "text")), 24.0);
|
||||
let bad = s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 0}));
|
||||
assert!(bad.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sticky_tool_remembers_the_last_size() {
|
||||
let mut s = board();
|
||||
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "A"})).unwrap();
|
||||
s.execute("board.setStyle", &json!({"ids": [id(&a, "id").0], "fontSize": 40})).unwrap();
|
||||
let b = s.execute("board.sticky", &json!({"x": 400, "y": 0, "text": "B"})).unwrap();
|
||||
assert_eq!(note_size(&s, id(&b, "text")), 40.0);
|
||||
let c = s.execute("board.sticky", &json!({"x": 800, "y": 0, "fontSize": 64})).unwrap();
|
||||
assert_eq!(note_size(&s, id(&c, "text")), 64.0);
|
||||
assert!(s.execute("board.sticky", &json!({"x": 0, "y": 400, "fontSize": 5000})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_sticky_grows_taller_and_shrinks_back() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = board();
|
||||
let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "Alpha"})).unwrap();
|
||||
let st = id(&r, "id");
|
||||
let ids = json!([st.0]);
|
||||
let (w, h16) = (node(&s, st).width, node(&s, st).height);
|
||||
s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 96})).unwrap();
|
||||
assert_eq!(node(&s, st).width, w, "the width stays");
|
||||
assert!(node(&s, st).height > h16, "Huge is taller than Small");
|
||||
s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 40})).unwrap();
|
||||
assert_eq!(node(&s, st).height, h16, "Large is square again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sticky_keeps_its_text_size_as_text_is_added() {
|
||||
// The note's growth needs text measured: without craft-fonts that is with a system font,
|
||||
// scanned here rather than by whichever test happens to run first (#333).
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = board();
|
||||
let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "one"})).unwrap();
|
||||
let (st, note) = (id(&r, "id"), id(&r, "text"));
|
||||
let (height, text_height) = (node(&s, st).height, node(&s, note).height);
|
||||
// Typing in the note: each step is a real edit that runs the normalize pass.
|
||||
crate::board::edit_text(&mut s, st).unwrap();
|
||||
for _ in 0..9 {
|
||||
crate::textedit::key(&mut s, "Enter", false, false, false).unwrap();
|
||||
crate::textedit::insert(&mut s, "another line").unwrap();
|
||||
}
|
||||
let ten = node(&s, note).kind.text().unwrap().clone();
|
||||
assert_eq!(ten.characters.matches('\n').count(), 9, "ten lines");
|
||||
assert_eq!(ten.style.font_size, 16.0);
|
||||
assert!(node(&s, note).height > text_height, "ten lines make the text taller");
|
||||
assert!(node(&s, st).height > height, "and the note");
|
||||
assert_eq!(node(&s, st).child_layout.sizing_v, figcraft_doc::Sizing::Hug, "the note hugs its text");
|
||||
let (w, h10) = (node(&s, st).width, node(&s, st).height);
|
||||
crate::textedit::insert(&mut s, &"a long paragraph ".repeat(15)).unwrap();
|
||||
crate::textedit::end(&mut s).unwrap();
|
||||
let t = node(&s, note).kind.text().unwrap().clone();
|
||||
assert!(t.characters.chars().count() >= 250);
|
||||
assert_eq!(t.style.font_size, 16.0);
|
||||
assert!(t.runs.iter().all(|r| r.style.font_size == 16.0));
|
||||
assert_eq!(node(&s, st).width, w, "the note keeps its width");
|
||||
assert!(node(&s, st).height > h10, "and grows taller");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sticky_saved_with_another_text_size_keeps_it() {
|
||||
let mut s = board();
|
||||
let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "old"})).unwrap();
|
||||
let (st, note) = (id(&r, "id"), id(&r, "text"));
|
||||
s.execute("node.set", &json!({"id": note, "props": {"fontSize": 11}})).unwrap();
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0);
|
||||
s.execute("node.set", &json!({"id": note, "props": {"characters": "old and now much longer than it was"}})).unwrap();
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0, "an edit");
|
||||
s.execute("node.set", &json!({"id": st, "props": {"x": 40}})).unwrap();
|
||||
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0, "a move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -166,9 +166,9 @@ fn styles_labels_and_their_refusals() {
|
||||
assert!(s.execute("board.label", &json!({"id": c, "text": ""})).unwrap()["label"].is_null());
|
||||
assert!(!s.doc().unwrap().contains(l));
|
||||
// What doesn't take a style or colour says so.
|
||||
assert!(s.execute("board.setStyle", &json!({"ids": [a], "fontSize": 30})).is_err(), "stickies size their own text");
|
||||
assert!(s.execute("board.setStyle", &json!({"ids": [c], "fontSize": 0})).is_err());
|
||||
let st = id(&s.execute("board.stamp", &json!({"x": 0, "y": 0, "stamp": "check"})).unwrap(), "id");
|
||||
assert!(s.execute("board.setStyle", &json!({"ids": [st], "fontSize": 30})).is_err(), "a stamp has no text to size");
|
||||
assert!(s.execute("board.setColor", &json!({"ids": [st], "color": "blue"})).is_err());
|
||||
assert!(s.execute("board.setColor", &json!({"ids": [a]})).is_err());
|
||||
assert!(s.execute("board.label", &json!({"id": a, "text": "x"})).is_err());
|
||||
|
||||
@@ -69,8 +69,8 @@ pub(crate) use edit::{copied_items, copy_map, rejoin};
|
||||
use edit::{label_cmd, set_color, set_style};
|
||||
pub(crate) use items::add_text;
|
||||
pub use items::{CONNECTED_GAP, connected_place};
|
||||
pub use items::{STICKY_TEXT_SIZE, edit_text, owner_of_text, text_of};
|
||||
use items::{add_connected, ink_cmd, next_sticky, shape_cmd, stamp_cmd, sticky_cmd};
|
||||
pub use items::{edit_text, owner_of_text, sticky_font_size, text_of};
|
||||
pub(crate) use mindmap::settle_mind_maps;
|
||||
pub(crate) use reshape::path_handle_at;
|
||||
pub use reshape::selected_connector_handles;
|
||||
@@ -100,12 +100,16 @@ const HIGHLIGHTER: (f64, f32) = (20.0, 0.45);
|
||||
const ERASER_PX: f64 = 8.0;
|
||||
/// The text sizes the contextual bar offers.
|
||||
pub const TEXT_SIZES: [(&str, f64); 4] = [("S", 12.0), ("M", 16.0), ("L", 24.0), ("XL", 36.0)];
|
||||
/// The text sizes a sticky's menu offers (FigJam's, measured 2026-11-12): name and size.
|
||||
pub const STICKY_SIZES: [(&str, f64); 5] = [("Small", 16.0), ("Medium", 24.0), ("Large", 40.0), ("Extra large", 64.0), ("Huge", 96.0)];
|
||||
|
||||
/// The board tools' choices: the colour new stickies get, the shape and stamp the tools place,
|
||||
/// how new connectors run and the marker's and highlighter's colours.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BoardTool {
|
||||
pub sticky: Color,
|
||||
/// The text size new stickies get (the last one chosen on a sticky).
|
||||
pub sticky_size: f64,
|
||||
pub shape: BoardShape,
|
||||
pub stamp: Stamp,
|
||||
pub routing: Routing,
|
||||
@@ -118,6 +122,7 @@ impl Default for BoardTool {
|
||||
let first = BOARD_COLORS.first().map_or(Color::WHITE, |c| c.1);
|
||||
Self {
|
||||
sticky: first,
|
||||
sticky_size: STICKY_TEXT_SIZE,
|
||||
shape: BoardShape::Rectangle,
|
||||
stamp: Stamp::ThumbsUp,
|
||||
routing: Routing::Elbow,
|
||||
@@ -132,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"board.sticky",
|
||||
"Sticky note",
|
||||
"{x, y (its top-left, in the parent), text?, color? (yellow|orange|red|pink|violet|blue|green|gray or hex; default the sticky tool's), author? (a name, or false for none; default yours), parent?} → {id, text}",
|
||||
"{x, y (its top-left, in the parent), text?, color? (yellow|orange|red|pink|violet|blue|green|gray or hex; default the sticky tool's), fontSize? (1 to 1000; default the sticky tool's, 16 at first), author? (a name, or false for none; default yours), parent?} → {id, text}",
|
||||
true,
|
||||
sticky_cmd
|
||||
),
|
||||
@@ -217,7 +222,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"board.setStyle",
|
||||
"Board style",
|
||||
"{ids?, shape? (shapes with text), fontSize? (their text), style?: straight|elbow|curved, startCap?, endCap? (connectors)}",
|
||||
"{ids?, shape? (shapes with text), fontSize? (the text of stickies, shapes, labels and mind nodes; stickies remember it for new ones), style?: straight|elbow|curved, startCap?, endCap? (connectors)}",
|
||||
true,
|
||||
set_style
|
||||
),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use figcraft_doc::RouteEnd;
|
||||
|
||||
use super::edit::set_font_size;
|
||||
use super::items::{owner_of_text, shape_padding, sticky_font_size, text_of};
|
||||
use super::items::shape_padding;
|
||||
use super::{
|
||||
Affine, BTreeSet, BezPath, BoardItem, Connector, Document, End, NodeId, NodeKind, PathEl, Point, Rect, Routing, Shape, VectorNetwork, is_board,
|
||||
};
|
||||
@@ -9,26 +8,15 @@ use super::{
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Derived data (the normalize pass).
|
||||
|
||||
/// Before text is measured: a sticky's note takes the size its length calls for, and a resized
|
||||
/// shape keeps its text inside its outline.
|
||||
/// Before text is measured: a resized shape keeps its text inside its outline. A sticky's text
|
||||
/// keeps whatever size it has (FigJam's size is the note's own setting).
|
||||
pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTreeSet<NodeId>) {
|
||||
if !is_board(doc) {
|
||||
return;
|
||||
}
|
||||
crate::board_table::settle_resize(doc, before, touched);
|
||||
for &id in touched {
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
if let Some(owner) =
|
||||
owner_of_text(doc, id).or(Some(id)).filter(|o| doc.node(*o).is_some_and(|k| matches!(k.board, Some(BoardItem::Sticky { .. }))))
|
||||
&& let Some(t) = text_of(doc, owner)
|
||||
&& let Some(NodeKind::Text(td)) = doc.node(t).map(|k| &k.kind)
|
||||
{
|
||||
let size = sticky_font_size(&td.characters);
|
||||
let off = td.style.font_size != size || td.runs.iter().any(|r| r.style.font_size != size);
|
||||
if off && let Some(NodeKind::Text(td)) = doc.node_mut(t).map(|k| &mut k.kind) {
|
||||
set_font_size(td, size);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(BoardItem::Shape { shape }) = n.board
|
||||
&& before.node(id).is_none_or(|b| (b.width, b.height) != (n.width, n.height))
|
||||
{
|
||||
|
||||
@@ -130,9 +130,12 @@ impl Restyle {
|
||||
BoardItem::Connector(ref c) => self.restyle_connector(doc, id, c.clone())?,
|
||||
_ => false,
|
||||
};
|
||||
// Text sizes: shapes' and labels' text (stickies size theirs to fit).
|
||||
// Text sizes: the text of stickies, shapes, labels and mind nodes (a sticky's note grows taller
|
||||
// when its text no longer fits, by its auto layout).
|
||||
let sized = match (self.size, &item) {
|
||||
(Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => resize_text(doc, id, size),
|
||||
(Some(size), BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => {
|
||||
resize_text(doc, id, size)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
Ok(changed || sized)
|
||||
@@ -191,13 +194,19 @@ pub(super) fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let restyle = Restyle::of(cmd, p)?;
|
||||
let doc = s.doc_mut()?;
|
||||
let mut changed = Vec::new();
|
||||
let mut sticky_sized = false;
|
||||
for (id, item) in items(doc, &ids) {
|
||||
let sticky = matches!(item, BoardItem::Sticky { .. });
|
||||
if restyle.apply(doc, id, item)? {
|
||||
changed.push(id);
|
||||
sticky_sized |= sticky && restyle.size.is_some();
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Err(bad(cmd, "nothing selected takes these (shapes with text, connectors, labels)"));
|
||||
return Err(bad(cmd, "nothing selected takes these (stickies, shapes with text, connectors, labels)"));
|
||||
}
|
||||
if let (true, Some(size)) = (sticky_sized, restyle.size) {
|
||||
s.tool.board.sticky_size = size;
|
||||
}
|
||||
Ok(json!({"ids": changed}))
|
||||
}
|
||||
|
||||
@@ -57,21 +57,13 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The text size a sticky's note gets: smaller the more it holds (by characters and lines, so
|
||||
/// every copy of the file picks the same size whatever fonts it has).
|
||||
pub fn sticky_font_size(text: &str) -> f64 {
|
||||
let weight = text.chars().count() + 24 * text.matches('\n').count();
|
||||
match weight {
|
||||
0..=24 => 24.0,
|
||||
25..=64 => 20.0,
|
||||
65..=140 => 16.0,
|
||||
141..=280 => 13.0,
|
||||
_ => 11.0,
|
||||
}
|
||||
}
|
||||
/// The text size of a new sticky's note, FigJam's "Small" default: 16, measured twice in the web
|
||||
/// app on 2026-11-12 from the size field's value (an earlier reading of 18 did not reproduce). It
|
||||
/// never changes as the note fills, the note grows taller instead.
|
||||
pub const STICKY_TEXT_SIZE: f64 = 16.0;
|
||||
|
||||
/// A sticky note's layers: the frame, the note and (when known) its author.
|
||||
fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, color: Color, author: &str) -> Result<(NodeId, NodeId)> {
|
||||
fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, color: Color, author: &str, size: f64) -> Result<(NodeId, NodeId)> {
|
||||
let id = add(doc, parent, NodeKind::Frame, "Sticky", at, (STICKY, STICKY), |n| {
|
||||
n.fills = vec![Paint::solid(color)];
|
||||
n.corners.radii = [2.0; 4];
|
||||
@@ -89,7 +81,7 @@ fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, c
|
||||
n.board = Some(BoardItem::Sticky { author: author.to_string() });
|
||||
})?;
|
||||
let inner = STICKY - 2.0 * STICKY_PAD;
|
||||
let note = add_text(doc, id, text, sticky_font_size(text), INK, TextAlignH::Left, inner)?;
|
||||
let note = add_text(doc, id, text, size, INK, TextAlignH::Left, inner)?;
|
||||
if !author.is_empty() {
|
||||
let a = add_text(doc, id, author, 10.0, AUTHOR_INK, TextAlignH::Left, inner)?;
|
||||
if let Some(n) = doc.node_mut(a) {
|
||||
@@ -111,7 +103,12 @@ pub(super) fn sticky_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = parent_of(cmd, s, p)?;
|
||||
let text = string(p, "text").unwrap_or_default();
|
||||
let at = (num_or(p, "x", 0.0), num_or(p, "y", 0.0));
|
||||
let (id, note) = make_sticky(s.doc_mut()?, parent, at, &text, color, &author)?;
|
||||
let size = match num(p, "fontSize") {
|
||||
None => s.tool.board.sticky_size,
|
||||
Some(v) if v.is_finite() && (1.0..=1000.0).contains(&v) => v,
|
||||
Some(_) => return Err(bad(cmd, "`fontSize` is from 1 to 1000")),
|
||||
};
|
||||
let (id, note) = make_sticky(s.doc_mut()?, parent, at, &text, color, &author, size)?;
|
||||
s.set_selection(vec![id]);
|
||||
Ok(json!({"id": id, "text": note}))
|
||||
}
|
||||
@@ -164,11 +161,11 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"above" => (0.0, -(STICKY + STICKY_GAP)),
|
||||
other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))),
|
||||
};
|
||||
let author = author(s);
|
||||
let (author, size) = (author(s), s.tool.board.sticky_size);
|
||||
if editing.is_some() {
|
||||
textedit::end(s)?;
|
||||
}
|
||||
let (id, note) = make_sticky(s.doc_mut()?, parent, (at.x + dx, at.y + dy), "", color, &author)?;
|
||||
let (id, note) = make_sticky(s.doc_mut()?, parent, (at.x + dx, at.y + dy), "", color, &author, size)?;
|
||||
s.set_selection(vec![id]);
|
||||
if boolean(p, "edit") == Some(true) {
|
||||
// Typing goes on in the new sticky once this step is recorded.
|
||||
@@ -236,13 +233,13 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => (to_at, from_side, to_side),
|
||||
};
|
||||
let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?);
|
||||
let (routing, author, page, size) = (s.tool.board.routing, author(s), s.page()?, s.tool.board.sticky_size);
|
||||
if editing.is_some() {
|
||||
textedit::end(s)?;
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
let (id, text) = match shape {
|
||||
None => make_sticky(doc, parent, to_at, "", color, &author)?,
|
||||
None => make_sticky(doc, parent, to_at, "", color, &author, size)?,
|
||||
Some(shape) => make_shape(doc, parent, to_at, next, shape, "", color)?,
|
||||
};
|
||||
let connector = Connector {
|
||||
|
||||
@@ -168,9 +168,13 @@ pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "board.mindMap";
|
||||
require(s, cmd)?;
|
||||
let parent = parent_of(cmd, s, p)?;
|
||||
// The view's centre is on the page, and `x`/`y` are in the parent: a map in a section or frame
|
||||
// takes the centre in that parent's coordinates (a parent that can't be inverted gives a
|
||||
// non-finite centre, which `coord` refuses).
|
||||
let (vx, vy) = {
|
||||
let v = &s.ds()?.view;
|
||||
(v.cx, v.cy)
|
||||
let ds = s.ds()?;
|
||||
let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy);
|
||||
(c.x, c.y)
|
||||
};
|
||||
let (x, y) = (coord(cmd, p, "x", vx)?, coord(cmd, p, "y", vy)?);
|
||||
let texts = starters(cmd, p)?;
|
||||
|
||||
@@ -3,6 +3,16 @@
|
||||
//! row's width, so a cell that wraps more text makes its row taller. Each row but the last draws
|
||||
//! a line under itself and the column lines are thin rectangles over the table that stretch with
|
||||
//! it (they are rebuilt after every edit, like the first row's header tint).
|
||||
//!
|
||||
//! Resizing (measured in FigJam's web app, 2026-11-09, #2172): a table never scales its text or
|
||||
//! its rows in proportion. A height change goes into the rows ([`settle_resize`]): the bottom or
|
||||
//! top edge grows the last row, a corner drag shares the change equally over every row (every
|
||||
//! cell fills its row, so the width is already shared equally), and the table keeps hugging its
|
||||
//! rows. A cell is at least [`MIN_CELL`] (40; FigJam's floor is about 52) wide and tall, and a row
|
||||
//! is never shorter than its wrapped text. There are no per-column widths yet: a side drag of
|
||||
//! the right edge splits the change equally where FigJam grows only the last column.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{
|
||||
@@ -22,6 +32,10 @@ pub const MAX_COLUMNS: usize = 20;
|
||||
/// A new column's width, and a cell's height before its text is measured.
|
||||
const CELL_W: f64 = 160.0;
|
||||
const CELL_H: f64 = 40.0;
|
||||
/// The least a cell is wide or tall (FigJam's is about 52).
|
||||
pub(crate) const MIN_CELL: f64 = CELL_H;
|
||||
/// The most a resize may ask one row to be tall.
|
||||
const MAX_ROW_H: f64 = 100_000.0;
|
||||
/// Room around a cell's text: [top, right, bottom, left].
|
||||
const CELL_PAD: [f64; 4] = [10.0, 12.0, 10.0, 12.0];
|
||||
const TEXT_SIZE: f64 = 14.0;
|
||||
@@ -125,6 +139,7 @@ fn make_cell(doc: &mut Document, row: NodeId, index: Option<usize>, width: f64,
|
||||
n.child_layout.sizing_h = Sizing::Fill;
|
||||
n.child_layout.sizing_v = Sizing::Hug;
|
||||
n.child_layout.min_h = Some(CELL_H);
|
||||
n.child_layout.min_w = Some(MIN_CELL);
|
||||
})?;
|
||||
add_text(doc, cell, text, TEXT_SIZE, INK, TextAlignH::Left, (width - CELL_PAD[1] - CELL_PAD[3]).max(1.0))?;
|
||||
Ok(cell)
|
||||
@@ -259,6 +274,57 @@ fn table_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A table resized by its height or a corner (the resize leaves it at a fixed height): the change
|
||||
/// goes into its rows, as in FigJam, and the table hugs them again. A bottom or top edge (or a
|
||||
/// height set by command) grows or shrinks the last row; a drag that changed both axes shares the
|
||||
/// change equally over every row. A row never gets shorter than [`MIN_CELL`] or than its text (the
|
||||
/// table hugs it), and the table is never narrower than its columns' minimum. A table already
|
||||
/// hugging (a peer's synced edit, a second pass) is left alone, so the change is made once.
|
||||
pub(crate) fn settle_resize(doc: &mut Document, before: &Document, touched: &BTreeSet<NodeId>) {
|
||||
let mut tables = BTreeSet::new();
|
||||
for &id in touched {
|
||||
if let Some(t) = table_of(doc, id) {
|
||||
tables.insert(t);
|
||||
}
|
||||
}
|
||||
for table in tables {
|
||||
let (Some(now), Some(was)) = (doc.node(table), before.node(table)) else { continue };
|
||||
if now.child_layout.sizing_v != Sizing::Fixed {
|
||||
continue;
|
||||
}
|
||||
let (w, h, bw, bh) = (now.width, now.height, was.width, was.height);
|
||||
let (rows, _) = parts(doc, table);
|
||||
let columns = rows.first().map_or(0, |r| cells(doc, *r).len());
|
||||
let dh = h - bh;
|
||||
if dh.is_finite() && dh.abs() > 1e-6 && !rows.is_empty() {
|
||||
let both = w.is_finite() && bw.is_finite() && (w - bw).abs() > 1e-6;
|
||||
let targets: Vec<NodeId> = if both { rows.clone() } else { rows.last().copied().into_iter().collect() };
|
||||
let share = dh / targets.len() as f64;
|
||||
for row in targets {
|
||||
let base = row_content(before, row).or_else(|| row_content(doc, row)).unwrap_or(CELL_H);
|
||||
let min_h = (base + share).clamp(MIN_CELL, MAX_ROW_H);
|
||||
for cell in cells(doc, row) {
|
||||
if let Some(c) = doc.node_mut(cell) {
|
||||
c.child_layout.min_h = Some(min_h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = doc.node_mut(table) {
|
||||
let least = MIN_CELL * columns as f64;
|
||||
if t.width.is_nan() || t.width < least {
|
||||
t.width = least;
|
||||
}
|
||||
t.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How tall a row's cells are: the row's height less the line under it.
|
||||
fn row_content(doc: &Document, row: NodeId) -> Option<f64> {
|
||||
cells(doc, row).into_iter().filter_map(|c| doc.node(c).map(|n| n.height)).reduce(f64::max)
|
||||
}
|
||||
|
||||
/// The table `id` is or is in.
|
||||
fn table_of(doc: &Document, id: NodeId) -> Option<NodeId> {
|
||||
std::iter::once(id).chain(doc.ancestors(id)).find(|a| doc.node(*a).is_some_and(|n| n.board == Some(BoardItem::Table)))
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! A boolean group's corner radius through the engine: it rounds the result (and the SVG export
|
||||
//! of it), children keep their own radius, Flatten bakes the arcs and clicks follow the result.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::booleans_tests::{area, click, ex};
|
||||
use crate::params::id_of;
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_geom::{Point, Shape};
|
||||
|
||||
const L_AREA: f64 = 34656.6;
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id_of(&ex(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn snapping_off(s: &mut Session) {
|
||||
ex(s, "select.none", json!({}));
|
||||
let ds = s.ds_mut().unwrap();
|
||||
ds.view.snap_objects = false;
|
||||
ds.view.snap_pixel = false;
|
||||
}
|
||||
|
||||
fn set_radius(s: &mut Session, id: NodeId, r: f64) {
|
||||
ex(s, "node.set", json!({"ids": [id], "props": {"cornerRadius": r}}));
|
||||
}
|
||||
|
||||
/// The L of two rectangles, united, nothing selected, snapping off.
|
||||
fn l_group(s: &mut Session) -> NodeId {
|
||||
let (a, b) = (rect(s, 0.0, 0.0, 200.0, 100.0), rect(s, 150.0, 0.0, 100.0, 200.0));
|
||||
let g = id_of(&ex(s, "bool.union", json!({"ids": [a, b]}))["id"]).unwrap();
|
||||
snapping_off(s);
|
||||
g
|
||||
}
|
||||
|
||||
/// Whether the page point is inside the group's drawn result.
|
||||
fn covers(s: &Session, g: NodeId, x: f64, y: f64) -> bool {
|
||||
let doc = s.doc().unwrap();
|
||||
let (path, _) = figcraft_render::node_outline(doc, doc.node(g).unwrap()).unwrap();
|
||||
let p = doc.world_transform(g).inverse() * Point::new(x, y);
|
||||
path.winding(p) % 2 != 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_boolean_group_rounds_every_sharp_corner_of_its_result() {
|
||||
let mut s = Session::new();
|
||||
let g = l_group(&mut s);
|
||||
assert!(covers(&s, g, 1.0, 1.0));
|
||||
set_radius(&mut s, g, 20.0);
|
||||
assert!(!covers(&s, g, 1.0, 1.0) && covers(&s, g, 148.0, 102.0));
|
||||
assert!((area(&s, g) - L_AREA).abs() < 1.0, "{}", area(&s, g));
|
||||
let doc = s.doc().unwrap();
|
||||
let svg = figcraft_svg::export_svg(doc, &[g], &figcraft_svg::SvgOptions::default()).unwrap();
|
||||
let d = svg.split("d=\"").nth(1).and_then(|r| r.split('"').next()).unwrap();
|
||||
let exported = figcraft_geom::svg_path(d).unwrap();
|
||||
assert!((exported.area().abs() - L_AREA).abs() < 1.0, "{}", exported.area());
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc().unwrap().node(g).unwrap().corners.radii, [0.0; 4], "one undo step");
|
||||
assert!((area(&s, g) - 35000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
/// The notch of the measurement: A (200 by 100 at the origin) minus a 100 square on its top edge,
|
||||
/// whose own radius is `a_radius`, under a group radius of `radius`.
|
||||
fn notch(s: &mut Session, a: NodeId, radius: f64) -> NodeId {
|
||||
let b = rect(s, 50.0, -50.0, 100.0, 100.0);
|
||||
let g = id_of(&ex(s, "bool.subtract", json!({"ids": [a, b]}))["id"]).unwrap();
|
||||
snapping_off(s);
|
||||
set_radius(s, g, radius);
|
||||
g
|
||||
}
|
||||
|
||||
/// The asserts of the measurement on a notched group at radius 20 under A's own 10.
|
||||
fn assert_notch_at_20(s: &Session, g: NodeId) {
|
||||
assert!(covers(s, g, 4.0, 4.0), "A's 10 was not enlarged to 20");
|
||||
assert!(!covers(s, g, 48.0, 2.0), "the cut's top corner rounds");
|
||||
assert!(covers(s, g, 52.0, 48.0), "the cut's inner corner fills in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn children_keep_their_radius_and_a_subtraction_rounds_its_cut() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
set_radius(&mut s, a, 10.0);
|
||||
let g = notch(&mut s, a, 20.0);
|
||||
assert_notch_at_20(&s, g);
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().corners.radii, [10.0; 4]);
|
||||
set_radius(&mut s, g, 500.0);
|
||||
assert_eq!(s.doc().unwrap().node(g).unwrap().corners.radii[0], 500.0, "the field keeps the value");
|
||||
assert!(!covers(&s, g, 40.0, 4.0), "25, not the 20 that half the 40-long edge would give");
|
||||
assert!(covers(&s, g, 27.0, 1.0), "and not more than 25");
|
||||
assert!(covers(&s, g, 100.0, 51.0) && !covers(&s, g, 100.0, 49.0), "the floor stays straight between 75 and 125");
|
||||
assert!(covers(&s, g, 4.0, 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_group_keeps_its_own_radius() {
|
||||
let mut s = Session::new();
|
||||
let (l, r) = (rect(&mut s, 0.0, 0.0, 120.0, 100.0), rect(&mut s, 80.0, 0.0, 120.0, 100.0));
|
||||
let inner = id_of(&ex(&mut s, "bool.union", json!({"ids": [l, r]}))["id"]).unwrap();
|
||||
set_radius(&mut s, inner, 10.0);
|
||||
let g = notch(&mut s, inner, 20.0);
|
||||
assert_notch_at_20(&s, g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_bakes_the_arcs_and_the_vector_has_no_radius() {
|
||||
let mut s = Session::new();
|
||||
let g = l_group(&mut s);
|
||||
set_radius(&mut s, g, 20.0);
|
||||
let flat = id_of(&ex(&mut s, "vector.flatten", json!({"ids": [g]}))["id"]).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(flat).unwrap();
|
||||
let NodeKind::Vector { network } = &n.kind else { panic!("a vector: {:?}", n.kind) };
|
||||
assert_eq!(n.corners.radii, [0.0; 4]);
|
||||
assert!(network.vertices.iter().all(|v| v.radius == 0.0));
|
||||
let path = figcraft_doc::geometry::shape_path(n).unwrap();
|
||||
assert!((path.area().abs() - L_AREA).abs() < 1.0, "{}", path.area());
|
||||
assert!((n.width - 250.0).abs() < 1e-6 && (n.height - 200.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_follow_the_rounded_result() {
|
||||
let mut s = Session::new();
|
||||
let g = l_group(&mut s);
|
||||
set_radius(&mut s, g, 20.0);
|
||||
click(&mut s, 1.0, 1.0, false);
|
||||
assert!(s.selection().is_empty(), "the cut-off corner reaches what is behind");
|
||||
click(&mut s, 148.0, 102.0, false);
|
||||
assert_eq!(s.selection(), vec![g], "the concave fillet belongs to the group");
|
||||
ex(&mut s, "select.none", json!({}));
|
||||
click(&mut s, 100.0, 50.0, false);
|
||||
assert_eq!(s.selection(), vec![g]);
|
||||
}
|
||||
@@ -11,21 +11,21 @@ use crate::tools::{PointerEvent, PointerKind};
|
||||
use figcraft_doc::{BoolOp, NodeId, NodeKind};
|
||||
use figcraft_geom::Shape;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
pub(crate) fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn ev(kind: PointerKind, x: f64, y: f64, cmd: bool) -> PointerEvent {
|
||||
pub(crate) fn ev(kind: PointerKind, x: f64, y: f64, cmd: bool) -> PointerEvent {
|
||||
PointerEvent { cmd, ..PointerEvent::at(kind, x, y, 1.0) }
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, x: f64, y: f64, cmd: bool) {
|
||||
pub(crate) fn click(s: &mut Session, x: f64, y: f64, cmd: bool) {
|
||||
s.pointer(&ev(PointerKind::Down, x, y, cmd)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, x, y, cmd)).unwrap();
|
||||
}
|
||||
|
||||
/// A layer's filled area (a boolean group's result; none of these have holes).
|
||||
fn area(s: &Session, id: NodeId) -> f64 {
|
||||
pub(crate) fn area(s: &Session, id: NodeId) -> f64 {
|
||||
let doc = s.doc().unwrap();
|
||||
figcraft_render::node_outline(doc, doc.node(id).unwrap()).unwrap().0.area().abs()
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::params::id_of;
|
||||
use crate::tools::{PointerEvent, PointerKind, pressure_profile};
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_geom::Point;
|
||||
use figcraft_geom::kurbo::PathEl;
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
id_of(&v["id"]).unwrap()
|
||||
@@ -149,3 +150,68 @@ fn the_pencil_draws_white_on_a_dark_background() {
|
||||
assert_eq!(stroke(&mut s, 0.0, 600.0).0, want, "on {bg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Pencil stroke stays where it was drawn: the fitted curve shot far off the stroke, a spike
|
||||
/// (#1741, its second point), where the stroke went out and back to the very point it left and
|
||||
/// where samples ran on nearly straight. Pointer pixels become fractional page points, so going
|
||||
/// back to a pixel lands on exactly the same point. Both sample runs are ones kurbo's fit took
|
||||
/// hundreds of units off.
|
||||
///
|
||||
/// Each stroke is drawn in a fresh session, with the Pencil and with the Marker and Highlighter
|
||||
/// of a board, whose ink comes from the same fit. Every point along the stroke drawn must lie
|
||||
/// within 1.5 (twice the fit's accuracy) of the polyline through the samples.
|
||||
#[test]
|
||||
fn the_pencil_keeps_its_stroke_where_it_was_drawn() {
|
||||
let (p, q) = ((86.043_565_719_086_97, -173.744_402_349_100_94), (87.851_850_739_335_35, -179.202_846_445_954_52));
|
||||
let back = [(80.0, -160.0), p, q, p, (95.0, -185.0)];
|
||||
let straight = [
|
||||
(204.0, -198.0),
|
||||
(209.598_690_794_015_5, -204.909_328_119_739_88),
|
||||
(211.277_914_263_870_97, -207.190_974_020_753_4),
|
||||
(214.246_506_828_720_84, -211.228_827_590_623_24),
|
||||
(218.0, -214.0),
|
||||
];
|
||||
for tool in ["pencil", "marker", "highlighter"] {
|
||||
for (what, samples) in [("out and back", &back[..]), ("nearly straight", &straight[..])] {
|
||||
let what = format!("{tool}, {what}");
|
||||
let mut s = if tool == "pencil" { Session::new() } else { crate::board_tests::board() };
|
||||
s.execute("tool.set", &json!({"tool": tool})).unwrap();
|
||||
let before: Vec<NodeId> = s.doc().unwrap().nodes().map(|n| n.id).collect();
|
||||
let (first, last) = (samples[0], samples[samples.len() - 1]);
|
||||
s.pointer(&PointerEvent::at(PointerKind::Down, first.0, first.1, 1.0)).unwrap();
|
||||
for (x, y) in &samples[1..] {
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, *x, *y, 1.0)).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, last.0, last.1, 1.0)).unwrap();
|
||||
// The layer the stroke made, and only it.
|
||||
let doc = s.doc().unwrap();
|
||||
let made: Vec<&figcraft_doc::Node> =
|
||||
doc.nodes().filter(|n| !before.contains(&n.id) && matches!(n.kind, NodeKind::Vector { .. })).collect();
|
||||
let [n] = made[..] else { panic!("{what}: {} vectors made", made.len()) };
|
||||
let NodeKind::Vector { network } = &n.kind else { panic!("{what}: not a vector") };
|
||||
let drawn = doc.world_transform(n.id) * network.stroke_path();
|
||||
let polyline = figcraft_geom::BezPath::from_vec(
|
||||
samples
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, (x, y))| if k == 0 { PathEl::MoveTo(Point::new(*x, *y)) } else { PathEl::LineTo(Point::new(*x, *y)) })
|
||||
.collect(),
|
||||
);
|
||||
let d = crate::vector_behaviour_tests::strays(&drawn, &polyline);
|
||||
assert!(d <= 1.5, "{what}: the stroke strays {d} from the samples: {}", drawn.to_svg());
|
||||
let samples_box = figcraft_geom::points_bounds(samples.iter().map(|(x, y)| Point::new(*x, *y))).unwrap();
|
||||
let node_box = doc.world_bounds(n.id).unwrap();
|
||||
if tool == "pencil" {
|
||||
assert!(samples_box.inflate(1.5, 1.5).contains_rect(node_box), "{what}: the layer {node_box:?}, the samples {samples_box:?}");
|
||||
}
|
||||
// The turn is a point of the stroke, where it was drawn.
|
||||
if samples == back {
|
||||
let xf = doc.world_transform(n.id);
|
||||
assert!(
|
||||
network.vertices.iter().any(|v| (xf * Point::new(v.x, v.y) - Point::new(q.0, q.1)).hypot() < 1e-6),
|
||||
"{what}: no point at the turn"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,32 @@ pub struct DropSlot {
|
||||
/// placed child whose centre is past the pointer, and the line to draw there. Hidden children and
|
||||
/// those ignoring auto layout don't take part.
|
||||
pub fn auto_layout_slot(doc: &Document, parent: NodeId, p: Point, exclude: &[NodeId]) -> Option<(usize, Option<[f64; 4]>)> {
|
||||
slot_in(doc, parent, p, exclude, None)
|
||||
}
|
||||
|
||||
/// [`auto_layout_slot`] for layers dragged within their own frame (measured in Figma's web app,
|
||||
/// 2026-11-09): the slot follows the leading edge of `moved` in the direction of `delta`. The caller
|
||||
/// passes `moved` as the layers' combined start bounds plus the raw (unsnapped) drag, and `delta`
|
||||
/// as that same drag on the page; only its sign along the flow axis matters, and a zero delta uses
|
||||
/// the low edge. Wrapping layouts keep the pointer rule.
|
||||
pub fn auto_layout_slot_within(
|
||||
doc: &Document,
|
||||
parent: NodeId,
|
||||
p: Point,
|
||||
exclude: &[NodeId],
|
||||
moved: figcraft_geom::Rect,
|
||||
delta: Point,
|
||||
) -> Option<(usize, Option<[f64; 4]>)> {
|
||||
slot_in(doc, parent, p, exclude, Some((moved, delta)))
|
||||
}
|
||||
|
||||
fn slot_in(
|
||||
doc: &Document,
|
||||
parent: NodeId,
|
||||
p: Point,
|
||||
exclude: &[NodeId],
|
||||
dragged: Option<(figcraft_geom::Rect, Point)>,
|
||||
) -> Option<(usize, Option<[f64; 4]>)> {
|
||||
let pn = doc.node(parent)?;
|
||||
let layout = pn.layout.as_ref()?;
|
||||
let vertical = layout.mode == LayoutMode::Vertical;
|
||||
@@ -34,11 +60,17 @@ pub fn auto_layout_slot(doc: &Document, parent: NodeId, p: Point, exclude: &[Nod
|
||||
let (k, line) = wrap_slot(doc, &flow_ids, p, vertical);
|
||||
return Some((index(k), line));
|
||||
}
|
||||
let pos = if vertical { p.y } else { p.x };
|
||||
let k = flow_ids
|
||||
.iter()
|
||||
.position(|c| doc.world_bounds(*c).is_some_and(|b| pos < if vertical { b.center().y } else { b.center().x }))
|
||||
.unwrap_or(flow_ids.len());
|
||||
let mid = |c: &NodeId| doc.world_bounds(*c).map(|b| if vertical { b.center().y } else { b.center().x });
|
||||
let k = if let Some((r, d)) = dragged {
|
||||
let (lo, hi, dd) = if vertical { (r.y0, r.y1, d.y) } else { (r.x0, r.x1, d.x) };
|
||||
// Forward: past every sibling whose middle the leading (high) edge has reached; backward: past
|
||||
// every one whose middle lies before the leading (low) edge. A zero delta (no move along the
|
||||
// flow) takes the backward rule, which leaves the layers where they were.
|
||||
flow_ids.iter().position(|c| mid(c).is_some_and(|m| if dd > 0.0 { m > hi } else { m >= lo })).unwrap_or(flow_ids.len())
|
||||
} else {
|
||||
let pos = if vertical { p.y } else { p.x };
|
||||
flow_ids.iter().position(|c| mid(c).is_some_and(|m| pos < m)).unwrap_or(flow_ids.len())
|
||||
};
|
||||
let line = flow_ids.get(k).and_then(|c| doc.world_bounds(*c)).map(|b| line_before(b, vertical, 2.0)).or_else(|| {
|
||||
flow_ids
|
||||
.last()
|
||||
|
||||
@@ -8,7 +8,7 @@ use figcraft_doc::{Document, NodeId};
|
||||
use figcraft_geom::Point;
|
||||
|
||||
use crate::cmd::edit::roots;
|
||||
use crate::tools::{SNAP_PX, selection_box};
|
||||
use crate::tools::{UNMEASURED_SNAP_PX, selection_box};
|
||||
use crate::{DocState, EngineError, Result, Session};
|
||||
|
||||
/// How near (screen pixels) a press must be to grab the origin handle.
|
||||
@@ -115,7 +115,7 @@ impl Session {
|
||||
let snapped = box_points(&ds.doc, &ds.selection).and_then(|b| {
|
||||
b.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, q)| (**q - p).hypot() * zoom.max(1e-6) <= SNAP_PX)
|
||||
.filter(|(_, q)| (**q - p).hypot() * zoom.max(1e-6) <= UNMEASURED_SNAP_PX)
|
||||
.min_by(|x, y| (*x.1 - p).hypot().total_cmp(&(*y.1 - p).hypot()))
|
||||
.map(|(i, q)| (i, *q))
|
||||
});
|
||||
|
||||
@@ -6,12 +6,16 @@
|
||||
//! [`INSET_PX`] in, so it can be grabbed at radius 0). Dragging it along the bisector sets the
|
||||
//! radius of every corner; with Alt, only that corner of a rectangle or frame (the documentation
|
||||
//! is silent on Alt).
|
||||
//! - **Count**: a polygon's or star's sits on its first point clockwise from the top; dragging it
|
||||
//! sets the count from the pointer's angle about the centre, measured clockwise from the top
|
||||
//! point: `round(360 / angle)`, clamped to 3 to 60 (measured in Figma's web app, 2026-11-12; a
|
||||
//! polygon's maximum wasn't read).
|
||||
//! - **Ratio**: a star's sits on its first inner point; dragging it towards or away from the
|
||||
//! centre sets the inner radius as a share of the outer one.
|
||||
//!
|
||||
//! Positions are in page coordinates and work for rotated and flipped layers at any zoom; the
|
||||
//! handles hide on layers smaller than [`MIN_PX`] on screen. The Move tool's gesture (`tools.rs`)
|
||||
//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`), one
|
||||
//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`, `pointCount`), one
|
||||
//! undo step per drag.
|
||||
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
@@ -20,18 +24,22 @@ use serde::Serialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// One shape handle: a corner's radius (corner index: tl, tr, br, bl; 0 for a polygon's or
|
||||
/// star's top point) or a star's ratio.
|
||||
/// star's top point), a star's ratio or a polygon's or star's point count.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "kind")]
|
||||
pub enum ShapeHandle {
|
||||
Radius { corner: usize },
|
||||
Ratio,
|
||||
Count,
|
||||
}
|
||||
|
||||
/// Layers smaller than this on screen (either side, in pixels) show no shape handles.
|
||||
pub const MIN_PX: f64 = 48.0;
|
||||
/// How far in from its corner a handle sits at least (screen pixels).
|
||||
pub const INSET_PX: f64 = 10.0;
|
||||
/// The fewest and most points the Count handle sets (a star's range in the help center).
|
||||
const COUNT_MIN: f64 = 3.0;
|
||||
const COUNT_MAX: f64 = 60.0;
|
||||
/// How near the pointer must be to pick a handle (screen pixels).
|
||||
const HIT_PX: f64 = 6.0;
|
||||
|
||||
@@ -113,6 +121,34 @@ fn ratio_point(n: &Node, count: u32, ratio: f64) -> Option<Point> {
|
||||
figcraft_geom::star_points(n.width, n.height, count, ratio).get(1).copied()
|
||||
}
|
||||
|
||||
/// The Count handle (local): a polygon's vertex 1 or a star's outer point 1, the first clockwise
|
||||
/// from the top.
|
||||
fn count_point(n: &Node) -> Option<Point> {
|
||||
match n.kind {
|
||||
NodeKind::Polygon { count } => figcraft_geom::polygon_points(n.width, n.height, count).get(1).copied(),
|
||||
NodeKind::Star { count, inner_ratio } => figcraft_geom::star_points(n.width, n.height, count, inner_ratio).get(2).copied(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The count a pointer at local point `q` sets: `round(360 / angle)` for its clockwise angle from
|
||||
/// the top about the centre, on the unit circle the shape's box maps from; finite for any `q`.
|
||||
fn count_at(n: &Node, q: Point) -> Option<f64> {
|
||||
let (rx, ry) = (n.width / 2.0, n.height / 2.0);
|
||||
if rx.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || ry.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
|
||||
return None;
|
||||
}
|
||||
let (x, y) = (q.x / rx - 1.0, q.y / ry - 1.0);
|
||||
// On the centre there is no direction (atan2 of two zeros would read as 180 degrees): treat it
|
||||
// as no angle, the most points.
|
||||
if x.hypot(y) < 1e-9 {
|
||||
return Some(COUNT_MAX);
|
||||
}
|
||||
let angle = x.atan2(-y).rem_euclid(std::f64::consts::TAU).to_degrees();
|
||||
let count = (360.0 / angle.max(1e-9)).round();
|
||||
count.is_finite().then(|| count.clamp(COUNT_MIN, COUNT_MAX))
|
||||
}
|
||||
|
||||
/// The shape handles of the selection at `zoom` (screen pixels per page unit): each handle and
|
||||
/// where it is (page coordinates).
|
||||
pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [f64; 2])> {
|
||||
@@ -128,6 +164,9 @@ pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [
|
||||
{
|
||||
out.push((ShapeHandle::Ratio, pt(p)));
|
||||
}
|
||||
if let Some(p) = count_point(n) {
|
||||
out.push((ShapeHandle::Count, pt(p)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -160,6 +199,10 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) ->
|
||||
};
|
||||
Some(Map::from_iter([(key.to_string(), json!(r))]))
|
||||
}
|
||||
ShapeHandle::Count => {
|
||||
count_point(n)?;
|
||||
Some(Map::from_iter([("pointCount".to_string(), json!(count_at(n, q)?))]))
|
||||
}
|
||||
ShapeHandle::Ratio => {
|
||||
let NodeKind::Star { count, .. } = n.kind else { return None };
|
||||
// Along the inner point's ray, measured on the unit circle the star's box maps from.
|
||||
@@ -172,11 +215,12 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// The live readout while dragging `h` of `id`: the corner's radius, or the star's ratio in percent.
|
||||
/// The live readout while dragging `h` of `id`: the corner's radius, the star's ratio in percent or the point count.
|
||||
pub fn value(doc: &Document, id: NodeId, h: ShapeHandle) -> Option<f64> {
|
||||
let n = doc.node(id)?;
|
||||
let v = match (h, &n.kind) {
|
||||
(ShapeHandle::Ratio, NodeKind::Star { inner_ratio, .. }) => inner_ratio * 100.0,
|
||||
(ShapeHandle::Count, NodeKind::Polygon { count }) | (ShapeHandle::Count, NodeKind::Star { count, .. }) => f64::from(*count),
|
||||
(ShapeHandle::Radius { corner }, _) => corners(n).into_iter().nth(corner).map(|(c, r)| r.clamp(0.0, c.max_r))?,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::guides;
|
||||
use crate::tools::SNAP_PX;
|
||||
use crate::tools::UNMEASURED_SNAP_PX;
|
||||
|
||||
/// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label
|
||||
/// (a distance) at its middle; `dashed` marks a measurement's extension line.
|
||||
@@ -438,14 +438,14 @@ impl Targets {
|
||||
}
|
||||
|
||||
/// Snap a guide on `owner` (a page or a top-level frame) to the nearest layer edge or centre along
|
||||
/// its own axis, within `SNAP_PX` screen pixels at `zoom`. Returns the new offset in `owner`'s
|
||||
/// its own axis, within `UNMEASURED_SNAP_PX` screen pixels at `zoom`. Returns the new offset in `owner`'s
|
||||
/// coordinates, or `None` when nothing is in reach.
|
||||
pub fn snap_guide(doc: &Document, page: NodeId, owner: NodeId, vertical: bool, offset: f64, zoom: f64) -> Option<f64> {
|
||||
// The guide moves along the owner's own axis (x for a vertical guide, y for a horizontal one),
|
||||
// which the owner's transform may scale: convert the screen-pixel reach into owner units.
|
||||
let [a, b, c, d, _, _] = doc.world_transform(owner).as_coeffs();
|
||||
let axis = if vertical { a.hypot(b) } else { c.hypot(d) };
|
||||
let threshold = SNAP_PX / (zoom.max(1e-6) * axis.max(1e-6));
|
||||
let threshold = UNMEASURED_SNAP_PX / (zoom.max(1e-6) * axis.max(1e-6));
|
||||
Targets::gather_for_guide(doc, page, owner).snap_axis(vertical, offset, threshold).map(|d| offset + d).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
|
||||
@@ -284,32 +284,57 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInse
|
||||
let text = normalized;
|
||||
edit(s, |t, te| {
|
||||
let (a, b) = range(te);
|
||||
// "- ", "* ", "1. " or "1) " typed at the start of a plain paragraph starts a list (the
|
||||
// creation characters of Create bulleted and numbered lists).
|
||||
// "- ", "* ", "<number>. " or "1) " typed at the start of a plain paragraph starts a list
|
||||
// (the creation characters of Create bulleted and numbered lists). As measured in Figma
|
||||
// (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number
|
||||
// field). "0. " and a bracket after a number other than 1 are not measured: plain text.
|
||||
if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
|
||||
let chars: Vec<char> = t.characters.chars().collect();
|
||||
let start = line_start(&chars, a);
|
||||
let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect();
|
||||
let mut first = 1_u32;
|
||||
let list = match typed.as_str() {
|
||||
"-" | "*" => ListStyle::Bulleted,
|
||||
"1." | "1)" => ListStyle::Numbered,
|
||||
_ => ListStyle::None,
|
||||
"1)" => ListStyle::Numbered,
|
||||
_ => match typed.strip_suffix('.').filter(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) {
|
||||
Some(d) => match d.parse::<u32>() {
|
||||
Ok(n) if (1..=MAX_TYPED_LIST_START).contains(&n) => {
|
||||
first = n;
|
||||
ListStyle::Numbered
|
||||
}
|
||||
_ => ListStyle::None,
|
||||
},
|
||||
None => ListStyle::None,
|
||||
},
|
||||
};
|
||||
if list != ListStyle::None {
|
||||
t.replace_range(start, a, "");
|
||||
t.set_para_lists(start, start, |pl| pl.list = list);
|
||||
t.set_para_lists(start, start, |pl| {
|
||||
pl.list = list;
|
||||
pl.start_offset = first - 1;
|
||||
});
|
||||
(te.caret, te.anchor) = (start, start);
|
||||
outcome = ImeInsertion::Transformed;
|
||||
return;
|
||||
}
|
||||
}
|
||||
t.replace_range(a, b, &text);
|
||||
// As measured in Figma (2026-11-11): an item made by Enter has no start of its own, so
|
||||
// unlisting the item before it makes it restart at 1 rather than at the copied start.
|
||||
// Every paragraph after the first that the insertion made loses the start it was copied.
|
||||
if text.contains('\n') {
|
||||
let end = a + text.chars().count();
|
||||
t.clear_list_starts(t.para_of(a) + 1, t.para_of(end));
|
||||
}
|
||||
te.caret = a + text.chars().count();
|
||||
te.anchor = te.caret;
|
||||
})?;
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// The largest number a typed `N. ` can start a numbered list at.
|
||||
const MAX_TYPED_LIST_START: u32 = 9999;
|
||||
|
||||
/// What a list key does to the selected items.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ListMove {
|
||||
|
||||
@@ -32,9 +32,9 @@ use handles::DRAG_SLOP_PX;
|
||||
pub(crate) use handles::scale_factor;
|
||||
pub use handles::{
|
||||
PENCIL_STROKE, SMALL_BOX_PX, anchor_name, anchor_of, box_sides_px, handle_at, handle_at_corners, label_at, locked_in, scale_anchor_point,
|
||||
selection_box, selection_frame,
|
||||
selection_box, selection_frame, shared_rotation_degrees,
|
||||
};
|
||||
pub(crate) use handles::{SNAP_PX, handle_cursor, readable_text_fills, resized_box};
|
||||
pub(crate) use handles::{SNAP_PX, UNMEASURED_SNAP_PX, handle_cursor, readable_text_fills, resized_box};
|
||||
#[cfg(test)]
|
||||
pub(crate) use pen::pressure_profile;
|
||||
|
||||
@@ -58,6 +58,7 @@ pub enum ToolId {
|
||||
Text,
|
||||
TextOnPath,
|
||||
Comment,
|
||||
Annotation,
|
||||
Eyedropper,
|
||||
ShapeBuilder,
|
||||
// Board tools.
|
||||
@@ -71,7 +72,7 @@ pub enum ToolId {
|
||||
}
|
||||
|
||||
impl ToolId {
|
||||
pub const ALL: [ToolId; 26] = [
|
||||
pub const ALL: [ToolId; 27] = [
|
||||
ToolId::Move,
|
||||
ToolId::Scale,
|
||||
ToolId::Hand,
|
||||
@@ -89,6 +90,7 @@ impl ToolId {
|
||||
ToolId::Text,
|
||||
ToolId::TextOnPath,
|
||||
ToolId::Comment,
|
||||
ToolId::Annotation,
|
||||
ToolId::Eyedropper,
|
||||
ToolId::ShapeBuilder,
|
||||
ToolId::Sticky,
|
||||
@@ -118,6 +120,7 @@ impl ToolId {
|
||||
ToolId::Text => "text",
|
||||
ToolId::TextOnPath => "textOnPath",
|
||||
ToolId::Comment => "comment",
|
||||
ToolId::Annotation => "annotation",
|
||||
ToolId::Eyedropper => "eyedropper",
|
||||
ToolId::ShapeBuilder => "shapeBuilder",
|
||||
ToolId::Sticky => "sticky",
|
||||
@@ -129,6 +132,11 @@ impl ToolId {
|
||||
ToolId::Stamp => "stamp",
|
||||
}
|
||||
}
|
||||
/// Whether Developer Mode keeps this tool: it only inspects, so the tools that edit leave it.
|
||||
/// The one list behind the engine's pointer routing and command allowlist and the toolbar.
|
||||
pub fn works_in_dev_mode(self) -> bool {
|
||||
matches!(self, ToolId::Move | ToolId::Hand | ToolId::Comment | ToolId::Annotation)
|
||||
}
|
||||
pub fn from_id(s: &str) -> Option<ToolId> {
|
||||
ToolId::ALL.into_iter().find(|t| t.id().eq_ignore_ascii_case(s))
|
||||
}
|
||||
@@ -151,6 +159,7 @@ impl ToolId {
|
||||
ToolId::Text => "Text",
|
||||
ToolId::TextOnPath => "Text on a path",
|
||||
ToolId::Comment => "Comment",
|
||||
ToolId::Annotation => "Annotation",
|
||||
ToolId::Eyedropper => "Pick color",
|
||||
ToolId::ShapeBuilder => "Shape builder",
|
||||
ToolId::Sticky => "Sticky note",
|
||||
@@ -445,6 +454,8 @@ pub(crate) enum Gesture {
|
||||
Rotate {
|
||||
center: Point,
|
||||
start_angle: f64,
|
||||
/// The rotation (Design panel convention) the layers share when the drag began, else 0.
|
||||
base: f64,
|
||||
ids: Vec<NodeId>,
|
||||
},
|
||||
Draw {
|
||||
@@ -575,8 +586,9 @@ pub struct ToolState {
|
||||
/// Vector edit mode's pen: where the last press that started something new (no path being
|
||||
/// drawn) was, and the undo depth before it, so a double-click there takes that edit back.
|
||||
pub(crate) pen_press: Option<(Point, usize)>,
|
||||
/// The Scale tool's anchor: column and row (0 start, 1 middle, 2 end) of the point of the
|
||||
/// selection box that stays put (`tool.scaleAnchor`).
|
||||
/// The Scale tool's origin: column and row (0 start, 1 middle, 2 end) of the point of the
|
||||
/// selection box that stays put when the Scale field sets a factor (`tool.scaleAnchor`; the
|
||||
/// centre, `(1, 1)`, until set). Handle drags ignore it and pivot on the opposite handle.
|
||||
pub scale_anchor: (u8, u8),
|
||||
/// The last drag move handled (a held button repeats it every frame).
|
||||
pub(crate) last_move: Option<PointerEvent>,
|
||||
|
||||
@@ -360,8 +360,13 @@ impl Session {
|
||||
pub(super) fn eyedrop(&mut self, ev: &PointerEvent) -> Result<()> {
|
||||
let ds = self.ds()?;
|
||||
let doc = ds.doc.clone();
|
||||
let view = figcraft_render::View { origin: (ev.x, ev.y), scale: ev.zoom.max(0.01), width: 1, height: 1 };
|
||||
let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &Default::default()) else { return Ok(()) };
|
||||
// One screen pixel centred on the pointer (its top left half a pixel up and to the left).
|
||||
let scale = ev.zoom.max(0.01);
|
||||
let view = figcraft_render::View { origin: (ev.x - 0.5 / scale, ev.y - 0.5 / scale), scale, width: 1, height: 1 };
|
||||
// As the canvas draws it: an image magnified past 2x shows its pixels, so the colour picked
|
||||
// is the pixel under the pointer, not a blend with its neighbours (#2189).
|
||||
let opts = figcraft_render::Options { magnified_image_pixels: true, ..Default::default() };
|
||||
let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &opts) else { return Ok(()) };
|
||||
let rgba = figcraft_render::to_rgba8(&pix);
|
||||
let c = figcraft_color::Color::from_rgba8(
|
||||
rgba.first().copied().unwrap_or(0),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::handles::{
|
||||
SNAP_PX, handle_at, in_quad, label_at, locked_in, on_corner_square, paints_below, resized_box, scale_factor, selection_box, selection_frame,
|
||||
shape_hint,
|
||||
shape_hint, shared_rotation_degrees,
|
||||
};
|
||||
use super::{
|
||||
Affine, ArcHandle, ArcHint, Cursor, Document, Gesture, Guide, Handle, ImageScaleMode, LayoutMode, NodeId, NodeKind, PaintKind, Point,
|
||||
@@ -58,7 +58,8 @@ impl Session {
|
||||
.moved_origin()
|
||||
.unwrap_or_else(|| Point::new(b.iter().map(|c| c.x).sum::<f64>() / 4.0, b.iter().map(|c| c.y).sum::<f64>() / 4.0));
|
||||
self.begin_interaction("Rotate")?;
|
||||
self.tool.gesture = Gesture::Rotate { center, start_angle: (ev.p() - center).atan2(), ids };
|
||||
self.tool.gesture =
|
||||
Gesture::Rotate { center, start_angle: (ev.p() - center).atan2(), base: shared_rotation_degrees(&doc, &ids), ids };
|
||||
return Ok(());
|
||||
}
|
||||
let nodes: Vec<(NodeId, Affine, f64, f64)> =
|
||||
@@ -216,6 +217,8 @@ impl Session {
|
||||
}
|
||||
}
|
||||
// Cmd/Ctrl (and Control on macOS) held while dragging suspends snapping.
|
||||
// The pointer's own drag, before snapping: a reorder in auto layout follows it.
|
||||
let raw = d;
|
||||
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
|
||||
let mut guides = Vec::new();
|
||||
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
|
||||
@@ -268,8 +271,18 @@ impl Session {
|
||||
// cell) under the pointer, as the frame shows it now. A frame other than the
|
||||
// one they come from is outlined too.
|
||||
let cell = if mode == LayoutMode::Grid { crate::drop::grid_cell_at(doc, target, p) } else { None };
|
||||
let idx =
|
||||
if mode == LayoutMode::Grid { 0 } else { crate::drop::auto_layout_slot(doc, target, p, &moving).map_or(0, |(i, _)| i) };
|
||||
// Within the frame they came from, the slot follows the leading edge of the
|
||||
// box they would fill (their combined start bounds moved by the drag), not
|
||||
// the pointer. The preview starts from the document as the drag began.
|
||||
let within = moving.iter().all(|m| doc.node(*m).is_some_and(|n| n.parent == Some(target)));
|
||||
let idx = if mode == LayoutMode::Grid {
|
||||
0
|
||||
} else if let (true, Some(b)) = (within, doc.bounds_of(&moving)) {
|
||||
let moved = Rect::new(b.x0 + raw.x, b.y0 + raw.y, b.x1 + raw.x, b.y1 + raw.y);
|
||||
crate::drop::auto_layout_slot_within(doc, target, p, &moving, moved, Point::new(raw.x, raw.y)).map_or(0, |(i, _)| i)
|
||||
} else {
|
||||
crate::drop::auto_layout_slot(doc, target, p, &moving).map_or(0, |(i, _)| i)
|
||||
};
|
||||
for m in &moving {
|
||||
if doc.get(*m)?.parent != Some(target) {
|
||||
doc.reparent(*m, target, None)?;
|
||||
@@ -350,10 +363,11 @@ impl Session {
|
||||
}
|
||||
return res;
|
||||
}
|
||||
Gesture::Rotate { center, start_angle, ids } => {
|
||||
Gesture::Rotate { center, start_angle, base, ids } => {
|
||||
let mut a = ((ev.p() - *center).atan2() - start_angle).to_degrees();
|
||||
if ev.shift {
|
||||
a = (a / 15.0).round() * 15.0;
|
||||
// The panel rotation is base - a; Shift lands it on a multiple of 15 degrees.
|
||||
a = base - ((base - a) / 15.0).round() * 15.0;
|
||||
}
|
||||
let (c, ids) = (*center, ids.clone());
|
||||
self.preview(|doc, _| {
|
||||
@@ -626,7 +640,7 @@ impl Session {
|
||||
/// text included, children by the same factor whatever their constraints.
|
||||
fn scale_drag(&mut self, ev: &PointerEvent, r: &ResizeStart, q: Point, guides: Vec<Guide>) -> Result<()> {
|
||||
let (frame, w0, h0) = r.frame;
|
||||
let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, self.tool.scale_anchor, ev.alt) else { return Ok(()) };
|
||||
let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, ev.alt) else { return Ok(()) };
|
||||
let nodes = r.nodes.clone();
|
||||
let inv = frame.inverse();
|
||||
// A layer's place in the box scales about the pivot; a negative factor turns it over.
|
||||
|
||||
@@ -71,8 +71,13 @@ const HANDLE_PX: f64 = 5.0;
|
||||
|
||||
const ROTATE_PX: f64 = 18.0;
|
||||
|
||||
/// Snap distance in screen pixels.
|
||||
pub(crate) const SNAP_PX: f64 = 5.0;
|
||||
/// Object snap distance in screen pixels: measured in Figma, where an edge snaps at a gap of 4.4
|
||||
/// screen px and not at 4.6, at 100% and at 200% zoom.
|
||||
pub(crate) const SNAP_PX: f64 = 4.5;
|
||||
|
||||
/// Snap distance in screen pixels for ruler guides and the rotation origin, not measured against
|
||||
/// Figma.
|
||||
pub(crate) const UNMEASURED_SNAP_PX: f64 = 5.0;
|
||||
|
||||
/// Screen pixels the pointer travels after a press before a move or resize starts: a click or a
|
||||
/// double-click made with an unsteady hand doesn't drag what it lands on.
|
||||
@@ -132,6 +137,14 @@ pub fn selection_frame(doc: &Document, sel: &[NodeId]) -> Option<(Affine, f64, f
|
||||
Some((rot * Affine::translate((b.x0, b.y0)), b.width(), b.height()))
|
||||
}
|
||||
|
||||
/// The rotation `ids` share on the page (degrees, counter-clockwise positive), else 0 (the handle
|
||||
/// box is page-aligned then). Figma's rotation field shows this page rotation, also for a layer
|
||||
/// inside a rotated frame or group, and Shift lands it on multiples of 15 degrees. Axis-aligned
|
||||
/// layers give 0, which is the same as 90, 180 and 270 for stepping in 15 degrees.
|
||||
pub fn shared_rotation_degrees(doc: &Document, ids: &[NodeId]) -> f64 {
|
||||
shared_rotation(doc, ids).map_or(0.0, |a| -a.to_degrees())
|
||||
}
|
||||
|
||||
/// The rotation (radians) every layer in `ids` shares, unless it's a multiple of 90 degrees (the
|
||||
/// page-aligned box is then the same box). Flipped layers count by their axis, not its direction.
|
||||
fn shared_rotation(doc: &Document, ids: &[NodeId]) -> Option<f64> {
|
||||
@@ -379,30 +392,22 @@ fn opposite(h: Handle) -> Handle {
|
||||
}
|
||||
|
||||
/// The Scale tool's factor and pivot (in the box's axes) for dragging `handle` of a `w0`×`h0` box
|
||||
/// to `q`. The pivot is the anchor point (`anchor`: column, row), or the opposite handle when the
|
||||
/// anchor lies on the side being dragged, or the centre (`from_center`). Corners follow the axis
|
||||
/// that moved the most; a negative factor flips. None when the box has no size to scale by.
|
||||
pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, anchor: (u8, u8), from_center: bool) -> Option<(f64, Point)> {
|
||||
/// to `q`. The pivot is the opposite handle's point, or the centre (`from_center`); the origin grid
|
||||
/// never decides it (measured in Figma's web app, 2026-11-09). Corners follow the axis that moved
|
||||
/// the most; a negative factor flips. None when the box has no size to scale by.
|
||||
pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, from_center: bool) -> Option<(f64, Point)> {
|
||||
const EPS: f64 = 1e-9;
|
||||
if !(q.x.is_finite() && q.y.is_finite() && w0.is_finite() && h0.is_finite()) || matches!(handle, Handle::Rotate(_)) {
|
||||
return None;
|
||||
}
|
||||
let h = handle_point(handle, w0, h0);
|
||||
let anchor_pt = anchor_in_box(anchor, w0, h0);
|
||||
// The axes the handle moves along.
|
||||
let (ax_x, ax_y) = match handle {
|
||||
Handle::Edge(0) | Handle::Edge(2) => (false, true),
|
||||
Handle::Edge(_) => (true, false),
|
||||
_ => (true, true),
|
||||
};
|
||||
let on_side = (ax_x && (anchor_pt.x - h.x).abs() < EPS) || (ax_y && (anchor_pt.y - h.y).abs() < EPS);
|
||||
let pivot = if from_center {
|
||||
Point::new(w0 / 2.0, h0 / 2.0)
|
||||
} else if on_side {
|
||||
handle_point(opposite(handle), w0, h0)
|
||||
} else {
|
||||
anchor_pt
|
||||
};
|
||||
let pivot = if from_center { Point::new(w0 / 2.0, h0 / 2.0) } else { handle_point(opposite(handle), w0, h0) };
|
||||
let ratio = |on: bool, to: f64, from: f64, p: f64| (on && (from - p).abs() > EPS).then(|| (to - p) / (from - p));
|
||||
let kx = ratio(ax_x, q.x, h.x, pivot.x);
|
||||
let ky = ratio(ax_y, q.y, h.y, pivot.y);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Document, Gesture, Node, NodeId, Overlay, Point, PointerEvent, PointerKind, Result, Session, ShapeHandle, ToolId, json, textedit};
|
||||
use super::{Document, Gesture, NodeId, Overlay, Point, PointerEvent, PointerKind, Result, Session, ShapeHandle, ToolId, json, textedit};
|
||||
|
||||
impl Session {
|
||||
/// Keys the current mode handles before menu shortcuts (vector edit mode's tools and point
|
||||
@@ -146,21 +146,9 @@ impl Session {
|
||||
self.ds_mut()?.focus = None;
|
||||
return Ok(());
|
||||
}
|
||||
// Escape selects the parent, then nothing.
|
||||
let doc = self.doc()?;
|
||||
let parents: Vec<NodeId> =
|
||||
sel.iter().filter_map(|i| doc.node(*i).and_then(|n| n.parent)).filter(|p| !doc.node(*p).is_some_and(Node::is_page)).collect();
|
||||
if !parents.is_empty() {
|
||||
let mut uniq = Vec::new();
|
||||
for p in parents {
|
||||
if !uniq.contains(&p) {
|
||||
uniq.push(p);
|
||||
}
|
||||
}
|
||||
self.set_selection(uniq);
|
||||
} else {
|
||||
self.set_selection(vec![]);
|
||||
}
|
||||
// Escape clears the selection whatever its nesting (measured in Figma: it never selects the
|
||||
// parent).
|
||||
self.set_selection(vec![]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -313,7 +313,8 @@ impl Session {
|
||||
if points.len() < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
// Smooth: fit a curve through the samples.
|
||||
// Smooth: fit a curve through the samples, kept from shooting past them where the stroke
|
||||
// turns back or runs nearly straight (#1741).
|
||||
let mut poly = figcraft_geom::BezPath::new();
|
||||
for (k, p) in points.iter().enumerate() {
|
||||
if k == 0 {
|
||||
@@ -322,7 +323,7 @@ impl Session {
|
||||
poly.line_to(*p);
|
||||
}
|
||||
}
|
||||
let fitted = figcraft_geom::kurbo::simplify::simplify_bezpath(poly.iter(), 0.75, &Default::default());
|
||||
let fitted = figcraft_geom::simplify_path(&poly, 0.75);
|
||||
let d = fitted.to_svg();
|
||||
if matches!(self.tool.tool, ToolId::Marker | ToolId::Highlighter) {
|
||||
return self.ink_finish(&d);
|
||||
|
||||
@@ -47,16 +47,23 @@ impl Session {
|
||||
/// the layers it touches (`deep`: nested ones too); `additive` (Shift) toggles them.
|
||||
pub(crate) fn marquee_selection(&self, r: Rect, within: Option<NodeId>, deep: bool, base: &[NodeId], additive: bool) -> Result<Vec<NodeId>> {
|
||||
let (doc, page) = (self.doc()?, self.page()?);
|
||||
let mut hits =
|
||||
if deep { figcraft_doc::geometry::marquee_deep(doc, page, r) } else { figcraft_doc::geometry::marquee_select(doc, page, r, within) };
|
||||
if let Some(f) = self.ds()?.focused() {
|
||||
let focused = self.ds()?.focused();
|
||||
let mut hits = match (deep, focused) {
|
||||
(true, _) => figcraft_doc::geometry::marquee_deep(doc, page, r),
|
||||
(false, Some(f)) => figcraft_doc::geometry::marquee(doc, page, r, Some(f)),
|
||||
(false, None) => figcraft_doc::geometry::marquee_select(doc, page, r, within),
|
||||
};
|
||||
if let Some(f) = focused {
|
||||
hits.retain(|h| *h != f && doc.is_ancestor(f, *h));
|
||||
}
|
||||
// A marquee over a frame from outside selects the frame only when it covers it fully.
|
||||
if within.is_none() && !deep {
|
||||
// A widget's layers are part of the widget: a marquee from outside never opens one.
|
||||
if !deep {
|
||||
hits.retain(|h| {
|
||||
let full = doc.world_bounds(*h).is_some_and(|b| r.contains(b.origin()) && r.contains(Point::new(b.x1, b.y1)));
|
||||
full || !doc.node(*h).is_some_and(|n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. }))
|
||||
doc.node(*h)
|
||||
.and_then(|n| n.parent)
|
||||
.filter(|p| Some(*p) != within)
|
||||
.and_then(|p| doc.node(p))
|
||||
.is_none_or(|p| !crate::widgets::is_widget(p))
|
||||
});
|
||||
}
|
||||
// Shift toggles: what was selected and is touched again comes out.
|
||||
@@ -103,7 +110,7 @@ impl Session {
|
||||
/// The tool pointer events go to: in Dev Mode every tool but the hand and comments selects.
|
||||
fn acting_tool(&self) -> ToolId {
|
||||
match self.tool.tool {
|
||||
t if self.tool.dev_mode && !matches!(t, ToolId::Hand | ToolId::Comment) => ToolId::Move,
|
||||
t if self.tool.dev_mode && !t.works_in_dev_mode() => ToolId::Move,
|
||||
t => t,
|
||||
}
|
||||
}
|
||||
@@ -169,6 +176,7 @@ impl Session {
|
||||
self.request_ui("comment.new", json!({"x": ev.x, "y": ev.y}));
|
||||
Ok(())
|
||||
}
|
||||
ToolId::Annotation => self.annotation_down(ev),
|
||||
ToolId::Eyedropper => self.eyedrop(ev),
|
||||
t if t.on_boards() => self.board_down(ev),
|
||||
t if t.draws_shape() => self.draw_down(ev),
|
||||
@@ -199,6 +207,19 @@ impl Session {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The Annotation tool's press: the layer under the pointer is selected and the UI is asked
|
||||
/// for its note (the engine writes nothing; the note is typed in the Inspect tab). A press on
|
||||
/// empty canvas does nothing.
|
||||
fn annotation_down(&mut self, ev: &PointerEvent) -> Result<()> {
|
||||
let ds = self.ds()?;
|
||||
let (doc, page) = (ds.doc.clone(), ds.page);
|
||||
// The same reach as the Move tool's pick (`ev.tol() * 2.0`); never the page itself.
|
||||
let Some(id) = self.hit(&doc, page, ev.p(), ev.tol() * 2.0).filter(|i| doc.node(*i).is_some_and(|n| !n.is_page())) else { return Ok(()) };
|
||||
self.set_selection(vec![id]);
|
||||
self.request_ui("annotation.new", json!({"id": id}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn hover(&mut self, ev: &PointerEvent) -> Result<()> {
|
||||
let tool = self.acting_tool();
|
||||
let ds = self.ds()?;
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
pub mod ops;
|
||||
pub(crate) mod point_snap;
|
||||
mod pointer;
|
||||
#[cfg(test)]
|
||||
mod position_tests;
|
||||
pub mod regions;
|
||||
#[cfg(test)]
|
||||
mod regions_tests;
|
||||
@@ -638,7 +640,7 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result<usize> {
|
||||
}
|
||||
|
||||
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
|
||||
fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
|
||||
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
|
||||
let doc = s.doc_mut()?;
|
||||
for EditPart { id, vertices: verts, segments: segs } in parts {
|
||||
edit(doc, id, |net| {
|
||||
@@ -706,7 +708,61 @@ fn handle_list(p: &Value, key: &str) -> Option<Vec<(usize, bool)>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Selection bounds' top-left in the parent's coordinates (what the X/Y fields show).
|
||||
/// One axis of `vector.edit.position`: left alone, set, or relative to each point's own value.
|
||||
#[derive(Clone, Copy)]
|
||||
enum AxisEdit {
|
||||
Keep,
|
||||
Set(f64),
|
||||
Add(f64),
|
||||
Mul(f64),
|
||||
Div(f64),
|
||||
}
|
||||
|
||||
impl AxisEdit {
|
||||
fn apply(self, cur: f64) -> Result<f64> {
|
||||
let v = match self {
|
||||
AxisEdit::Keep => cur,
|
||||
AxisEdit::Set(v) => v,
|
||||
AxisEdit::Add(n) => cur + n,
|
||||
AxisEdit::Mul(n) => cur * n,
|
||||
AxisEdit::Div(n) if n != 0.0 => cur / n,
|
||||
AxisEdit::Div(_) => return Err(bad("vector.edit.position", "cannot divide by zero")),
|
||||
};
|
||||
if v.is_finite() { Ok(v) } else { Err(bad("vector.edit.position", "the result is not a number")) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `p[key]`: absent is `Keep`, a number is `Set`, `{add|mul|div: n}` is relative; anything else is refused.
|
||||
fn axis_edit(p: &Value, key: &str) -> Result<AxisEdit> {
|
||||
let junk = || bad("vector.edit.position", format!("`{key}` must be a number or {{add|mul|div: number}}"));
|
||||
match get(p, key) {
|
||||
None => Ok(AxisEdit::Keep),
|
||||
Some(Value::Object(o)) => {
|
||||
let (Some((k, v)), 1) = (o.iter().next(), o.len()) else { return Err(junk()) };
|
||||
let n = match v {
|
||||
Value::Number(n) => n.as_f64().filter(|n| n.is_finite()),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(junk)?;
|
||||
match k.as_str() {
|
||||
"add" => Ok(AxisEdit::Add(n)),
|
||||
"mul" => Ok(AxisEdit::Mul(n)),
|
||||
"div" if n != 0.0 => Ok(AxisEdit::Div(n)),
|
||||
_ => Err(junk()),
|
||||
}
|
||||
}
|
||||
Some(v) => f64_of(v).filter(|_| !v.is_boolean()).map(AxisEdit::Set).ok_or_else(junk),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected points in the parent's coordinates (what the X/Y fields show).
|
||||
pub fn selected_parent_points(doc: &Document, ve: &VectorEdit) -> Vec<Point> {
|
||||
let Some(net) = network(doc, ve.id) else { return Vec::new() };
|
||||
let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default();
|
||||
selected_points(net, ve).into_iter().filter_map(|v| net.vertices.get(v)).map(|v| t * v.point()).collect()
|
||||
}
|
||||
|
||||
/// Selection bounds' top-left in the parent's coordinates (the `x` and `y` of `vector.edit.bounds`).
|
||||
pub fn selection_position(doc: &Document, ve: &VectorEdit) -> Option<Point> {
|
||||
let net = network(doc, ve.id)?;
|
||||
let t = doc.node(ve.id)?.transform;
|
||||
@@ -935,18 +991,50 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
edit_sets(s, sets, |net, v, w| ops::move_vertices(net, v, local_offset(w, d)))?;
|
||||
Ok(json!({"ok": true}))
|
||||
}),
|
||||
spec!("vector.edit.position", "Point position", "{x?, y?} (the selected points' top-left, in the parent's coordinates)", true, |s, p| {
|
||||
let ve = editing(s)?;
|
||||
let doc = s.doc()?;
|
||||
let cur = selection_position(doc, &ve).ok_or_else(|| bad("vector.edit.position", "select points"))?;
|
||||
let target = Point::new(num_or(p, "x", cur.x), num_or(p, "y", cur.y));
|
||||
let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default();
|
||||
let inv = t.inverse();
|
||||
let d = inv * target - inv * cur;
|
||||
let v = network(doc, ve.id).map(|n| selected_points(n, &ve)).unwrap_or_default();
|
||||
edit(s.doc_mut()?, ve.id, |net| ops::move_vertices(net, &v, d))?;
|
||||
Ok(json!({"ok": true}))
|
||||
}),
|
||||
spec!(
|
||||
"vector.edit.position",
|
||||
"Point position",
|
||||
"{x?, y?}: each a number (every selected point's own coordinate becomes it) or {add: n}, {mul: n} or {div: n} (applied to each selected point's own coordinate); in the parent's coordinates",
|
||||
true,
|
||||
|s, p| {
|
||||
let ve = editing(s)?;
|
||||
let doc = s.doc()?;
|
||||
let (ax, ay) = (axis_edit(p, "x")?, axis_edit(p, "y")?);
|
||||
let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default();
|
||||
let inv = t.inverse();
|
||||
let net = network(doc, ve.id).ok_or_else(|| bad("vector.edit.position", "select points"))?;
|
||||
let mut moves: Vec<(usize, Vec2)> = Vec::new();
|
||||
for i in selected_points(net, &ve) {
|
||||
let Some(v) = net.vertices.get(i) else { continue };
|
||||
let cur = t * v.point();
|
||||
let target = Point::new(ax.apply(cur.x)?, ay.apply(cur.y)?);
|
||||
let d = inv * target - v.point();
|
||||
if !(d.x.is_finite() && d.y.is_finite()) {
|
||||
return Err(bad("vector.edit.position", "the result is not a number"));
|
||||
}
|
||||
moves.push((i, d));
|
||||
}
|
||||
if moves.is_empty() {
|
||||
return Err(bad("vector.edit.position", "select points"));
|
||||
}
|
||||
// Points that all share one offset move as one, so moving every point of a layer
|
||||
// by one offset still carries the regions' paint frames, as a drag of all of them
|
||||
// does. Otherwise no one move covers every point, so each point moves alone.
|
||||
let d0 = moves[0].1;
|
||||
let uniform = moves.iter().all(|(_, d)| (*d - d0).hypot() < 1e-9);
|
||||
edit(s.doc_mut()?, ve.id, |net| {
|
||||
if uniform {
|
||||
let all: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
|
||||
ops::move_vertices(net, &all, d0);
|
||||
} else {
|
||||
for (i, d) in &moves {
|
||||
ops::move_vertices(net, &[*i], *d);
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
),
|
||||
spec!("vector.edit.setHandle", "Set handle", "{segment, start (bool), x, y (local), independent?}", true, |s, p| {
|
||||
let ve = editing(s)?;
|
||||
let seg = index("vector.edit.setHandle", p, "segment")?;
|
||||
|
||||
@@ -124,9 +124,62 @@ pub fn move_handles(net: &mut VectorNetwork, hs: &[(usize, bool)], d: Vec2, inde
|
||||
}
|
||||
}
|
||||
|
||||
/// Each handle of a sharp point turned smooth by a mirror mode is this fraction of the length of its
|
||||
/// own segment. Measured in the incumbent (0.3905 and 0.390 at two angles): known to about 3 digits only.
|
||||
const MIRROR_SMOOTH_FACTOR: f64 = 0.3905;
|
||||
|
||||
/// Give a sharp point (two segments, no handles) the handles a mirror mode makes in the incumbent.
|
||||
/// Both lie on one line through the point, along `(B - A) / |BA|^2 + (C - B) / |BC|^2` (A, C: the far
|
||||
/// ends of the two segments). "Angle": each is [`MIRROR_SMOOTH_FACTOR`] x its own segment.
|
||||
/// "Angle and length": both are that factor x the shorter segment (medium confidence: the
|
||||
/// measurement could not separate this from other rules). Open-path ends, points with a handle
|
||||
/// already and coincident neighbours are left alone. Returns whether handles were made.
|
||||
fn smooth_sharp_point(net: &mut VectorNetwork, vi: usize, mode: HandleMirroring) -> bool {
|
||||
if mode == HandleMirroring::None {
|
||||
return false;
|
||||
}
|
||||
let inc = net.incident(vi);
|
||||
let [(s1, a1), (s2, a2)] = inc.as_slice() else { return false };
|
||||
let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2)) else { return false };
|
||||
if tvec(h1).hypot() > 1e-9 || tvec(h2).hypot() > 1e-9 {
|
||||
return false;
|
||||
}
|
||||
let far = |s: usize, st: bool| net.segments.get(s).and_then(|x| net.vertices.get(if st { x.b } else { x.a })).map(|v| v.point());
|
||||
let (Some(b), Some(a), Some(c)) = (net.vertices.get(vi).map(|v| v.point()), far(*s1, *a1), far(*s2, *a2)) else { return false };
|
||||
let (ab, bc) = (b - a, c - b);
|
||||
let (la, lc) = (ab.hypot(), bc.hypot());
|
||||
if !(la > 1e-9 && lc > 1e-9 && la.is_finite() && lc.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let d = ab / (la * la) + bc / (lc * lc);
|
||||
if !finite(d) || d.hypot() < 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let d = d.normalize();
|
||||
let (l_in, l_out) = if mode == HandleMirroring::AngleAndLength {
|
||||
let l = MIRROR_SMOOTH_FACTOR * la.min(lc);
|
||||
(l, l)
|
||||
} else {
|
||||
(MIRROR_SMOOTH_FACTOR * la, MIRROR_SMOOTH_FACTOR * lc)
|
||||
};
|
||||
let (in_h, out_h) = (-d * l_in, d * l_out);
|
||||
if !(finite(in_h) && finite(out_h)) {
|
||||
return false;
|
||||
}
|
||||
net.set_handle(*s1, *a1, (in_h.x, in_h.y));
|
||||
net.set_handle(*s2, *a2, (out_h.x, out_h.y));
|
||||
true
|
||||
}
|
||||
|
||||
/// Set the mirroring of vertices and make their handles agree with it.
|
||||
pub fn set_mirroring(net: &mut VectorNetwork, verts: &[usize], mode: HandleMirroring) {
|
||||
for &vi in verts {
|
||||
if smooth_sharp_point(net, vi, mode) {
|
||||
if let Some(v) = net.vertices.get_mut(vi) {
|
||||
v.mirror = Some(mode);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let inc = net.incident(vi);
|
||||
if let [(s1, a1), (s2, a2)] = inc.as_slice()
|
||||
&& let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2))
|
||||
@@ -312,6 +365,7 @@ fn remove_vertex_index(net: &mut VectorNetwork, vi: usize) {
|
||||
|
||||
/// Remove segments (fixing region loops); points left without any segment go too.
|
||||
pub fn remove_segments(net: &mut VectorNetwork, segs: &[usize]) {
|
||||
let before = net.segments.len();
|
||||
let mut touched: Vec<usize> = segs.iter().filter_map(|s| net.segments.get(*s)).flat_map(|s| [s.a, s.b]).collect();
|
||||
remove_segments_only(net, segs);
|
||||
touched.sort_unstable();
|
||||
@@ -322,6 +376,9 @@ pub fn remove_segments(net: &mut VectorNetwork, segs: &[usize]) {
|
||||
}
|
||||
}
|
||||
reopen_loops(net);
|
||||
if net.segments.len() != before {
|
||||
close_bridged_loops(net);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_segments_only(net: &mut VectorNetwork, segs: &[usize]) {
|
||||
@@ -349,6 +406,7 @@ fn remove_segments_only(net: &mut VectorNetwork, segs: &[usize]) {
|
||||
|
||||
/// Delete vertices, joining their neighbours where a vertex had exactly two segments (`heal`).
|
||||
pub fn delete_vertices(net: &mut VectorNetwork, idx: &[usize], heal: bool) {
|
||||
let before = net.vertices.len();
|
||||
let mut idx: Vec<usize> = idx.to_vec();
|
||||
idx.sort_unstable();
|
||||
idx.dedup();
|
||||
@@ -408,6 +466,9 @@ pub fn delete_vertices(net: &mut VectorNetwork, idx: &[usize], heal: bool) {
|
||||
}
|
||||
net.sanitize();
|
||||
reopen_loops(net);
|
||||
if net.vertices.len() != before {
|
||||
close_bridged_loops(net);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles for the curve that heals over deleted point `vi` between `(vertex, handle)` ends `o1`
|
||||
@@ -470,6 +531,24 @@ fn reopen_loops(net: &mut VectorNetwork) {
|
||||
}
|
||||
}
|
||||
|
||||
/// After points or segments were removed: an open loop whose two ends a segment in no loop already
|
||||
/// joins (a bridge drawn between two points before what lay between them was deleted) closes
|
||||
/// through that segment, at the loop's end so its winding is kept, as `connect` closes it (#1951).
|
||||
/// Every loop takes what [`VectorNetwork::closing_segment`] gives it against one snapshot of the
|
||||
/// network, which is what rounding walks: two fills that shared the removed border share the
|
||||
/// bridge, as they shared the border. Only a removal can open a loop at two points a segment
|
||||
/// already joins (a cut's ends are new points), so only `delete_vertices` and `remove_segments`
|
||||
/// run this, and only when they removed something.
|
||||
fn close_bridged_loops(net: &mut VectorNetwork) {
|
||||
let index = net.loop_index();
|
||||
let closings: Vec<Option<usize>> = net.regions.iter().flat_map(|r| r.loops.iter()).map(|lp| net.closing_segment(lp, &index)).collect();
|
||||
for (lp, closing) in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()).zip(closings) {
|
||||
if let Some(closing) = closing {
|
||||
lp.push(closing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut a segment at `t` into two open ends at the same spot. Returns the two end vertices.
|
||||
pub fn cut_segment(net: &mut VectorNetwork, seg: usize, t: f64) -> Option<(usize, usize)> {
|
||||
let mid = split_segment(net, seg, t)?;
|
||||
@@ -923,6 +1002,72 @@ mod tests {
|
||||
assert!((a + b).hypot() < 1e-9, "made symmetric: {a:?} {b:?}");
|
||||
}
|
||||
|
||||
/// An open path A, B, C (the measured triangle of #2110) with B sharp.
|
||||
fn triangle_path() -> VectorNetwork {
|
||||
VectorNetwork::from_points(&[Point::new(-250.0, -174.0), Point::new(117.0, -174.0), Point::new(-67.0, 194.0)], false)
|
||||
}
|
||||
|
||||
fn handles_at_b(n: &VectorNetwork) -> (Vec2, Vec2) {
|
||||
(tvec(n.segments[0].tb), tvec(n.segments[1].ta))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_smooth_a_sharp_point_as_measured() {
|
||||
// Mirror angle and length: both handles 0.3905 x the shorter segment (367), opposite.
|
||||
let mut n = triangle_path();
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::AngleAndLength);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
assert!((o - Vec2::new(86.24, 114.47)).hypot() < 0.1, "{o:?}");
|
||||
assert!((i + o).hypot() < 1e-9, "{i:?} {o:?}");
|
||||
assert!((o.hypot() - 143.3).abs() < 0.1, "{}", o.hypot());
|
||||
// Mirror angle: each handle 0.3905 x its own segment; still collinear.
|
||||
let mut n = triangle_path();
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::Angle);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
assert!((i - Vec2::new(-86.24, -114.47)).hypot() < 0.1, "{i:?}");
|
||||
assert!((o - Vec2::new(96.69, 128.33)).hypot() < 0.1, "{o:?}");
|
||||
assert!((i.x * o.y - i.y * o.x).abs() < 1e-6, "collinear");
|
||||
assert!((i.hypot() - 143.3).abs() < 0.1 && (o.hypot() - 160.7).abs() < 0.1);
|
||||
assert_eq!(n.mirroring(1), HandleMirroring::Angle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_smooth_other_angles_and_several_points() {
|
||||
// A right angle at B with legs 100 and 50: d = (1,0)/100 + (0,1)/50, so the line leans to +y.
|
||||
let mut n = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0)], false);
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::Angle);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
let want = Vec2::new(0.01, 0.02).normalize();
|
||||
assert!((o.normalize() - want).hypot() < 1e-9, "{o:?}");
|
||||
assert!((o.hypot() - 19.525).abs() < 1e-9 && (i.hypot() - 39.05).abs() < 1e-9, "{i:?} {o:?}");
|
||||
// Two sharp points of a closed square, both selected: both become smooth.
|
||||
let mut sq = square();
|
||||
set_mirroring(&mut sq, &[0, 2], HandleMirroring::AngleAndLength);
|
||||
for v in [0, 2] {
|
||||
assert!(sq.incident(v).iter().all(|(s, st)| sq.handle(*s, *st).is_some_and(|h| tvec(h).hypot() > 1.0)), "vertex {v}");
|
||||
assert_eq!(sq.mirroring(v), HandleMirroring::AngleAndLength);
|
||||
}
|
||||
assert!(sq.segments.iter().all(|s| tvec(s.ta).x.is_finite() && tvec(s.tb).y.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_leave_unmeasured_points_alone() {
|
||||
// Open-path ends have only one segment.
|
||||
let mut n = open_line();
|
||||
set_mirroring(&mut n, &[0, 2], HandleMirroring::Angle);
|
||||
assert!(n.segments.iter().all(|s| s.is_straight()));
|
||||
// A zero-length neighbour: stays sharp, finite.
|
||||
let mut z = VectorNetwork::from_points(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0), Point::new(60.0, 0.0)], false);
|
||||
set_mirroring(&mut z, &[1], HandleMirroring::AngleAndLength);
|
||||
assert!(z.segments.iter().all(|s| s.is_straight()));
|
||||
// One handle already: the old behaviour (the lone handle stays, the other mirrors it).
|
||||
let mut h = open_line();
|
||||
h.segments[1].ta = (10.0, 5.0);
|
||||
set_mirroring(&mut h, &[1], HandleMirroring::Angle);
|
||||
assert_eq!(h.segments[1].ta, (10.0, 5.0));
|
||||
assert_eq!(h.segments[0].tb, (-10.0, -5.0));
|
||||
}
|
||||
|
||||
fn loop_is_continuous(n: &VectorNetwork, lp: &[usize]) -> bool {
|
||||
let ends: Vec<(usize, usize)> = n
|
||||
.loop_walk(lp)
|
||||
@@ -1107,6 +1252,24 @@ mod tests {
|
||||
assert!(d.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite()));
|
||||
}
|
||||
|
||||
/// A curved bridge between two points of a ring, then the point between them deleted (Delete,
|
||||
/// no healing): the region's loop closes through the bridge, so the fill follows its curve and
|
||||
/// is as long as the stroke (#1951).
|
||||
#[test]
|
||||
fn deleting_a_point_behind_a_curved_bridge_keeps_the_bridge_in_the_loop() {
|
||||
use figcraft_geom::BezPath;
|
||||
use figcraft_geom::kurbo::ParamCurveArclen;
|
||||
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y));
|
||||
let mut n = VectorNetwork::from_points(&pts, true);
|
||||
connect(&mut n, 1, 3, (25.0, 25.0), (-25.0, -25.0)).unwrap();
|
||||
assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (7, 6), "the ring kept");
|
||||
delete_vertices(&mut n, &[2], false);
|
||||
assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (5, 5), "the loop holds the bridge: {:?}", n.regions);
|
||||
let length = |p: &BezPath| p.segments().map(|s| s.arclen(1e-9)).sum::<f64>();
|
||||
let (fill, stroke) = (length(&n.fill_path()), length(&n.stroke_path()));
|
||||
assert!((fill - stroke).abs() < 1e-6, "fill {fill} and stroke {stroke} follow the same outline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_polygon() {
|
||||
let pts = [Point::new(5.0, 5.0), Point::new(50.0, 50.0), Point::new(15.0, 5.0)];
|
||||
@@ -1175,4 +1338,169 @@ mod tests {
|
||||
assert!(ends.iter().any(|x| (x - (centre.x - 0.5)).abs() < 0.01), "{ends:?}");
|
||||
assert!(ends.iter().any(|x| (x - (centre.x + 0.5)).abs() < 0.01), "{ends:?}");
|
||||
}
|
||||
|
||||
/// An open chain of four segments over five points whose two ends a fifth segment (in no
|
||||
/// loop) joins, as a bridge drawn before the point between them was deleted.
|
||||
fn bridged_open_chain() -> VectorNetwork {
|
||||
let corners = [
|
||||
Point::new(0.0, 0.0),
|
||||
Point::new(525.0, 525.0),
|
||||
Point::new(0.0, 525.0),
|
||||
Point::new(333.0, 0.0),
|
||||
Point::new(525.0, 183.0),
|
||||
Point::new(900.0, 900.0),
|
||||
];
|
||||
let mut n = VectorNetwork::from_points(&corners, false);
|
||||
n.segments = [(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)].iter().map(|&(a, b)| Segment::line(a, b)).collect();
|
||||
n.regions.clear();
|
||||
for v in &mut n.vertices {
|
||||
v.radius = 125.0;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_over_one_open_chain_all_close_through_the_joining_segment() {
|
||||
use figcraft_geom::BezPath;
|
||||
use figcraft_geom::kurbo::ParamCurveArclen;
|
||||
let mut n = bridged_open_chain();
|
||||
for _ in 0..2 {
|
||||
n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
}
|
||||
delete_vertices(&mut n, &[5], false);
|
||||
for (i, r) in n.regions.iter().enumerate() {
|
||||
assert_eq!(r.loops[0], vec![3, 1, 2, 0, 4], "region {i} closes through the segment: {:?}", n.regions);
|
||||
}
|
||||
let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::<f64>();
|
||||
let stroke = length(&n.stroke_path());
|
||||
let rounded = n.rounded().unwrap();
|
||||
for i in 0..2 {
|
||||
let fill = length(&rounded.region_path(i).unwrap());
|
||||
assert!((fill - stroke).abs() < 1e-6, "region {i}: fill {fill} and stroke {stroke} trace the same outline");
|
||||
}
|
||||
}
|
||||
|
||||
/// Many independent open chains, each with its own closing segment, all close through it.
|
||||
#[test]
|
||||
fn many_open_chains_each_close_through_their_own_segment() {
|
||||
let one = bridged_open_chain();
|
||||
let (nv, ns) = (one.vertices.len(), one.segments.len());
|
||||
let mut n = VectorNetwork::default();
|
||||
for (i, dx) in (0..50usize).zip((0..50u32).map(|k| f64::from(k) * 1000.0)) {
|
||||
n.vertices.extend(one.vertices.iter().map(|v| Vertex { x: v.x + dx, ..*v }));
|
||||
n.segments.extend(one.segments.iter().map(|s| Segment { a: s.a + i * nv, b: s.b + i * nv, ..*s }));
|
||||
let base = i * ns;
|
||||
n.regions.push(Region {
|
||||
loops: vec![vec![base + 3, base + 1, base + 2, base]],
|
||||
winding: WindingRule::NonZero,
|
||||
fills: None,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
close_bridged_loops(&mut n);
|
||||
for (i, r) in n.regions.iter().enumerate() {
|
||||
assert_eq!(r.loops[0].last(), Some(&(i * ns + 4)), "chain {i} closes through its own segment");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_joining_two_different_chains_closes_both() {
|
||||
let mut n = bridged_open_chain();
|
||||
n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
n.regions.push(Region { loops: vec![vec![0, 2, 1, 3]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
delete_vertices(&mut n, &[5], false);
|
||||
assert_eq!(n.regions[0].loops[0].len(), 5);
|
||||
assert_eq!(n.regions[1].loops[0].len(), 5, "the same segment set is the same chain");
|
||||
let mut m = bridged_open_chain();
|
||||
m.segments.push(Segment::line(1, 2));
|
||||
m.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
m.regions.push(Region { loops: vec![vec![3, 5, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
let drawn = m.rounded().unwrap();
|
||||
delete_vertices(&mut m, &[5], false);
|
||||
assert_eq!(m.regions[0].loops[0], vec![3, 1, 2, 0, 4], "{:?}", m.regions);
|
||||
assert_eq!(m.regions[1].loops[0], vec![3, 5, 2, 0, 4], "different chains share the segment too: {:?}", m.regions);
|
||||
let after = m.rounded().unwrap();
|
||||
for i in 0..2 {
|
||||
assert_eq!(after.region_path(i).unwrap(), drawn.region_path(i).unwrap(), "region {i} is stored as rounding drew it");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two fills that shared a border, a bridge drawn between the border's ends, then the border's
|
||||
/// middle point deleted: both fills close through the bridge (#1951).
|
||||
#[test]
|
||||
fn two_fills_that_shared_a_deleted_border_both_close_through_the_bridge() {
|
||||
use figcraft_geom::Shape;
|
||||
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y));
|
||||
let mut n = VectorNetwork::from_points(&pts, true);
|
||||
n.vertices.push(Vertex::new(50.0, 50.0));
|
||||
n.segments.push(Segment::line(1, 6));
|
||||
n.segments.push(Segment::line(6, 4));
|
||||
n.regions.clear();
|
||||
for lp in [vec![0, 6, 7, 4, 5], vec![1, 2, 3, 7, 6]] {
|
||||
n.regions.push(Region { loops: vec![lp], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
}
|
||||
connect(&mut n, 1, 4, (30.0, 30.0), (30.0, -30.0)).unwrap();
|
||||
delete_vertices(&mut n, &[6], false);
|
||||
assert_eq!(n.regions[0].loops[0], vec![4, 5, 0, 6]);
|
||||
assert_eq!(n.regions[1].loops[0], vec![1, 2, 3, 6], "the second fill closes through the bridge too");
|
||||
let area = |i: usize| n.region_path(i).unwrap().area().abs();
|
||||
assert!((area(0) + area(1) - 10_000.0).abs() < 1e-6, "the fills meet along the bridge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_nothing_leaves_an_open_loop_alone() {
|
||||
let mut n = bridged_open_chain();
|
||||
n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
|
||||
let before = n.clone();
|
||||
remove_segments(&mut n, &[]);
|
||||
assert_eq!(n, before);
|
||||
remove_segments(&mut n, &[99]);
|
||||
assert_eq!(n, before);
|
||||
delete_vertices(&mut n, &[], false);
|
||||
assert_eq!(n, before);
|
||||
delete_vertices(&mut n, &[99], true);
|
||||
assert_eq!(n, before);
|
||||
delete_vertices(&mut n, &[5], false);
|
||||
assert_eq!(n.regions[0].loops[0], vec![3, 1, 2, 0, 4]);
|
||||
}
|
||||
|
||||
/// The same bridge as the curved-bridge test, reached by removing segments.
|
||||
#[test]
|
||||
fn removing_segments_behind_a_curved_bridge_keeps_the_bridge_in_the_loop() {
|
||||
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y));
|
||||
let mut n = VectorNetwork::from_points(&pts, true);
|
||||
connect(&mut n, 1, 3, (25.0, 25.0), (-25.0, -25.0)).unwrap();
|
||||
remove_segments(&mut n, &[1, 2]);
|
||||
assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (5, 5));
|
||||
assert_eq!(n.regions[0].loops[0], vec![1, 2, 3, 0, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_open_loops_with_no_closing_segment_round_as_before() {
|
||||
let mut n = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false);
|
||||
n.segments.clear();
|
||||
n.vertices.clear();
|
||||
for k in 0..40 {
|
||||
let x = f64::from(k) * 100.0;
|
||||
let base = n.vertices.len();
|
||||
for p in [(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 50.0), (x, 50.0)] {
|
||||
n.vertices.push(Vertex { radius: 8.0, ..Vertex::new(p.0, p.1) });
|
||||
}
|
||||
let first = n.segments.len();
|
||||
// Three sides of a square, an open loop with nothing to close it.
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 3)] {
|
||||
n.segments.push(Segment::line(base + a, base + b));
|
||||
}
|
||||
n.regions.push(Region {
|
||||
loops: vec![vec![first, first + 1, first + 2]],
|
||||
winding: WindingRule::NonZero,
|
||||
fills: None,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let r = n.rounded().unwrap();
|
||||
assert_eq!(r.regions.len(), 40);
|
||||
// Each loop gained only its two inner corners' arcs (two corners, one arc each).
|
||||
assert!(r.regions.iter().all(|reg| reg.loops[0].len() == 5), "{:?}", r.regions[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! `vector.edit.position`: with several points, a number sets every selected point's own
|
||||
//! coordinate, and `{add}`, `{mul}`, `{div}` apply to each point's own.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::tests::{ex, net, rect};
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
/// Every point in the parent's coordinates (the layer re-fits its box after an edit, so its own
|
||||
/// coordinates shift).
|
||||
fn xs(s: &Session, id: NodeId) -> Vec<(f64, f64)> {
|
||||
let t = s.doc().unwrap().node(id).unwrap().transform;
|
||||
net(s, id).vertices.iter().map(|v| t * v.point()).map(|p| (p.x, p.y)).collect()
|
||||
}
|
||||
|
||||
fn parent_xy(s: &Session) -> Vec<(f64, f64)> {
|
||||
let ve = s.ds().unwrap().vector_edit.clone().unwrap();
|
||||
selected_parent_points(s.doc().unwrap(), &ve).iter().map(|p| (p.x, p.y)).collect()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.ds().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_sets_every_selected_points_own_coordinate() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
let before = xs(&s, id);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]}));
|
||||
// The rectangle's points 0 and 1 differ in x; both end at -200 and keep their y.
|
||||
assert!(!near(before[0].0, before[1].0));
|
||||
ex(&mut s, "vector.edit.position", json!({"x": -200}));
|
||||
let after = xs(&s, id);
|
||||
assert!(near(after[0].0, -200.0) && near(after[1].0, -200.0), "{after:?}");
|
||||
assert!(near(after[0].1, before[0].1) && near(after[1].1, before[1].1));
|
||||
assert_eq!(after[2], before[2]);
|
||||
// One undo step restores.
|
||||
assert!(s.undo().unwrap());
|
||||
assert_eq!(xs(&s, id), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_point_sets_its_own_coordinates() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
let before = xs(&s, id);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [2]}));
|
||||
ex(&mut s, "vector.edit.position", json!({"x": 7, "y": 9}));
|
||||
let after = xs(&s, id);
|
||||
assert!(near(after[2].0, 7.0) && near(after[2].1, 9.0));
|
||||
assert_eq!(after[0], before[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_edits_apply_to_each_points_own_value() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
let before = xs(&s, id);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]}));
|
||||
ex(&mut s, "vector.edit.position", json!({"x": {"add": 10}}));
|
||||
let a = xs(&s, id);
|
||||
assert!(near(a[0].0, before[0].0 + 10.0) && near(a[1].0, before[1].0 + 10.0), "{a:?}");
|
||||
ex(&mut s, "vector.edit.position", json!({"y": {"mul": 2}}));
|
||||
let b = xs(&s, id);
|
||||
assert!(near(b[0].1, a[0].1 * 2.0) && near(b[1].1, a[1].1 * 2.0), "{b:?}");
|
||||
ex(&mut s, "vector.edit.position", json!({"x": {"div": 2}}));
|
||||
let c = xs(&s, id);
|
||||
assert!(near(c[0].0, a[0].0 / 2.0) && near(c[1].0, a[1].0 / 2.0), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_keeps_its_handles_relative_to_it() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [1]}));
|
||||
ex(&mut s, "vector.edit.smooth", json!({}));
|
||||
let before = net(&s, id);
|
||||
assert!(before.segments.iter().any(|g| g.ta != (0.0, 0.0) || g.tb != (0.0, 0.0)));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]}));
|
||||
ex(&mut s, "vector.edit.position", json!({"x": {"add": 25}}));
|
||||
let after = net(&s, id);
|
||||
let tangents = |n: &VectorNetwork| n.segments.iter().map(|g| (g.ta, g.tb)).collect::<Vec<_>>();
|
||||
assert_eq!(tangents(&before), tangents(&after));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_values_are_in_the_parents_coordinates() {
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "shape.rectangle", json!({"x": 40, "y": 30, "width": 100, "height": 100}));
|
||||
let id = crate::params::id_of(&r["id"]).unwrap();
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]}));
|
||||
let before = parent_xy(&s);
|
||||
assert!(near(before[0].0, 40.0), "{before:?}");
|
||||
ex(&mut s, "vector.edit.position", json!({"x": 10}));
|
||||
let after = parent_xy(&s);
|
||||
assert!(near(after[0].0, 10.0) && near(after[1].0, 10.0), "{after:?}");
|
||||
assert!(near(after[0].1, before[0].1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_every_point_by_one_offset_carries_the_regions_paint_frame() {
|
||||
// `{add}` on every point is a plain translation: the region's paint frame goes with the
|
||||
// points, as when they are dragged together.
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
{
|
||||
let node = s.doc_mut().unwrap().get_mut(id).unwrap();
|
||||
let NodeKind::Vector { network } = &mut node.kind else { panic!("expected a vector") };
|
||||
assert!(!network.regions.is_empty(), "the rectangle has a region");
|
||||
for region in &mut network.regions {
|
||||
region.paint_space = Some(figcraft_doc::RegionPaintSpace { width: 100.0, height: 100.0, transform: Affine::IDENTITY });
|
||||
}
|
||||
}
|
||||
let frame = |s: &Session| {
|
||||
let world = s.doc().unwrap().world_transform(id);
|
||||
world * net(s, id).regions[0].paint_space.as_ref().unwrap().transform
|
||||
};
|
||||
let before = frame(&s);
|
||||
let all: Vec<usize> = (0..net(&s, id).vertices.len()).collect();
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": all}));
|
||||
ex(&mut s, "vector.edit.position", json!({"x": {"add": 10}}));
|
||||
let (want, got) = ((Affine::translate((10.0, 0.0)) * before).as_coeffs(), frame(&s).as_coeffs());
|
||||
assert!(want.iter().zip(got).all(|(a, b)| near(*a, b)), "{got:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_is_refused_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
let before = xs(&s, id);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]}));
|
||||
let steps = undo_steps(&s);
|
||||
for junk in [
|
||||
json!({"x": {"div": 0}}),
|
||||
json!({"x": {"pow": 2}}),
|
||||
json!({"x": "a"}),
|
||||
json!({"x": {"add": 1, "mul": 2}}),
|
||||
json!({"y": {"add": "x"}}),
|
||||
json!({"x": {}}),
|
||||
json!({"x": [1]}),
|
||||
json!({"x": true}),
|
||||
json!({"x": {"add": true}}),
|
||||
// A valid x with a refused y changes neither.
|
||||
json!({"x": 5, "y": {"div": 0}}),
|
||||
// Point 1's x of 100 overflows; point 0's 0 alone would not.
|
||||
json!({"x": {"mul": 1e308}}),
|
||||
] {
|
||||
assert!(s.execute("vector.edit.position", &junk).is_err(), "{junk}");
|
||||
}
|
||||
assert_eq!(xs(&s, id), before);
|
||||
assert_eq!(undo_steps(&s), steps, "a refused edit leaves no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_selected_is_refused() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": []}));
|
||||
let (before, steps) = (xs(&s, id), undo_steps(&s));
|
||||
assert!(parent_xy(&s).is_empty());
|
||||
let err = s.execute("vector.edit.position", &json!({"x": 5})).unwrap_err();
|
||||
assert!(err.to_string().contains("select points"), "{err}");
|
||||
assert_eq!((xs(&s, id), undo_steps(&s)), (before, steps));
|
||||
}
|
||||
@@ -407,6 +407,24 @@ fn mirroring_position_and_join_commands() {
|
||||
assert!(s.execute("vector.join", &json!({"ids": [id]})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_mode_on_sharp_points_is_one_undo_step() {
|
||||
// #2110: a mirror mode turns sharp points smooth; the whole command undoes in one step.
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "vector.create", json!({"points": [[-250, -174], [117, -174], [-67, 194]], "closed": false}));
|
||||
let id = crate::params::id_of(&r["id"]).unwrap();
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [1]}));
|
||||
ex(&mut s, "vector.edit.mirroring", json!({"mode": "angleAndLength"}));
|
||||
let n = net(&s, id);
|
||||
let (i, o) = (n.segments[0].tb, n.segments[1].ta);
|
||||
assert!((o.0 - 86.24).abs() < 0.1 && (o.1 - 114.47).abs() < 0.1, "{o:?}");
|
||||
assert!((i.0 + o.0).abs() < 1e-9 && (i.1 + o.1).abs() < 1e-9, "{i:?}");
|
||||
s.undo().unwrap();
|
||||
let n = net(&s, id);
|
||||
assert!(n.segments.iter().all(|x| x.is_straight()), "one undo restores the sharp point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_dropped_on_another_merges_into_it() {
|
||||
// #401: an open path's end dragged onto its start closes the path at that point.
|
||||
@@ -659,6 +677,27 @@ fn a_rounded_chamfer_made_other_ways_fills_along_its_arcs() {
|
||||
fill_traces_stroke(&s, id, "drawn with the pen");
|
||||
}
|
||||
|
||||
/// The reporter's sequence (#1951): a bridge drawn between the two new points while the corner is
|
||||
/// still there (both have two segments, so the region keeps its ring), then the corner deleted with
|
||||
/// Delete. The region's loop must close through the bridge, so the rounded fill traces the stroke.
|
||||
#[test]
|
||||
fn deleting_the_corner_behind_a_pen_bridge_closes_the_loop_through_the_bridge() {
|
||||
let mut s = Session::new();
|
||||
let id = rect(&mut s);
|
||||
ex(&mut s, "vector.edit.addVertex", json!({"segment": 0, "t": 0.5}));
|
||||
ex(&mut s, "vector.edit.addVertex", json!({"segment": 1, "t": 0.5}));
|
||||
let n = net(&s, id);
|
||||
let (top, right) = (vertex_at(&n, 50.0, 0.0), vertex_at(&n, 100.0, 50.0));
|
||||
ex(&mut s, "vector.edit.connect", json!({"a": top, "b": right}));
|
||||
let n = net(&s, id);
|
||||
assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (7, 6), "bridged, the ring kept: {:?}", n.regions);
|
||||
let corner = vertex_at(&n, 100.0, 0.0);
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [corner]}));
|
||||
ex(&mut s, "vector.edit.delete", json!({}));
|
||||
ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]}));
|
||||
fill_traces_stroke(&s, id, "bridged, then the corner deleted");
|
||||
}
|
||||
|
||||
/// The rounded chamfered rectangle `id` (five points on the origin's 100×100 box, the top-right
|
||||
/// corner cut off between (50, 0) and (100, 50)): one region with every segment in its loop, and a
|
||||
/// fill that keeps off every sharp point and traces the same outline as the stroke.
|
||||
|
||||
@@ -291,6 +291,7 @@ pub static MENU: &[MenuItem] = &[
|
||||
m!("Tools", "Pencil", "tool.pencil"),
|
||||
m!("Tools", "Text", "tool.text"),
|
||||
m!("Tools", "Comment", "tool.comment"),
|
||||
m!("Tools", "Annotation", "tool.annotation"),
|
||||
m!("Tools", "Shape builder", "tool.shapeBuilder"),
|
||||
m!("Tools", "Actions", "app.actions"),
|
||||
];
|
||||
|
||||
@@ -164,12 +164,27 @@ pub fn can_align(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
align_target(doc, &roots(doc, ids)).is_some()
|
||||
}
|
||||
|
||||
/// Whether `ids` is one layer that its auto layout frame places: Figma greys out Align for it,
|
||||
/// since the frame decides where it goes (measured in Figma's web app, 2026-11-12).
|
||||
pub fn align_blocked_by_auto_layout(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
matches!(roots(doc, ids).as_slice(), [id] if in_auto_layout_flow(doc, *id))
|
||||
}
|
||||
|
||||
/// Whether the layer sits in an auto layout frame and takes part in its flow (not absolutely positioned).
|
||||
fn in_auto_layout_flow(doc: &Document, id: NodeId) -> bool {
|
||||
let Some(n) = doc.node(id) else { return false };
|
||||
!n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
|
||||
}
|
||||
|
||||
/// What `roots` align to: one layer to its parent frame, several to their combined bounds.
|
||||
fn align_target(doc: &Document, roots: &[NodeId]) -> Option<Rect> {
|
||||
match roots {
|
||||
[] => None,
|
||||
[id] => {
|
||||
let parent = doc.node(*id)?.parent.filter(|pp| !doc.node(*pp).is_some_and(Node::is_page))?;
|
||||
if in_auto_layout_flow(doc, *id) {
|
||||
return None;
|
||||
}
|
||||
Some(doc.world_bounds(parent).unwrap_or_default())
|
||||
}
|
||||
_ => Some(doc.bounds_of(roots).unwrap_or_default()),
|
||||
@@ -223,53 +238,25 @@ fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Tidy up: snap the selection into a grid of rows/columns with even spacing.
|
||||
/// Tidy up: even the gaps of a row, a column or a grid, keeping the order and sizes (see
|
||||
/// `selection::tidy`). Nothing moves, and no undo step is added, when it is unavailable.
|
||||
fn tidy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("arrange.tidy", s, p)?;
|
||||
let spacing = num(p, "spacing");
|
||||
if spacing.is_some_and(|v| !v.is_finite() || v.abs() > 1_000_000.0) {
|
||||
return Err(bad("arrange.tidy", "spacing out of range"));
|
||||
}
|
||||
let snap = s.ds()?.view.snap_pixel;
|
||||
let moves = crate::tidy::tidy_moves(s.doc()?, &ids, spacing, snap);
|
||||
if moves.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if moves.iter().any(|(_, dx, dy)| !dx.is_finite() || !dy.is_finite()) {
|
||||
return Err(bad("arrange.tidy", "non-finite result"));
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
let ids = roots(doc, &ids);
|
||||
let mut items: Vec<(NodeId, Rect)> = ids.iter().filter_map(|i| doc.world_bounds(*i).map(|b| (*i, b))).collect();
|
||||
if items.len() < 2 {
|
||||
return ok();
|
||||
}
|
||||
// Group into rows by vertical centre overlap.
|
||||
items.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0));
|
||||
let mut rows: Vec<Vec<(NodeId, Rect)>> = Vec::new();
|
||||
for it in items {
|
||||
match rows.last_mut() {
|
||||
Some(row) if row.iter().any(|(_, b)| it.1.center().y < b.y1 && it.1.center().y > b.y0) => row.push(it),
|
||||
_ => rows.push(vec![it]),
|
||||
}
|
||||
}
|
||||
let all: Vec<Rect> = rows.iter().flatten().map(|(_, b)| *b).collect();
|
||||
let (Some(origin), maxw, maxh) = (
|
||||
all.iter().copied().reduce(|a, b| a.union(b)),
|
||||
all.iter().map(Rect::width).fold(0.0, f64::max),
|
||||
all.iter().map(Rect::height).fold(0.0, f64::max),
|
||||
) else {
|
||||
return ok();
|
||||
};
|
||||
let gap = num(p, "spacing").unwrap_or_else(|| {
|
||||
// Keep the average existing horizontal gap (min 10).
|
||||
10f64.max(
|
||||
rows.iter()
|
||||
.filter(|r| r.len() > 1)
|
||||
.map(|r| {
|
||||
(r.iter().map(|(_, b)| b.x1).fold(f64::MIN, f64::max)
|
||||
- r.iter().map(|(_, b)| b.x0).fold(f64::MAX, f64::min)
|
||||
- r.iter().map(|(_, b)| b.width()).sum::<f64>())
|
||||
/ (r.len() - 1) as f64
|
||||
})
|
||||
.fold(0.0, f64::max),
|
||||
)
|
||||
});
|
||||
for (ri, row) in rows.iter_mut().enumerate() {
|
||||
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0));
|
||||
for (ci, (id, b)) in row.iter().enumerate() {
|
||||
let x = origin.x0 + ci as f64 * (maxw + gap);
|
||||
let y = origin.y0 + ri as f64 * (maxh + gap);
|
||||
move_world(doc, *id, x - b.x0, y - b.y0)?;
|
||||
}
|
||||
for (id, dx, dy) in moves {
|
||||
move_world(doc, id, dx, dy)?;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res
|
||||
pub(crate) use instance::{swap_at, swap_instance};
|
||||
use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props};
|
||||
pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props};
|
||||
use variants::{add_variant, combine};
|
||||
pub use variants::{can_add_variant, can_combine_variants};
|
||||
use variants::{add_variant, combine, create_set};
|
||||
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
|
||||
|
||||
/// `component.hideWhenPublishing`: the leading `.` of the names of this file's components and
|
||||
/// sets (those `ids` are or are in), put on or taken off.
|
||||
@@ -72,6 +72,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
s.set_selection(out.iter().filter_map(id_of).collect());
|
||||
Ok(json!({"ids": out}))
|
||||
}),
|
||||
spec!(
|
||||
"component.createSet",
|
||||
"Create component set",
|
||||
"{ids? (layers, not components, sets or instances)} (each becomes a component, wrapped in place in a component set: variants \"Property 1=<name>\" left to right, 20 px around)",
|
||||
true,
|
||||
create_set
|
||||
),
|
||||
spec!(
|
||||
"component.combineVariants",
|
||||
"Combine as variants",
|
||||
|
||||
@@ -8,7 +8,7 @@ use super::{
|
||||
req_string, req_targets, set_boolean_default, slot_edited, slots_of, string, takes_value, targets, variant_conflicts, variant_name,
|
||||
variant_options, variant_props, variant_set,
|
||||
};
|
||||
use crate::components::prop_list;
|
||||
use crate::components::{instance_prop_list, prop_list};
|
||||
|
||||
/// Whether instance `id` has a component property `name` that a `kind` variable can drive (a
|
||||
/// boolean property takes a boolean variable, a text or variant property a string one).
|
||||
@@ -606,7 +606,8 @@ pub(crate) fn describe_props(doc: &Document, id: NodeId) -> Value {
|
||||
}
|
||||
// Slots: the frames (on a main) or this instance's copy, with whether it holds its own content.
|
||||
let slots = slots_of(doc, if values.is_some() { id } else { variant_set(doc, comp).unwrap_or(comp) });
|
||||
for (k, d) in prop_list(doc, comp) {
|
||||
let defs = if values.is_some() { instance_prop_list(doc, comp) } else { prop_list(doc, comp) };
|
||||
for (k, d) in defs {
|
||||
let mut v = def_json(&k, &d);
|
||||
if !takes_value(&d) {
|
||||
let layers: Vec<NodeId> = slots.iter().filter(|(_, n)| *n == k).map(|(l, _)| *l).collect();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, inside_instance, json, owning_instance,
|
||||
req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
|
||||
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, create, id_of, inside_instance, json,
|
||||
owning_instance, req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
|
||||
};
|
||||
|
||||
/// Wrap components in a new component set (named after the first) placed around them.
|
||||
@@ -94,6 +94,75 @@ pub(super) fn combine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"id": set}))
|
||||
}
|
||||
|
||||
/// Why `ids` (distinct) can't each become a component of a new set (`component.createSet`), or
|
||||
/// `None` when they can: layers inside an instance, library copies, instances, components and
|
||||
/// component sets, and a layer inside another one of `ids`.
|
||||
fn create_set_refusal(doc: &Document, ids: &[NodeId]) -> Option<&'static str> {
|
||||
if ids.iter().any(|i| inside_instance(doc, *i)) {
|
||||
Some("layers inside an instance can't become components")
|
||||
} else if ids.iter().any(|i| doc.is_remote(*i)) {
|
||||
Some(crate::library::READ_ONLY)
|
||||
} else if ids.iter().any(|i| {
|
||||
doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. } | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))
|
||||
}) {
|
||||
Some("select layers that aren't components, component sets or instances")
|
||||
} else if roots(doc, ids).len() != ids.len() {
|
||||
Some("a layer can't be in a set with one inside it")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether "Create component set" is on offer for `ids`: at least one layer that
|
||||
/// [`create_set_refusal`] lets through.
|
||||
pub fn can_create_set(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
let distinct: Vec<NodeId> = ids.iter().copied().collect::<BTreeSet<_>>().into_iter().collect();
|
||||
!distinct.is_empty() && distinct.iter().all(|i| doc.contains(*i)) && create_set_refusal(doc, &distinct).is_none()
|
||||
}
|
||||
|
||||
/// `component.createSet`: each target becomes a component (as `component.createMultiple` makes
|
||||
/// them) and all are wrapped in place in a component set, 20 px around, named as Figma names them:
|
||||
/// variants "Property 1=<layer name>" in left-to-right order (a name holding `=` is kept); layers
|
||||
/// that all share a name give a set of that name with "Property 1=Default" variants; otherwise the
|
||||
/// set is "Component N".
|
||||
pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "component.createSet";
|
||||
let mut seen = BTreeSet::new();
|
||||
let ids: Vec<NodeId> = req_targets(cmd, s, p)?.into_iter().filter(|i| seen.insert(*i)).collect();
|
||||
let doc = s.doc()?;
|
||||
if let Some(why) = create_set_refusal(doc, &ids) {
|
||||
return Err(EngineError::Disabled(cmd.into(), why.into()));
|
||||
}
|
||||
let mut made = Vec::new();
|
||||
for i in roots(doc, &ids) {
|
||||
let r = create(s, &json!({"ids": [i]}))?;
|
||||
made.push(id_of(&r["id"]).ok_or_else(|| bad(cmd, "component creation failed"))?);
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
// Left to right by world x, ties by y: the variants' order, and the values' order.
|
||||
let mut by_x: Vec<(NodeId, f64, f64)> = made.iter().map(|i| doc.world_bounds(*i).map_or((*i, 0.0, 0.0), |b| (*i, b.x0, b.y0))).collect();
|
||||
by_x.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.2.total_cmp(&b.2)));
|
||||
let names: Vec<String> = by_x.iter().map(|(i, ..)| doc.node(*i).map(|n| n.name.clone()).unwrap_or_default()).collect();
|
||||
let same = names.windows(2).all(|w| w.first() == w.get(1)) && names.first().is_some_and(|n| !n.is_empty() && !n.contains('='));
|
||||
let set_name = match names.first() {
|
||||
Some(n) if same => n.clone(),
|
||||
_ => doc.next_name("Component"),
|
||||
};
|
||||
for ((i, ..), name) in by_x.iter().zip(&names) {
|
||||
let node = doc.get_mut(*i)?;
|
||||
if same {
|
||||
node.name = "Property 1=Default".into();
|
||||
} else if !name.contains('=') {
|
||||
node.name = format!("Property 1={name}");
|
||||
}
|
||||
}
|
||||
let ordered = z_sorted(doc, &made);
|
||||
let set = wrap_in_set(cmd, doc, &ordered)?;
|
||||
doc.get_mut(set)?.name = set_name;
|
||||
s.set_selection(vec![set]);
|
||||
Ok(json!({"id": set}))
|
||||
}
|
||||
|
||||
/// Grow a component set so it wraps its variants with 20 px of padding (right and bottom).
|
||||
pub(super) fn fit_set(doc: &mut Document, set: NodeId) {
|
||||
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
|
||||
|
||||
@@ -17,6 +17,10 @@ mod clipboard;
|
||||
mod props;
|
||||
pub(crate) use props::{edit_region_fills, fill_regions};
|
||||
mod select;
|
||||
mod vector_clipboard;
|
||||
pub use vector_clipboard::clipboard_svg;
|
||||
#[cfg(test)]
|
||||
mod vector_clipboard_tests;
|
||||
|
||||
pub(crate) use clipboard::apply_copied_props;
|
||||
pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into};
|
||||
@@ -117,12 +121,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
true,
|
||||
duplicate
|
||||
),
|
||||
spec!("edit.copy", "Copy", "{ids?}", false, copy),
|
||||
spec!("edit.cut", "Cut", "{ids?}", true, cut),
|
||||
spec!(
|
||||
"edit.copy",
|
||||
"Copy",
|
||||
"{ids?} in vector edit mode with points or segments selected (and no ids): just those, the segments touching a selected point, as a temporary vector on the clipboard (one per edited layer) with the edited layer's look, kept at its place on the page; points that touch no segment have nothing to copy, so Copy with only those is refused (Disabled). Returns {copied, segments}",
|
||||
false,
|
||||
copy
|
||||
),
|
||||
spec!(
|
||||
"edit.cut",
|
||||
"Cut",
|
||||
"{ids?} in vector edit mode with points or segments selected (and no ids): copies them as Copy does, then removes them as Delete does; the path splits in the same layer and edit mode stays on. Returns {cut (layers), segments}. With only lone points (nothing to copy) it is refused (Disabled) and changes nothing, as Copy is; Delete removes lone points",
|
||||
true,
|
||||
cut
|
||||
),
|
||||
spec!(
|
||||
"edit.paste",
|
||||
"Paste",
|
||||
"{parent?, x?, y? (page coordinates of the pasted top-left)} a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
|
||||
"{parent?, x?, y? (page coordinates of the pasted top-left; give both or neither, one alone is refused)} in vector edit mode (and no parent): the copied vectors' segments and the outlines of shapes, booleans and lines join the edited vector's network (at x/y when given, else in place), their points selected, as one undo step; layers with no outline (text, images, instances, frames, groups) are skipped and named in `skipped` (present only when some were), and when none has an outline the paste is refused (Disabled), as it is past 500,000 segments in one vector. Returns {ids: [] (always empty: no layer is created), edited (the vector's id), vertices (points added), skipped?}, unlike a paste outside edit mode, which returns the new layers' `ids`; a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
|
||||
true,
|
||||
paste
|
||||
),
|
||||
@@ -191,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"select.layersAt",
|
||||
"Layers at a point",
|
||||
"{x, y (page coordinates)} → {layers: [{id, name, type, depth}]} (every layer under the point, front-most first; what the context menu's Select layer lists)",
|
||||
"{x, y (page coordinates)} → {layers: [{id, name, type, depth, locked}]} (every layer under the point, locked ones too, front-most first; locked is true when the layer or an ancestor is locked; what the context menu's Select layer lists)",
|
||||
false,
|
||||
layers_at
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, id, json, num, ok,
|
||||
req_targets, roots, string, targets, z_sorted,
|
||||
Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, get, id, json, num,
|
||||
ok, req_targets, roots, string, targets, vector_clipboard, z_sorted,
|
||||
};
|
||||
|
||||
/// The copied form of the selection.
|
||||
@@ -12,6 +12,18 @@ pub fn copy_to_clipboard(s: &mut Session, cmd: &str, ids: &[NodeId]) -> Result<(
|
||||
return Err(EngineError::Disabled(cmd.into(), "pages can't be copied; use page.duplicate".into()));
|
||||
}
|
||||
let (nodes, images, bounds) = copied(&ds.doc, &layers);
|
||||
store_clipboard(s, cmd, nodes, images, bounds)
|
||||
}
|
||||
|
||||
/// Make `nodes` (the copied layers, each root's transform in page space) the clipboard's layers.
|
||||
pub(super) fn store_clipboard(
|
||||
s: &mut Session,
|
||||
cmd: &str,
|
||||
nodes: Vec<(NodeId, Vec<Node>)>,
|
||||
images: BTreeMap<String, ImageData>,
|
||||
bounds: Option<figcraft_geom::Rect>,
|
||||
) -> Result<()> {
|
||||
let ds = s.ds()?;
|
||||
let (source, source_path, uid) = (ds.doc.clone(), ds.path.clone(), ds.uid);
|
||||
s.clipboard.source = Some(source);
|
||||
s.clipboard.source_path = source_path;
|
||||
@@ -43,21 +55,26 @@ fn copied(doc: &Document, ids: &[NodeId]) -> Copied {
|
||||
if let Some(r) = sub.first_mut() {
|
||||
r.transform = world;
|
||||
}
|
||||
for n in &sub {
|
||||
for p in n.fills.iter().chain(n.strokes.iter()) {
|
||||
if let figcraft_color::PaintKind::Image(img) = &p.kind
|
||||
&& let Some(d) = doc.images.get(&img.image)
|
||||
{
|
||||
images.insert(img.image.clone(), d.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
collect_images(doc, &sub, &mut images);
|
||||
nodes.push((*i, sub));
|
||||
}
|
||||
let bounds = doc.bounds_of(&ids);
|
||||
(nodes, images, bounds)
|
||||
}
|
||||
|
||||
/// The images the paints of `nodes` use, taken from `doc` into `images`.
|
||||
pub(super) fn collect_images(doc: &Document, nodes: &[Node], images: &mut BTreeMap<String, ImageData>) {
|
||||
for n in nodes {
|
||||
for p in n.fills.iter().chain(n.strokes.iter()) {
|
||||
if let figcraft_color::PaintKind::Image(img) = &p.kind
|
||||
&& let Some(d) = doc.images.get(&img.image)
|
||||
{
|
||||
images.insert(img.image.clone(), d.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The markers around the copied layers in the clipboard's HTML, spelt as that format spells them.
|
||||
pub const CLIP_OPEN: &str = "(figma)";
|
||||
|
||||
@@ -167,13 +184,34 @@ fn layers_missing_images(doc: &figcraft_doc::Document, ids: &[NodeId]) -> Vec<St
|
||||
names
|
||||
}
|
||||
|
||||
/// Whether the command names its layers (`ids` / `id`): it then acts on them even in vector edit mode.
|
||||
fn names_layers(p: &Value) -> bool {
|
||||
get(p, "ids").is_some() || get(p, "id").is_some()
|
||||
}
|
||||
|
||||
pub(super) fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// In vector edit mode with points or segments selected, Copy takes just those (#1875).
|
||||
if !names_layers(p)
|
||||
&& let Some(sel) = vector_clipboard::edit_selection(s)
|
||||
&& sel.any
|
||||
{
|
||||
// Only lone points selected: nothing to copy, and not the whole layer either.
|
||||
return vector_clipboard::copy_selection(s, "edit.copy", sel);
|
||||
}
|
||||
let ids = req_targets("edit.copy", s, p)?;
|
||||
copy_to_clipboard(s, "edit.copy", &ids)?;
|
||||
Ok(json!({"copied": s.clipboard.nodes.len()}))
|
||||
}
|
||||
|
||||
pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// In vector edit mode with points or segments selected, Cut takes just those and stays in edit mode (#1875).
|
||||
if !names_layers(p)
|
||||
&& let Some(sel) = vector_clipboard::edit_selection(s)
|
||||
&& sel.any
|
||||
{
|
||||
// Lone points with nothing to copy: `cut_selection` refuses, as Copy does.
|
||||
return vector_clipboard::cut_selection(s, sel);
|
||||
}
|
||||
let ids = req_targets("edit.cut", s, p)?;
|
||||
copy_to_clipboard(s, "edit.cut", &ids)?;
|
||||
let doc = s.doc()?;
|
||||
@@ -238,6 +276,10 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
|
||||
}
|
||||
|
||||
pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// While editing a vector, the copied layers join its network (#1875); `parent` asks for layers.
|
||||
if id(p, "parent").is_none() && s.ds()?.vector_edit.is_some() {
|
||||
return vector_clipboard::paste_into_vector(s, p);
|
||||
}
|
||||
let page = s.page()?;
|
||||
// Figma pastes into the selected frame (if one is selected), at the same position when it fits,
|
||||
// else in the frame's centre; otherwise in place on the page (or the viewport centre).
|
||||
@@ -287,14 +329,22 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let sel = s.selection();
|
||||
let page = s.page()?;
|
||||
let doc = s.doc()?;
|
||||
let (parent, at) = match sel.first() {
|
||||
let (parent, at, above) = match sel.first() {
|
||||
Some(i) => {
|
||||
let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page);
|
||||
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)))
|
||||
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1))
|
||||
}
|
||||
None => (page, None),
|
||||
None => (page, None, None),
|
||||
};
|
||||
let ids = paste_into(s, parent, at)?;
|
||||
if let Some(above) = above {
|
||||
let doc = s.doc_mut()?;
|
||||
for (k, i) in
|
||||
ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
|
||||
{
|
||||
doc.reorder(i, above + k)?;
|
||||
}
|
||||
}
|
||||
s.set_selection(ids.clone());
|
||||
Ok(json!({"ids": ids}))
|
||||
}
|
||||
|
||||
@@ -113,8 +113,12 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A new rotation for the selection turns it about its moved rotation origin: each layer's
|
||||
// point under the origin stays put.
|
||||
let ds = s.ds()?;
|
||||
let pivot =
|
||||
ds.moved_origin().filter(|_| props.contains_key("rotation") && !props.contains_key("x") && !props.contains_key("y") && ds.selection == ids);
|
||||
let pivot = ds.moved_origin().filter(|_| {
|
||||
(props.contains_key("rotation") || props.contains_key("absoluteRotation"))
|
||||
&& !props.contains_key("x")
|
||||
&& !props.contains_key("y")
|
||||
&& ds.selection == ids
|
||||
});
|
||||
let pinned: Vec<(NodeId, figcraft_geom::Point)> = match pivot {
|
||||
Some(o) => roots(&ds.doc, &ids)
|
||||
.into_iter()
|
||||
@@ -161,6 +165,11 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
let before = crate::cmd::styles::bound_before(doc, &ids);
|
||||
let mut ids = ids;
|
||||
if props.contains_key("absoluteRotation") {
|
||||
// A page angle depends on the parents': turn a selected parent before the layers in it.
|
||||
ids.sort_by_key(|i| doc.ancestors(*i).len());
|
||||
}
|
||||
for i in ids {
|
||||
crate::cmd::props::apply("node.set", doc, i, skipped.get(&i).unwrap_or(&props))?;
|
||||
}
|
||||
@@ -245,7 +254,7 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("node.reparent", s, p)?;
|
||||
let parent = req_id("node.reparent", p, "parent")?;
|
||||
let index = num(p, "index").map(|i| i.max(0.0) as usize);
|
||||
let index = opt_index("node.reparent", p, "index")?;
|
||||
let doc = s.doc_mut()?;
|
||||
let ids = z_sorted(doc, &roots(doc, &ids));
|
||||
// `index` is where the first moved layer ends up among the parent's children (bottom first),
|
||||
|
||||
@@ -8,9 +8,13 @@ pub(super) fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let zoom = s.ds()?.view.zoom.max(1e-6);
|
||||
let sel = s.selection();
|
||||
let result = crate::booleans::result_outline(doc, &sel);
|
||||
let layers: Vec<Value> = figcraft_doc::geometry::layers_at(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result))
|
||||
let opts = figcraft_doc::geometry::HitOpts { locked: true };
|
||||
let layers: Vec<Value> = figcraft_doc::geometry::layers_at_opts(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result), opts)
|
||||
.into_iter()
|
||||
.filter_map(|(id, depth)| doc.node(id).map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth})))
|
||||
.filter_map(|(id, depth)| {
|
||||
doc.node(id)
|
||||
.map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth, "locked": crate::tools::locked_in(doc, id)}))
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"layers": layers}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Copy, cut and paste in vector edit mode (#1875).
|
||||
//!
|
||||
//! With points or segments selected, Copy and Cut take just those: a temporary vector holding the
|
||||
//! selected segments (and the segments touching a selected point) goes on the ordinary layer
|
||||
//! clipboard, kept at its place on the page, so a paste outside edit mode is a plain layer paste
|
||||
//! in place. Cut then removes the selection the way Delete does and stays in edit mode. Paste
|
||||
//! while editing adds the clipboard's layers to the edited vector's network, in place: a vector
|
||||
//! with its segments, a shape or boolean with its outline.
|
||||
|
||||
use crate::bad;
|
||||
use figcraft_doc::{NodeKind, Region, VectorNetwork};
|
||||
|
||||
use super::clipboard::{collect_images, store_clipboard};
|
||||
use super::{Affine, BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, Result, Session, Value, json, num};
|
||||
use crate::canvas::vectoredit::{self, EditPart};
|
||||
|
||||
/// The most segments a vector network takes through a paste.
|
||||
const MAX_SEGMENTS: usize = 500_000;
|
||||
|
||||
/// What the edited layers have selected.
|
||||
pub(super) struct EditSelection {
|
||||
/// Whether any edited layer has a point or a segment selected.
|
||||
pub any: bool,
|
||||
/// Each edited layer with something to copy, and the sub-network that is.
|
||||
pub parts: Vec<(NodeId, VectorNetwork)>,
|
||||
/// What Cut removes, per edited layer: the same points and segments the copy was built from.
|
||||
pub delete: Vec<EditPart>,
|
||||
}
|
||||
|
||||
/// The selection of the vector being edited (and the other layers edited with it), or `None` when
|
||||
/// not in vector edit mode.
|
||||
pub(super) fn edit_selection(s: &Session) -> Option<EditSelection> {
|
||||
let ds = s.ds().ok()?;
|
||||
let ve = ds.vector_edit.as_ref()?;
|
||||
let mut sel = EditSelection { any: false, parts: Vec::new(), delete: Vec::new() };
|
||||
for part in ve.parts() {
|
||||
if part.vertices.is_empty() && part.segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
sel.any = true;
|
||||
let Some(net) = vectoredit::network(&ds.doc, part.id) else { continue };
|
||||
let active = part.id == ve.id;
|
||||
// Points selected only through a selected region don't pull in the segments touching
|
||||
// them: the region's own segments are the selection.
|
||||
let vertices: Vec<usize> = part.vertices.iter().copied().filter(|v| !active || !ve.region_vertices.contains(v)).collect();
|
||||
let mut segments = part.segments.clone();
|
||||
if active {
|
||||
segments.extend(ve.regions.iter().filter_map(|r| net.regions.get(*r)).flat_map(|r| r.loops.iter().flatten().copied()));
|
||||
}
|
||||
sel.delete.push(EditPart { id: part.id, vertices: vertices.clone(), segments: segments.clone() });
|
||||
if let Some(sub) = sub_network(net, &vertices, &segments) {
|
||||
sel.parts.push((part.id, sub));
|
||||
}
|
||||
}
|
||||
Some(sel)
|
||||
}
|
||||
|
||||
/// The part of `net` that is the segments `segments` and those touching a point of `vertices`,
|
||||
/// with the points they join; `None` when there are none (a lone point with no segment draws
|
||||
/// nothing). The regions whose every segment is kept stay regions.
|
||||
fn sub_network(net: &VectorNetwork, vertices: &[usize], segments: &[usize]) -> Option<VectorNetwork> {
|
||||
let picked: BTreeSet<usize> = vertices.iter().copied().collect();
|
||||
let mut keep: BTreeSet<usize> = segments.iter().copied().filter(|i| *i < net.segments.len()).collect();
|
||||
for (i, sg) in net.segments.iter().enumerate() {
|
||||
if picked.contains(&sg.a) || picked.contains(&sg.b) {
|
||||
keep.insert(i);
|
||||
}
|
||||
}
|
||||
let used: BTreeSet<usize> = keep.iter().filter_map(|i| net.segments.get(*i)).flat_map(|sg| [sg.a, sg.b]).collect();
|
||||
let vmap: BTreeMap<usize, usize> = used.iter().enumerate().map(|(new, old)| (*old, new)).collect();
|
||||
let smap: BTreeMap<usize, usize> = keep.iter().enumerate().map(|(new, old)| (*old, new)).collect();
|
||||
let mut out = VectorNetwork {
|
||||
vertices: used.iter().filter_map(|v| net.vertices.get(*v).cloned()).collect(),
|
||||
segments: keep
|
||||
.iter()
|
||||
.filter_map(|i| net.segments.get(*i))
|
||||
.filter_map(|sg| {
|
||||
let mut sg = *sg;
|
||||
sg.a = *vmap.get(&sg.a)?;
|
||||
sg.b = *vmap.get(&sg.b)?;
|
||||
Some(sg)
|
||||
})
|
||||
.collect(),
|
||||
regions: Vec::new(),
|
||||
};
|
||||
if out.segments.is_empty() || out.segments.len() != keep.len() || out.vertices.len() != used.len() {
|
||||
return None;
|
||||
}
|
||||
for r in &net.regions {
|
||||
let loops: Option<Vec<Vec<usize>>> = r.loops.iter().map(|l| l.iter().map(|i| smap.get(i).copied()).collect::<Option<Vec<usize>>>()).collect();
|
||||
if let Some(loops) = loops.filter(|l| !l.is_empty()) {
|
||||
out.regions.push(Region { loops, ..r.clone() });
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The clipboard's layer for edited vector `id` holding `sub`: it keeps the layer's look (fills,
|
||||
/// strokes, effects, opacity, blend) and its place on the page. A variable width profile runs
|
||||
/// along the whole path, so it stays only when every segment is copied.
|
||||
fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option<Node> {
|
||||
let mut n = doc.node(id)?.clone();
|
||||
let whole = vectoredit::network(doc, id).is_some_and(|all| all.segments.len() == sub.segments.len());
|
||||
let b = sub.bounds().filter(|b| b.x0.is_finite() && b.y0.is_finite() && b.width().is_finite() && b.height().is_finite())?;
|
||||
sub.translate(-b.x0, -b.y0);
|
||||
n.transform = doc.world_transform(id) * Affine::translate((b.x0, b.y0));
|
||||
n.width = b.width();
|
||||
n.height = b.height();
|
||||
n.kind = NodeKind::Vector { network: sub };
|
||||
n.parent = None;
|
||||
n.children.clear();
|
||||
n.name = "Vector".into();
|
||||
if !whole {
|
||||
n.stroke.width_profile = None;
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// Put the selection's sub-networks on the layer clipboard. Returns how many segments went.
|
||||
fn copy_parts(s: &mut Session, cmd: &str, sel: &EditSelection) -> Result<usize> {
|
||||
let doc = s.doc()?;
|
||||
let mut nodes = Vec::new();
|
||||
let mut images = BTreeMap::new();
|
||||
let mut bounds: Option<figcraft_geom::Rect> = None;
|
||||
let mut segments = 0;
|
||||
for (id, sub) in &sel.parts {
|
||||
segments += sub.segments.len();
|
||||
let Some(n) = clip_node(doc, *id, sub.clone()) else { continue };
|
||||
let r = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect());
|
||||
bounds = Some(bounds.map_or(r, |b| b.union(r)));
|
||||
collect_images(doc, std::slice::from_ref(&n), &mut images);
|
||||
nodes.push((*id, vec![n]));
|
||||
}
|
||||
if nodes.is_empty() {
|
||||
return Err(EngineError::Disabled(cmd.into(), "the selection has nothing to copy".into()));
|
||||
}
|
||||
store_clipboard(s, cmd, nodes, images, bounds)?;
|
||||
Ok(segments)
|
||||
}
|
||||
|
||||
/// Copy the selected segments (see [`edit_selection`]).
|
||||
pub(super) fn copy_selection(s: &mut Session, cmd: &str, sel: EditSelection) -> Result<Value> {
|
||||
let segments = copy_parts(s, cmd, &sel)?;
|
||||
Ok(json!({"copied": s.clipboard.nodes.len(), "segments": segments}))
|
||||
}
|
||||
|
||||
/// Cut: copy the selected segments, then remove the selection as Delete does (the path splits in
|
||||
/// the same layer and edit mode stays on). Cut is Copy plus Delete, so it is refused exactly where
|
||||
/// Copy is: a selection with nothing to copy (only lone points that touch no segment) is
|
||||
/// `Disabled` and changes nothing, clipboard included. Delete removes such points.
|
||||
pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result<Value> {
|
||||
if sel.parts.is_empty() {
|
||||
return Err(EngineError::Disabled("edit.cut".into(), "the selection has nothing to copy (Delete removes lone points)".into()));
|
||||
}
|
||||
let cut = sel.parts.len();
|
||||
let segments = copy_parts(s, "edit.cut", &sel)?;
|
||||
vectoredit::delete_selection(s, sel.delete, false)?;
|
||||
Ok(json!({"cut": cut, "segments": segments}))
|
||||
}
|
||||
|
||||
/// The SVG of the layers a partial vector-edit copy or cut put on the clipboard, for the system
|
||||
/// clipboard: they are temporary layers that live only in the clipboard, so they are placed in a
|
||||
/// scratch document to export. `None` when the clipboard holds none or the export fails.
|
||||
pub fn clipboard_svg(s: &Session) -> Option<String> {
|
||||
let mut scratch = Document::new("Clipboard");
|
||||
let page = scratch.current_page?;
|
||||
for (k, v) in &s.clipboard.images {
|
||||
scratch.images.insert(k.clone(), v.clone());
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
for (root, nodes) in &s.clipboard.nodes {
|
||||
let map: BTreeMap<NodeId, NodeId> = nodes.iter().map(|n| (n.id, scratch.alloc_id())).collect();
|
||||
ids.push(scratch.paste_nodes(nodes, &map, *root, page, None).ok()?);
|
||||
}
|
||||
let bytes = crate::cmd::file::export_bytes(&scratch, &ids, figcraft_doc::ExportFormat::Svg, 1.0).ok()?;
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// The network of the outline of copied layer `n` in its own coordinates: a vector's segments, a
|
||||
/// shape's or boolean's outline. `None` for the layers with no outline to add (text, images,
|
||||
/// frames, groups, instances, …). `doc` is the file the layer was copied from.
|
||||
fn outline_network(doc: &Document, n: &Node) -> Option<VectorNetwork> {
|
||||
let net = match &n.kind {
|
||||
NodeKind::Vector { network } => network.clone(),
|
||||
k if k.is_shape() || matches!(k, NodeKind::BooleanOp { .. }) => {
|
||||
let (path, rule) = figcraft_render::node_outline(doc, n)?;
|
||||
let mut net = VectorNetwork::from_path(&path);
|
||||
if matches!(n.kind, NodeKind::Line) {
|
||||
net.regions.clear();
|
||||
}
|
||||
if rule == figcraft_render::FillRule::EvenOdd {
|
||||
for r in &mut net.regions {
|
||||
r.winding = figcraft_doc::WindingRule::EvenOdd;
|
||||
}
|
||||
}
|
||||
net
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
(!net.segments.is_empty()).then_some(net)
|
||||
}
|
||||
|
||||
/// `net` moved by `m` (points, handles, the regions' paint frames and the points' radii).
|
||||
fn placed(mut net: VectorNetwork, m: Affine) -> Option<VectorNetwork> {
|
||||
let c = m.as_coeffs();
|
||||
if !c.iter().all(|x| x.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let linear = Affine::new([c[0], c[1], c[2], c[3], 0.0, 0.0]);
|
||||
let scale = m.determinant().abs().sqrt();
|
||||
for v in &mut net.vertices {
|
||||
let p = m * v.point();
|
||||
(v.x, v.y) = (p.x, p.y);
|
||||
v.radius *= scale;
|
||||
}
|
||||
for sg in &mut net.segments {
|
||||
let (ta, tb) = (linear * figcraft_geom::Point::new(sg.ta.0, sg.ta.1), linear * figcraft_geom::Point::new(sg.tb.0, sg.tb.1));
|
||||
sg.ta = (ta.x, ta.y);
|
||||
sg.tb = (tb.x, tb.y);
|
||||
}
|
||||
for r in &mut net.regions {
|
||||
if let Some(frame) = r.paint_space.as_mut() {
|
||||
frame.transform = m * frame.transform;
|
||||
}
|
||||
}
|
||||
let finite = net.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite())
|
||||
&& net.segments.iter().all(|sg| [sg.ta.0, sg.ta.1, sg.tb.0, sg.tb.1].iter().all(|x| x.is_finite()));
|
||||
finite.then_some(net)
|
||||
}
|
||||
|
||||
/// Paste while editing a vector: the clipboard's layers join its network in place (with `x`, `y`:
|
||||
/// the copied top-left moved there), their points selected. Layers with no outline are skipped
|
||||
/// (named in `skipped`); when none has one, nothing is pasted.
|
||||
pub(super) fn paste_into_vector(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.paste";
|
||||
if s.clipboard.nodes.is_empty() {
|
||||
return Err(EngineError::Disabled(CMD.into(), "the clipboard is empty".into()));
|
||||
}
|
||||
let target = vectoredit::editing(s)?.id;
|
||||
let shift = match (num(p, "x"), num(p, "y"), s.clipboard.bounds) {
|
||||
(Some(x), Some(y), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
|
||||
(None, None, _) | (Some(_), Some(_), None) => Affine::IDENTITY,
|
||||
_ => return Err(bad(CMD, "give both x and y, or neither")),
|
||||
};
|
||||
let live = s.doc()?;
|
||||
// Borrow the clipboard (it holds the source document and the images) to build the pieces.
|
||||
let clip = &s.clipboard;
|
||||
let source: &Document = clip.source.as_deref().unwrap_or(live);
|
||||
let to_local = live.world_transform(target).inverse() * shift;
|
||||
let mut pieces = Vec::new();
|
||||
let mut skipped: Vec<String> = Vec::new();
|
||||
for (_, nodes) in &clip.nodes {
|
||||
let Some(root) = nodes.first() else { continue };
|
||||
match outline_network(source, root).and_then(|net| placed(net, to_local * root.transform)) {
|
||||
Some(net) => pieces.push(net),
|
||||
None => skipped.push(root.name.clone()),
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Disabled(
|
||||
CMD.into(),
|
||||
"none of the copied layers has an outline to add to the vector (text, frames and groups have none)".into(),
|
||||
));
|
||||
}
|
||||
let have = vectoredit::network(live, target).map_or(0, |n| n.segments.len());
|
||||
if have.saturating_add(pieces.iter().map(|n| n.segments.len()).sum::<usize>()) > MAX_SEGMENTS {
|
||||
return Err(EngineError::Disabled(CMD.into(), format!("a vector takes at most {MAX_SEGMENTS} segments")));
|
||||
}
|
||||
let mut pasted: Vec<usize> = Vec::new();
|
||||
vectoredit::edit(s.doc_mut()?, target, |net| {
|
||||
for piece in pieces {
|
||||
let (vo, so) = (net.vertices.len(), net.segments.len());
|
||||
pasted.extend(vo..vo + piece.vertices.len());
|
||||
net.vertices.extend(piece.vertices);
|
||||
net.segments.extend(piece.segments.into_iter().map(|mut sg| {
|
||||
sg.a += vo;
|
||||
sg.b += vo;
|
||||
sg
|
||||
}));
|
||||
net.regions.extend(piece.regions.into_iter().map(|mut r| {
|
||||
for i in r.loops.iter_mut().flatten() {
|
||||
*i += so;
|
||||
}
|
||||
r
|
||||
}));
|
||||
}
|
||||
})?;
|
||||
let selected = pasted.clone();
|
||||
vectoredit::set_state(s, |ve| {
|
||||
ve.clear_selection();
|
||||
ve.clear_regions();
|
||||
ve.vertices = selected;
|
||||
ve.anchor = None;
|
||||
ve.pen_out = None;
|
||||
ve.width_point = None;
|
||||
})?;
|
||||
// `ids` stays empty: no layer is created, the pasted outlines joined layer `edited`.
|
||||
let mut out = json!({"ids": [], "edited": target, "vertices": pasted.len()});
|
||||
if !skipped.is_empty() {
|
||||
out["skipped"] = json!(skipped);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! Copy, cut and paste in vector edit mode (#1875), measured in Figma: Copy takes the selected
|
||||
//! segments (a lone point: the segments touching it) and a paste outside is a new vector in place;
|
||||
//! Cut removes them, splitting the path in the same layer; Paste while editing adds the clipboard's
|
||||
//! segments or a copied layer's outline to the vector's network in place, selected.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{EngineError, Session, params};
|
||||
use figcraft_doc::{NodeId, NodeKind, VectorNetwork};
|
||||
|
||||
fn ex(s: &mut Session, c: &str, p: Value) -> Value {
|
||||
s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}"))
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
params::id_of(&v["id"]).unwrap()
|
||||
}
|
||||
|
||||
/// Open path A-B-C-D (three segments) with a look of its own, in edit mode.
|
||||
fn path(s: &mut Session) -> NodeId {
|
||||
let r = ex(s, "vector.create", json!({"points": [[100, 100], [200, 150], [300, 100], [400, 200]], "closed": false}));
|
||||
let id = id_of(&r);
|
||||
ex(s, "node.set", json!({"id": id, "props": {"strokeWeight": 7, "opacity": 0.5}}));
|
||||
ex(s, "vector.edit.begin", json!({"id": id}));
|
||||
id
|
||||
}
|
||||
|
||||
fn net(s: &Session, id: NodeId) -> VectorNetwork {
|
||||
crate::vectoredit::network(s.doc().unwrap(), id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn layers(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().node(s.page().unwrap()).unwrap().children.clone()
|
||||
}
|
||||
|
||||
/// The network's points on the page, rounded, in vertex order.
|
||||
fn page_points(s: &Session, id: NodeId) -> Vec<(i64, i64)> {
|
||||
let w = s.doc().unwrap().world_transform(id);
|
||||
net(s, id).vertices.iter().map(|v| w * v.point()).map(|p| (p.x.round() as i64, p.y.round() as i64)).collect()
|
||||
}
|
||||
|
||||
/// The number of separate paths a network is made of.
|
||||
fn subpaths(n: &VectorNetwork) -> usize {
|
||||
let mut group: Vec<usize> = (0..n.vertices.len()).collect();
|
||||
fn root(g: &[usize], mut i: usize) -> usize {
|
||||
while g[i] != i {
|
||||
i = g[i];
|
||||
}
|
||||
i
|
||||
}
|
||||
for sg in &n.segments {
|
||||
let (a, b) = (root(&group, sg.a), root(&group, sg.b));
|
||||
group[a] = b;
|
||||
}
|
||||
(0..n.vertices.len()).filter(|i| root(&group, *i) == *i && n.segments.iter().any(|sg| root(&group, sg.a) == *i)).count()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, vertices: &[usize], segments: &[usize]) {
|
||||
ex(s, "vector.edit.select", json!({"vertices": vertices, "segments": segments}));
|
||||
}
|
||||
|
||||
fn leave(s: &mut Session) {
|
||||
ex(s, "vector.edit.end", json!({}));
|
||||
assert!(s.ds().unwrap().vector_edit.is_none());
|
||||
}
|
||||
|
||||
fn world_rect(s: &Session, id: NodeId) -> (f64, f64, f64, f64) {
|
||||
let b = s.doc().unwrap().world_bounds(id).unwrap();
|
||||
(b.x0, b.y0, b.width(), b.height())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_segment_pastes_outside_as_a_new_vector_in_place() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
let r = ex(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(r["segments"], 1);
|
||||
assert_eq!(net(&s, id).segments.len(), 3, "Copy changes nothing");
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let all = layers(&s);
|
||||
assert_eq!(all.len(), 2);
|
||||
let new = all[1];
|
||||
let n = net(&s, new);
|
||||
assert_eq!((n.vertices.len(), n.segments.len()), (2, 1));
|
||||
assert_eq!(page_points(&s, new), vec![(200, 150), (300, 100)], "at the segment's own page position");
|
||||
assert_eq!(world_rect(&s, new), (200.0, 100.0, 100.0, 50.0));
|
||||
// The layer's look comes along (the width profile aside).
|
||||
let node = s.doc().unwrap().node(new).unwrap();
|
||||
assert_eq!((node.stroke.weight, node.opacity), (7.0, 0.5));
|
||||
assert_eq!(s.selection(), vec![new]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_point_takes_the_segments_touching_it() {
|
||||
let mut s = Session::new();
|
||||
path(&mut s);
|
||||
select(&mut s, &[1], &[]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let new = *layers(&s).last().unwrap();
|
||||
let n = net(&s, new);
|
||||
assert_eq!((n.vertices.len(), n.segments.len()), (3, 2), "A-B and B-C");
|
||||
assert_eq!(page_points(&s, new), vec![(100, 100), (200, 150), (300, 100)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_selected_still_copies_the_whole_layer() {
|
||||
let mut s = Session::new();
|
||||
path(&mut s);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let new = *layers(&s).last().unwrap();
|
||||
assert_eq!(net(&s, new).segments.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_removes_the_segment_in_the_same_layer_and_stays_in_edit_mode() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!(layers(&s), vec![id], "no new layer");
|
||||
let n = net(&s, id);
|
||||
assert_eq!(n.segments.len(), 2);
|
||||
assert_eq!(subpaths(&n), 2, "the path split in two");
|
||||
let ve = s.ds().unwrap().vector_edit.clone().expect("edit mode stays on");
|
||||
assert!(ve.segments.is_empty() && ve.vertices.is_empty());
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let all = layers(&s);
|
||||
assert_eq!(all.len(), 2);
|
||||
let new = all[1];
|
||||
assert_eq!(net(&s, new).segments.len(), 1);
|
||||
assert_eq!(page_points(&s, new), vec![(200, 150), (300, 100)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_is_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!(net(&s, id).segments.len(), 2);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(net(&s, id).segments.len(), 3);
|
||||
assert_eq!(page_points(&s, id), vec![(100, 100), (200, 150), (300, 100), (400, 200)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_point_takes_its_segments_with_it() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[1], &[]);
|
||||
ex(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!(net(&s, id).segments.len(), 1, "only C-D is left");
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let new = *layers(&s).last().unwrap();
|
||||
assert_eq!(net(&s, new).segments.len(), 2, "A-B and B-C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_segments_while_editing_adds_them_to_the_same_network_in_place() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let r = ex(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(r["vertices"], 2);
|
||||
assert_eq!(layers(&s), vec![id], "no new layer");
|
||||
let n = net(&s, id);
|
||||
assert_eq!((n.vertices.len(), n.segments.len()), (6, 4));
|
||||
assert_eq!(page_points(&s, id)[4..], [(200, 150), (300, 100)], "on top of the original");
|
||||
let ve = s.ds().unwrap().vector_edit.clone().unwrap();
|
||||
assert_eq!(ve.vertices, vec![4, 5], "the pasted points are selected");
|
||||
assert!(ve.segments.is_empty());
|
||||
// One undo reverts it.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(net(&s, id).segments.len(), 3);
|
||||
assert_eq!(net(&s, id).vertices.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_at_a_point_moves_the_copied_top_left_there() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
ex(&mut s, "edit.paste", json!({"x": 0, "y": 0}));
|
||||
assert_eq!(page_points(&s, id)[4..], [(0, 50), (100, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_a_rectangle_while_editing_adds_its_outline_in_the_vectors_coordinates() {
|
||||
let mut s = Session::new();
|
||||
let rect = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 500, "y": 300, "width": 60, "height": 40})));
|
||||
ex(&mut s, "select.set", json!({"ids": [rect]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let id = path(&mut s);
|
||||
let before = world_rect(&s, id);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(layers(&s), vec![rect, id], "no new layer");
|
||||
let n = net(&s, id);
|
||||
assert_eq!((n.vertices.len(), n.segments.len()), (8, 7), "four corners, four sides, joined to the path");
|
||||
let mut corners: Vec<(i64, i64)> = page_points(&s, id)[4..].to_vec();
|
||||
corners.sort_unstable();
|
||||
assert_eq!(corners, vec![(500, 300), (500, 340), (560, 300), (560, 340)]);
|
||||
let ve = s.ds().unwrap().vector_edit.clone().unwrap();
|
||||
assert_eq!(ve.vertices, vec![4, 5, 6, 7]);
|
||||
let after = world_rect(&s, id);
|
||||
assert!(after.2 > before.2 && after.3 > before.3, "the vector's bounds grow: {before:?} to {after:?}");
|
||||
assert_eq!((after.0, after.1), (before.0, before.1));
|
||||
assert_eq!(after.0 + after.2, 560.0);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(net(&s, id).vertices.len(), 4);
|
||||
assert_eq!(world_rect(&s, id), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_vector_takes_pasted_points_in_its_own_coordinates() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
ex(&mut s, "node.set", json!({"id": id, "props": {"rotation": 90}}));
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let before = page_points(&s, id);
|
||||
assert_ne!(before[0], (100, 100), "the vector is rotated");
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let after = page_points(&s, id);
|
||||
assert_eq!(after[4..], before[1..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_with_no_outline_are_skipped_and_named() {
|
||||
let mut s = Session::new();
|
||||
let rect = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 500, "y": 300, "width": 60, "height": 40})));
|
||||
let text = id_of(&ex(&mut s, "text.create", json!({"text": "hello", "x": 500, "y": 400})));
|
||||
let name = s.doc().unwrap().node(text).unwrap().name.clone();
|
||||
// Only text: nothing to add, and nothing changes.
|
||||
ex(&mut s, "select.set", json!({"ids": [text]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let id = path(&mut s);
|
||||
let err = s.execute("edit.paste", &json!({})).unwrap_err();
|
||||
assert!(matches!(err, EngineError::Disabled(..)), "{err}");
|
||||
assert_eq!(net(&s, id).vertices.len(), 4);
|
||||
// The rectangle joins, the text is named as skipped.
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.copy", json!({"ids": [rect, text]}));
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
let r = ex(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(r["skipped"], json!([name]));
|
||||
assert_eq!(net(&s, id).vertices.len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parent_still_pastes_layers_while_editing() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[1]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let page = s.page().unwrap();
|
||||
ex(&mut s, "edit.paste", json!({"parent": page}));
|
||||
assert_eq!(layers(&s).len(), 2);
|
||||
assert_eq!(net(&s, id).segments.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_clipboard_refuses_to_paste_while_editing() {
|
||||
let mut s = Session::new();
|
||||
path(&mut s);
|
||||
assert!(matches!(s.execute("edit.paste", &json!({})), Err(EngineError::Disabled(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_face_copies_its_own_outline_with_the_fill() {
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60}));
|
||||
let id = id_of(&r);
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
select(&mut s, &[], &[0, 1, 2, 3]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let new = *layers(&s).last().unwrap();
|
||||
let n = net(&s, new);
|
||||
assert_eq!((n.segments.len(), n.regions.len()), (4, 1), "the closed shape stays filled");
|
||||
assert!(matches!(s.doc().unwrap().node(new).unwrap().kind, NodeKind::Vector { .. }));
|
||||
}
|
||||
|
||||
/// Everything junk must not change when a command is refused: the vector, the layers, the edit
|
||||
/// selection and what the clipboard holds.
|
||||
fn state(s: &Session, id: NodeId) -> String {
|
||||
let ve = s.ds().unwrap().vector_edit.clone();
|
||||
let clip: Vec<String> = s.clipboard.nodes.iter().flat_map(|(_, n)| n).map(|n| format!("{:?}", n.kind)).collect();
|
||||
format!("{:?}|{:?}|{:?}|{:?}|{}", net(s, id), layers(s), ve.map(|v| (v.vertices, v.segments)), clip, s.clipboard.layers_generation)
|
||||
}
|
||||
|
||||
fn finite(n: &VectorNetwork) -> bool {
|
||||
n.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite())
|
||||
&& n.segments.iter().all(|sg| [sg.ta.0, sg.ta.1, sg.tb.0, sg.tb.1].iter().all(|x| x.is_finite()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_cut_and_paste_survive_junk_in_vector_edit_mode() {
|
||||
let junk = [
|
||||
json!({}),
|
||||
json!(null),
|
||||
json!([1, 2]),
|
||||
json!({"ids": ["x", -1, 99999]}),
|
||||
json!({"id": "nope", "x": "NaN", "y": 1e308}),
|
||||
json!({"parent": "nope", "x": -1e308, "y": "x"}),
|
||||
json!({"x": 1e308, "y": 1e308}),
|
||||
json!({"x": 1e308}),
|
||||
];
|
||||
for cmd in ["edit.copy", "edit.cut", "edit.paste", "edit.pasteOver", "edit.pasteReplace"] {
|
||||
for j in &junk {
|
||||
// Both a selection with a text layer next to it, and after a copy from the selection.
|
||||
for copied in [false, true] {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
if copied {
|
||||
select(&mut s, &[2], &[]);
|
||||
let _ = s.execute("edit.copy", &json!({}));
|
||||
} else {
|
||||
select(&mut s, &[1], &[0]);
|
||||
ex(&mut s, "text.create", json!({"text": "t"}));
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
select(&mut s, &[1], &[0]);
|
||||
}
|
||||
let before = state(&s, id);
|
||||
match s.execute(cmd, j) {
|
||||
Err(EngineError::Internal { cmd, msg }) => panic!("{cmd} panicked on {j}: {msg}"),
|
||||
Err(_) => {
|
||||
if cmd != "edit.pasteOver" && cmd != "edit.pasteReplace" {
|
||||
assert_eq!(state(&s, id), before, "{cmd} {j} was refused but changed something");
|
||||
}
|
||||
}
|
||||
// Accepted: whatever it made has finite coordinates.
|
||||
Ok(_) => {
|
||||
if let Some(n) = crate::vectoredit::network(s.doc().unwrap(), id) {
|
||||
assert!(finite(n), "{cmd} {j} left non-finite coordinates");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_paste_position_is_refused_or_stays_finite() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[0]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let before = state(&s, id);
|
||||
match s.execute("edit.paste", &json!({"x": 1e308, "y": 1e308})) {
|
||||
Err(e) => {
|
||||
assert!(!matches!(e, EngineError::Internal { .. }), "{e}");
|
||||
assert_eq!(state(&s, id), before, "a refused paste changed something");
|
||||
}
|
||||
// It is accepted here: 1e308 plus a few hundred is still finite, so the points are too.
|
||||
Ok(_) => assert!(finite(&net(&s, id)), "the points are finite"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_with_only_lone_points_is_refused_like_copy_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
// A point no segment touches.
|
||||
crate::vectoredit::edit(s.doc_mut().unwrap(), id, |n| n.vertices.push(figcraft_doc::Vertex::new(50.0, 50.0))).unwrap();
|
||||
// Something on the clipboard first, then only the lone point selected.
|
||||
select(&mut s, &[0], &[]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
select(&mut s, &[4], &[]);
|
||||
let before = state(&s, id);
|
||||
for cmd in ["edit.copy", "edit.cut"] {
|
||||
let err = s.execute(cmd, &json!({})).expect_err(cmd);
|
||||
assert!(matches!(err, EngineError::Disabled(..)), "{cmd}: {err}");
|
||||
assert_eq!(state(&s, id), before, "{cmd} changed something");
|
||||
}
|
||||
// Delete is the way to remove it.
|
||||
ex(&mut s, "vector.edit.delete", json!({}));
|
||||
assert_eq!(net(&s, id).vertices.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_of_x_and_y_is_refused_and_pastes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let id = path(&mut s);
|
||||
select(&mut s, &[], &[0]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let before = state(&s, id);
|
||||
for p in [json!({"x": 10}), json!({"y": 10})] {
|
||||
let err = s.execute("edit.paste", &p).expect_err("one coordinate");
|
||||
assert!(err.to_string().contains("give both x and y, or neither"), "{err}");
|
||||
assert_eq!(state(&s, id), before);
|
||||
}
|
||||
ex(&mut s, "edit.paste", json!({"x": 10, "y": 10}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_copy_has_an_svg_for_the_system_clipboard() {
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60}));
|
||||
assert!(crate::cmd::edit::clipboard_svg(&s).is_none(), "nothing copied yet");
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id_of(&r)}));
|
||||
select(&mut s, &[], &[0, 1, 2, 3]);
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let svg = crate::cmd::edit::clipboard_svg(&s).expect("svg");
|
||||
assert!(svg.contains("<svg") && svg.contains("<path"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cutting_a_selected_region_deletes_exactly_the_segments_it_copies_and_keeps_a_tail() {
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "vector.create", json!({"points": [[100, 100], [200, 100], [150, 200]], "closed": true}));
|
||||
let id = id_of(&r);
|
||||
// A tail: one open segment from the first corner to a new point.
|
||||
crate::vectoredit::edit(s.doc_mut().unwrap(), id, |n| {
|
||||
n.vertices.push(figcraft_doc::Vertex::new(20.0, 20.0));
|
||||
let tail = n.vertices.len() - 1;
|
||||
crate::vectoredit::ops::connect(n, 0, tail, (0.0, 0.0), (0.0, 0.0));
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((net(&s, id).segments.len(), net(&s, id).regions.len()), (4, 1));
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [0]}));
|
||||
ex(&mut s, "edit.cut", json!({}));
|
||||
let n = net(&s, id);
|
||||
assert_eq!(n.segments.len(), 1, "only the tail is left");
|
||||
assert!(n.regions.is_empty());
|
||||
leave(&mut s);
|
||||
ex(&mut s, "edit.paste", json!({}));
|
||||
let new = *layers(&s).last().unwrap();
|
||||
assert_eq!(net(&s, new).segments.len(), 3, "the copy holds the region's three segments, not the tail");
|
||||
}
|
||||
@@ -26,8 +26,8 @@ pub(crate) use export::FORBIDDEN_FILE_NAME_CHARS;
|
||||
use export::add_member;
|
||||
pub(super) use export::export_setting;
|
||||
pub use export::{
|
||||
ExportJob, copy_png, drawn_layers, export_area, export_bytes, export_bytes_with, export_jobs, export_scale, exportable_layers, fig_bytes,
|
||||
frames_pdf, jobs_for, penpot_bytes, safe_file_name,
|
||||
ExportJob, backdrop_layers, copy_png, drawn_layers, export_area, export_bytes, export_bytes_with, export_jobs, export_scale, exportable_layers,
|
||||
fig_bytes, frames_pdf, jobs_for, penpot_bytes, safe_file_name,
|
||||
};
|
||||
use export::{export, export_frames_pdf, export_layers, pdf_bytes};
|
||||
use load::font_report;
|
||||
@@ -41,7 +41,7 @@ use open::append_pages;
|
||||
pub(crate) use open::open;
|
||||
use open::{import, open_recent, revert};
|
||||
pub(crate) use save::save_ends_preview;
|
||||
pub use save::{FileSnapshot, file_bytes, thumbnail};
|
||||
pub use save::{FileSnapshot, file_bytes, file_bytes_at, thumbnail};
|
||||
use save::{color_profile, mark_saved, save, save_as};
|
||||
pub use version::MAX_AUTOSAVES;
|
||||
pub(crate) use version::{add_version, keep_in_history, read_version, unique_id};
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"file.export",
|
||||
"Export",
|
||||
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, PDF and XML are always sRGB), quality? (JPG: 1-100, default 90)}",
|
||||
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, XML and RGB PDF output are always sRGB; PDF with cmyk is DeviceCMYK), quality? (JPG: 1-100, default 90)}",
|
||||
false,
|
||||
export
|
||||
),
|
||||
@@ -372,7 +372,8 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal
|
||||
&& !setting.include_bounding_box
|
||||
&& !ids.iter().any(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Slice)));
|
||||
match setting.format {
|
||||
// SVG and PDF colours are sRGB: a Display P3 file exports converted (out-of-gamut colours clip).
|
||||
// SVG and RGB PDF colors are sRGB: a Display P3 file exports converted (out-of-gamut colours clip).
|
||||
// PDF with `cmyk` converts from those sRGB colors to DeviceCMYK.
|
||||
ExportFormat::Svg => {
|
||||
let opts = figcraft_svg::SvgOptions {
|
||||
include_ids: setting.svg_id_attribute,
|
||||
@@ -408,7 +409,10 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal
|
||||
Ok((pdf_bytes(doc, &groups, &setting.print, (!own_area).then_some(area))?, Vec::new()))
|
||||
}
|
||||
_ => {
|
||||
let mut pix = figcraft_render::render_area(doc, &drawn, area, scale)
|
||||
// Layers exported on their own still read the page beneath them for a background blur
|
||||
// or glass (#2213); a "contents only" off export already draws the whole page.
|
||||
let page = if setting.contents_only { backdrop_layers(doc, ids) } else { Vec::new() };
|
||||
let mut pix = figcraft_render::render_area_over(doc, &drawn, &page, area, scale)
|
||||
.ok_or_else(|| EngineError::Other("render failed (empty or too large)".into()))?;
|
||||
// The render is in the document's profile; the setting's profile converts the pixels
|
||||
// (out-of-gamut colors clip) and tags the file.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::load::{ext, write};
|
||||
use super::save::thumbnail;
|
||||
use super::*;
|
||||
use crate::params::f64_of;
|
||||
use crate::params::{f64_of, req_targets};
|
||||
|
||||
/// Encode `ids` (or the page) in `format` at `scale`.
|
||||
pub fn export_bytes(doc: &Document, ids: &[NodeId], format: ExportFormat, scale: f64) -> Result<Vec<u8>> {
|
||||
@@ -55,6 +55,12 @@ pub fn drawn_layers(doc: &Document, ids: &[NodeId], setting: &ExportSetting) ->
|
||||
crate::cmd::edit::z_sorted(doc, &crate::cmd::edit::roots(doc, &own))
|
||||
}
|
||||
|
||||
/// The top-level layers of the page of `ids`, bottom to top: what a background blur or glass in an
|
||||
/// export of `ids` reads from (empty when `ids` are on no page).
|
||||
pub fn backdrop_layers(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.first().and_then(|i| doc.page_of(*i)).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The frame or group a slice sits in: None on the page or in a section.
|
||||
fn slice_container(doc: &Document, slice: NodeId) -> Option<NodeId> {
|
||||
let parent = doc.node(slice)?.parent?;
|
||||
@@ -86,7 +92,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => {}
|
||||
}
|
||||
let doc = s.doc()?;
|
||||
let mut ids = targets(s, p);
|
||||
let mut ids = export_targets(cmd, s, p)?;
|
||||
if ids.is_empty() {
|
||||
ids = doc.get(s.page()?)?.children.clone();
|
||||
}
|
||||
@@ -325,11 +331,22 @@ pub fn exportable_layers(doc: &Document, page: NodeId) -> Vec<NodeId> {
|
||||
doc.subtree(page).into_iter().skip(1).filter(|i| doc.node(*i).is_some_and(|n| !n.exports.is_empty())).collect()
|
||||
}
|
||||
|
||||
/// Named layers (`ids` / `id`), checked like other commands; empty when none are named, so the
|
||||
/// caller can fall back to its default instead of silently dropping a bad id.
|
||||
fn export_targets(cmd: &str, s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let named = match get(p, "ids") {
|
||||
Some(Value::Array(a)) if !a.is_empty() => true,
|
||||
Some(Value::Array(_) | Value::Null) | None => get(p, "id").is_some_and(|v| !v.is_null()),
|
||||
Some(_) => true,
|
||||
};
|
||||
if named { req_targets(cmd, s, p) } else { Ok(targets(s, p)) }
|
||||
}
|
||||
|
||||
pub(super) fn export_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.exportLayers";
|
||||
let doc = s.doc()?;
|
||||
let assets = boolean(p, "assets").unwrap_or(false);
|
||||
let mut ids = targets(s, p);
|
||||
let mut ids = export_targets(cmd, s, p)?;
|
||||
if ids.is_empty() {
|
||||
ids = if assets { vec![s.page()?] } else { exportable_layers(doc, s.page()?) };
|
||||
}
|
||||
|
||||
@@ -75,7 +75,9 @@ pub fn load_bytes(bytes: &[u8], name_hint: &str) -> Result<(Document, Vec<String
|
||||
pub fn load_path(path: &str, variables: Option<&Value>) -> Result<(figcraft_format::Loaded, bool)> {
|
||||
let bytes = read(path)?;
|
||||
let sibling = if variables.is_none() { sibling_variables(path) } else { None };
|
||||
load_with(&bytes, path, variables.or(sibling.as_ref()), &rest_images(path))
|
||||
let (mut loaded, rest) = load_with(&bytes, path, variables.or(sibling.as_ref()), &rest_images(path))?;
|
||||
crate::library::resolve_links(&mut loaded.doc, path);
|
||||
Ok((loaded, rest))
|
||||
}
|
||||
|
||||
/// Load from bytes. Returns the document with its notes (repairs of a native file, or import
|
||||
@@ -399,11 +401,19 @@ pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option<Result<figcraft_forma
|
||||
}))
|
||||
}
|
||||
|
||||
/// The most layers all of a Penpot file's raw SVG placeholders may expand to together.
|
||||
const MAX_PENPOT_SVG_LAYERS: usize = 100_000;
|
||||
|
||||
/// Turn Penpot raw SVG placeholders into editable FigCraft SVG content, using the
|
||||
/// normal SVG importer. The parser (figcraft-format) only stores bounded XML so it
|
||||
/// does not need to depend on the SVG crate; the engine does this second pass.
|
||||
/// Any failure leaves the original placeholder and XML data intact for later use.
|
||||
fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
|
||||
expand_penpot_raw_svgs_within(doc, notes, MAX_PENPOT_SVG_LAYERS);
|
||||
}
|
||||
|
||||
/// [`expand_penpot_raw_svgs`] with at most `room` layers made in all.
|
||||
fn expand_penpot_raw_svgs_within(doc: &mut Document, notes: &mut Vec<String>, mut room: usize) {
|
||||
let layers = doc
|
||||
.nodes()
|
||||
.filter_map(|node| {
|
||||
@@ -413,12 +423,24 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut ok_count = 0usize;
|
||||
// The SVG importer caps its own layers per file; `room` is the cap over all of a file's placeholders.
|
||||
for (id, name, width, height, xml, empty) in layers {
|
||||
if room == 0 {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
|
||||
}
|
||||
if notes.len() < 100 {
|
||||
notes.push(format!("Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !empty {
|
||||
notes.push(format!("Penpot SVG '{name}': has separate child layers; the original tree was preserved to prevent duplicate rendering"));
|
||||
continue;
|
||||
}
|
||||
match figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name) {
|
||||
let before = doc.node_count();
|
||||
let imported = figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name);
|
||||
match imported {
|
||||
Ok(imported) => {
|
||||
// An SVG can be syntactically valid yet contain no supported drawable
|
||||
// elements. Do not claim success or leave an empty extra frame.
|
||||
@@ -432,6 +454,21 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Charged once the empty ones are gone; one that doesn't fit is taken out again.
|
||||
let added = doc.node_count().saturating_sub(before);
|
||||
if added > room {
|
||||
let _ = doc.remove(imported.frame);
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
|
||||
}
|
||||
if notes.len() < 100 {
|
||||
notes.push(format!(
|
||||
"Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
room -= added;
|
||||
let size = doc.node(imported.frame).map(|n| (n.width, n.height));
|
||||
if let Some((svg_w, svg_h)) = size
|
||||
&& svg_w.is_finite()
|
||||
@@ -470,6 +507,28 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether some of the first `len` characters are in none of `runs`. Where runs start and stop
|
||||
/// covering is summed once, so runs overlapping any number of times cost no more than their count.
|
||||
fn has_uncovered(len: usize, runs: &[figcraft_doc::StyleRun]) -> bool {
|
||||
let mut change = vec![0i64; len + 1];
|
||||
for run in runs {
|
||||
let (start, end) = (run.start.min(len), run.end.min(len));
|
||||
if start < end {
|
||||
if let Some(c) = change.get_mut(start) {
|
||||
*c += 1;
|
||||
}
|
||||
if let Some(c) = change.get_mut(end) {
|
||||
*c -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut open = 0i64;
|
||||
change.iter().take(len).any(|c| {
|
||||
open += c;
|
||||
open <= 0
|
||||
})
|
||||
}
|
||||
|
||||
/// Non-destructive font diagnostic for the action palette, CLI and control API.
|
||||
/// Includes styled runs, not just the default typeface of each text layer.
|
||||
pub(super) fn font_report(doc: &Document) -> Value {
|
||||
@@ -485,21 +544,15 @@ fn font_report_with_families(doc: &Document, installed: &[String]) -> Value {
|
||||
if text.characters.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut covered = vec![false; text.characters.chars().count().min(100_000)];
|
||||
let len = text.characters.chars().count().min(100_000);
|
||||
let mut used = BTreeSet::new();
|
||||
for run in &text.runs {
|
||||
let start = run.start.min(covered.len());
|
||||
let end = run.end.min(covered.len());
|
||||
if start < end {
|
||||
if !run.style.font_family.trim().is_empty() {
|
||||
used.insert(run.style.font_family.clone());
|
||||
}
|
||||
for entry in covered.iter_mut().take(end).skip(start) {
|
||||
*entry = true;
|
||||
}
|
||||
if run.start.min(len) < run.end.min(len) && !run.style.font_family.trim().is_empty() {
|
||||
used.insert(run.style.font_family.clone());
|
||||
}
|
||||
}
|
||||
if covered.iter().any(|entry| !entry) {
|
||||
let uncovered = has_uncovered(len, &text.runs);
|
||||
if uncovered {
|
||||
used.insert(text.style.font_family.clone());
|
||||
}
|
||||
for family in used {
|
||||
@@ -599,19 +652,14 @@ fn missing_penpot_font_warnings(doc: &Document, families: &[String]) -> Vec<Stri
|
||||
if text_len == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut covered = vec![false; text_len.min(100_000)];
|
||||
let len = text_len.min(100_000);
|
||||
let mut used = BTreeSet::new();
|
||||
for run in &text.runs {
|
||||
let start = run.start.min(covered.len());
|
||||
let end = run.end.min(covered.len());
|
||||
if start < end {
|
||||
if run.start.min(len) < run.end.min(len) {
|
||||
used.insert(run.style.font_family.clone());
|
||||
for flag in covered.iter_mut().take(end).skip(start) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if covered.iter().any(|present| !present) {
|
||||
if has_uncovered(len, &text.runs) {
|
||||
used.insert(text.style.font_family.clone());
|
||||
}
|
||||
for family in used {
|
||||
@@ -652,8 +700,10 @@ fn link_instances(doc: &mut Document) {
|
||||
let mut insts: Vec<(usize, NodeId)> =
|
||||
doc.nodes().filter(|n| matches!(n.kind, NodeKind::Instance { .. })).map(|n| (doc.ancestors(n.id).len(), n.id)).collect();
|
||||
insts.sort_by_key(|a| std::cmp::Reverse(a.0));
|
||||
// Rebasing leaves the mains alone, so each main's layer paths are worked out once.
|
||||
let mut mains = crate::components::MainPaths::new();
|
||||
for (_, i) in insts {
|
||||
crate::components::rebase_instance(doc, i);
|
||||
crate::components::rebase_instance_with(doc, i, &mut mains);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -790,6 +840,47 @@ mod penpot_svg_v10_tests {
|
||||
use super::*;
|
||||
use figcraft_doc::TextData;
|
||||
|
||||
#[test]
|
||||
fn placeholders_share_one_layer_allowance() {
|
||||
let mut doc = Document::new("Two SVGs");
|
||||
let page = doc.first_page().unwrap();
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="5" height="5" fill="red"/><rect x="5" width="5" height="5" fill="blue"/></svg>"#;
|
||||
let ids: Vec<NodeId> = (0..2)
|
||||
.map(|i| {
|
||||
let id = doc.create(page, NodeKind::Frame, &format!("S{i}"), 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let layer = doc.node_mut(id).unwrap();
|
||||
layer.plugin_data.insert("penpot.svgRawXml".into(), svg.into());
|
||||
layer.plugin_data.insert("penpot.svgRawStatus".into(), "pending".into());
|
||||
id
|
||||
})
|
||||
.collect();
|
||||
let mut warnings = Vec::new();
|
||||
let nodes = doc.node_count();
|
||||
expand_penpot_raw_svgs_within(&mut doc, &mut warnings, 4);
|
||||
assert!(doc.node_count() - nodes <= 4, "never more layers than the allowance");
|
||||
let status = |i: usize| doc.node(ids[i]).unwrap().plugin_data.get("penpot.svgRawStatus").cloned();
|
||||
assert_eq!(status(0).as_deref(), Some("expanded"), "the first uses the allowance");
|
||||
assert_eq!(status(1).as_deref(), Some("not-expanded"));
|
||||
assert!(doc.node(ids[1]).unwrap().children.is_empty());
|
||||
assert!(warnings.iter().any(|w| w.contains("over the limit")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_overlapping_style_runs_are_summed_once() {
|
||||
use figcraft_doc::StyleRun;
|
||||
let mut doc = Document::new("Runs");
|
||||
let page = doc.first_page().unwrap();
|
||||
let mut t = TextData::new("x".repeat(100_000));
|
||||
t.style.font_family = "Unused Base".into();
|
||||
let mut run = t.style.clone();
|
||||
run.font_family = "Run Font".into();
|
||||
t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect();
|
||||
doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap();
|
||||
let report = font_report_with_families(&doc, &[]);
|
||||
assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}");
|
||||
assert_eq!(report["fonts"][0]["family"], "Run Font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_inline_svg_into_editable_shapes_without_discarding_source() {
|
||||
let mut doc = Document::new("SVG fixture");
|
||||
|
||||
@@ -30,8 +30,9 @@ pub(super) fn open_recent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
allow(&path, Access::Read)?;
|
||||
Some(path)
|
||||
}
|
||||
(None, Some(i)) => {
|
||||
Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i.max(0.0) as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
|
||||
(None, Some(_)) => {
|
||||
let i = req_index(CMD, p, "index")?;
|
||||
Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -42,6 +42,11 @@ pub fn file_bytes(ds: &DocState) -> Result<Vec<u8>> {
|
||||
FileSnapshot::of(ds).encode()
|
||||
}
|
||||
|
||||
/// [`file_bytes`] for the file at `path` (library links are stored relative to its folder too).
|
||||
pub fn file_bytes_at(ds: &DocState, path: &str) -> Result<Vec<u8>> {
|
||||
FileSnapshot::of(ds).encode_at(Some(path))
|
||||
}
|
||||
|
||||
/// A document's file as it is at one moment, so the slow part of saving it (the thumbnail and the
|
||||
/// encoding) can run on another thread while editing goes on: [`encode`](Self::encode) there, then
|
||||
/// [`save`](Self::save) the bytes back on the session's thread.
|
||||
@@ -73,8 +78,17 @@ impl FileSnapshot {
|
||||
|
||||
/// The file's bytes: content, thumbnail and version history.
|
||||
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||
self.encode_at(self.path.as_deref())
|
||||
}
|
||||
|
||||
/// [`encode`](Self::encode) for the file at `path`: library links also say where their
|
||||
/// files are from its folder.
|
||||
fn encode_at(&self, path: Option<&str>) -> Result<Vec<u8>> {
|
||||
let mut doc = (*self.doc).clone();
|
||||
doc.current_page = Some(self.page);
|
||||
if let Some(path) = path {
|
||||
crate::library::relate_links(&mut doc, path);
|
||||
}
|
||||
let thumb = thumbnail(&doc);
|
||||
figcraft_format::save_bytes_with_history(&doc, thumb.as_deref(), &self.versions, &self.branches)
|
||||
.map_err(|e| EngineError::Other(e.to_string()))
|
||||
@@ -177,7 +191,7 @@ fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
|
||||
{
|
||||
Arc::make_mut(&mut snapshot.doc).name = file_stem(path);
|
||||
}
|
||||
let bytes = snapshot.encode()?;
|
||||
let bytes = snapshot.encode_at(path.as_deref().or(snapshot.path.as_deref()))?;
|
||||
let Some(path) = path else {
|
||||
// The download can still be refused: the caller marks the file saved once it was delivered.
|
||||
let name = format!("{}.figcraft", ds.doc.name);
|
||||
|
||||
@@ -5,7 +5,7 @@ use figcraft_doc::{Document, ImagePreset, Node};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, ok};
|
||||
use crate::params::{f64_of, get, num, req_index, req_string, req_targets, string, targets};
|
||||
use crate::params::{f64_of, get, req_index, req_string, req_targets, string, targets};
|
||||
use crate::{EngineError, Result, Session, bad, spec};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -236,7 +236,10 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => with_values(cmd, ImageFilters::NONE, v)?,
|
||||
None => {
|
||||
let stroke = strokes(cmd, p)?;
|
||||
let index = num(p, "index").filter(|k| k.is_finite() && *k >= 0.0).map(|k| k as usize);
|
||||
let index = match get(p, "index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(req_index(cmd, p, "index")?),
|
||||
};
|
||||
let doc = s.doc()?;
|
||||
targets(s, p)
|
||||
.iter()
|
||||
|
||||
@@ -646,7 +646,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
l.path = path.clone();
|
||||
l.name = m.name.clone();
|
||||
}
|
||||
None => libs.enabled.push(LibraryLink { id: m.id.clone(), name: m.name.clone(), path: path.clone(), version: m.version }),
|
||||
None => libs.enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.clone(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
let mut out = assets_json(&lib);
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::{Result, bad};
|
||||
pub const STROKE_SIDES: [&str; 4] = ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"];
|
||||
|
||||
/// Keys `node.set` understands (documented for agents).
|
||||
pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), \
|
||||
pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page: the layer's angle plus its parents', what the Design panel's field shows; one of the two per call), \
|
||||
fills (paints or colours; gradients as {type: linearGradient|radialGradient|angularGradient|diamondGradient, stops: [\"#hex\", ...], from?, to?} too), fill (colour, {$var: variable id or name}, or \"none\"/null: no fill), strokes, stroke (colour, {$var: variable id or name}, or \"none\"/null: no stroke), strokeWeight, strokeAlign (inside|center|outside), strokeSides [t,r,b,l], strokeTopWeight / strokeRightWeight / strokeBottomWeight / strokeLeftWeight (one side; turns on individual strokes), \
|
||||
strokeCap / startCap / endCap, strokeJoin, miterAngle (degrees: sharper joins bevel; or miterLimit as a ratio), dashes [..], dashCap (none|round|square; null: dashes take startCap and endCap), widthProfile (preset uniform|wedge|taper|eye|rounded|pinch, [[t, scale], ...] or null), brush (preset id, {preset, spacing, sizeJitter, rotationJitter, scatter, seed} or null), cornerRadius (n or [tl,tr,br,bl]), cornerSmoothing (0-1), effects, \
|
||||
clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, padding (n or [t,r,b,l]), paddingTop/Right/Bottom/Left, \
|
||||
@@ -29,7 +29,7 @@ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (l
|
||||
(auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \
|
||||
textDecorationColor (colour, or auto/null: the text's), textCase (original|upper|lower|title|smallCaps), paragraphSpacing, paragraphIndent, \
|
||||
listStyle (none|bulleted|numbered; with start/end: the paragraphs those chars touch), indentation (list nesting level 0-8, same range rule), \
|
||||
listSpacing (px between list items, in place of paragraphSpacing), hangingPunctuation, hangingList (markers outside the box), leadingTrim (vertical trim: none|capHeight), maxLines, features ({tag: bool}, e.g. {\"liga\": false, \"tnum\": true}), \
|
||||
listSpacing (px between list items, in place of paragraphSpacing), wrapStyle (auto|balance|pretty; with start/end: the paragraphs those chars touch), hangingPunctuation, hangingList (markers outside the box), leadingTrim (vertical trim: none|capHeight), maxLines, features ({tag: bool}, e.g. {\"liga\": false, \"tnum\": true}), \
|
||||
fontVariations / variationSettings ({axis: number}, e.g. {\"wght\": 550, \"wdth\": 85}; null = none), \
|
||||
path (a vector's SVG path data: replaces its geometry, keeping the layer, its paints, styles and bindings; width/height in the same call scale it as \
|
||||
node.create does; its own box goes at the layer's x/y, or with x/y given, at x + its left edge and y + its top as node.create places it), pointCount, innerRadius, arcStart, arcSweep, \
|
||||
@@ -456,7 +456,7 @@ fn apply_order(k: &str, v: &Value) -> u8 {
|
||||
match k {
|
||||
"path" | "width" | "height" | "w" | "h" => 0,
|
||||
"layout" | "layoutMode" => 1,
|
||||
"rotation" => 3,
|
||||
"rotation" | "absoluteRotation" => 3,
|
||||
"x" | "y" => 4,
|
||||
"fillStyle" | "strokeStyle" | "effectStyle" | "textStyle" | "gridStyle" => 5,
|
||||
"boundVariables" => 6,
|
||||
@@ -595,6 +595,27 @@ fn apply_geometry(
|
||||
let n = doc.get_mut(id)?;
|
||||
n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg);
|
||||
}
|
||||
"absoluteRotation" => {
|
||||
let deg = f64_of(v).ok_or_else(|| bad(cmd, "`absoluteRotation` must be degrees"))?;
|
||||
if props.contains_key("rotation") {
|
||||
return Err(bad(cmd, "give one of `rotation` and `absoluteRotation`"));
|
||||
}
|
||||
let (w, h) = {
|
||||
let n = doc.get(id)?;
|
||||
(n.width, n.height)
|
||||
};
|
||||
let world = figcraft_geom::set_rotation_about_center(doc.world_transform(id), w, h, deg);
|
||||
let parent = doc.get(id)?.parent;
|
||||
let pw = parent.map(|p| doc.world_transform(p)).unwrap_or(figcraft_geom::Affine::IDENTITY);
|
||||
let local = pw.inverse() * world;
|
||||
if local.as_coeffs().iter().all(|c| c.is_finite()) {
|
||||
doc.get_mut(id)?.transform = local;
|
||||
} else {
|
||||
// A degenerate parent can't be inverted: turn the local angle instead.
|
||||
let n = doc.get_mut(id)?;
|
||||
n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg);
|
||||
}
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
@@ -657,7 +678,7 @@ fn apply_look(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value) ->
|
||||
"startCap" => doc.get_mut(id)?.stroke.cap_start = enum_of(v).ok_or_else(|| bad(cmd, format!("startCap: {STROKE_CAP_HELP}")))?,
|
||||
"endCap" => doc.get_mut(id)?.stroke.cap_end = enum_of(v).ok_or_else(|| bad(cmd, format!("endCap: {STROKE_CAP_HELP}")))?,
|
||||
"strokeJoin" => doc.get_mut(id)?.stroke.join = enum_of(v).ok_or_else(|| bad(cmd, "strokeJoin: miter|bevel|round"))?,
|
||||
"miterLimit" => doc.get_mut(id)?.stroke.miter_limit = f64_of(v).unwrap_or(4.0).clamp(1.0, 100.0),
|
||||
"miterLimit" => doc.get_mut(id)?.stroke.miter_limit = f64_of(v).ok_or_else(|| bad(cmd, "`miterLimit` must be a number"))?.clamp(1.0, 100.0),
|
||||
"miterAngle" => {
|
||||
let deg = f64_of(v).ok_or_else(|| bad(cmd, "`miterAngle` must be degrees"))?;
|
||||
doc.get_mut(id)?.stroke.miter_limit = StrokeProps::miter_limit_for(deg);
|
||||
@@ -707,7 +728,9 @@ fn apply_corners(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value)
|
||||
*slot = r;
|
||||
}
|
||||
}
|
||||
"cornerSmoothing" => doc.get_mut(id)?.corners.smoothing = f64_of(v).unwrap_or(0.0).clamp(0.0, 1.0),
|
||||
"cornerSmoothing" => {
|
||||
doc.get_mut(id)?.corners.smoothing = f64_of(v).ok_or_else(|| bad(cmd, "`cornerSmoothing` must be a number"))?.clamp(0.0, 1.0)
|
||||
}
|
||||
"effects" => doc.get_mut(id)?.effects = effects_from(cmd, v)?,
|
||||
"clip" | "clipsContent" => doc.get_mut(id)?.clip = v.as_bool().ok_or_else(|| bad(cmd, "`clip` must be a boolean"))?,
|
||||
"isMask" => doc.get_mut(id)?.is_mask = v.as_bool().ok_or_else(|| bad(cmd, format!("`{k}` must be a boolean")))?,
|
||||
@@ -981,8 +1004,12 @@ fn apply_text(cmd: &str, doc: &mut Document, id: NodeId, props: &Map<String, Val
|
||||
text_mut(cmd, doc.get_mut(id)?)?.auto_resize =
|
||||
enum_of(v).ok_or_else(|| bad(cmd, "textAutoResize: widthAndHeight|height|none|truncate"))?
|
||||
}
|
||||
"paragraphSpacing" => text_mut(cmd, doc.get_mut(id)?)?.paragraph_spacing = f64_of(v).unwrap_or(0.0).max(0.0),
|
||||
"paragraphIndent" => text_mut(cmd, doc.get_mut(id)?)?.paragraph_indent = f64_of(v).unwrap_or(0.0).max(0.0),
|
||||
"paragraphSpacing" => {
|
||||
text_mut(cmd, doc.get_mut(id)?)?.paragraph_spacing = f64_of(v).ok_or_else(|| bad(cmd, "`paragraphSpacing` must be a number"))?.max(0.0)
|
||||
}
|
||||
"paragraphIndent" => {
|
||||
text_mut(cmd, doc.get_mut(id)?)?.paragraph_indent = f64_of(v).ok_or_else(|| bad(cmd, "`paragraphIndent` must be a number"))?.max(0.0)
|
||||
}
|
||||
"listStyle" | "indentation" => {
|
||||
let t = text_mut(cmd, doc.get_mut(id)?)?;
|
||||
let (start, end) = range_of(props, t.char_count());
|
||||
@@ -1008,7 +1035,14 @@ fn apply_text(cmd: &str, doc: &mut Document, id: NodeId, props: &Map<String, Val
|
||||
}
|
||||
"leadingTrim" => text_mut(cmd, doc.get_mut(id)?)?.leading_trim = enum_of(v).ok_or_else(|| bad(cmd, "leadingTrim: none|capHeight"))?,
|
||||
"wrapStyle" | "textWrap" => {
|
||||
text_mut(cmd, doc.get_mut(id)?)?.wrap_style = enum_of(v).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))?
|
||||
let w: figcraft_doc::WrapStyle = enum_of(v).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))?;
|
||||
let t = text_mut(cmd, doc.get_mut(id)?)?;
|
||||
if props.contains_key("start") || props.contains_key("end") {
|
||||
let (start, end) = range_of(props, t.char_count());
|
||||
t.set_para_wrap_styles(start, end, w);
|
||||
} else {
|
||||
t.set_wrap_style(w);
|
||||
}
|
||||
}
|
||||
"maxLines" => {
|
||||
let lines = f64_of(v).unwrap_or(0.0).clamp(0.0, 10_000.0) as u32;
|
||||
|
||||
@@ -496,7 +496,9 @@ fn collect_flatten_parts(
|
||||
}
|
||||
let part = match &node.kind {
|
||||
NodeKind::Vector { network } => {
|
||||
let mut part = network.clone();
|
||||
// Rounded points bake into the path (the arc's end points joined by curves), drawn the way
|
||||
// the layer draws them, so the shape looks the same and the box fits the real geometry.
|
||||
let mut part = figcraft_doc::geometry::drawn_network(network, node.corners.smoothing).into_owned();
|
||||
if !part.regions.is_empty() && part.regions.iter().all(|region| region.fills.is_none() && region.paint_space.is_none()) {
|
||||
let winding = if part.regions.iter().any(|region| region.winding == WindingRule::EvenOdd) {
|
||||
WindingRule::EvenOdd
|
||||
@@ -799,7 +801,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
WindingRule::NonZero
|
||||
};
|
||||
let path = drawn.fill_path();
|
||||
let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
|
||||
let path = figcraft_geom::simplify_path(&path, tol);
|
||||
let (path, output_winding) = match figcraft_pathops::simplify_with_rule(&path, winding == WindingRule::EvenOdd) {
|
||||
Ok(path) => (path, WindingRule::EvenOdd),
|
||||
Err(_) => (path, winding),
|
||||
@@ -809,7 +811,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
for (index, region) in source.regions.iter().enumerate() {
|
||||
let Some(path) = drawn.region_path(index) else { continue };
|
||||
let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
|
||||
let path = figcraft_geom::simplify_path(&path, tol);
|
||||
let path = figcraft_pathops::simplify_with_rule(&path, region.winding == WindingRule::EvenOdd).unwrap_or(path);
|
||||
append_region_path(&mut net, &path, region, region.winding);
|
||||
}
|
||||
@@ -826,7 +828,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
open.regions.clear();
|
||||
if !open.segments.is_empty() {
|
||||
let path = open.stroke_path();
|
||||
let simplified = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
|
||||
let simplified = figcraft_geom::simplify_path(&path, tol);
|
||||
let mut loose = VectorNetwork::from_path(&simplified);
|
||||
loose.regions.clear();
|
||||
append_network(&mut net, loose);
|
||||
@@ -834,7 +836,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if source.regions.is_empty() {
|
||||
let path = source.stroke_path();
|
||||
let simplified = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
|
||||
let simplified = figcraft_geom::simplify_path(&path, tol);
|
||||
net = VectorNetwork::from_path(&simplified);
|
||||
net.regions.clear();
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"style.bind",
|
||||
"Bind variable in style",
|
||||
"{style, field, variable? (id or name; none: unbind)} bind a variable to a field of the style's value: a paint style's `fills/<i>/color` (or `fill`: its first paint) and `fills/<i>/stops/<j>/color`, an effect style's `effects/<i>/<color|radius|spread|offsetX|offsetY|startRadius>` (glass: `lightAngle|lightIntensity|refraction|depth|dispersion|radius|splay`), a grid style's `layoutGrids/<i>/<size|count|gutter|offset>`, a text style's `fontSize|lineHeight|letterSpacing` (numbers, px) and `fontFamily|fontStyle` (strings). Every layer using the style shows the field resolved in its own modes; the style keeps it resolved in the default modes",
|
||||
"{style, field, variable? (id or name; none: unbind)} bind a variable to a field of the style's value: a paint style's `fills/<i>/color` (or `fill`: its first paint) and `fills/<i>/stops/<j>/color`, an effect style's `effects/<i>/<color|radius|spread|offsetX|offsetY|startRadius>` (glass: `lightAngle|lightIntensity|refraction|depth|dispersion|radius|splay`), a grid style's `layoutGrids/<i>/<size|count|gutter|offset>`, a text style's `fontSize|lineHeight|letterSpacing|fontWeight` (numbers; line height and letter spacing in px, as the reference tool applies them; a weight picks the family's face nearest it and the `wght` axis of a variable font) and `fontFamily|fontStyle` (strings; a weight bound as a number replaces a bound style name and the reverse). Every layer using the style shows the field resolved in its own modes; the style keeps it resolved in the default modes",
|
||||
true,
|
||||
bind_style
|
||||
),
|
||||
@@ -275,6 +275,9 @@ fn paragraph_style_json(cmd: &str, v: &Value) -> Result<ParagraphStyle> {
|
||||
"paragraphSpacing" | "paragraph_spacing" => ps.paragraph_spacing = length(k, x)?,
|
||||
"paragraphIndent" | "paragraph_indent" => ps.paragraph_indent = length(k, x)?,
|
||||
"listStyle" | "list" => ps.list = super::props::enum_of(x).ok_or_else(|| bad(cmd, "listStyle: none|bulleted|numbered"))?,
|
||||
"wrapStyle" | "textWrap" | "wrap_style" => {
|
||||
ps.wrap_style = super::props::enum_of(x).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))?;
|
||||
}
|
||||
"features" | "openTypeFeatures" | "fontFeatures" | "textFeatures" => {
|
||||
ps.features = super::props::features_of(cmd, x)?.into_iter().filter_map(|(tag, on)| Some((tag, on?))).collect();
|
||||
}
|
||||
@@ -289,10 +292,11 @@ fn paragraph_style_json(cmd: &str, v: &Value) -> Result<ParagraphStyle> {
|
||||
fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option<ParagraphStyle> {
|
||||
let t = n.kind.text()?;
|
||||
let mut ps = t.paragraph_style();
|
||||
if let Some((a, b)) = range
|
||||
&& let Some(pl) = t.common_para_list(a, b)
|
||||
{
|
||||
ps.list = pl.list;
|
||||
if let Some((a, b)) = range {
|
||||
if let Some(pl) = t.common_para_list(a, b) {
|
||||
ps.list = pl.list;
|
||||
}
|
||||
ps.wrap_style = t.common_wrap_style(a, b).unwrap_or(t.wrap_style);
|
||||
}
|
||||
Some(ps)
|
||||
}
|
||||
@@ -520,6 +524,11 @@ fn bind_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
rebind_paint_alpha(paints, &mut [], &key, true);
|
||||
}
|
||||
match key.as_str() {
|
||||
"fontWeight" => style.bound.remove("fontStyle"),
|
||||
"fontStyle" => style.bound.remove("fontWeight"),
|
||||
_ => None,
|
||||
};
|
||||
style.bound.insert(key, id);
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -98,6 +98,15 @@ fn set_direction(s: &mut Session, p: &Value, d: TextDirection) -> Result<Value>
|
||||
para_range(s, p, |t, a, b| t.set_para_lists(a, b, |pl| pl.direction = d))
|
||||
}
|
||||
|
||||
/// The wrap style of the targeted texts: the edited paragraphs while editing (the paragraph
|
||||
/// level), else the whole layer (the layer level: every paragraph, overrides included).
|
||||
fn set_wrap_style(s: &mut Session, p: &Value, w: figcraft_doc::WrapStyle) -> Result<Value> {
|
||||
match textedit::selected_range(s) {
|
||||
Some((_, a, b)) => para(s, p, |t| t.set_para_wrap_styles(a, b, w)),
|
||||
None => para(s, p, |t| t.set_wrap_style(w)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every targeted char has `pred` (to decide toggle direction).
|
||||
fn all_have(s: &Session, p: &Value, pred: impl Fn(&TextStyle) -> bool) -> bool {
|
||||
let Ok(doc) = s.doc() else { return false };
|
||||
@@ -445,12 +454,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"text.wrapStyle",
|
||||
"Wrap style",
|
||||
"{style: auto|balance|pretty, ids?} where lines break when the text wraps: Auto fits as many words as fit on each line, Balance makes the lines close to the same length, Pretty keeps lines full but leaves no one word alone on the last",
|
||||
"{style: auto|balance|pretty, ids?} where lines break when the text wraps (while editing: the selected paragraphs; else the whole layer): Auto fits as many words as fit on each line, Balance makes the lines close to the same length, Pretty keeps lines full but leaves no one word alone on the last",
|
||||
true,
|
||||
|s, p| {
|
||||
let w: figcraft_doc::WrapStyle =
|
||||
get(p, "style").and_then(super::props::enum_of).ok_or_else(|| bad("text.wrapStyle", "`style`: auto|balance|pretty"))?;
|
||||
para(s, p, |t| t.wrap_style = w)
|
||||
set_wrap_style(s, p, w)
|
||||
}
|
||||
),
|
||||
spec!(
|
||||
|
||||
@@ -184,7 +184,10 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "variable.duplicate";
|
||||
let v = req_string(cmd, p, "variable")?;
|
||||
let doc = s.doc_mut()?;
|
||||
let pos = doc.variables.variables.iter().position(|x| x.id == v || x.name == v).ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
// An exact id first, then a name: an earlier variable named like another's id must not be the
|
||||
// one copied.
|
||||
let vars = &doc.variables.variables;
|
||||
let pos = vars.iter().position(|x| x.id == v).or_else(|| vars.iter().position(|x| x.name == v)).ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
let mut copy = doc.variables.variables.get(pos).cloned().ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
let taken = |n: &str| doc.variables.variables.iter().any(|x| x.collection == copy.collection && x.name == n);
|
||||
let name = (1..1000)
|
||||
|
||||
+108
-21
@@ -100,12 +100,16 @@ fn zoom_to(s: &mut Session, z: f64) -> Result<Value> {
|
||||
Ok(json!({"zoom": v.zoom}))
|
||||
}
|
||||
|
||||
/// How far an arrow key pans the view with nothing selected (screen pixels; Shift: ten times).
|
||||
pub const PAN_STEP_PX: f64 = 20.0;
|
||||
/// How far an arrow key pans the view with nothing selected (screen pixels). Measured in Figma at
|
||||
/// 100% zoom: about 64 px (62-64 in two trials, +/-3 px).
|
||||
pub const PAN_STEP_PX: f64 = 64.0;
|
||||
|
||||
/// Shift multiplies the arrow pan by this much (Figma: about 320 px, five steps).
|
||||
pub const PAN_BIG_STEPS: f64 = 5.0;
|
||||
|
||||
/// `view.pan`: the arrow keys with nothing selected move the view by keyboard steps.
|
||||
fn pan(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let step = if boolean(p, "big").unwrap_or(false) { PAN_STEP_PX * 10.0 } else { PAN_STEP_PX };
|
||||
let step = if boolean(p, "big").unwrap_or(false) { PAN_STEP_PX * PAN_BIG_STEPS } else { PAN_STEP_PX };
|
||||
let dir = |k| num(p, k).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-100.0, 100.0) * step;
|
||||
let (dx, dy) = (dir("dx"), dir("dy"));
|
||||
let v = view(s)?;
|
||||
@@ -235,6 +239,26 @@ pub(crate) fn tool(s: &mut Session, t: ToolId) -> Result<Value> {
|
||||
Ok(json!({"tool": t.id()}))
|
||||
}
|
||||
|
||||
/// Shift+T and choosing the Annotation tool: with a layer selected (or named by `id`/`ids`) the UI
|
||||
/// is asked for its note at once; in the tool, a press on a layer selects it and asks (the engine
|
||||
/// never writes the note). A named target is checked first: one that isn't a layer in the document
|
||||
/// is an error and the tool stays as it was.
|
||||
fn annotation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let named = p.get("id").is_some_and(|v| !v.is_null()) || p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let first = crate::params::targets(s, p).into_iter().find(|i| s.doc().is_ok_and(|d| d.node(*i).is_some_and(|n| !n.is_page())));
|
||||
if named && first.is_none() {
|
||||
return Err(bad("tool.annotation", "`id` must name a layer in this document (not a page)".to_string()));
|
||||
}
|
||||
let r = tool(s, ToolId::Annotation)?;
|
||||
if let Some(id) = first {
|
||||
if named {
|
||||
crate::cmd::edit::select_and_page(s, vec![id])?;
|
||||
}
|
||||
s.request_ui("annotation.new", json!({"id": id}));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The View menu's commands and their parameters.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -259,25 +283,34 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!("view.zoomSelection", "Zoom to selection", "{}", false, |s, _| {
|
||||
let ds = s.ds_mut()?;
|
||||
if let Some(b) = ds.doc.bounds_of(&ds.selection) {
|
||||
ds.view.fit(b, 256.0);
|
||||
ds.view.fit_selection(b, 256.0);
|
||||
}
|
||||
Ok(json!({"zoom": ds.view.zoom}))
|
||||
}),
|
||||
spec!("view.set", "Set view", "{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size)}", false, |s, p| {
|
||||
let v = view(s)?;
|
||||
if let Some(z) = num(p, "zoom") {
|
||||
v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM);
|
||||
spec!(
|
||||
"view.set",
|
||||
"Set view",
|
||||
"{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size), bottomInset? (height of the strip the bottom toolbar covers)}",
|
||||
false,
|
||||
|s, p| {
|
||||
let v = view(s)?;
|
||||
if let Some(z) = num(p, "zoom") {
|
||||
v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM);
|
||||
}
|
||||
v.cx = num_or(p, "cx", v.cx);
|
||||
v.cy = num_or(p, "cy", v.cy);
|
||||
if let Some(w) = num(p, "vw") {
|
||||
v.vw = w.clamp(10.0, 20000.0);
|
||||
}
|
||||
if let Some(h) = num(p, "vh") {
|
||||
v.vh = h.clamp(10.0, 20000.0);
|
||||
}
|
||||
if let Some(i) = num(p, "bottomInset") {
|
||||
v.bottom_inset = i.clamp(0.0, 20000.0);
|
||||
}
|
||||
Ok(serde_json::to_value(&*v).unwrap_or(Value::Null))
|
||||
}
|
||||
v.cx = num_or(p, "cx", v.cx);
|
||||
v.cy = num_or(p, "cy", v.cy);
|
||||
if let Some(w) = num(p, "vw") {
|
||||
v.vw = w.clamp(10.0, 20000.0);
|
||||
}
|
||||
if let Some(h) = num(p, "vh") {
|
||||
v.vh = h.clamp(10.0, 20000.0);
|
||||
}
|
||||
Ok(serde_json::to_value(&*v).unwrap_or(Value::Null))
|
||||
}),
|
||||
),
|
||||
spec!(
|
||||
"view.zoomAt",
|
||||
"Zoom tool",
|
||||
@@ -298,7 +331,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!("view.multiplayerCursors", "Multiplayer cursors", "{on?} others' cursors in a live session", false, |s, p| {
|
||||
toggle(s, p, "view.multiplayerCursors")
|
||||
}),
|
||||
spec!("view.pan", "Pan the view", "{dx, dy (arrow-key steps, e.g. 1 or -1), big? (ten times as far, like Shift)}", false, pan),
|
||||
spec!("view.pan", "Pan the view", "{dx, dy (arrow-key steps, e.g. 1 or -1), big? (five times as far, like Shift)}", false, pan),
|
||||
spec!("view.outlines", "Outlines", "{on?}", false, |s, p| toggle(s, p, "view.outlines")),
|
||||
spec!("view.outlinesSelection", "Outlines for selection", "{on?} outline mode for the selected layers only", false, |s, p| {
|
||||
toggle(s, p, "view.outlinesSelection")
|
||||
@@ -410,6 +443,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
false,
|
||||
|s, p| pref(s, p, |x| &mut x.scroll_wheel_zoom)
|
||||
),
|
||||
spec!(
|
||||
"pref.invertZoom",
|
||||
"Invert zoom direction",
|
||||
"{on?} reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in (a trackpad pinch and panning are unchanged) → {on}",
|
||||
false,
|
||||
|s, p| pref(s, p, |x| &mut x.invert_zoom)
|
||||
),
|
||||
spec!("pref.reduceMotion", "Reduce motion", "{on?}", false, |s, p| pref(s, p, |x| &mut x.reduce_motion)),
|
||||
spec!(
|
||||
"pref.uiScale",
|
||||
@@ -528,7 +568,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"tool.set",
|
||||
"Choose tool",
|
||||
"{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp}",
|
||||
"{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|annotation|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp}",
|
||||
false,
|
||||
|s, p| {
|
||||
let t = req_string("tool.set", p, "tool")?;
|
||||
@@ -536,6 +576,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
if t.on_boards() {
|
||||
crate::board::require(s, &format!("tool.{}", t.id()))?;
|
||||
}
|
||||
if t == ToolId::Annotation {
|
||||
return annotation(s, &json!({}));
|
||||
}
|
||||
tool(s, t)
|
||||
}
|
||||
),
|
||||
@@ -607,7 +650,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"tool.scaleAnchor",
|
||||
"Scale anchor",
|
||||
"{anchor?: tl|t|tr|l|c|r|bl|b|br} (the point of the selection that stays put when the Scale tool scales; omit to read it)",
|
||||
"{anchor?: tl|t|tr|l|c|r|bl|b|br} (the origin of the Scale tool's factor field: the point of the selection that stays put; defaults to c, handle drags pivot on the opposite handle whatever it is; omit to read it)",
|
||||
false,
|
||||
|s, p| {
|
||||
if let Some(a) = string(p, "anchor") {
|
||||
@@ -638,6 +681,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
tool(s, ToolId::TextOnPath)
|
||||
}),
|
||||
spec!("tool.comment", "Comment", "{}", false, |s, _| tool(s, ToolId::Comment)),
|
||||
// Shift+T: with a layer selected (or an `id`) the UI is asked for its note at once; in the
|
||||
// tool, a press on a layer selects it and asks (the engine never writes the note).
|
||||
spec!("tool.annotation", "Annotation", "{id?|ids?}", false, annotation),
|
||||
spec!("tool.shapeBuilder", "Shape builder", "{}", false, |s, _| tool(s, ToolId::ShapeBuilder)),
|
||||
// `apply: false` is for the UI colour picker: the eyedropper only samples (into
|
||||
// `ToolState::picked`) and the picker writes the colour to the paint it edits.
|
||||
@@ -672,4 +718,45 @@ mod start_on_home_tests {
|
||||
let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap();
|
||||
assert!(!old.start_on_home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arrows_pan_64_px_and_320_with_shift_as_measured_in_figma() {
|
||||
let mut s = crate::Session::new();
|
||||
s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap();
|
||||
s.execute("view.pan", &json!({"dx": 1})).unwrap();
|
||||
let v = &s.ds().unwrap().view;
|
||||
assert_eq!((v.cx, v.cy), (364.0, 200.0), "one press pans 64 px");
|
||||
s.execute("view.pan", &json!({"dy": -1, "big": true})).unwrap();
|
||||
let v = &s.ds().unwrap().view;
|
||||
assert_eq!((v.cx, v.cy), (364.0, -120.0), "Shift pans 320 px");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arrow_pan_is_the_same_screen_distance_at_any_zoom_on_both_axes() {
|
||||
// (zoom, dx, dy, big, expected centre change in document px)
|
||||
let cases = [
|
||||
(2.0, 1.0, 0.0, false, 32.0, 0.0),
|
||||
(0.5, 1.0, 0.0, false, 128.0, 0.0),
|
||||
(2.0, 0.0, 1.0, true, 0.0, 160.0),
|
||||
(0.5, 0.0, 1.0, true, 0.0, 640.0),
|
||||
(1.0, -1.0, 0.0, false, -64.0, 0.0),
|
||||
(1.0, 1.0, 0.0, true, 320.0, 0.0),
|
||||
(1.0, -1.0, 0.0, true, -320.0, 0.0),
|
||||
(1.0, 0.0, -1.0, false, 0.0, -64.0),
|
||||
(1.0, 0.0, 1.0, false, 0.0, 64.0),
|
||||
(1.0, 0.0, -1.0, true, 0.0, -320.0),
|
||||
];
|
||||
for (zoom, dx, dy, big, ex, ey) in cases {
|
||||
let mut s = crate::Session::new();
|
||||
s.execute("view.set", &json!({"zoom": zoom, "cx": 300, "cy": 200})).unwrap();
|
||||
s.execute("view.pan", &json!({"dx": dx, "dy": dy, "big": big})).unwrap();
|
||||
let v = &s.ds().unwrap().view;
|
||||
let got = (v.cx - 300.0, v.cy - 200.0);
|
||||
assert!(
|
||||
(got.0 - ex).abs() < 1e-6 && (got.1 - ey).abs() < 1e-6,
|
||||
"zoom {zoom} dx {dx} dy {dy} big {big}: moved {got:?}, expected {:?}",
|
||||
(ex, ey)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::automation::params::id_of;
|
||||
use crate::components::tests::{chars, copy_of, ex, fill, healthy, idv, kids, node};
|
||||
use figcraft_doc::*;
|
||||
|
||||
@@ -1000,3 +1001,245 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() {
|
||||
s.execute("edit.delete", &json!({"ids": [k.inst]})).unwrap();
|
||||
assert!(s.doc().unwrap().node(k.inst).is_none());
|
||||
}
|
||||
|
||||
/// Create multiple components (#2088): each selected layer becomes its own component in place,
|
||||
/// keeping its name and position; all stay selected and one undo reverts them all.
|
||||
#[test]
|
||||
fn create_multiple_components_keeps_names_and_places_and_is_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
let mut frames = Vec::new();
|
||||
for (i, name) in ["Card", "Badge", "Tile"].into_iter().enumerate() {
|
||||
let x = 150.0 * i as f64;
|
||||
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
|
||||
let f = id_of(&v["id"]).unwrap();
|
||||
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
|
||||
frames.push(f);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let out = s.execute("component.createMultiple", &json!({"ids": frames})).unwrap();
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let made: Vec<NodeId> = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect();
|
||||
assert_eq!(made.len(), 3);
|
||||
assert_eq!(s.selection(), made, "all of them stay selected");
|
||||
let doc = s.doc().unwrap();
|
||||
for (i, (c, name)) in made.iter().zip(["Card", "Badge", "Tile"]).enumerate() {
|
||||
let n = doc.node(*c).unwrap();
|
||||
assert!(matches!(n.kind, NodeKind::Component { .. }), "{name} is a component");
|
||||
assert_eq!(n.name, name);
|
||||
let b = doc.world_bounds(*c).unwrap();
|
||||
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "{name} stays in place");
|
||||
}
|
||||
s.undo().unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
|
||||
}
|
||||
|
||||
/// Frames named `names` at x = 150 * i (mirrored when `reverse`), y 20, 100 x 60.
|
||||
fn named_frames(s: &mut Session, names: &[&str], reverse: bool) -> Vec<NodeId> {
|
||||
let n = names.len();
|
||||
names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, name)| {
|
||||
let x = 150.0 * if reverse { n - 1 - i } else { i } as f64;
|
||||
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
|
||||
let f = id_of(&v["id"]).unwrap();
|
||||
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
|
||||
f
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The set's name and its children's names in layer order.
|
||||
fn set_names(s: &Session, set: NodeId) -> (String, Vec<String>) {
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(set).unwrap();
|
||||
(n.name.clone(), n.children.iter().map(|c| doc.node(*c).unwrap().name.clone()).collect())
|
||||
}
|
||||
|
||||
/// The set's variant names ordered by world x.
|
||||
fn names_by_x(s: &Session, set: NodeId) -> Vec<String> {
|
||||
let doc = s.doc().unwrap();
|
||||
let mut v: Vec<(f64, String)> =
|
||||
doc.node(set).unwrap().children.iter().map(|c| (doc.world_bounds(*c).unwrap().x0, doc.node(*c).unwrap().name.clone())).collect();
|
||||
v.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
v.into_iter().map(|(_, n)| n).collect()
|
||||
}
|
||||
|
||||
/// Create component set (#2088, measured in Figma): variants "Property 1=<name>" in left-to-right
|
||||
/// order, the set "Component 1", wrapped in place 20 px around, selected, one undo step.
|
||||
#[test]
|
||||
fn create_set_names_variants_by_layer_name_and_wraps_in_place() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["Primary", "Secondary", "Ghost"], false);
|
||||
let before = undo_len(&s);
|
||||
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let set = id_of(&out["id"]).unwrap();
|
||||
assert_eq!(s.selection(), vec![set], "the set is selected");
|
||||
assert_eq!(set_names(&s, set).0, "Component 1");
|
||||
assert_eq!(names_by_x(&s, set), ["Property 1=Primary", "Property 1=Secondary", "Property 1=Ghost"]);
|
||||
let doc = s.doc().unwrap();
|
||||
for (i, c) in doc.node(set).unwrap().children.iter().enumerate() {
|
||||
assert!(matches!(doc.node(*c).unwrap().kind, NodeKind::Component { .. }));
|
||||
let b = doc.world_bounds(*c).unwrap();
|
||||
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "frames stay put");
|
||||
}
|
||||
let sb = doc.world_bounds(set).unwrap();
|
||||
assert_eq!((sb.x0, sb.y0, sb.x1, sb.y1), (-20.0, 0.0, 420.0, 100.0), "20 px on every side");
|
||||
s.undo().unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(doc.node(set).is_none());
|
||||
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_set_orders_left_to_right_whatever_the_selection_order() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["A", "B", "C"], true);
|
||||
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
|
||||
let set = id_of(&out["id"]).unwrap();
|
||||
assert_eq!(names_by_x(&s, set), ["Property 1=C", "Property 1=B", "Property 1=A"]);
|
||||
let (_, kids) = set_names(&s, set);
|
||||
assert_eq!(kids.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_set_keeps_names_already_in_prop_value_form() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["Size=Small", "Size=Large", "Size=Medium"], false);
|
||||
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
|
||||
let set = id_of(&out["id"]).unwrap();
|
||||
assert_eq!(set_names(&s, set).0, "Component 1");
|
||||
assert_eq!(names_by_x(&s, set), ["Size=Small", "Size=Large", "Size=Medium"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_set_with_one_shared_name_names_the_set_and_makes_default_variants() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["Card", "Card", "Card"], false);
|
||||
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
|
||||
let set = id_of(&out["id"]).unwrap();
|
||||
let (name, kids) = set_names(&s, set);
|
||||
assert_eq!(name, "Card");
|
||||
assert_eq!(kids, ["Property 1=Default", "Property 1=Default", "Property 1=Default"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_set_refuses_instances_and_leaves_the_document_alone() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["A", "B"], false);
|
||||
let c = s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap();
|
||||
let comp = id_of(&c["id"]).unwrap();
|
||||
let inst = s.execute("instance.create", &json!({"component": comp})).unwrap();
|
||||
let inst = id_of(&inst["id"]).unwrap();
|
||||
let before = undo_len(&s);
|
||||
let e = s.execute("component.createSet", &json!({"ids": [inst, frames[1]]})).unwrap_err();
|
||||
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
assert!(matches!(s.doc().unwrap().node(frames[1]).unwrap().kind, NodeKind::Frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_set_refuses_a_target_inside_another_target_and_leaves_the_document_alone() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["Outer", "Inner"], false);
|
||||
s.execute("node.reparent", &json!({"ids": [frames[1]], "parent": frames[0]})).unwrap();
|
||||
let before = undo_len(&s);
|
||||
let e = s.execute("component.createSet", &json!({"ids": [frames[0], frames[1]]})).unwrap_err();
|
||||
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(matches!(doc.node(frames[0]).unwrap().kind, NodeKind::Frame));
|
||||
assert!(matches!(doc.node(frames[1]).unwrap().kind, NodeKind::Frame));
|
||||
}
|
||||
|
||||
/// Every node's id, parent, name and kind, to compare a document before and after a refused command.
|
||||
fn snapshot(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().nodes().map(|n| format!("{:?}|{:?}|{}|{:?}", n.id, n.parent, n.name, n.kind)).collect()
|
||||
}
|
||||
|
||||
/// A refused `component.createSet`: `Disabled`, no undo step, the document and the selection as they were.
|
||||
fn assert_create_set_refused(s: &mut Session, ids: &[NodeId]) {
|
||||
let (before, undo, selection) = (snapshot(s), undo_len(s), s.selection());
|
||||
let e = s.execute("component.createSet", &json!({"ids": ids})).unwrap_err();
|
||||
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
|
||||
assert_eq!(undo_len(s), undo, "no undo step");
|
||||
assert_eq!(snapshot(s), before, "the document is unchanged");
|
||||
assert_eq!(s.selection(), selection, "the selection is unchanged");
|
||||
}
|
||||
|
||||
/// Nothing to wrap is refused before anything is created.
|
||||
#[test]
|
||||
fn create_set_refuses_no_layers_and_leaves_the_document_alone() {
|
||||
let mut s = Session::new();
|
||||
named_frames(&mut s, &["A"], false);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert_create_set_refused(&mut s, &[]);
|
||||
}
|
||||
|
||||
/// One layer is allowed: a set of one variant, as many layers would make.
|
||||
#[test]
|
||||
fn create_set_with_one_layer_makes_a_one_variant_set() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["Solo"], false);
|
||||
let before = undo_len(&s);
|
||||
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let set = id_of(&out["id"]).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(doc.node(set).unwrap().children.len(), 1);
|
||||
assert_eq!(names_by_x(&s, set), ["Property 1=Default"], "a lone layer shares its name with itself");
|
||||
assert!(matches!(doc.node(doc.node(set).unwrap().children[0]).unwrap().kind, NodeKind::Component { .. }));
|
||||
s.undo().unwrap();
|
||||
assert!(matches!(s.doc().unwrap().node(frames[0]).unwrap().kind, NodeKind::Frame));
|
||||
}
|
||||
|
||||
/// Each refusal branch of `create_set`, with `can_create_set` agreeing with it.
|
||||
#[test]
|
||||
fn create_set_refuses_every_ineligible_selection_and_leaves_the_document_alone() {
|
||||
use crate::cmd::component::can_create_set;
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["A", "B", "C"], false);
|
||||
let comp = id_of(&s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap()["id"]).unwrap();
|
||||
let inst = id_of(&s.execute("instance.create", &json!({"component": comp})).unwrap()["id"]).unwrap();
|
||||
let set_frames = named_frames(&mut s, &["V1", "V2"], false);
|
||||
let set = id_of(&s.execute("component.createSet", &json!({"ids": set_frames})).unwrap()["id"]).unwrap();
|
||||
// A layer inside the instance (its copy of the card's content).
|
||||
let in_inst = s.doc().unwrap().node(inst).unwrap().children.first().copied();
|
||||
// A library copy.
|
||||
let remote = {
|
||||
let doc = s.doc_mut().unwrap();
|
||||
let store = doc.ensure_library_store();
|
||||
let remote = doc.alloc_id();
|
||||
doc.insert(Node::new(remote, NodeKind::Frame, "Remote", 10.0, 10.0), store, None).unwrap();
|
||||
remote
|
||||
};
|
||||
let ok = frames[1];
|
||||
assert!(can_create_set(s.doc().unwrap(), &[ok, frames[2]]));
|
||||
assert!(!can_create_set(s.doc().unwrap(), &[]));
|
||||
let mut cases = vec![("instance", inst), ("library copy", remote), ("component", comp), ("component set", set)];
|
||||
if let Some(i) = in_inst {
|
||||
cases.push(("inside an instance", i));
|
||||
}
|
||||
for (what, bad) in cases {
|
||||
assert!(!can_create_set(s.doc().unwrap(), &[ok, bad]), "{what}: not offered");
|
||||
assert_create_set_refused(&mut s, &[ok, bad]);
|
||||
assert_create_set_refused(&mut s, &[bad]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that fails leaves no trace: the checks before the creation loop catch every
|
||||
/// refusal the loop's own commands could hit, and `Session::execute` restores the document, the
|
||||
/// selection and the undo stack on any error, so no half-made components can survive.
|
||||
#[test]
|
||||
fn a_failing_create_set_leaves_no_components_behind() {
|
||||
let mut s = Session::new();
|
||||
let frames = named_frames(&mut s, &["A", "B"], false);
|
||||
let (before, undo, selection) = (snapshot(&s), undo_len(&s), s.selection());
|
||||
let e = s.execute("component.createSet", &json!({"ids": [frames[0], NodeId(u64::MAX)]}));
|
||||
assert!(e.is_err());
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
assert_eq!(snapshot(&s), before);
|
||||
assert_eq!(s.selection(), selection);
|
||||
}
|
||||
@@ -453,7 +453,13 @@ fn library_setup(path: &str) -> (Session, DesignSystem, Session, DesignSystem, V
|
||||
let lib = crate::library::Cache::default().load(path).unwrap();
|
||||
let mut doc = Document::new("Consumer");
|
||||
let m = &lib.manifest;
|
||||
doc.libraries_mut().enabled.push(LibraryLink { id: m.id.clone(), name: m.name.clone(), path: path.to_string(), version: m.version });
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
..Default::default()
|
||||
});
|
||||
let map = crate::library::import(&mut doc, &lib, &ds.assets(), false).unwrap();
|
||||
let mut local = ds.remap(&map);
|
||||
local.theme = doc.libraries.collections.iter().find(|r| r.key == ds.theme).map(|r| r.local.clone()).unwrap();
|
||||
|
||||
@@ -107,6 +107,7 @@ fn each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer() {
|
||||
(ToolId::TextOnPath, NONE, ON_SQUARE_EDGE, Text, "the I-beam over a shape's path: a click puts text on it"),
|
||||
(ToolId::Pen, NONE, EMPTY, Pen(PenCursor::New), "the pen: a new point"),
|
||||
(ToolId::Comment, NONE, EMPTY, Comment, "the comment pin"),
|
||||
(ToolId::Annotation, NONE, ON_SQUARE, Crosshair, "the annotation tool marks the layer it is pressed on"),
|
||||
(ToolId::Eyedropper, NONE, ON_SQUARE, Eyedropper, "the eyedropper"),
|
||||
];
|
||||
for (tool, m, at, want, why) in rows {
|
||||
|
||||
@@ -106,3 +106,67 @@ fn other_content_is_refused_without_changes() {
|
||||
assert_eq!(s.doc().unwrap().nodes().count(), before);
|
||||
assert!(s.clipboard.nodes.is_empty());
|
||||
}
|
||||
|
||||
// The next three pin the paste-placement rules measured in Figma's web app on 2026-11-08 (a
|
||||
// synthetic file): in place when the original is in view, at the view's centre when it is off
|
||||
// screen, and in a selected frame's centre when the frame is elsewhere. The fourth pins
|
||||
// FigCraft's own branch for a selected frame that contains the original (in place inside it),
|
||||
// which was not measured.
|
||||
|
||||
fn copied_rect(s: &mut Session) -> NodeId {
|
||||
let r = id(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap());
|
||||
s.execute("edit.copy", &json!({"ids": [r]})).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn pasted(s: &mut Session) -> NodeId {
|
||||
let r = s.execute("edit.paste", &json!({})).unwrap();
|
||||
params::id_of(&r["ids"][0]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_with_the_original_in_view_lands_in_place_above_it() {
|
||||
let mut s = Session::new();
|
||||
let page = s.page().unwrap();
|
||||
let r = copied_rect(&mut s);
|
||||
s.execute("view.set", &json!({"zoom": 1, "cx": 125, "cy": 125})).unwrap();
|
||||
let c = pasted(&mut s);
|
||||
let b = s.doc().unwrap().world_bounds(c).unwrap();
|
||||
assert_eq!((b.x0, b.y0), (100.0, 100.0));
|
||||
assert_eq!(s.selection(), [c]);
|
||||
assert_eq!(s.doc().unwrap().node(page).unwrap().children, [r, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_with_the_original_off_screen_lands_at_the_view_centre() {
|
||||
let mut s = Session::new();
|
||||
copied_rect(&mut s);
|
||||
s.execute("view.set", &json!({"zoom": 1, "cx": 5000, "cy": 3000})).unwrap();
|
||||
let c = pasted(&mut s);
|
||||
let b = s.doc().unwrap().world_bounds(c).unwrap();
|
||||
assert_eq!((b.center().x, b.center().y), (5000.0, 3000.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_into_a_selected_far_frame_lands_at_its_centre() {
|
||||
let mut s = Session::new();
|
||||
copied_rect(&mut s);
|
||||
let f = id(&s.execute("frame.create", &json!({"x": 2000, "y": 1000, "width": 300, "height": 300})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [f]})).unwrap();
|
||||
let c = pasted(&mut s);
|
||||
assert_eq!(s.doc().unwrap().node(c).unwrap().parent, Some(f));
|
||||
let b = s.doc().unwrap().world_bounds(c).unwrap();
|
||||
assert_eq!((b.center().x, b.center().y), (2150.0, 1150.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_into_a_selected_frame_holding_the_original_keeps_its_place() {
|
||||
let mut s = Session::new();
|
||||
copied_rect(&mut s);
|
||||
let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 500, "height": 500})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [f]})).unwrap();
|
||||
let c = pasted(&mut s);
|
||||
assert_eq!(s.doc().unwrap().node(c).unwrap().parent, Some(f));
|
||||
let b = s.doc().unwrap().world_bounds(c).unwrap();
|
||||
assert_eq!((b.x0, b.y0), (100.0, 100.0));
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
//! their iOS and Android code syntax in SwiftUI and Compose. The output is a starting point, not a
|
||||
//! pixel-exact translation.
|
||||
|
||||
use figcraft_color::{Color, PaintKind};
|
||||
use figcraft_color::{Color, Gradient, GradientKind, Paint, PaintKind};
|
||||
use figcraft_doc::{
|
||||
ContentAlign, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Shadow, Sizing,
|
||||
TextAlignH, TextCase, TextDecoration, Variable,
|
||||
@@ -345,6 +345,35 @@ fn first_fill(n: &Node) -> Option<Color> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A layer's visible fills with their place in the document. Document order is bottom first, as
|
||||
/// the renderer paints them; the index tells a target which paint is the bottom one.
|
||||
fn visible_fills(n: &Node) -> impl DoubleEndedIterator<Item = (usize, &Paint)> {
|
||||
n.fills.iter().enumerate().filter(|(_, p)| p.visible)
|
||||
}
|
||||
|
||||
/// A gradient's sorted stops as (position, colour), the paint's opacity folded into each colour.
|
||||
/// A lone stop is written twice (at 1 as well), since Android and Flutter need two colours.
|
||||
fn gradient_stops(g: &Gradient, opacity: f32) -> Vec<(f64, Color)> {
|
||||
let mut stops: Vec<(f64, Color)> = g.sorted_stops().iter().map(|s| (f64::from(s.position), s.color.with_alpha(s.color.a * opacity))).collect();
|
||||
if let [(_, only)] = stops[..] {
|
||||
stops.push((1.0, only));
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
/// A gradient's main axis in pixels on a `w` x `h` box.
|
||||
fn gradient_axis(g: &Gradient, w: f64, h: f64) -> (f64, f64) {
|
||||
((g.to.0 - g.from.0) * w, (g.to.1 - g.from.1) * h)
|
||||
}
|
||||
|
||||
/// The kind a native target writes: a diamond reads as a radial gradient.
|
||||
fn native_gradient_kind(g: &Gradient) -> GradientKind {
|
||||
match g.kind {
|
||||
GradientKind::Diamond => GradientKind::Radial,
|
||||
k => k,
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke_color(n: &Node) -> Option<Color> {
|
||||
if !n.has_visible_stroke() {
|
||||
return None;
|
||||
@@ -506,6 +535,44 @@ mod tests {
|
||||
assert!(!css.contains("#000000 0%"), "{css}");
|
||||
}
|
||||
|
||||
/// The measured frame: white at the bottom, a 20% gradient above it, 50% black on top.
|
||||
fn layered_frame(s: &mut Session) -> figcraft_doc::NodeId {
|
||||
let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 120})).unwrap()["id"]).unwrap();
|
||||
let mut g = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK));
|
||||
g.opacity = 0.2;
|
||||
let mut top = figcraft_color::Paint::solid(Color::BLACK);
|
||||
top.opacity = 0.5;
|
||||
s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![figcraft_color::Paint::solid(Color::WHITE), g, top];
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_fills_are_one_layered_background_top_first() {
|
||||
let mut s = Session::new();
|
||||
let f = layered_frame(&mut s);
|
||||
let css = code_for(s.doc().unwrap(), f, CodeLang::Css);
|
||||
let bg: Vec<&str> = css.lines().filter(|l| l.starts_with("background:")).collect();
|
||||
assert_eq!(bg.len(), 1, "{css}");
|
||||
let v = bg[0];
|
||||
assert!(
|
||||
v.starts_with(
|
||||
"background: linear-gradient(0deg, rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.50)), linear-gradient(180deg, rgba(0, 0, 0, 0.20) 0%, "
|
||||
),
|
||||
"{v}"
|
||||
);
|
||||
assert!(v.ends_with(", #FFFFFF;"), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_solid_fill_stays_a_plain_colour() {
|
||||
let mut s = Session::new();
|
||||
let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap()["id"]).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![figcraft_color::Paint::solid(Color::WHITE)];
|
||||
let css = code_for(s.doc().unwrap(), f, CodeLang::Css);
|
||||
assert!(css.contains("background: #FFFFFF;\n"), "{css}");
|
||||
assert!(!css.contains("gradient"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftui_and_compose_for_an_auto_layout_card() {
|
||||
let mut s = Session::new();
|
||||
@@ -675,6 +742,27 @@ mod tests {
|
||||
assert!(!dart.lines().any(|l| l.trim_start().starts_with("void main()")), "a name never leaves its comment: {dart}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flutter_writes_no_spacing_for_the_space_distributions() {
|
||||
// The space distributions spread the children themselves; a `spacing:` beside them would
|
||||
// add the gap on top.
|
||||
let mut s = Session::new();
|
||||
let row = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 40})).unwrap()["id"]).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": row})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 50, "height": 20, "parent": row})).unwrap();
|
||||
s.execute("layout.add", &json!({"ids": [row], "direction": "horizontal"})).unwrap();
|
||||
for (align, flutter) in [("spaceBetween", "spaceBetween"), ("spaceAround", "spaceAround"), ("spaceEvenly", "spaceEvenly")] {
|
||||
s.execute("node.set", &json!({"id": row, "props": {"gap": 10, "mainAlign": align}})).unwrap();
|
||||
let dart = code_for(s.doc().unwrap(), row, CodeLang::Flutter);
|
||||
assert!(dart.contains(&format!("mainAxisAlignment: MainAxisAlignment.{flutter},")), "{dart}");
|
||||
assert!(!dart.contains("spacing:"), "{align} spreads the children itself: {dart}");
|
||||
}
|
||||
// A packed line keeps its gap.
|
||||
s.execute("node.set", &json!({"id": row, "props": {"gap": 10, "mainAlign": "center"}})).unwrap();
|
||||
let dart = code_for(s.doc().unwrap(), row, CodeLang::Flutter);
|
||||
assert!(dart.contains("spacing: 10,"), "{dart}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flutter_expands_and_stretches_fill_children() {
|
||||
let mut s = Session::new();
|
||||
@@ -765,4 +853,188 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// White, a 20% default linear gradient of black, then 50% black: bottom to top.
|
||||
fn three_fills() -> Vec<figcraft_color::Paint> {
|
||||
let mut gradient = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK));
|
||||
gradient.opacity = 0.2;
|
||||
let mut top = figcraft_color::Paint::solid(Color::BLACK);
|
||||
top.opacity = 0.5;
|
||||
vec![figcraft_color::Paint::solid(Color::WHITE), gradient, top]
|
||||
}
|
||||
|
||||
/// A 200 x `h` layer of `kind` (`frame`, `rectangle` or `ellipse`, a rectangle with corner
|
||||
/// radius 8) with exactly `fills`.
|
||||
fn fill_layer(s: &mut Session, kind: &str, h: f64, fills: Vec<figcraft_color::Paint>) -> NodeId {
|
||||
let id = match kind {
|
||||
"frame" => id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(),
|
||||
_ => id_of(&s.execute(&format!("shape.{kind}"), &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(),
|
||||
};
|
||||
if kind == "rectangle" {
|
||||
s.execute("node.set", &json!({"id": id, "props": {"cornerRadius": 8}})).unwrap();
|
||||
}
|
||||
s.doc_mut().unwrap().get_mut(id).unwrap().fills = fills;
|
||||
id
|
||||
}
|
||||
|
||||
fn one_gradient(s: &mut Session, g: figcraft_color::Gradient) -> NodeId {
|
||||
fill_layer(s, "frame", 120.0, vec![figcraft_color::Paint::gradient(g)])
|
||||
}
|
||||
|
||||
const SWIFT_WHITE: &str = "Color(red: 1, green: 1, blue: 1, opacity: 1)";
|
||||
const SWIFT_HALF: &str = "Color(red: 0, green: 0, blue: 0, opacity: 0.5)";
|
||||
const SWIFT_GRADIENT: &str = "LinearGradient(stops: [Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0.2), location: 0), Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0), location: 1)], startPoint: UnitPoint(x: 0.5, y: 0), endPoint: UnitPoint(x: 0.5, y: 1))";
|
||||
|
||||
#[test]
|
||||
fn swiftui_writes_every_fill_top_first() {
|
||||
let mut s = Session::new();
|
||||
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), f, CodeLang::SwiftUi);
|
||||
let backgrounds: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect();
|
||||
let want = [format!(".background({SWIFT_HALF})"), format!(".background({SWIFT_GRADIENT})"), format!(".background({SWIFT_WHITE})")];
|
||||
assert_eq!(backgrounds, want.iter().map(String::as_str).collect::<Vec<_>>(), "{code}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftui_shapes_fill_with_the_bottom_paint_and_overlay_the_rest() {
|
||||
let mut s = Session::new();
|
||||
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), r, CodeLang::SwiftUi);
|
||||
let mods: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with('.')).collect();
|
||||
let want = [
|
||||
format!(".fill({SWIFT_WHITE})"),
|
||||
format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_GRADIENT}))"),
|
||||
format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_HALF}))"),
|
||||
".frame(width: 200, height: 120)".to_string(),
|
||||
];
|
||||
assert_eq!(mods, want.iter().map(String::as_str).collect::<Vec<_>>(), "{code}");
|
||||
assert!(!code.contains(".background("), "{code}");
|
||||
let mut half = figcraft_color::Paint::solid(Color::BLACK);
|
||||
half.opacity = 0.5;
|
||||
let e = fill_layer(&mut s, "ellipse", 120.0, vec![figcraft_color::Paint::solid(Color::WHITE), half]);
|
||||
let code = code_for(s.doc().unwrap(), e, CodeLang::SwiftUi);
|
||||
assert!(code.contains(&format!(".overlay(Ellipse().fill({SWIFT_HALF}))")), "{code}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_writes_every_fill_bottom_first() {
|
||||
let mut s = Session::new();
|
||||
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), f, CodeLang::Compose);
|
||||
let want = "Modifier.size(200.dp, 120.dp).background(Color(0xFFFFFFFF), RectangleShape).background(Brush.linearGradient(0f to Color(0x33000000), 1f to Color(0x00000000), start = Offset(0f, 0f), end = Offset(0f, Float.POSITIVE_INFINITY)), RectangleShape).background(Color(0x80000000), RectangleShape)";
|
||||
assert!(code.contains(want), "{code}");
|
||||
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), r, CodeLang::Compose);
|
||||
assert_eq!(code.matches(".background(").count(), 3, "{code}");
|
||||
assert_eq!(code.matches(", RoundedCornerShape(8.dp))").count(), 3, "{code}");
|
||||
assert!(code.contains(".background(Color(0xFFFFFFFF), RoundedCornerShape(8.dp)).background(Brush."), "{code}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flutter_nests_a_box_per_fill_bottom_outermost() {
|
||||
let mut s = Session::new();
|
||||
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter);
|
||||
let want = "DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Color(0xFFFFFFFF),
|
||||
),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(begin: Alignment(0, -1), end: Alignment(0, 1), colors: [Color(0x33000000), Color(0x00000000)], stops: [0, 1]),
|
||||
),
|
||||
child: Container(
|
||||
width: 200,
|
||||
height: 120,
|
||||
decoration: BoxDecoration(
|
||||
color: Color(0x80000000),
|
||||
),
|
||||
)
|
||||
)
|
||||
)";
|
||||
assert_eq!(code, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flutter_keeps_the_shadow_under_every_fill() {
|
||||
let mut s = Session::new();
|
||||
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
|
||||
s.execute("effect.add", &json!({"ids": [f], "type": "dropShadow"})).unwrap();
|
||||
let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter);
|
||||
assert_eq!(code.matches("boxShadow:").count(), 1, "{code}");
|
||||
let (shadow, gradient) = (code.find("boxShadow:").unwrap(), code.find("gradient:").unwrap());
|
||||
assert!(shadow < gradient, "the shadow is on the outermost box: {code}");
|
||||
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
|
||||
let code = code_for(s.doc().unwrap(), r, CodeLang::Flutter);
|
||||
assert_eq!(code.matches("borderRadius: BorderRadius.circular(8)").count(), 3, "{code}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_gradients_are_written_as_gradients() {
|
||||
use figcraft_color::{Gradient, GradientKind};
|
||||
let mut s = Session::new();
|
||||
let radial = one_gradient(&mut s, Gradient::default_for(GradientKind::Radial, Color::BLACK));
|
||||
let doc = s.doc().unwrap();
|
||||
let sw = code_for(doc, radial, CodeLang::SwiftUi);
|
||||
assert!(sw.contains("RadialGradient(stops: ["), "{sw}");
|
||||
assert!(sw.contains("center: UnitPoint(x: 0.5, y: 0.5), startRadius: 0, endRadius: 60)"), "{sw}");
|
||||
let kt = code_for(doc, radial, CodeLang::Compose);
|
||||
assert!(kt.contains(".background(Brush.radialGradient(0f to Color(0xFF000000), 1f to Color(0x00000000)), RectangleShape)"), "{kt}");
|
||||
let dart = code_for(doc, radial, CodeLang::Flutter);
|
||||
assert!(
|
||||
dart.contains(
|
||||
"gradient: RadialGradient(center: Alignment(0, 0), radius: 0.5, colors: [Color(0xFF000000), Color(0x00000000)], stops: [0, 1])"
|
||||
),
|
||||
"{dart}"
|
||||
);
|
||||
let angular = one_gradient(&mut s, Gradient::default_for(GradientKind::Angular, Color::BLACK));
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(code_for(doc, angular, CodeLang::SwiftUi).contains("angle: .degrees(90))"));
|
||||
assert!(code_for(doc, angular, CodeLang::Compose).contains("Brush.sweepGradient("));
|
||||
assert!(code_for(doc, angular, CodeLang::Flutter).contains("transform: GradientRotation(1.57))"));
|
||||
// Compose snaps a linear gradient to one of eight directions.
|
||||
let mut directed = |from: (f64, f64), to: (f64, f64)| {
|
||||
let mut g = Gradient::default_for(GradientKind::Linear, Color::BLACK);
|
||||
(g.from, g.to) = (from, to);
|
||||
let id = one_gradient(&mut s, g);
|
||||
code_for(s.doc().unwrap(), id, CodeLang::Compose)
|
||||
};
|
||||
let up = directed((0.5, 1.0), (0.5, 0.0));
|
||||
assert!(up.contains("start = Offset(0f, Float.POSITIVE_INFINITY), end = Offset(0f, 0f)"), "{up}");
|
||||
let right = directed((0.0, 0.5), (1.0, 0.5));
|
||||
assert!(right.contains("end = Offset(Float.POSITIVE_INFINITY, 0f)"), "{right}");
|
||||
let corner = directed((0.0, 0.0), (1.0, 1.0));
|
||||
assert!(corner.contains("end = Offset(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)"), "{corner}");
|
||||
// A single stop is written twice, since a brush needs two colours.
|
||||
let mut one = Gradient::default_for(GradientKind::Linear, Color::BLACK);
|
||||
one.stops.truncate(1);
|
||||
let id = one_gradient(&mut s, one);
|
||||
let kt = code_for(s.doc().unwrap(), id, CodeLang::Compose);
|
||||
assert_eq!(kt.matches(" to Color(").count(), 2, "{kt}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_solid_fill_is_unchanged_in_native_code() {
|
||||
let mut hidden = figcraft_color::Paint::solid(Color::BLACK);
|
||||
hidden.visible = false;
|
||||
let mut s = Session::new();
|
||||
for fills in [vec![figcraft_color::Paint::solid(Color::WHITE)], vec![figcraft_color::Paint::solid(Color::WHITE), hidden]] {
|
||||
let f = fill_layer(&mut s, "frame", 100.0, fills);
|
||||
let doc = s.doc().unwrap();
|
||||
let sw = code_for(doc, f, CodeLang::SwiftUi);
|
||||
let backgrounds: Vec<&str> = sw.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect();
|
||||
assert_eq!(backgrounds, [format!(".background({SWIFT_WHITE})")], "{sw}");
|
||||
assert!(!sw.contains("Gradient"), "{sw}");
|
||||
let kt = code_for(doc, f, CodeLang::Compose);
|
||||
assert!(kt.contains("Modifier.size(200.dp, 100.dp).background(Color(0xFFFFFFFF), RectangleShape))"), "{kt}");
|
||||
assert!(!kt.contains("Brush"), "{kt}");
|
||||
let dart = code_for(doc, f, CodeLang::Flutter);
|
||||
assert!(
|
||||
dart.starts_with("Container(\n width: 200,\n height: 100,\n decoration: BoxDecoration(\n color: Color(0xFFFFFFFF),\n ),\n)"),
|
||||
"{dart}"
|
||||
);
|
||||
assert!(!dart.contains("DecoratedBox"), "{dart}");
|
||||
assert!(code_for(doc, f, CodeLang::ArkUi).contains(".backgroundColor('#FFFFFF')"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::swift::one_line;
|
||||
use super::{
|
||||
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
|
||||
CodeLang, Color, Ctx, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill, gradient_axis,
|
||||
gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
|
||||
};
|
||||
use figcraft_doc::Document;
|
||||
|
||||
@@ -22,14 +23,66 @@ fn bound_dp(doc: &Document, n: &Node, fields: &[&str], value: f64) -> String {
|
||||
bound(doc, n, fields, format!("{}.dp", num(value)))
|
||||
}
|
||||
|
||||
/// One end of a linear brush's axis along one direction: `sign` is 0 for none, 1 for with the
|
||||
/// axis and -1 against it. `Float.POSITIVE_INFINITY` stands for the far edge, which a modifier
|
||||
/// can't know in pixels.
|
||||
fn compose_edge(sign: i8) -> (&'static str, &'static str) {
|
||||
match sign {
|
||||
0 => ("0f", "0f"),
|
||||
s if s > 0 => ("0f", "Float.POSITIVE_INFINITY"),
|
||||
_ => ("Float.POSITIVE_INFINITY", "0f"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A direction's sign: its component counts as none when it is at most tan 22.5 degrees of the other.
|
||||
fn compose_sign(v: f64, other: f64) -> i8 {
|
||||
if v.abs() <= 0.4142 * other.abs() {
|
||||
0
|
||||
} else if v > 0.0 {
|
||||
1
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient fill as a Compose `Brush` for a `w` x `h` layer. A linear gradient snaps to the
|
||||
/// nearest of eight directions; radial and angular ones sit at the box's centre.
|
||||
fn compose_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
|
||||
let stops = gradient_stops(g, opacity).into_iter().map(|(at, c)| format!("{}f to {}", num(at), kotlin_color(c))).collect::<Vec<_>>().join(", ");
|
||||
match native_gradient_kind(g) {
|
||||
GradientKind::Linear => {
|
||||
let (dx, dy) = gradient_axis(g, w, h);
|
||||
let (sx, sy) = if dx == 0.0 && dy == 0.0 { (0, 1) } else { (compose_sign(dx, dy), compose_sign(dy, dx)) };
|
||||
let ((x0, x1), (y0, y1)) = (compose_edge(sx), compose_edge(sy));
|
||||
format!("Brush.linearGradient({stops}, start = Offset({x0}, {y0}), end = Offset({x1}, {y1}))")
|
||||
}
|
||||
GradientKind::Angular => format!("Brush.sweepGradient({stops})"),
|
||||
_ => format!("Brush.radialGradient({stops})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One paint (the one at document index `i`) as the first argument of `background`; `None` for an
|
||||
/// image or pattern. Only a solid at index 0 takes the `fill` variable's name.
|
||||
fn compose_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { .. } => {
|
||||
let c = kotlin_color(p.solid_color()?);
|
||||
Some(if i == 0 { bound(doc, n, &["fill"], c) } else { c })
|
||||
}
|
||||
PaintKind::Gradient(g) => Some(compose_gradient(g, n.width, n.height, p.opacity)),
|
||||
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Modifier chain for a layer (size, shadow, background, border, alpha, padding).
|
||||
fn modifier(doc: &Document, n: &Node, shape: &str, padding: bool) -> String {
|
||||
let mut m = format!("Modifier.size({}, {})", bound_dp(doc, n, &["width"], n.width), bound_dp(doc, n, &["height"], n.height));
|
||||
if let Some(s) = drop_shadow(n) {
|
||||
m.push_str(&format!(".shadow({}.dp, {shape})", num(s.radius / 2.0)));
|
||||
}
|
||||
if let Some(c) = first_fill(n) {
|
||||
m.push_str(&format!(".background({}, {shape})", bound(doc, n, &["fill"], kotlin_color(c))));
|
||||
// Each background draws and lets the rest of the chain draw over it: bottom fill first.
|
||||
for b in visible_fills(n).filter_map(|(i, p)| compose_paint(doc, n, i, p)) {
|
||||
m.push_str(&format!(".background({b}, {shape})"));
|
||||
}
|
||||
if let Some(c) = stroke_color(n) {
|
||||
m.push_str(&format!(
|
||||
|
||||
@@ -160,17 +160,48 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
put("transform", format!("rotate({}deg)", num(-rot)));
|
||||
put("transform-origin", "top left".into());
|
||||
}
|
||||
for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { color } => {
|
||||
let key = if matches!(n.kind, NodeKind::Text(_)) { "color" } else { "background" };
|
||||
let c = color.with_alpha(color.a * p.opacity).to_css();
|
||||
// A variable binds the first paint's colour.
|
||||
put(key, if i == 0 { tok(doc, n, &["fill"], c, t) } else { c });
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
// Text: a solid is the ink (`color`), one per fill, so the last (top) one wins.
|
||||
for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { color } => {
|
||||
let c = color.with_alpha(color.a * p.opacity).to_css();
|
||||
// A variable binds the first paint's colour.
|
||||
put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c });
|
||||
}
|
||||
PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)),
|
||||
PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()),
|
||||
PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()),
|
||||
}
|
||||
PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)),
|
||||
PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()),
|
||||
PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()),
|
||||
}
|
||||
} else {
|
||||
// One `background` with every visible fill as a layer, top first (a document's fills run
|
||||
// bottom to top, as the renderer paints them). CSS allows a plain colour only as the last
|
||||
// layer, so a solid above another fill becomes a one-colour gradient.
|
||||
let visible: Vec<(usize, &figcraft_color::Paint)> = n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect();
|
||||
let layers: Vec<String> = visible
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.map(|(pos, (i, p))| match &p.kind {
|
||||
PaintKind::Solid { color } => {
|
||||
let c = color.with_alpha(color.a * p.opacity).to_css();
|
||||
if pos > 0 {
|
||||
format!("linear-gradient(0deg, {c}, {c})")
|
||||
} else if *i == 0 {
|
||||
// A variable binds the first paint's colour.
|
||||
tok(doc, n, &["fill"], c, t)
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}
|
||||
PaintKind::Gradient(g) => css_gradient(g, n.width, n.height, p.opacity),
|
||||
PaintKind::Image(_) => "url(image.png) center / cover".into(),
|
||||
PaintKind::Pattern(_) => "url(pattern.png) repeat".into(),
|
||||
})
|
||||
.collect();
|
||||
if !layers.is_empty() {
|
||||
put("background", layers.join(", "));
|
||||
}
|
||||
}
|
||||
for (key, value) in css_borders(doc, n, t) {
|
||||
@@ -302,10 +333,12 @@ fn text_decls(doc: &Document, n: &Node, tx: &figcraft_doc::TextData, t: &mut Tok
|
||||
TextAlignH::Right => put("text-align", "right".into()),
|
||||
TextAlignH::Justified => put("text-align", "justify".into()),
|
||||
}
|
||||
match tx.wrap_style {
|
||||
figcraft_doc::WrapStyle::Auto => {}
|
||||
figcraft_doc::WrapStyle::Balance => put("text-wrap", "balance".into()),
|
||||
figcraft_doc::WrapStyle::Pretty => put("text-wrap", "pretty".into()),
|
||||
// CSS has one `text-wrap` per element: written when every paragraph has the same one.
|
||||
let wrap = (0..tx.paragraph_count()).map(|p| tx.para_wrap_style(p)).collect::<Vec<_>>();
|
||||
match wrap.first().copied().filter(|w| wrap.iter().all(|x| x == w)) {
|
||||
Some(figcraft_doc::WrapStyle::Balance) => put("text-wrap", "balance".into()),
|
||||
Some(figcraft_doc::WrapStyle::Pretty) => put("text-wrap", "pretty".into()),
|
||||
_ => {}
|
||||
}
|
||||
// A base direction forced on every paragraph (CSS has one per element).
|
||||
let dir = tx.paragraphs.first().map(|p| p.direction).filter(|d| tx.paragraphs.iter().all(|p| p.direction == *d));
|
||||
|
||||
@@ -2,8 +2,9 @@ use figcraft_doc::AutoLayout;
|
||||
|
||||
use super::swift::one_line;
|
||||
use super::{
|
||||
CodeLang, CrossAlign, Ctx, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Param, Sizing, TextAlignH, TextDecoration,
|
||||
drop_shadow, first_fill, kotlin_color, literal, num, radius, stroke_color,
|
||||
CodeLang, CrossAlign, Ctx, GradientKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Paint, PaintKind, Param,
|
||||
Sizing, TextAlignH, TextDecoration, drop_shadow, first_fill, gradient_axis, gradient_stops, kotlin_color, literal, native_gradient_kind, num,
|
||||
radius, stroke_color, visible_fills,
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ Flutter (Dart)
|
||||
@@ -74,22 +75,72 @@ fn flutter_padding(n: &Node) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A gradient's colours and stops, the tail of every Flutter gradient constructor.
|
||||
fn flutter_colors(g: &figcraft_color::Gradient, opacity: f32) -> String {
|
||||
let stops = gradient_stops(g, opacity);
|
||||
let colors = stops.iter().map(|(_, c)| kotlin_color(*c)).collect::<Vec<_>>().join(", ");
|
||||
let at = stops.iter().map(|(at, _)| num(*at)).collect::<Vec<_>>().join(", ");
|
||||
format!("colors: [{colors}], stops: [{at}]")
|
||||
}
|
||||
|
||||
/// A point of the unit box as Flutter's `Alignment`, which runs from -1 to 1.
|
||||
fn flutter_alignment(p: (f64, f64)) -> String {
|
||||
format!("Alignment({}, {})", num(2.0 * p.0 - 1.0), num(2.0 * p.1 - 1.0))
|
||||
}
|
||||
|
||||
/// A gradient fill on a layer of `w` x `h` as a Flutter gradient.
|
||||
fn flutter_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
|
||||
let (dx, dy) = gradient_axis(g, w, h);
|
||||
let (tail, from) = (flutter_colors(g, opacity), flutter_alignment(g.from));
|
||||
match native_gradient_kind(g) {
|
||||
GradientKind::Linear => format!("LinearGradient(begin: {from}, end: {}, {tail})", flutter_alignment(g.to)),
|
||||
GradientKind::Angular => format!("SweepGradient(center: {from}, {tail}, transform: GradientRotation({}))", num(dy.atan2(dx))),
|
||||
_ => {
|
||||
// Flutter's radius is a fraction of the box's shorter side.
|
||||
let (reach, side) = (dx.hypot(dy), w.min(h));
|
||||
let radius = if reach > 0.0 && side > 0.0 { reach / side } else { 0.5 };
|
||||
format!("RadialGradient(center: {from}, radius: {}, {tail})", num(radius))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One paint as a `BoxDecoration` part (`color: ...` or `gradient: ...`); `None` for an image or
|
||||
/// pattern, which no native target writes yet.
|
||||
fn flutter_paint(n: &Node, p: &Paint) -> Option<String> {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { .. } => Some(format!("color: {}", kotlin_color(p.solid_color()?))),
|
||||
PaintKind::Gradient(g) => Some(format!("gradient: {}", flutter_gradient(g, n.width, n.height, p.opacity))),
|
||||
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a layer is written as a `Container`: the layers with a box to paint.
|
||||
fn paints_a_box(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Rectangle | NodeKind::Group) || n.kind.is_frame_like()
|
||||
}
|
||||
|
||||
/// A layer's fills as `BoxDecoration` parts, bottom first.
|
||||
fn flutter_fill_parts(n: &Node) -> Vec<String> {
|
||||
visible_fills(n).filter_map(|(_, p)| flutter_paint(n, p)).collect()
|
||||
}
|
||||
|
||||
/// A layer's fill, shape, corner radius, stroke and shadow as a `BoxDecoration`; `None` when it has
|
||||
/// none of them. `pad` is the indentation of the constructor itself.
|
||||
fn box_decoration(n: &Node, pad: &str) -> Option<String> {
|
||||
/// none of them. `pad` is the indentation of the constructor itself; `fill` is the one fill part
|
||||
/// this decoration paints, and `stroke` and `shadow` say whether it carries those.
|
||||
fn box_decoration(n: &Node, pad: &str, fill: Option<&str>, stroke: bool, shadow: bool) -> Option<String> {
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if let Some(c) = first_fill(n) {
|
||||
parts.push(format!("color: {}", kotlin_color(c)));
|
||||
if let Some(f) = fill {
|
||||
parts.push(f.to_string());
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Ellipse { .. }) {
|
||||
parts.push("shape: BoxShape.circle".into());
|
||||
} else if radius(n) > 0.0 {
|
||||
parts.push(format!("borderRadius: BorderRadius.circular({})", num(radius(n))));
|
||||
}
|
||||
if let Some(c) = stroke_color(n) {
|
||||
if let Some(c) = stroke_color(n).filter(|_| stroke) {
|
||||
parts.push(format!("border: Border.all(color: {}, width: {})", kotlin_color(c), num(n.stroke.weight)));
|
||||
}
|
||||
if let Some(s) = drop_shadow(n) {
|
||||
if let Some(s) = drop_shadow(n).filter(|_| shadow) {
|
||||
parts.push(format!(
|
||||
"boxShadow: [BoxShadow(color: {}, blurRadius: {}, offset: Offset({}, {}))]",
|
||||
kotlin_color(s.color),
|
||||
@@ -105,6 +156,42 @@ fn box_decoration(n: &Node, pad: &str) -> Option<String> {
|
||||
Some(format!("BoxDecoration(\n{}{pad})", parts.iter().map(|p| format!("{inner}{p},\n")).collect::<String>()))
|
||||
}
|
||||
|
||||
/// What a `Container` paints itself: its own fill (the top one), and whether it carries the shadow
|
||||
/// (only when no `DecoratedBox` does).
|
||||
struct Painted {
|
||||
fill: Option<String>,
|
||||
shadow: bool,
|
||||
}
|
||||
|
||||
/// Opens a `DecoratedBox` for each fill under the top one, the bottom fill outermost, and returns
|
||||
/// what is left for the `Container`. The outermost box carries the drop shadow: a decoration paints
|
||||
/// its shadow first, so on the `Container` it would lie over the lower fills.
|
||||
fn flutter_fill_boxes(n: &Node, depth: &mut usize, close: &mut Vec<String>, out: &mut String) -> Painted {
|
||||
let mut parts = flutter_fill_parts(n);
|
||||
let top = parts.pop();
|
||||
let shadow = parts.is_empty();
|
||||
for (at, part) in parts.iter().enumerate() {
|
||||
let (pad, inner) = (flutter_indent(*depth), flutter_indent(*depth + 1));
|
||||
if close.is_empty() {
|
||||
out.push_str(&pad);
|
||||
}
|
||||
let deco = box_decoration(n, &inner, Some(part), false, at == 0).unwrap_or_default();
|
||||
out.push_str(&format!("DecoratedBox(\n{inner}decoration: {deco},\n{inner}child: "));
|
||||
close.push(format!("\n{pad})"));
|
||||
*depth += 1;
|
||||
}
|
||||
Painted { fill: top, shadow }
|
||||
}
|
||||
|
||||
/// The call an instance below the root is (an instance swap parameter is a widget); `None` for
|
||||
/// every other layer.
|
||||
fn flutter_call(ctx: &Ctx, n: &Node, depth: usize) -> Option<String> {
|
||||
match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
|
||||
Some(p) => Some(p.ident.clone()),
|
||||
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
|
||||
}
|
||||
}
|
||||
|
||||
/// Flutter for a layer and its subtree at `depth`. A layer a boolean parameter shows sits behind an
|
||||
/// `if (…)`: Dart's lists take conditions, so the element itself carries it.
|
||||
pub(crate) fn flutter(ctx: &Ctx, id: NodeId, depth: usize, out: &mut String, place: Place) {
|
||||
@@ -150,9 +237,13 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
|
||||
close.push(format!("\n{pad})"));
|
||||
depth += 1;
|
||||
}
|
||||
// An instance is a call, made once: it gets no fill boxes, so this is its final depth.
|
||||
let call = flutter_call(ctx, n, depth);
|
||||
let painted =
|
||||
if call.is_none() && paints_a_box(n) { flutter_fill_boxes(n, &mut depth, &mut close, out) } else { Painted { fill: None, shadow: true } };
|
||||
// A wrapper leaves its line open ("child: "), so the widget carries no indentation of its own.
|
||||
let mut body = String::new();
|
||||
flutter_widget(ctx, n, depth, &mut body);
|
||||
flutter_widget(ctx, n, depth, call, &painted, &mut body);
|
||||
out.push_str(if close.is_empty() { body.as_str() } else { body.trim_start() });
|
||||
for c in close.iter().rev() {
|
||||
out.push_str(c);
|
||||
@@ -161,13 +252,8 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
|
||||
|
||||
/// A layer's own look and its subtree as a Flutter widget at `depth`: a complete expression whose
|
||||
/// closing parenthesis sits at `depth`.
|
||||
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
|
||||
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, call: Option<String>, painted: &Painted, out: &mut String) {
|
||||
let (pad, inner) = (flutter_indent(depth), flutter_indent(depth + 1));
|
||||
// Nested instances are calls; an instance swap parameter is a widget.
|
||||
let call = match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
|
||||
Some(p) => Some(p.ident.clone()),
|
||||
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
|
||||
};
|
||||
if let Some(call) = call {
|
||||
out.push_str(call.trim_end_matches('\n'));
|
||||
return;
|
||||
@@ -216,7 +302,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
|
||||
}
|
||||
NodeKind::Ellipse { .. } | NodeKind::Rectangle => {
|
||||
out.push_str(&format!("{pad}Container(\n{inner}width: {},\n{inner}height: {},\n", num(n.width), num(n.height)));
|
||||
if let Some(d) = box_decoration(n, &inner) {
|
||||
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
|
||||
out.push_str(&format!("{inner}decoration: {d},\n"));
|
||||
}
|
||||
out.push_str(&format!("{pad})"));
|
||||
@@ -232,7 +318,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
|
||||
if !padded_inside && let Some(p) = flutter_padding(n) {
|
||||
out.push_str(&format!("{inner}padding: {p},\n"));
|
||||
}
|
||||
if let Some(d) = box_decoration(n, &inner) {
|
||||
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
|
||||
out.push_str(&format!("{inner}decoration: {d},\n"));
|
||||
}
|
||||
if children.is_empty() && slot.is_none() {
|
||||
@@ -335,7 +421,7 @@ fn flutter_line(ctx: &Ctx, l: &AutoLayout, flow: &[Placed], slot: Option<&Param>
|
||||
out.push_str(&format!("{inner}textBaseline: TextBaseline.alphabetic,\n"));
|
||||
}
|
||||
// The gap between the children; the space distributions already spread them.
|
||||
if l.gap > 0.0 && flutter_main_align(l.main_align).is_none_or(|m| !m.contains("Space")) {
|
||||
if l.gap > 0.0 && !matches!(l.main_align, MainAlign::SpaceBetween | MainAlign::SpaceAround | MainAlign::SpaceEvenly) {
|
||||
out.push_str(&format!("{inner}spacing: {},\n", num(l.gap)));
|
||||
}
|
||||
out.push_str(&format!("{inner}children: [\n"));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::{
|
||||
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
|
||||
CodeLang, Color, Ctx, Document, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill,
|
||||
gradient_axis, gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ SwiftUI
|
||||
@@ -8,6 +9,47 @@ fn swift_color(c: Color) -> String {
|
||||
format!("Color(red: {}, green: {}, blue: {}, opacity: {})", num(f64::from(c.r)), num(f64::from(c.g)), num(f64::from(c.b)), num(f64::from(c.a)))
|
||||
}
|
||||
|
||||
fn swift_point(p: (f64, f64)) -> String {
|
||||
format!("UnitPoint(x: {}, y: {})", num(p.0), num(p.1))
|
||||
}
|
||||
|
||||
/// A gradient fill on a layer of `w` x `h` as a SwiftUI gradient.
|
||||
fn swift_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
|
||||
let stops = gradient_stops(g, opacity)
|
||||
.into_iter()
|
||||
.map(|(at, c)| format!("Gradient.Stop(color: {}, location: {})", swift_color(c), num(at)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let (dx, dy) = gradient_axis(g, w, h);
|
||||
match native_gradient_kind(g) {
|
||||
GradientKind::Linear => format!("LinearGradient(stops: [{stops}], startPoint: {}, endPoint: {})", swift_point(g.from), swift_point(g.to)),
|
||||
GradientKind::Angular => {
|
||||
format!("AngularGradient(stops: [{stops}], center: {}, angle: .degrees({}))", swift_point(g.from), num(dy.atan2(dx).to_degrees()))
|
||||
}
|
||||
_ => format!("RadialGradient(stops: [{stops}], center: {}, startRadius: 0, endRadius: {})", swift_point(g.from), num(dx.hypot(dy))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One paint (the one at document index `i`) as SwiftUI; `None` for an image or pattern, which no
|
||||
/// native target writes yet. Only a solid at index 0 takes the `fill` variable's name.
|
||||
fn swift_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { .. } => {
|
||||
let c = swift_color(p.solid_color()?);
|
||||
Some(if i == 0 { named(doc, n, "iOS", &["fill"], c) } else { c })
|
||||
}
|
||||
PaintKind::Gradient(g) => Some(swift_gradient(g, n.width, n.height, p.opacity)),
|
||||
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The modifiers filling a rectangle or ellipse: the bottom paint fills the `shape`, and each paint
|
||||
/// above it is a copy of the shape laid over it.
|
||||
fn swift_shape_fills(doc: &Document, n: &Node, shape: &str) -> Vec<String> {
|
||||
let paints = visible_fills(n).filter_map(|(i, p)| swift_paint(doc, n, i, p));
|
||||
paints.enumerate().map(|(at, c)| if at == 0 { format!(".fill({c})") } else { format!(".overlay({shape}.fill({c}))") }).collect()
|
||||
}
|
||||
|
||||
fn swift_weight(w: u16) -> &'static str {
|
||||
match w {
|
||||
0..=150 => ".thin",
|
||||
@@ -84,16 +126,12 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
}
|
||||
NodeKind::Ellipse { .. } => {
|
||||
out.push_str(&format!("{pad}Ellipse()\n"));
|
||||
if let Some(c) = &fill {
|
||||
mods.push(format!(".fill({c})"));
|
||||
}
|
||||
mods.extend(swift_shape_fills(doc, n, "Ellipse()"));
|
||||
mods.push(format!(".frame(width: {w}, height: {h})"));
|
||||
}
|
||||
NodeKind::Rectangle => {
|
||||
out.push_str(&format!("{pad}RoundedRectangle(cornerRadius: {corner})\n"));
|
||||
if let Some(c) = &fill {
|
||||
mods.push(format!(".fill({c})"));
|
||||
}
|
||||
mods.extend(swift_shape_fills(doc, n, &format!("RoundedRectangle(cornerRadius: {corner})")));
|
||||
mods.push(format!(".frame(width: {w}, height: {h})"));
|
||||
}
|
||||
k if k.is_frame_like() || matches!(k, NodeKind::Group) => {
|
||||
@@ -142,9 +180,8 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
}
|
||||
}
|
||||
mods.push(format!(".frame(width: {w}, height: {h}, alignment: .topLeading)"));
|
||||
if let Some(c) = &fill {
|
||||
mods.push(format!(".background({c})"));
|
||||
}
|
||||
// Each background goes behind the ones before it, so the top fill is written first.
|
||||
mods.extend(visible_fills(n).rev().filter_map(|(i, p)| swift_paint(doc, n, i, p)).map(|c| format!(".background({c})")));
|
||||
if radius(n) > 0.0 {
|
||||
mods.push(format!(".clipShape(RoundedRectangle(cornerRadius: {corner}))"));
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ pub fn dev_mode_allows(id: &str) -> bool {
|
||||
// Edits recorded as one grouped undo step, so their spec says no history of its own.
|
||||
const GROUPED: [&str; 1] = ["data.fill"];
|
||||
match id.strip_prefix("tool.") {
|
||||
Some(t) => matches!(t, "move" | "hand" | "comment"),
|
||||
Some(t) => crate::tools::ToolId::from_id(t).is_some_and(crate::tools::ToolId::works_in_dev_mode),
|
||||
None if id == "file.revert" || GROUPED.contains(&id) => false,
|
||||
None => OWN.iter().any(|p| id.starts_with(p)) || crate::cmd::find_command(id).is_none_or(|c| !c.history),
|
||||
}
|
||||
|
||||
@@ -105,6 +105,23 @@ fn arb(v: &str) -> String {
|
||||
format!("[{}]", v.trim().replace('_', "\\_").replace(' ', "_"))
|
||||
}
|
||||
|
||||
/// Whether `v` has a comma outside any parentheses (a multi-layer `background`).
|
||||
fn layered(v: &str) -> bool {
|
||||
let mut depth = 0usize;
|
||||
v.chars().any(|c| match c {
|
||||
'(' => {
|
||||
depth += 1;
|
||||
false
|
||||
}
|
||||
')' => {
|
||||
depth = depth.saturating_sub(1);
|
||||
false
|
||||
}
|
||||
',' => depth == 0,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The custom property a `var(--name, fallback)` value reads, when that one call is the whole
|
||||
/// value (not `var(--a, 4px) 8px`, four corners of which only the first is a variable).
|
||||
fn var_name(v: &str) -> Option<&str> {
|
||||
@@ -270,6 +287,8 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
|
||||
Ok(o) if ((o * 100.0).round() - o * 100.0).abs() < 1e-9 => one(format!("opacity-{}", num(o * 100.0))),
|
||||
_ => one(util("opacity", "", v, "")),
|
||||
},
|
||||
// Several fills are one layered `background`: commas between the layers, outside any call.
|
||||
("background", v) if layered(v) => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))),
|
||||
("background", v) if v.contains("gradient(") => one(format!("bg-{}", arb(v))),
|
||||
// An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour.
|
||||
("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))),
|
||||
@@ -413,10 +432,11 @@ fn zero_padding(sides: [bool; 4]) -> Vec<&'static str> {
|
||||
pub(crate) fn merge(mobile: Option<&[(String, String)]>, desktop: &[(String, String)]) -> Vec<String> {
|
||||
let hidden = [("display".to_string(), "hidden".to_string())];
|
||||
// A mobile frame's widths are the phone's, not caps: below the breakpoint boxes fill the page.
|
||||
// Except a cap desktop has too: that is the layer's own size (a badge, an avatar), kept at every width.
|
||||
let fluid: Vec<(String, String)>;
|
||||
let mobile = match mobile {
|
||||
Some(m) => {
|
||||
fluid = m.iter().filter(|(k, _)| k != "max-width").cloned().collect();
|
||||
fluid = m.iter().filter(|(k, c)| k != "max-width" || desktop.iter().any(|(_, d)| d == c)).cloned().collect();
|
||||
fluid.as_slice()
|
||||
}
|
||||
None => &hidden,
|
||||
|
||||
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user