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

# Conflicts:
#	ROADMAP.md
#	docs/components-parity.md
This commit is contained in:
bflatastic committed 2026-11-28 20:28:39 +07:00
commit 9ae491f9ea
120 files changed
+3321 -486

No files matched your search

Generated
+35 -55
View File
@@ -274,15 +274,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -1039,6 +1030,15 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "constant_time_eq"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
dependencies = [
"rustversion",
]
[[package]]
name = "cookie-factory"
version = "0.3.3"
@@ -1327,7 +1327,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.1",
"zip",
]
[[package]]
@@ -1879,7 +1879,7 @@ dependencies = [
"verifysign",
"winreg",
"winsafe",
"zip 9.1.1",
"zip",
]
[[package]]
@@ -1962,7 +1962,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.1",
"zip",
]
[[package]]
@@ -2099,17 +2099,6 @@ version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "deunicode"
version = "1.6.2"
@@ -2716,6 +2705,7 @@ dependencies = [
"log",
"proptest",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde_json",
"tungstenite",
@@ -2780,7 +2770,7 @@ dependencies = [
"thiserror 2.0.21",
"wat",
"web-time",
"zip 2.6.1",
"zip",
]
[[package]]
@@ -2809,7 +2799,7 @@ dependencies = [
"serde_json",
"sha1",
"sha2",
"zip 2.6.1",
"zip",
]
[[package]]
@@ -2927,7 +2917,7 @@ dependencies = [
"toml",
"tungstenite",
"wat",
"zip 2.6.1",
"zip",
]
[[package]]
@@ -8704,6 +8694,20 @@ name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerotrie"
@@ -8744,33 +8748,21 @@ dependencies = [
[[package]]
name = "zip"
version = "2.6.1"
version = "9.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zip"
version = "9.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4"
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
dependencies = [
"constant_time_eq",
"crc32fast",
"flate2",
"getrandom 0.4.3",
"indexmap",
"libc",
"memchr",
"nix",
"typed-path",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
@@ -8785,18 +8777,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.5.3"
+1 -1
View File
@@ -121,7 +121,7 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil
# dependencies, BSD-3-Clause, no_std so the web build keeps it too).
deunicode = "1.6"
linesweeper = "0.5"
zip = { version = "2", default-features = false, features = ["deflate"] }
zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] }
# `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe).
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
+1
View File
@@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-28 | minor | M8: the MCP prompt `implement_design` takes an agent through building the selected design in a codebase: `design_context` for what the designer set, connected components reused through `component_mappings` and `sync_mappings`, tokens before literal values, real files from `export_assets`, the annotations and `responsive` for what the design states beyond its size, and `compare_design` to check the result. With nothing selected it asks which frame to build, and it reports what it approximated, assumed or couldn't check. A test now checks that every tool and result field the server instructions and prompts name exists, as one already did for command ids. Numbers unchanged |
| 2026-11-28 | minor | M7, #1687: variables export and import as DTCG design tokens (format 2025.10), the files token build pipelines read. `variable.export {format: "dtcg", mode?}` (also Variables ▸ Export… ▸ Design tokens (DTCG)…, saved as `.tokens.json`) writes a group per collection and a token per variable, nested by the `/` parts of its name: colours as `colorSpace`/`components`/`alpha` objects (with `hex` in sRGB, `display-p3` in a Display P3 file), numbers as px dimensions or plain numbers where layers use them unitless, aliases as `{group.token}` (one leaving the exported collections as the value it shows), colour calculations as the colour they show; strings and booleans, which DTCG has no type for, every mode's value and the variable's scopes go under `$extensions` (`ai.storyteller.figcraft`), and `mode` picks which mode is `$value`. `variable.import` reads a file holding a `$value` as tokens: each top-level group a collection (top-level tokens one named Tokens), types handed down from groups, `color` (object or `#hex`), `dimension` (px, rem at 16 px, or the older `16px` string), `number`, `fontWeight` (number or name), `duration` (ms), `fontFamily`, strings, booleans and aliases (an untyped alias takes its target's type); without our modes a collection fills the default mode of this file's collection of its name. Composite tokens (typography, shadows and the like) are skipped and counted in the warnings, never dropped silently. Tests: `dtcg_tests` (format, three) and `variables_io_tests::design_tokens_export_and_import_round_trip`, `plain_design_tokens_update_the_default_mode` (engine). Numbers unchanged |
| 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. |
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
+1 -1
View File
@@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec<u8> {
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
for i in 0..src.len() {
let f = src.by_index_raw(i).unwrap();
if bomb > 0 && f.name() == "library/document.json" {
if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" {
continue;
}
out.raw_copy_file(f).unwrap();
+1 -1
View File
@@ -90,7 +90,7 @@ impl Store {
if let Some(why) = self.low_disk() {
return Err(why);
}
let replica = Replica::from_snapshot(snapshot).map_err(|e| format!("the file couldn't be read: {e}"))?;
let replica = Replica::from_snapshot(snapshot.to_vec()).map_err(|e| format!("the file couldn't be read: {e}"))?;
if replica.document().node_count() > self.cfg.core.max_nodes {
return Err(format!("the file has more than {} layers", self.cfg.core.max_nodes));
}
+136 -33
View File
@@ -24,6 +24,17 @@
//! - Everything else is a copy or export that never becomes the document: `false` — rendered
//! images, SVG and PDF, `.fig` copies, and the variables exports (a `.variables.json`
//! sidecar's `.json` extension doesn't make it a document).
//! - Confirmed saves, opt-in: with `?save=managed` in the URL, or `data-save="managed"` on the
//! canvas ([`crate::query::confirms_saves`]), each Save and Save As of the document carries an
//! `id` (`save-1`, `save-2`, …) and the document keeps its unsaved changes until the host answers
//! `figcraft:saved` with that `id` ([`crate::host_saves`]). Then it is saved as of the file the
//! host stored, so edits made meanwhile stay unsaved, and a Save As becomes the document's file
//! only then. Answers for any other `id` are ignored; a newer save replaces the one waiting; a
//! file the host opens forgets it (the user is told). Without an answer within 30 seconds the save counts as not
//! stored: the user is told and the host gets `figcraft:failed` with the `id`. Copies and exports
//! carry no `id` and `saveAs: false`. A host that doesn't opt in sees no change: every file
//! counts as saved once it is posted. `craft-web-host` has no message yet for a host to refuse a
//! save, so a refusal shows as the timeout.
//! - `figcraft:dirty` whenever unsaved changes appear or go away, `figcraft:failed` when the app
//! couldn't start.
//!
@@ -31,10 +42,14 @@
//! edit; `?author=` names the user for comments and board notes.
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use craft_web_host::web::{FileData, Host, Message};
use figcraft_ui_egui::FigApp;
use figcraft_engine::cmd::file::FileSnapshot;
use figcraft_ui_egui::{Delivery, FigApp};
use crate::host_saves::HostSaves;
/// The app id in the host messages (`figcraft:ready`).
const APP: &str = "figcraft";
@@ -42,38 +57,87 @@ const APP: &str = "figcraft";
/// The longest user name taken from `?author=`.
const MAX_AUTHOR_CHARS: usize = 200;
/// Files the host sent, on their way to the app's own open queue ([`figcraft_ui_egui::pending_open`]):
/// `(name, bytes)`.
pub type OpenQueue = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
/// What the host sent, in the order it came, for the shell's next frame ([`Bridge::frame`]).
enum FromHost {
/// A file to open: `(name, bytes)`.
Open(String, Vec<u8>),
/// The save with this `id` is stored.
Saved(String),
}
#[derive(Clone)]
pub struct Bridge {
host: Rc<Host>,
/// The file the host opened, and after a `saveAs` hand-over the document's file: the name a
/// Save under (`saveAs: false`) is decided against.
host_file: Rc<RefCell<Option<String>>>,
/// The host confirms saves (`?save=managed`): document saves wait for its `saved`.
confirms_saves: bool,
/// The document's file and the save waiting for the host ([`crate::host_saves`]).
saves: Rc<RefCell<HostSaves<FileSnapshot>>>,
/// Messages heard and not yet handled. The listener only queues them: a page host can answer
/// while a post is still running, so nothing else is borrowed there.
inbox: Rc<RefCell<VecDeque<FromHost>>>,
}
impl Bridge {
/// The bridge for this page, or `None` when FigCraft isn't hosted: no `?host=parent` and no
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
/// with downloads), or a parent on another origin.
pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), host_file: Rc::default() })
/// with downloads), or a parent on another origin. `confirms_saves`: the host opted in to
/// confirmed saves.
pub fn connect(canvas: &web_sys::HtmlCanvasElement, confirms_saves: bool) -> Option<Self> {
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), confirms_saves, saves: Rc::default(), inbox: Rc::default() })
}
/// Hear the files the host sends, and queue each one on `opens` for the app's own open path
/// (the shell drains it into [`figcraft_ui_egui::pending_open`] every frame, so a host file
/// opens like a dropped one).
pub fn listen(&self, opens: OpenQueue, ctx: egui::Context) {
let host_file = self.host_file.clone();
/// Hear the host's messages. They are handled in the shell's next frame ([`Bridge::frame`]),
/// in the order they came.
pub fn listen(&self, ctx: egui::Context) {
let inbox = self.inbox.clone();
self.host.listen(move |message| {
if let Message::Open { name, data } = message {
deliver_open(&opens, &ctx, &host_file, &name, &data);
let heard = match message {
Message::Open { name, data } => open_bytes(&name, &data),
Message::Saved { id } => Some(FromHost::Saved(id)),
_ => None,
};
if let Some(heard) = heard {
inbox.borrow_mut().push_back(heard);
ctx.request_repaint();
}
});
}
/// Every frame: handle what the host sent, in order (a file opens on the app's own open path,
/// as a dropped one does; a `saved` marks its document saved), and end a save that waited too
/// long. `now_ms`: the app's clock, which also wakes the app when the waiting save times out.
pub fn frame(&self, fig: &mut FigApp, ctx: &egui::Context, now_ms: u64) {
let heard = std::mem::take(&mut *self.inbox.borrow_mut());
for message in heard {
match message {
FromHost::Open(name, bytes) => {
let forgotten = self.saves.borrow_mut().opened(&name);
if let Some(save) = forgotten {
fig.document_not_stored(&save.name, &figcraft_ui_egui::save_forgotten_on_open());
}
queue_open(fig, name, bytes);
}
FromHost::Saved(id) => {
let confirmed = self.saves.borrow_mut().saved(&id);
match confirmed {
Some(save) => fig.document_stored(&save.name, save.file),
None => log::info!("host confirmed save {id:?}, which isn't the one waiting; ignored"),
}
}
}
}
let expired = self.saves.borrow_mut().expire(now_ms);
if let Some(save) = expired {
let secs = self.saves.borrow().timeout_ms() / 1000;
let _ = self.host.post_failed(&format!("save {} was not confirmed within {secs} seconds", save.id), Some(&save.id));
fig.document_not_stored(&save.name, &figcraft_ui_egui::save_unconfirmed(usize::try_from(secs).unwrap_or(usize::MAX)));
}
let wait = self.saves.borrow().wait_ms(now_ms);
if let Some(wait) = wait {
ctx.request_repaint_after(std::time::Duration::from_millis(wait));
}
}
/// `?author=`: the host's name for the user signs comments and board notes.
pub fn set_author(app: &mut FigApp, author: &str) {
let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect();
@@ -93,24 +157,53 @@ impl Bridge {
/// The document file the host opened or the last Save As made, if any.
pub fn host_file(&self) -> Option<String> {
self.host_file.borrow().clone()
self.saves.borrow().host_file().map(str::to_string)
}
/// Hand a file the app would otherwise download to the host; `false` when nothing was
/// delivered. The `saveAs` rule is this module's documentation's.
/// Hand a file the app would otherwise download to the host, without an `id`; `false` when
/// nothing was delivered. To a host that confirms saves only copies and exports come this way
/// (the document's own file goes through [`post_document`](Self::post_document)), so they are
/// `saveAs: false`; to one that doesn't, the `saveAs` rule is this module's documentation's.
pub fn post_save(&self, path: &str, bytes: &[u8]) -> bool {
let name = file_name(path);
let host_file = self.host_file.borrow().clone();
let save_as = crate::hostmode::save_as(&name, host_file.as_deref());
let save_as = !self.confirms_saves && self.saves.borrow().save_as(&name);
let sent = self.host.post_save(&name, bytes, None, save_as).is_ok();
// After a Save As hand-over the host has the new file: the next Save of it sends its name
// with `saveAs: false`. A failed send changes nothing, so a retry is still a Save As.
if sent && save_as {
*self.host_file.borrow_mut() = Some(name);
self.saves.borrow_mut().adopt(&name);
}
sent
}
/// Hand the host the document's own file (Save, Save As) as `file`. To a host that confirms
/// saves it goes with an `id` and stays unsaved until the host answers ([`Delivery::Pending`]);
/// otherwise as [`post_save`](Self::post_save).
pub fn post_document(&self, path: &str, bytes: &[u8], file: FileSnapshot, now_ms: u64, ctx: &egui::Context) -> Delivery {
if !self.confirms_saves {
return if self.post_save(path, bytes) { Delivery::Saved } else { Delivery::Refused };
}
let name = file_name(path);
// Recorded before the post: a page host can answer while it is still dispatching.
let (started, timeout_ms) = {
let mut saves = self.saves.borrow_mut();
(saves.start(&name, file, now_ms), saves.timeout_ms())
};
match self.host.post_save(&name, bytes, Some(&started.id), started.save_as) {
Ok(()) => {
// Schedule the timeout wakeup immediately so an idle tab still times out if the
// host never answers after this frame.
ctx.request_repaint_after(std::time::Duration::from_millis(timeout_ms));
Delivery::Pending
}
Err(e) => {
log::error!("couldn't hand {name} to the host: {e}");
self.saves.borrow_mut().failed(&started.id);
Delivery::Refused
}
}
}
/// Report unsaved changes when they appear or go away, not every frame (the crate does not
/// repeat a state it already reported).
pub fn set_dirty(&self, dirty: bool) {
@@ -118,23 +211,33 @@ impl Bridge {
}
}
/// The file an open message carries, queued for the app's own open path, or nothing when the
/// payload isn't one (a `File` the app doesn't read, or over the open limit).
fn deliver_open(opens: &OpenQueue, ctx: &egui::Context, host_file: &RefCell<Option<String>>, name: &str, data: &FileData) {
/// The app's own open queue gets a file the host sent: the same "Opening as a new file" card as a
/// dropped file, and `file.open` with the contents once read.
fn queue_open(fig: &mut FigApp, name: String, bytes: Vec<u8>) {
let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes)));
fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen {
label: name.clone(),
params: serde_json::json!({ "name": name }),
command: "file.open",
target: None,
read: Some(read),
});
}
/// The file an open message carries, copied out for the next frame, or nothing when the payload
/// isn't one (a `File` the app doesn't read, or over the open limit). Once handled it is the
/// document's file: a Save of it under this name is `saveAs: false`.
fn open_bytes(name: &str, data: &FileData) -> Option<FromHost> {
let name = crate::hostmode::open_name(name);
let FileData::Bytes(array) = data else {
log::warn!("host file {name} came as a File; FigCraft reads bytes only; not opened");
return;
return None;
};
if figcraft_ui_egui::browser_can_read(&name, data.size()).is_err() {
log::warn!("host file {name} is too large to open in the browser; not opened");
return;
return None;
}
// The document's file is now the one the host sent: a Save of it under this name is
// `saveAs: false`.
*host_file.borrow_mut() = Some(name.clone());
opens.borrow_mut().push((name, array.to_vec()));
ctx.request_repaint();
Some(FromHost::Open(name, array.to_vec()))
}
/// The last component of `path`, or the whole of it when there is none.
+262
View File
@@ -0,0 +1,262 @@
//! Confirmed saves: what the bridge ([`crate::host`]) knows about the files it handed a host page,
//! kept apart from the browser so every step is testable without one (like [`crate::hostmode`]).
//!
//! A host that confirms saves (`?save=managed`, [`crate::query::confirms_saves`]) gets each
//! Save and Save As of the document with an `id` and answers `saved` with that `id` once it stored
//! the file. Until then the document keeps its unsaved changes. Only one document save waits at a
//! time: a newer one replaces it, and an answer for any other `id` (an older save, a repeat, one
//! the host made up) is ignored. A save the host doesn't answer within the timeout counts as not
//! stored. A file the host opens forgets the save still waiting, so a late answer can't touch
//! the file opened since.
//!
//! The file the host opened, or the one the last Save As made, is kept here too: a Save As becomes
//! the document's file only once the host confirms it, so after a failed one the next Save is
//! still a Save As.
/// How long a document save waits for the host's answer before it counts as not stored.
pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
/// A document save handed to the host and not answered yet.
#[derive(Debug)]
pub struct PendingSave<F> {
/// The `id` the save carried; the host's `saved` names it.
pub id: String,
/// The file name it went out under.
pub name: String,
/// It went out as `saveAs: true`: confirmed, it becomes the document's file.
pub save_as: bool,
/// When it was handed over, in the caller's clock (milliseconds).
pub started_at_ms: u64,
/// The document as handed over. In the app this is its `FileSnapshot` (the tab's uid, its
/// revision and contents), which marks the document saved as of the snapshot once confirmed.
pub file: F,
}
/// A document save just handed to [`HostSaves::start`]: what to post with it.
#[derive(Debug, PartialEq, Eq)]
pub struct Started {
pub id: String,
pub save_as: bool,
}
/// The bridge's record of the document's file and the save waiting for the host.
#[derive(Debug)]
pub struct HostSaves<F> {
host_file: Option<String>,
/// The number in the next save's `id`. Never reset, so an `id` is never used twice on a page.
next_id: u64,
pending: Option<PendingSave<F>>,
timeout_ms: u64,
}
impl<F> Default for HostSaves<F> {
fn default() -> Self {
Self::new(DEFAULT_TIMEOUT_MS)
}
}
impl<F> HostSaves<F> {
pub fn new(timeout_ms: u64) -> Self {
Self { host_file: None, next_id: 1, pending: None, timeout_ms }
}
/// How long a save waits for its answer, in milliseconds.
pub fn timeout_ms(&self) -> u64 {
self.timeout_ms
}
/// The file the host opened, or the one the last confirmed (or, without confirmation, posted)
/// Save As made.
pub fn host_file(&self) -> Option<&str> {
self.host_file.as_deref()
}
/// Whether a file named `name` goes out as `saveAs: true` now ([`crate::hostmode::save_as`]).
pub fn save_as(&self, name: &str) -> bool {
crate::hostmode::save_as(name, self.host_file.as_deref())
}
/// A Save As went to a host that doesn't confirm saves: `name` is the document's file now.
pub fn adopt(&mut self, name: &str) {
self.host_file = Some(name.to_string());
}
/// The host sent the file `name` to open: it is the document's file now. A save still waiting
/// was for the document open before, so it is forgotten and returned; its answer, if one
/// comes, is ignored, and that document keeps its unsaved changes.
pub fn opened(&mut self, name: &str) -> Option<PendingSave<F>> {
self.host_file = Some(name.to_string());
self.pending.take()
}
/// A Save or Save As of the document as `file`, under `name`, handed over at `now_ms`: the `id`
/// and `saveAs` to post it with. A save still waiting is replaced, so its answer is ignored.
pub fn start(&mut self, name: &str, file: F, now_ms: u64) -> Started {
let id = format!("save-{}", self.next_id);
self.next_id += 1;
let save_as = self.save_as(name);
self.pending = Some(PendingSave { id: id.clone(), name: name.to_string(), save_as, started_at_ms: now_ms, file });
Started { id, save_as }
}
/// The host's `saved` for `id`: the save it confirms, when that is the one waiting. A Save As
/// becomes the document's file now. Any other `id` changes nothing.
pub fn saved(&mut self, id: &str) -> Option<PendingSave<F>> {
let save = self.take(id)?;
if save.save_as {
self.host_file = Some(save.name.clone());
}
Some(save)
}
/// The save `id` could not be stored (the post failed, or the host refused it): the save,
/// when that is the one waiting. The document's file stays as it was. Any other `id` changes
/// nothing.
pub fn failed(&mut self, id: &str) -> Option<PendingSave<F>> {
self.take(id)
}
/// The save waiting since longer than the timeout at `now_ms`, which then counts as failed.
pub fn expire(&mut self, now_ms: u64) -> Option<PendingSave<F>> {
let waiting = self.pending.as_ref()?;
if now_ms.saturating_sub(waiting.started_at_ms) < self.timeout_ms {
return None;
}
self.pending.take()
}
/// How long from `now_ms` until the waiting save times out (so the app wakes then), or
/// `None` when none waits.
pub fn wait_ms(&self, now_ms: u64) -> Option<u64> {
let waiting = self.pending.as_ref()?;
Some((waiting.started_at_ms.saturating_add(self.timeout_ms)).saturating_sub(now_ms))
}
fn take(&mut self, id: &str) -> Option<PendingSave<F>> {
if self.pending.as_ref().is_some_and(|p| p.id == id) { self.pending.take() } else { None }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The document as handed over: in these tests, a label for the revision saved.
type Saves = HostSaves<&'static str>;
fn opened(name: &str) -> Saves {
let mut saves = Saves::default();
assert!(saves.opened(name).is_none());
saves
}
#[test]
fn each_save_gets_an_id_of_its_own() {
let mut saves = opened("Poster.figcraft");
let first = saves.start("Poster.figcraft", "r1", 0).id;
let second = saves.start("Poster.figcraft", "r2", 0).id;
assert_ne!(first, second);
saves.opened("Other.figcraft");
let third = saves.start("Other.figcraft", "r3", 0).id;
assert!(third != first && third != second, "opening a file doesn't start the ids over");
}
#[test]
fn a_confirmed_save_hands_back_what_was_saved() {
let mut saves = opened("Poster.figcraft");
let started = saves.start("Poster.figcraft", "r1", 5);
assert!(!started.save_as, "a Save of the host's own file");
let save = saves.saved(&started.id).expect("the waiting save");
assert_eq!((save.file, save.name.as_str(), save.started_at_ms), ("r1", "Poster.figcraft", 5));
assert!(saves.wait_ms(5).is_none(), "nothing waits any more");
assert!(saves.saved(&started.id).is_none(), "a repeated answer changes nothing");
}
#[test]
fn a_save_as_becomes_the_document_s_file_only_once_confirmed() {
let mut saves = opened("Poster.figcraft");
let started = saves.start("Poster 2.figcraft", "r1", 0);
assert!(started.save_as);
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "not before the host stored it");
saves.saved(&started.id);
assert_eq!(saves.host_file(), Some("Poster 2.figcraft"));
assert!(!saves.start("Poster 2.figcraft", "r2", 0).save_as, "the next Save is of that file");
}
#[test]
fn a_failed_save_as_leaves_the_document_s_file_so_a_retry_is_still_a_save_as() {
let mut saves = opened("Poster.figcraft");
let started = saves.start("Poster 2.figcraft", "r1", 0);
let save = saves.failed(&started.id).expect("the waiting save");
assert_eq!(save.file, "r1");
assert_eq!(saves.host_file(), Some("Poster.figcraft"));
assert!(saves.start("Poster 2.figcraft", "r1", 0).save_as);
}
#[test]
fn answers_for_other_ids_change_nothing() {
let mut saves = opened("Poster.figcraft");
let started = saves.start("Poster 2.figcraft", "r1", 0);
for id in ["", "save-0", "save-99", "Save-1 ", "nonsense"] {
assert!(saves.saved(id).is_none(), "{id:?}");
assert!(saves.failed(id).is_none(), "{id:?}");
}
assert_eq!(saves.host_file(), Some("Poster.figcraft"));
assert!(saves.saved(&started.id).is_some(), "the real answer still counts");
}
#[test]
fn a_newer_save_replaces_the_one_waiting() {
let mut saves = opened("Poster.figcraft");
let older = saves.start("Poster 2.figcraft", "r1", 0);
let newer = saves.start("Poster.figcraft", "r2", 10);
assert!(saves.saved(&older.id).is_none(), "a late answer for the older save is ignored");
assert!(saves.failed(&older.id).is_none());
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "the older Save As never became the file");
assert_eq!(saves.saved(&newer.id).map(|s| s.file), Some("r2"));
}
#[test]
fn a_save_left_unanswered_times_out() {
let mut saves = Saves::new(1_000);
saves.opened("Poster.figcraft");
let started = saves.start("Poster 2.figcraft", "r1", 100);
assert!(saves.expire(100).is_none());
assert!(saves.expire(1_099).is_none(), "still inside the timeout");
let remaining = saves.wait_ms(600).expect("a save waits");
assert!(remaining > 0 && remaining < saves.timeout_ms(), "{remaining}");
let save = saves.expire(1_100).expect("timed out");
assert_eq!(save.file, "r1");
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "a timed-out Save As isn't the file");
assert!(saves.saved(&started.id).is_none(), "an answer after the timeout is ignored");
assert!(saves.expire(5_000).is_none() && saves.wait_ms(5_000).is_none());
}
#[test]
fn a_clock_that_goes_back_does_not_end_the_wait_early() {
let mut saves = Saves::new(1_000);
saves.start("Untitled.figcraft", "r1", 500);
assert!(saves.expire(0).is_none());
assert!(saves.wait_ms(0).is_some_and(|w| w >= saves.timeout_ms()));
}
#[test]
fn opening_a_file_forgets_the_save_still_waiting() {
let mut saves = opened("Poster.figcraft");
let started = saves.start("Poster 2.figcraft", "r1", 0);
let dropped = saves.opened("Other.figcraft").expect("the save that waited");
assert_eq!(dropped.file, "r1");
assert!(saves.saved(&started.id).is_none(), "its late answer is ignored");
assert_eq!(saves.host_file(), Some("Other.figcraft"), "and can't rename the file opened since");
assert!(saves.expire(u64::MAX).is_none());
}
#[test]
fn without_confirmation_a_save_as_is_the_document_s_file_once_posted() {
let mut saves = Saves::default();
assert!(saves.save_as("Untitled.figcraft"), "the host never sent a file");
saves.adopt("Untitled.figcraft");
assert!(!saves.save_as("Untitled.figcraft"));
assert!(!saves.save_as("Untitled.png"), "an export is never the document's file");
}
}
+5 -2
View File
@@ -21,13 +21,14 @@
//! `http://` on a trusted network to reach plain `ws://` hosts on other machines.
//! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `<iframe>`) or
//! `data-host="page"` on the canvas (the page's own document) hands the page the app's files
//! instead of downloading them and reports unsaved changes (`host`);
//! instead of downloading them and reports unsaved changes (`host`); with `?save=managed` (or
//! `data-save="managed"`) a document save waits for the page's confirmation (`host_saves`);
//!
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?control` installs
//! `window.figcraft`, the page's control channel (`api.rs`), which is off without it; `?host=parent`
//! (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the document to open
//! and stores what FigCraft saves. `&author=` names the user for comments and board notes in either
//! host mode.
//! host mode, and `&save=managed` makes document saves wait for the host's `saved`.
//!
//! URL fragment: `#join=<invite link or join code>` joins that live session once the page has
//! loaded, so a bookmark opens a shared file. `join` takes the rest of the fragment: put it last.
@@ -39,6 +40,8 @@ mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod host_saves;
#[cfg(any(target_arch = "wasm32", test))]
mod hostmode;
#[cfg(any(target_arch = "wasm32", test))]
mod kept;
+8
View File
@@ -38,3 +38,11 @@ pub fn page_server(content: &str) -> Option<String> {
pub fn control(search: &str) -> bool {
search.strip_prefix('?').unwrap_or(search).split('&').any(|entry| entry.split('=').next() == Some("control"))
}
/// Whether the host confirms saves ([`crate::host_saves`]): `search` (`location.search`, with or
/// without its `?`) has exactly `save=managed`, or the canvas has `data-save="managed"` (a page
/// running FigCraft in its own document). Without either, a file counts as saved once it is
/// handed to the host, as before.
pub fn confirms_saves(search: &str, data_save: Option<&str>) -> bool {
search.strip_prefix('?').unwrap_or(search).split('&').any(|entry| entry == "save=managed") || data_save == Some("managed")
}
+14 -2
View File
@@ -1,6 +1,7 @@
//! `#join=` and `?control` in the page's URL, and the server the page names for itself.
//! `#join=`, `?control` and `?save=managed` in the page's URL, and the server the page names for
//! itself.
use crate::query::{control, join_link, page_server};
use crate::query::{confirms_saves, control, join_link, page_server};
#[test]
fn join_takes_the_rest_of_the_fragment() {
@@ -82,3 +83,14 @@ fn a_page_rejects_server_delimiters_that_endpoint_parsing_would_strip() {
assert_eq!(page_server(&server), None, "{server:?} must not replace the default server");
}
}
#[test]
fn confirmed_saves_are_opt_in() {
assert!(confirms_saves("?host=parent&save=managed", None));
assert!(confirms_saves("save=managed", None), "no leading ?");
assert!(confirms_saves("", Some("managed")), "a page host's canvas attribute");
for search in ["", "?host=parent", "?save", "?save=", "?save=auto", "?save=managedx", "?xsave=managed", "?save=Managed"] {
assert!(!confirms_saves(search, None), "{search:?}");
}
assert!(!confirms_saves("?host=parent", Some("auto")));
}
+34 -24
View File
@@ -1,7 +1,8 @@
//! The browser shell: web `Services` and the eframe web runner.
use figcraft_engine::Session;
use figcraft_ui_egui::{ContentsFuture, FigApp, Services};
use figcraft_engine::cmd::file::FileSnapshot;
use figcraft_ui_egui::{ContentsFuture, Delivery, FigApp, Services};
use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "figcraft_canvas";
@@ -36,11 +37,11 @@ pub fn start() {
// documents in it and stores what it saves (`host`); unframed there is no parent, so that URL
// on its own stays the normal app with downloads. `data-host="page"` on the canvas opts a
// page in instead: it runs FigCraft in its own document and talks over DOM `CustomEvent`s on
// the canvas.
let bridge = crate::host::Bridge::connect(&canvas);
// the canvas. `?save=managed` (or `data-save="managed"` on the canvas) opts the host in to
// confirmed saves: a document save waits for its `saved` (`host_saves`).
let confirms_saves = crate::query::confirms_saves(&query(), canvas.get_attribute("data-save").as_deref());
let bridge = crate::host::Bridge::connect(&canvas, confirms_saves);
let app_bridge = bridge.clone();
// Files the host sends, on their way into the app's own open queue each frame.
let opens: crate::host::OpenQueue = std::rc::Rc::default();
let mut options = eframe::WebOptions::default();
// `?webgl`: force the WebGL2 backend (troubleshooting, and headless browsers whose WebGPU
// adapter request returns nothing).
@@ -101,9 +102,9 @@ pub fn start() {
}
// The host's files arrive on the app's own open path (a dropped file's).
if let Some(bridge) = &app_bridge {
bridge.listen(opens.clone(), cc.egui_ctx.clone());
bridge.listen(cc.egui_ctx.clone());
}
Ok(Box::new(WebShell { fig, host: app_bridge, opens }))
Ok(Box::new(WebShell { fig, host: app_bridge }))
}),
)
.await;
@@ -169,6 +170,12 @@ fn page_meta(name: &str) -> Option<String> {
document.query_selector(&format!("meta[name=\"{name}\"]")).ok().flatten()?.get_attribute("content")
}
/// The clock confirmed saves time out by (milliseconds; `Date.now()`, which
/// [`crate::host_saves`] tolerates going back).
fn now_ms() -> u64 {
js_sys::Date::now().max(0.0) as u64
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
@@ -181,31 +188,22 @@ struct WebShell {
fig: FigApp,
/// The host bridge, when the page hosts the app (`?host=parent` or `data-host="page"`).
host: Option<crate::host::Bridge>,
/// Files the host sent, waiting to join the app's own open queue.
opens: crate::host::OpenQueue,
}
impl eframe::App for WebShell {
// eframe runs `logic` for visible tabs and, with only `run_logic`, for hidden ones: keep
// autosave/live/control deadlines moving without a paint. `FigApp::ui` does not repeat it.
/// Run the browser shell's eframe logic callback: hand the host's files to the app's open
/// queue, guard `background_tick` so hidden tabs still advance autosave, live and control
/// deadlines without painting, and report unsaved changes to the host. `FigApp::ui` does
/// not repeat it.
/// Run the browser shell's eframe logic callback: handle what the host sent (its files join
/// the app's open queue, its save confirmations mark documents saved), guard `background_tick`
/// so hidden tabs still advance autosave, live and control deadlines without painting, and
/// report unsaved changes to the host. `FigApp::ui` does not repeat it.
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// Every frame, hidden or not, starts here: what the last one left is what a panic keeps.
UNSAVED.with(|u| u.try_borrow_mut().map(|mut u| u.follow(&self.fig.session))).ok();
// Files the host sent join the app's own open queue (a dropped file's): the same
// "Opening as a new file" card, and `file.open` with the contents once read.
for (name, bytes) in std::mem::take(&mut *self.opens.borrow_mut()) {
let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes)));
self.fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen {
label: name.clone(),
params: serde_json::json!({ "name": name }),
command: "file.open",
target: None,
read: Some(read),
});
// Files the host sent join the app's own open queue (a dropped file's), and its answers to
// confirmed saves land, in the order they came (crate::host).
if let Some(bridge) = &self.host {
bridge.frame(&mut self.fig, ctx, now_ms());
}
figcraft_ui_egui::windows::guard(&mut self.fig, ctx, |fig| fig.background_tick(ctx));
// The host hears when unsaved changes appear or go away (crate::host).
@@ -282,6 +280,18 @@ impl Services for WebServices {
}
}
}
/// The document's own file (Save, Save As): as [`download`](Self::download), except that a
/// host that confirms saves gets it with an `id` and it stays unsaved until the host answers
/// ([`crate::host`]).
fn deliver_document(&mut self, name: &str, bytes: &[u8], file: FileSnapshot) -> Delivery {
if crate::api::capture(name, bytes) {
return Delivery::Saved;
}
if let Some(bridge) = &self.host {
return bridge.post_document(name, bytes, file, now_ms(), &self.ctx);
}
if self.download(name, bytes) { Delivery::Saved } else { Delivery::Refused }
}
fn host_file(&self) -> Option<String> {
self.host.as_ref()?.host_file()
}
+106 -16
View File
@@ -1,10 +1,11 @@
//! Localhost JSON-lines control server: each line `{"id", "method", "params"}` is queued for the UI
//! thread; the reply line `{"id", "ok", "result" | "error"}` is written when the frame handled it.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::io::{BufRead, BufReader, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::time::{Duration, Instant};
use figcraft_engine::events::{self, EventLog};
use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate, RequestState};
@@ -14,6 +15,9 @@ type Queue = Arc<Mutex<Vec<ControlRequest>>>;
type CtxSlot = Arc<Mutex<Option<egui::Context>>>;
const MAX_LINE: usize = 32 * 1024 * 1024;
/// Bytes of request lines all connections hold at once (#1111): a line is counted as it is read
/// and until its reply is written, so eight clients can't make the app hold eight full lines.
const MAX_IN_FLIGHT: usize = 64 * 1024 * 1024;
const MAX_CONNECTIONS: usize = 8;
const MAX_QUEUED_REQUESTS: usize = 8;
const TIMEOUT: Duration = Duration::from_secs(60);
@@ -115,8 +119,9 @@ pub fn start(port: u16, busy: Duration, queue: Queue, ctx: CtxSlot, events: Arc<
eprintln!("FigCraft control server listening on 127.0.0.1:{port}");
let spawned = std::thread::Builder::new().name("figcraft-control".into()).spawn(move || {
let mut workers = Vec::new();
let budget = Arc::new(AtomicUsize::new(0));
for stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
spawn_connection(stream, queue.clone(), ctx.clone(), events.clone(), &mut workers, TIMEOUT);
spawn_connection(stream, queue.clone(), ctx.clone(), events.clone(), &budget, &mut workers, TIMEOUT);
}
});
if let Err(e) = spawned {
@@ -129,45 +134,129 @@ fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: imp
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
}
/// Since when a connection has been waiting for its client (`None` while the UI runs one of its
/// requests).
type Idle = Arc<Mutex<Option<Instant>>>;
/// One connection's thread, a handle on its socket and since when it has been idle.
struct Worker {
thread: std::thread::JoinHandle<()>,
stream: TcpStream,
idle: Idle,
}
fn spawn_connection(
stream: TcpStream,
queue: Queue,
ctx: CtxSlot,
events: Arc<EventLog>,
workers: &mut Vec<std::thread::JoinHandle<()>>,
budget: &Arc<AtomicUsize>,
workers: &mut Vec<Worker>,
timeout: Duration,
) {
workers.retain(|worker| !worker.is_finished());
workers.retain(|worker| !worker.thread.is_finished());
if workers.len() >= MAX_CONNECTIONS {
return;
// A client keeping slots it doesn't use can't lock others out (#1110): the connection idle
// longest (between requests or in `events.poll`; clients reconnect) gives its slot up. One
// whose request the UI is running keeps it.
let idle = |w: &Worker| *w.idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let longest = workers.iter().enumerate().filter_map(|(i, w)| Some((i, idle(w)?))).min_by_key(|(_, since)| *since);
let Some((i, _)) = longest else { return };
let _ = workers.swap_remove(i).stream.shutdown(Shutdown::Both);
}
let Ok(handle) = stream.try_clone() else { return };
let idle: Idle = Arc::new(Mutex::new(Some(Instant::now())));
let (budget, mine) = (budget.clone(), idle.clone());
match std::thread::Builder::new().name("figcraft-control-conn".into()).spawn(move || {
let _ = serve_with_events(stream, queue, ctx, events, timeout);
let _ = serve_with_events(stream, queue, ctx, events, &budget, &mine, timeout);
}) {
Ok(worker) => workers.push(worker),
Ok(thread) => workers.push(Worker { thread, stream: handle, idle }),
Err(e) => log::error!("control connection thread: {e}"),
}
}
/// Bytes of a line reserved from the shared budget, given back when dropped.
struct Held<'a> {
budget: &'a AtomicUsize,
bytes: usize,
}
impl Drop for Held<'_> {
fn drop(&mut self) {
self.budget.fetch_sub(self.bytes, Ordering::SeqCst);
}
}
/// What [`read_line`] read.
enum Line<'a> {
End,
/// A line, its newline included if it had one; longer than [`MAX_LINE`] when it was too long.
Read(Held<'a>),
/// The connections hold [`MAX_IN_FLIGHT`] bytes already.
Busy,
}
/// Read a line of at most [`MAX_LINE`] bytes plus its newline into `line`, taking its bytes from
/// `budget` as they arrive.
fn read_line<'a>(reader: &mut impl BufRead, line: &mut Vec<u8>, budget: &'a AtomicUsize) -> std::io::Result<Line<'a>> {
let mut held = Held { budget, bytes: 0 };
loop {
let buf = reader.fill_buf()?;
if buf.is_empty() {
return Ok(if line.is_empty() { Line::End } else { Line::Read(held) });
}
let room = MAX_LINE + 1 - line.len();
let (take, done) = match buf.iter().position(|b| *b == b'\n') {
Some(i) if i < room => (i + 1, true),
_ => (buf.len().min(room), false),
};
if budget.try_update(Ordering::SeqCst, Ordering::SeqCst, |used| used.checked_add(take).filter(|t| *t <= MAX_IN_FLIGHT)).is_err() {
return Ok(Line::Busy);
}
held.bytes += take;
line.extend_from_slice(&buf[..take]);
reader.consume(take);
if done || line.len() > MAX_LINE {
return Ok(Line::Read(held));
}
}
}
/// Serve one control connection: read bounded JSON lines, reject oversized frames and a
/// full queue, queue one request, wait under its gate, and write one reply. Non-JSON input
/// answers with an error and closes the connection so HTTP body lines cannot become commands.
/// Serve a connection with a private event log (the tests; the app shares its session's log).
#[cfg(test)]
fn serve(out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> std::io::Result<()> {
serve_with_events(out, queue, ctx, Arc::new(EventLog::default()), timeout)
serve_with_events(out, queue, ctx, Arc::new(EventLog::default()), &AtomicUsize::new(0), &Mutex::new(None), timeout)
}
fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc<EventLog>, timeout: Duration) -> std::io::Result<()> {
fn serve_with_events(
mut out: TcpStream,
queue: Queue,
ctx: CtxSlot,
events: Arc<EventLog>,
budget: &AtomicUsize,
idle: &Mutex<Option<Instant>>,
timeout: Duration,
) -> std::io::Result<()> {
out.set_read_timeout(Some(timeout))?;
out.set_write_timeout(Some(timeout))?;
let mut reader = BufReader::new(out.try_clone()?);
let mut line = Vec::new();
let set_idle = |since: Option<Instant>| *idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = since;
loop {
line.clear();
if (&mut reader).take((MAX_LINE + 1) as u64).read_until(b'\n', &mut line)? == 0 {
break;
}
set_idle(Some(Instant::now()));
// A new buffer each time: an idle connection keeps no large line's capacity.
let mut line = Vec::new();
let _held = match read_line(&mut reader, &mut line, budget)? {
Line::End => break,
Line::Read(held) => held,
Line::Busy => {
let error = "the control server holds too many large requests: retry when they are answered";
writeln!(out, "{}", json!({"id": null, "ok": false, "error": error}))?;
break;
}
};
if line.last() == Some(&b'\n') {
line.pop();
}
@@ -205,6 +294,7 @@ fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc
continue;
}
let needs_frame = matches!(method.as_str(), "ui.screenshot" | "ui.input");
set_idle(None);
pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, state: gate.clone() });
drop(pending);
if let Some(c) = ctx.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {
+59 -29
View File
@@ -277,46 +277,54 @@ fn a_failed_accept_waits_before_the_next() {
assert_eq!(waits, 3, "one wait per failed accept");
}
/// With every slot taken, a new client gets the slot of the connection idle longest, never one
/// whose request the UI is running (#1110), and finished slots are reused.
#[test]
fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() {
fn connection_limit_frees_the_longest_idle_slot_and_reuses_finished_ones() {
let pending = queue();
let ctx = context();
let budget = Arc::new(AtomicUsize::new(0));
let mut workers = Vec::new();
let mut clients = Vec::new();
let spawn = |server, workers: &mut Vec<Worker>| {
let events = Arc::new(figcraft_engine::events::EventLog::default());
spawn_connection(server, pending.clone(), ctx.clone(), events, &budget, workers, Duration::from_secs(5));
};
for _ in 0..MAX_CONNECTIONS {
let (client, server) = pair();
spawn_connection(
server,
pending.clone(),
ctx.clone(),
Arc::new(figcraft_engine::events::EventLog::default()),
&mut workers,
Duration::from_secs(5),
);
spawn(server, &mut workers);
clients.push(client);
// Each idle from its own moment.
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(workers.len(), MAX_CONNECTIONS);
let (mut extra, server) = pair();
spawn_connection(
server,
pending.clone(),
ctx.clone(),
Arc::new(figcraft_engine::events::EventLog::default()),
&mut workers,
Duration::from_secs(5),
);
assert_eq!(extra.read(&mut [0]).unwrap(), 0);
assert_eq!(workers.len(), MAX_CONNECTIONS);
for client in clients {
client.shutdown(Shutdown::Both).unwrap();
}
// The oldest connection waits for the UI: it is busy, not idle.
clients[0].write_all(b"{\"id\":1,\"method\":\"ui.inspect\"}\n").unwrap();
let start = Instant::now();
while workers.iter().any(|worker| !worker.is_finished()) {
while pending.lock().unwrap().is_empty() {
assert!(start.elapsed() < Duration::from_secs(5));
std::thread::sleep(Duration::from_millis(1));
}
let (mut extra, server) = pair();
spawn(server, &mut workers);
assert_eq!(workers.len(), MAX_CONNECTIONS);
assert_eq!(clients[1].read(&mut [0]).unwrap(), 0, "the connection idle longest was closed");
extra.write_all(b"invalid\n").unwrap();
assert_eq!(reply(&mut BufReader::new(extra.try_clone().unwrap()))["ok"], false, "the new client is served");
assert!(pending.lock().unwrap().len() == 1, "the busy request is still queued");
pending.lock().unwrap().clear();
for client in clients.iter().skip(2) {
client.shutdown(Shutdown::Both).unwrap();
}
let _ = clients[0].shutdown(Shutdown::Both);
// The busy worker waits out its request's 5 s timeout before it sees the shutdown.
let start = Instant::now();
while workers.iter().any(|worker| !worker.thread.is_finished()) {
assert!(start.elapsed() < Duration::from_secs(15));
std::thread::sleep(Duration::from_millis(5));
}
let (mut client, server) = pair();
spawn_connection(server, pending, ctx, Arc::new(figcraft_engine::events::EventLog::default()), &mut workers, Duration::from_secs(5));
spawn(server, &mut workers);
assert_eq!(workers.len(), 1);
client.write_all(b"invalid\n").unwrap();
assert_eq!(reply(&mut BufReader::new(client.try_clone().unwrap()))["ok"], false);
@@ -325,7 +333,26 @@ fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() {
// returns Ok. Closing the client is what the worker is waiting for, so the result is moot:
// the other shutdowns in this file run while the peer is still open and stay checked.
let _ = client.shutdown(Shutdown::Both);
workers.pop().unwrap().join().unwrap();
workers.pop().unwrap().thread.join().unwrap();
}
/// Lines are counted against one budget shared by every connection while they are held (#1111):
/// a line past it is refused before it is read whole, and a line answered gives its bytes back.
#[test]
fn lines_past_the_shared_budget_are_refused_and_given_back_when_done() {
let frame = b"{\"id\":1,\"method\":\"ui.inspect\"}\n".to_vec();
let nearly_full = AtomicUsize::new(MAX_IN_FLIGHT - 4);
let mut line = Vec::new();
assert!(matches!(read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &nearly_full).unwrap(), Line::Busy));
assert_eq!(nearly_full.load(Ordering::SeqCst), MAX_IN_FLIGHT - 4, "nothing kept from the refused line");
let budget = AtomicUsize::new(0);
let mut line = Vec::new();
{
let Line::Read(_held) = read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &budget).unwrap() else { panic!("read") };
assert_eq!(line, frame);
assert!(budget.load(Ordering::SeqCst) >= frame.len(), "held while it is served");
}
assert_eq!(budget.load(Ordering::SeqCst), 0, "given back");
}
#[test]
@@ -358,7 +385,8 @@ fn events_poll_is_answered_without_the_ui_queue() {
let log = Arc::new(figcraft_engine::events::EventLog::default());
log.push("comment.added", "Doc", None, json!({"commentId": 7}));
let l = log.clone();
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
let worker =
std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5)));
client.write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":0,\"timeoutMs\":0}}\n").unwrap();
let mut reader = BufReader::new(client);
let r = reply(&mut reader);
@@ -484,7 +512,8 @@ fn events_poll_rejects_an_unknown_topic_without_the_ui_queue() {
let q = pending.clone();
let log = Arc::new(figcraft_engine::events::EventLog::default());
let l = log.clone();
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
let worker =
std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5)));
let mut reader = BufReader::new(client);
reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"topics\":[\"nope\"],\"timeoutMs\":0}}\n").unwrap();
let r = reply(&mut reader);
@@ -503,7 +532,8 @@ fn events_poll_reports_reset_for_a_cursor_ahead_of_the_log() {
log.push("comment.added", "Doc", None, json!({"commentId": 1}));
let q = queue();
let l = log.clone();
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
let worker =
std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5)));
let mut reader = BufReader::new(client);
reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":2,\"timeoutMs\":0}}\n").unwrap();
let r = reply(&mut reader);
+22 -7
View File
@@ -4,7 +4,15 @@
//! first, on Windows too. A Vulkan driver that faults there takes the app down as the window opens:
//! an access violation inside the vendor's driver, which no guard of ours can catch (seen on a laptop
//! with two AMD GPUs whose drivers were years apart). Direct3D 12 is part of Windows, so on Windows
//! wgpu is offered Direct3D 12, and OpenGL for hardware without a Direct3D 12 driver.
//! wgpu is offered Direct3D 12 alone at first.
//!
//! Not OpenGL beside it: wgpu's OpenGL backend on Windows makes a hidden window on a thread of its
//! own that handles no window messages, as soon as the instance is created, whichever backend then
//! draws. Windows hands an input language change (Alt+Shift or Win+Space to a Russian layout,
//! #2264) to every thread of the app with a window, so the main window waited on that hidden one
//! and the app hung. Direct3D 12 always lists its software adapter (WARP), so a GPU with no
//! Direct3D 12 driver (Intel Haswell, which wgpu leaves out of Direct3D 12, and older ones) now
//! draws on WARP rather than on its OpenGL driver.
//!
//! Two shader compilers lost the device before the window opened ("Parent device is lost", #965,
//! #1438), both on wgpu's indirect-call validation shaders, which wgpu compiles with every device:
@@ -14,10 +22,12 @@
//! out: FigCraft draws nothing indirectly, so they would check nothing.
//!
//! When the graphics still fail before the window's first frame, the app starts again with the
//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; and last the first
//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; then the first
//! backends again with lower requirements on the power-saving GPU (macOS has no OpenGL in wgpu, so
//! that is its only other try). The attempts are a fixed list, so this ends; the message the last
//! one shows names what was tried.
//! that is its only other try); and on Windows last OpenGL with lower requirements, each on its own
//! so that OpenGL starts only when Direct3D 12 failed. An OpenGL start on Windows can still hang on
//! an input language change. The attempts are a fixed list, so this ends; the message the last one
//! shows names what was tried.
//!
//! `WGPU_BACKEND` (`dx12`, `vulkan`, `gl`, `metal`) still names the backend on every system, and
//! is then the one attempt. `WGPU_DX12_COMPILER` and `WGPU_VALIDATION_INDIRECT_CALL` still choose
@@ -36,8 +46,9 @@ pub const ATTEMPT_ENV: &str = "FIGCRAFT_GRAPHICS_ATTEMPT";
/// begins once the first was presented.
pub const STARTUP_FRAMES: u64 = 2;
/// Direct3D 12, then OpenGL: wgpu ranks a hardware GPU on either ahead of Direct3D's software one.
const WINDOWS: Backends = Backends::DX12.union(Backends::GL);
/// Direct3D 12 alone: an OpenGL instance beside it hangs the window on an input language change
/// (see the module docs).
const WINDOWS: Backends = Backends::DX12;
/// The graphics APIs by name, in the order the startup message lists them.
const NAMES: [(Backends, &str); 4] =
@@ -54,7 +65,8 @@ pub struct Attempt {
/// The ways to start, in order: only `WGPU_BACKEND`'s backends (`requested`) when it is set;
/// otherwise [`WINDOWS`] on Windows, else eframe's `defaults`, then Vulkan on Windows, OpenGL
/// except on macOS, and those first backends again with lower requirements.
/// except on macOS, those first backends again with lower requirements, and on Windows OpenGL with
/// lower requirements.
pub fn attempts(requested: Option<Backends>, windows: bool, macos: bool, defaults: Backends) -> Vec<Attempt> {
let normal = |backends| Attempt { backends, lower: false };
if let Some(requested) = requested {
@@ -69,6 +81,9 @@ pub fn attempts(requested: Option<Backends>, windows: bool, macos: bool, default
list.push(normal(Backends::GL));
}
list.push(Attempt { backends: first, lower: true });
if windows {
list.push(Attempt { backends: Backends::GL, lower: true });
}
list
}
+15 -5
View File
@@ -1,6 +1,7 @@
//! The graphics attempts: no Vulkan on Windows at first (a faulting Vulkan driver crashed the app
//! as its window opened), another backend and then lower requirements when the graphics fail
//! before the first frame (#965, #1438), and never more starts than attempts.
//! as its window opened), never OpenGL beside Direct3D 12 there (its hidden window hung the app on
//! an input language change, #2264), another backend and then lower requirements when the graphics
//! fail before the first frame (#965, #1438), and never more starts than attempts.
use std::time::Duration;
@@ -13,8 +14,6 @@ use crate::graphics::{ATTEMPT_ENV, Attempt, Plan, STARTUP_FRAMES, apply, attempt
/// What eframe offers when `WGPU_BACKEND` isn't set.
const DEFAULTS: Backends = Backends::PRIMARY.union(Backends::GL);
const DX12_GL: Backends = Backends::DX12.union(Backends::GL);
const fn normal(backends: Backends) -> Attempt {
Attempt { backends, lower: false }
}
@@ -26,10 +25,21 @@ const fn lower(backends: Backends) -> Attempt {
#[test]
fn windows_starts_on_direct3d_then_vulkan_then_opengl_then_lower_requirements() {
let list = attempts(None, true, false, DEFAULTS);
assert_eq!(list, [normal(DX12_GL), normal(Backends::VULKAN), normal(Backends::GL), lower(DX12_GL)]);
assert_eq!(list, [normal(Backends::DX12), normal(Backends::VULKAN), normal(Backends::GL), lower(Backends::DX12), lower(Backends::GL)]);
assert!(!list[0].backends.contains(Backends::VULKAN), "a Vulkan driver that faults can't be picked at first");
}
#[test]
fn windows_never_starts_opengl_beside_direct3d_but_still_falls_back_to_it() {
let list = attempts(None, true, false, DEFAULTS);
for attempt in &list {
assert!(!attempt.backends.contains(Backends::DX12 | Backends::GL), "OpenGL's hidden window hangs a Direct3D 12 start: {attempt:?}");
}
assert!(list.iter().any(|a| a.backends.contains(Backends::VULKAN)), "Vulkan is still tried");
assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && !a.lower), "OpenGL is still tried");
assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && a.lower), "and with lower requirements");
}
#[test]
fn linux_falls_back_to_opengl_then_lower_requirements() {
assert_eq!(attempts(None, false, false, DEFAULTS), [normal(DEFAULTS), normal(Backends::GL), lower(DEFAULTS)]);
+7
View File
@@ -144,4 +144,11 @@ display_name = "Terra854"
[people.andrejskvorc]
real_name = "Andrej Skvorc"
[people.victorazesc]
sync_github_name = true
[people.brytoncooper]
real_name = "Bryton Cooper"
display_name = "Bryton Cooper"
sync_github_name = true
+4 -3
View File
@@ -19,12 +19,13 @@ web-time = "1"
# Native transport: blocking tungstenite with a reader and a writer thread per connection.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tungstenite = { version = "0.30", default-features = false, features = ["handshake"] }
# `wss://`: TLS with ring as the crypto provider and Mozilla's root certificates compiled in (no
# OS certificate store, no OpenSSL). Over our own split reader/writer stream (`tls.rs`), so not
# tungstenite's single-owner TLS stream.
# `wss://`: TLS with ring as the crypto provider, the public root certificates of webpki-roots
# compiled in and the operating system's certificate store read (no OpenSSL). Over our own split
# reader/writer stream (`tls.rs`), so not tungstenite's single-owner TLS stream.
rustls = { version = "0.23", default-features = false, features = ["std", "ring", "tls12", "logging"] }
rustls-pki-types = { version = "1", features = ["std"] }
webpki-roots = "1"
rustls-native-certs = "0.8"
getrandom = "0.4"
base64 = { workspace = true }
+1 -1
View File
@@ -687,7 +687,7 @@ fn welcomes_are_packed_only_for_clients_that_read_them() {
};
message::unpack(&mut delta_welcome, 64 << 20).unwrap();
let delta_doc = Client::join(delta_welcome).unwrap().document().clone();
let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone();
let plain_doc = figcraft_collab::Replica::from_snapshot(plain).unwrap().document().clone();
assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document");
host.stop();
}
+17 -4
View File
@@ -1,6 +1,7 @@
//! TLS for `wss://` addresses (native): rustls with ring, trusting Mozilla's root certificates
//! (compiled in) plus any in the PEM file `FIGCRAFT_CA_FILE` names (a private authority or a
//! self-signed server). Certificates are always verified.
//! TLS for `wss://` addresses (native): rustls with ring, trusting the public root certificates of
//! webpki-roots (compiled in), the authorities this computer trusts (its certificate store, unless
//! `FIGCRAFT_NO_SYSTEM_ROOTS` is set) and any in the PEM file `FIGCRAFT_CA_FILE` names (a private
//! authority or a self-signed server). Certificates are always verified.
//!
//! A connection's reader and writer threads share one TLS session ([`Tls`]), each holding it only
//! to decrypt or encrypt: the reader waits for bytes on its own socket handle without it, and a
@@ -20,6 +21,9 @@ use rustls::{CertificateError, ClientConfig, ClientConnection, RootCertStore};
/// The variable naming a PEM file of extra certificate authorities to trust.
pub const CA_FILE: &str = "FIGCRAFT_CA_FILE";
/// The variable that, set, leaves the operating system's certificate store out.
pub const NO_SYSTEM_ROOTS: &str = "FIGCRAFT_NO_SYSTEM_ROOTS";
/// One connection's TLS session, shared by its reader and writer.
pub type Tls = Arc<Mutex<ClientConnection>>;
@@ -44,7 +48,7 @@ pub fn handshake(stream: &TcpStream, host: &str) -> Result<Tls, String> {
fn explain(host: &str, e: &io::Error) -> String {
let why = |c: &CertificateError| match c {
CertificateError::UnknownIssuer => format!(
"isn't signed by an authority this app trusts (for a private or self-signed certificate, set {CA_FILE} to its authority's PEM file)"
"isn't signed by an authority this app trusts (for a private or self-signed certificate, add its authority to this computer's trusted certificates, or set {CA_FILE} to its authority's PEM file)"
),
CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => "is for another name".into(),
CertificateError::Expired | CertificateError::ExpiredContext { .. } => "has expired".into(),
@@ -67,6 +71,15 @@ fn config() -> Result<Arc<ClientConfig>, String> {
fn make_config() -> Result<Arc<ClientConfig>, String> {
let mut roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
// A private authority an administrator installed (a company's, a proxy's) is trusted as the
// computer's other apps trust it (#2342). An unreadable store adds nothing.
if std::env::var_os(NO_SYSTEM_ROOTS).is_none() {
let system = rustls_native_certs::load_native_certs();
for e in &system.errors {
log::warn!("system certificate store: {e}");
}
roots.add_parsable_certificates(system.certs);
}
if let Some(path) = std::env::var_os(CA_FILE) {
let shown = std::path::Path::new(&path).display().to_string();
let certs: Vec<CertificateDer> = CertificateDer::pem_file_iter(&path)
+1 -1
View File
@@ -18,7 +18,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() {
// A joiner's copy, built from the snapshot, is a board with the sticky's metadata.
let snap = host.snapshot().unwrap();
assert!(snap.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Kind, .. })));
let joiner = Replica::from_snapshot(&snap).unwrap();
let joiner = Replica::from_snapshot(snap).unwrap();
assert_eq!(joiner.document().kind, FileKind::Board);
assert_eq!(joiner.document().node(a).unwrap().board, host.document().node(a).unwrap().board);
// Re-attaching a connector's end is one property write, the same after the wire.
+3
View File
@@ -45,6 +45,9 @@ impl<'de> Deserialize<'de> for Json {
f.write_str("JSON text")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Json, E> {
// A full snapshot holds one of these per property: while one is read, on the web
// the heap grows in large steps ([`crate::heap`]).
crate::heap::keep_ahead();
// serde_json caps nesting depth, so hostile input can't overflow the stack.
serde_json::from_str(v).map(Json).map_err(E::custom)
}
+2 -2
View File
@@ -90,7 +90,7 @@ impl Client {
return Err(Error::Protocol("expected a welcome with the document".into()));
};
let mut confirmed = match catch_up {
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?,
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(snapshot)?,
CatchUp::DeltaSnapshot(bytes) => {
let limits = crate::Limits::default();
crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?
@@ -604,7 +604,7 @@ impl Client {
}
}
CatchUp::Snapshot(snapshot) => {
let mut confirmed = Replica::from_snapshot(&snapshot)?;
let mut confirmed = Replica::from_snapshot(snapshot)?;
confirmed.document_mut().set_client_id(self.id);
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
}
@@ -40,6 +40,7 @@ pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -
/// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated
/// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`.
pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
let _reading = crate::heap::reading();
let declared = parse_header(bytes)?;
if declared > max_bytes {
return Err(Error::TooLarge(max_bytes));
@@ -280,6 +281,7 @@ impl<'de> Visitor<'de> for VectorsSeed<'_> {
}
self.0.vector_sizes.push(size);
self.0.vectors.push(figcraft_doc::Shared::new(net));
crate::heap::keep_ahead();
}
Ok(())
}
@@ -313,6 +315,7 @@ impl<'de> Visitor<'de> for RecordsSeed<'_> {
if let Err(err) = self.0.ingest_record(rec) {
return Err(self.0.fail(err));
}
crate::heap::keep_ahead();
}
Ok(())
}
+2 -2
View File
@@ -163,7 +163,7 @@ fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() {
let replica = Replica::new(doc);
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap();
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality");
assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity");
}
@@ -311,7 +311,7 @@ fn full_metadata_and_design_review_roundtrip_matches_legacy_json() {
doc.take_dirty();
let replica = Replica::new(doc);
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII);
assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity");
+4 -4
View File
@@ -77,7 +77,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() {
// A snapshot holding settings over the limits (an old file's) opens clamped to what fits:
// the preset, grid and disabled rules exactly as saved, the lists to the limit.
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
assert!(clamped, "the settings needed clamping, and the caller is told");
assert_eq!(left_out, 0, "nothing needed leaving out");
let cfg = &r2.document().design_review;
@@ -99,7 +99,7 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them
assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}");
// A snapshot with a longer list opens with the ones that fit, not without the settings.
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
assert!(clamped);
assert_eq!(left_out, 0, "nothing needed leaving out");
let cfg = &r2.document().design_review;
@@ -232,9 +232,9 @@ fn snapshots_rebuild_the_same_state() {
b.styles.push(style("s"));
let r = diff(&a, &b).unwrap().replica;
let snap = r.snapshot().unwrap();
let back = Replica::from_snapshot(&snap).unwrap();
let back = Replica::from_snapshot(snap).unwrap();
assert_eq!(back, r);
assert!(Replica::from_snapshot(&[]).is_err(), "a snapshot needs a page");
assert!(Replica::from_snapshot(Vec::new()).is_err(), "a snapshot needs a page");
}
#[test]
+153
View File
@@ -0,0 +1,153 @@
//! Room kept ahead in a web page's heap while a large file is read (#2041).
//!
//! The allocator Rust links on `wasm32-unknown-unknown` (dlmalloc) asks the page for more memory
//! one 64 KiB page at a time whenever it runs out, and the browser changes the protection of the
//! whole memory at every grow. Joining a 121k-layer file grew the heap by about 1.5 GB in about
//! 20,000 grows; their total cost rises with the square of the heap size and took minutes on
//! Windows. Memory the allocator got is reused once freed and never handed back, so allocating one
//! large block and freeing it at once leaves that much room for what follows, for one grow.
//! [`keep_ahead`] does that whenever the memory grew since its last call: half the heap again, at
//! most [`MAX_STEP`], so the heap grows in a few dozen steps.
//!
//! It acts only while a snapshot is read ([`reading`]): the hooks sit in code every live edit runs
//! too (applying a batch, reading a property value), and an edit never reserves memory. Off the web
//! it does nothing. Between the steps of a read it only reads the memory size unless the memory
//! grew.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// A WebAssembly memory page.
const PAGE: usize = 64 * 1024;
/// The most room reserved at once: past a heap of twice this, the heap grows by this much a step
/// rather than by half, so a page close to the browser's limit doesn't ask for more than it needs.
const MAX_STEP: usize = 256 << 20;
/// How many bytes of room to reserve when the memory is `now` pages and was `seen` pages at the
/// last look (0: never looked, so only the size is noted).
fn room(seen: usize, now: usize) -> Option<usize> {
(seen != 0 && now > seen).then(|| (now.saturating_mul(PAGE) / 2).min(MAX_STEP))
}
/// How many snapshot reads are under way (a full snapshot is applied inside a welcome's read).
static READING: AtomicUsize = AtomicUsize::new(0);
/// The memory size at the last look, in pages.
static SEEN: AtomicUsize = AtomicUsize::new(0);
/// Set when a reservation fails near the browser's memory limit so the rest of this read does not
/// retry failing large reservations on every subsequent growth.
static EXHAUSTED: AtomicBool = AtomicBool::new(false);
/// A snapshot read under way: [`keep_ahead`] acts until it is dropped, on error paths too.
pub(crate) struct Reading(());
impl Drop for Reading {
fn drop(&mut self) {
READING.fetch_sub(1, Ordering::Relaxed);
}
}
/// Start a snapshot read: growth from here on gets room kept ahead.
pub(crate) fn reading() -> Reading {
if READING.fetch_add(1, Ordering::Relaxed) == 0 {
EXHAUSTED.store(false, Ordering::Relaxed);
SEEN.store(memory_pages().unwrap_or(0), Ordering::Relaxed);
}
Reading(())
}
/// Reserve room ahead in the heap if a snapshot is being read and the memory grew since the last
/// call (see the module docs).
pub(crate) fn keep_ahead() {
if READING.load(Ordering::Relaxed) == 0 || EXHAUSTED.load(Ordering::Relaxed) {
return;
}
let Some(now) = memory_pages() else { return };
if let Some(bytes) = room(SEEN.load(Ordering::Relaxed), now) {
let mut block: Vec<u8> = Vec::new();
// Near the browser's memory limit this fails and nothing changes: stop trying large
// reservations for the rest of this read and let the heap grow as needed.
if block.try_reserve_exact(bytes).is_ok() {
// Opaque to the optimizer, which could otherwise drop an allocation nothing reads.
drop(std::hint::black_box(block));
} else {
EXHAUSTED.store(true, Ordering::Relaxed);
}
}
SEEN.store(memory_pages().unwrap_or(now), Ordering::Relaxed);
}
/// The size of the page's memory in pages (`None` off the web: the system allocator there maps
/// large blocks on its own).
fn memory_pages() -> Option<usize> {
#[cfg(target_arch = "wasm32")]
{
Some(core::arch::wasm32::memory_size(0))
}
#[cfg(not(target_arch = "wasm32"))]
{
None
}
}
#[cfg(test)]
mod tests {
use super::{PAGE, room};
/// A heap that grows by whole pages when an allocation doesn't fit, as the web allocator's.
struct Heap {
pages: usize,
free: usize,
grows: usize,
seen: usize,
}
impl Heap {
fn alloc(&mut self, n: usize) {
if self.free < n {
let pages = (n - self.free).div_ceil(PAGE);
self.pages += pages;
self.free += pages * PAGE;
self.grows += 1;
}
self.free -= n;
}
fn keep_ahead(&mut self) {
if let Some(bytes) = room(self.seen, self.pages) {
self.alloc(bytes);
self.free += bytes;
}
self.seen = self.pages;
}
}
/// Reading a file the size of #2041's (46 MB to 1.66 GB in small allocations) grows the heap
/// in a few dozen steps with room kept ahead between allocations, not in one step per page.
#[test]
fn room_kept_ahead_turns_page_by_page_growth_into_a_few_steps() {
let run = |ahead: bool| {
let mut h = Heap { pages: (46 << 20) / PAGE, free: 0, grows: 0, seen: 0 };
while h.pages * PAGE < 1660 << 20 {
h.alloc(400);
if ahead {
h.keep_ahead();
}
}
h.grows
};
let (plain, ahead) = (run(false), run(true));
assert!(plain > 20_000, "page by page: {plain} grows");
assert!(ahead * 200 < plain, "{ahead} grows with room kept ahead, {plain} without");
}
/// The first look only notes the size, and an unchanged or smaller memory reserves nothing.
#[test]
fn room_is_reserved_only_after_the_memory_grew() {
assert_eq!(room(0, 1000), None);
assert_eq!(room(1000, 1000), None);
assert!(room(1000, 1001).is_some());
assert!(room(1000, 1001) <= room(5000, 5001), "more room for a larger heap");
}
}
+2 -2
View File
@@ -169,7 +169,7 @@ fn a_snapshot_holding_an_image_the_checks_refuse_still_opens_without_it() {
let mut snapshot = crate::Replica::new(crate::sim_tests::base()).snapshot().unwrap();
let (key, bytes) = forged();
snapshot.push(put(&key, 2, 1, bytes));
let r = crate::Replica::from_snapshot(&snapshot).expect("the snapshot opens");
let r = crate::Replica::from_snapshot(snapshot).expect("the snapshot opens");
assert!(!r.document().images.contains_key(&key));
}
@@ -254,5 +254,5 @@ fn a_snapshot_with_a_broken_layer_change_still_fails_to_open() {
// A property of a layer that isn't there: an error when applied (unlike deleting it).
let missing = figcraft_doc::NodeId(u64::MAX);
snapshot.push(Change::Set { id: missing, prop: crate::change::Prop::Name, value: Json(json!("x")) });
assert!(crate::Replica::from_snapshot(&snapshot).is_err());
assert!(crate::Replica::from_snapshot(snapshot).is_err());
}
+1
View File
@@ -28,6 +28,7 @@ pub mod delta_snapshot;
mod diff;
mod docprops;
pub mod frac;
mod heap;
mod history;
pub mod merge;
pub mod message;
+1
View File
@@ -1192,6 +1192,7 @@ pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> {
if let ServerMsg::Welcome { catch_up, .. } = msg {
match catch_up {
CatchUp::Packed(packed) => {
let _reading = crate::heap::reading();
let mut raw = Vec::new();
let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
flate2::read::DeflateDecoder::new(packed.as_slice())
+1 -1
View File
@@ -57,7 +57,7 @@ fn a_packed_welcome_is_much_smaller_and_reads_back_the_same() {
assert_eq!(back, plain);
// The client opens the same document from it.
let ServerMsg::Welcome { catch_up: CatchUp::Snapshot(changes), .. } = &plain else { panic!("not a snapshot") };
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes).unwrap().document());
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes.clone()).unwrap().document());
}
#[test]
+9 -4
View File
@@ -70,8 +70,10 @@ impl Replica {
Replica { doc, positions }
}
/// Rebuild a replica from a [`snapshot`](Self::snapshot).
pub fn from_snapshot(changes: &[Change]) -> Result<Replica, Error> {
/// Rebuild a replica from a [`snapshot`](Self::snapshot). It takes the changes, so a large
/// file's snapshot isn't copied on the way in (#2041): the few that need it (review settings
/// past the limits) are rewritten in place.
pub fn from_snapshot(changes: Vec<Change>) -> Result<Replica, Error> {
Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r)
}
@@ -81,9 +83,9 @@ impl Replica {
/// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened,
/// because a session whose settings had to be clamped can no longer replay its saved batches
/// for clients that resume (they hold the value past the limits).
pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> {
pub(crate) fn from_snapshot_leaving_out(mut changes: Vec<Change>) -> Result<(Replica, usize, bool), Error> {
let _reading = crate::heap::reading();
let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() };
let mut changes = changes.to_vec();
let clamped = docprops::clamp_snapshot_design_review(&mut changes);
let left_out = r.apply_kept(&mut changes, Change::is_image)?;
if r.doc.pages.is_empty() {
@@ -199,6 +201,9 @@ impl Replica {
let (mut relist, mut relist_all) = (BTreeSet::new(), false);
let mut index = docprops::Index::default();
for c in changes {
// While a snapshot is applied, on the web the heap grows in large steps instead of
// page by page ([`crate::heap`]); a live batch doesn't reserve anything.
crate::heap::keep_ahead();
match self.apply_one(c, &mut out, &mut index) {
Ok(Relist::No) => {}
Ok(Relist::Page(p)) => {
+1 -1
View File
@@ -214,7 +214,7 @@ impl Server {
/// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped
/// (clients then catch up with a snapshot).
pub fn restore(state: SessionState, token: impl Into<String>, limits: Limits) -> Result<Server, Error> {
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?;
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(state.snapshot)?;
let mut server = Server::new(replica.document().clone(), token, limits);
server.state = replica;
server.session = state.session;
+2 -1
View File
@@ -14,7 +14,7 @@ pub fn shape_path(n: &Node) -> Option<BezPath> {
| NodeKind::Component { .. }
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. } => figcraft_geom::rounded_rect(w, h, c.radii, c.smoothing),
| NodeKind::Section { .. } => figcraft_geom::styled_rect(w, h, c.radii, c.smoothing, c.style),
NodeKind::Slice => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0),
NodeKind::Ellipse { start, sweep, inner } => figcraft_geom::ellipse(w, h, *start, *sweep, *inner),
NodeKind::Polygon { count } => figcraft_geom::smoothed_polygon(&figcraft_geom::polygon_points(w, h, *count), c.radii[0], c.smoothing),
@@ -84,6 +84,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
}
NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. } | NodeKind::Section { .. } => {
n.local_rect().inflate(tol_l, tol_l).contains(lp)
&& (n.corners.style.is_round() || shape_path(n).is_some_and(|path| path.contains(lp) || (tol_l > 0.0 && near_path(&path, lp, tol_l))))
}
NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => {
let drawn = drawn_network(network, n.corners.smoothing);
+1 -1
View File
@@ -719,7 +719,7 @@ impl Node {
let blend = if kind.is_container() { BlendMode::PassThrough } else { BlendMode::Normal };
let clip = matches!(kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. });
let corners = match &kind {
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], smoothing: 0.0 },
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], ..Corners::default() },
_ => Corners::default(),
};
Self {
+2
View File
@@ -1004,6 +1004,8 @@ impl Effect {
pub struct Corners {
pub radii: [f64; 4],
pub smoothing: f64,
#[serde(skip_serializing_if = "figcraft_geom::CornerStyle::is_round")]
pub style: figcraft_geom::CornerStyle,
}
impl Corners {
+14
View File
@@ -305,6 +305,20 @@ fn collections_and_modes_resolve_stored_ids_never_by_name() {
assert_eq!(theme.find_mode("Dark").map(|m| m.id.as_str()), Some("m2"));
}
#[test]
fn corner_style_roundtrips_and_old_radii_default_to_round() {
use figcraft_geom::CornerStyle;
let legacy = serde_json::json!({"radii": [2.0, 4.0, 6.0, 8.0], "smoothing": 0.4});
let mut corners: crate::Corners = serde_json::from_value(legacy.clone()).unwrap();
assert_eq!(corners.style, CornerStyle::Round);
assert_eq!(serde_json::to_value(corners).unwrap(), legacy);
for style in [CornerStyle::Chamfer, CornerStyle::Concave] {
corners.style = style;
let saved = serde_json::to_value(corners).unwrap();
assert_eq!(serde_json::from_value::<crate::Corners>(saved).unwrap(), corners);
}
}
#[test]
fn serde_roundtrip_and_repair() {
let mut d = Document::new("x");
+28
View File
@@ -125,6 +125,34 @@ fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() {
assert_eq!(s.message, None);
}
/// #2178: through the API, the sizing an edit changes on another layer comes back in `warnings`
/// (the canvas shows it as a notice), naming that layer; an edit that changes no other layer's
/// sizing has none.
#[test]
fn node_set_warns_about_the_other_layers_it_turns_fixed() {
let mut s = Session::new();
let root = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let menu = rect(&mut s, root, 200.0, 100.0, "#222222");
let content = rect(&mut s, root, 600.0, 900.0, "#FFFFFF");
let warnings = |v: Value| v["warnings"].as_array().cloned().unwrap_or_default();
let names = |w: &[Value], n: NodeId, key: &str| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with(&format!("{n} ")) && w.contains(key)));
let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingV": "fill"}})).unwrap());
assert!(w.is_empty(), "a non-Fill sibling is left, the root keeps hugging: {w:?}");
let w = warnings(s.execute("node.set", &json!({"id": content, "props": {"sizingV": "fill"}})).unwrap());
assert_eq!(sizing(&s, root).1, Sizing::Fixed);
assert!(names(&w, root, "sizingV"), "the root turned Fixed: {w:?}");
assert!(!names(&w, content, "sizingV"), "not the layer edited: {w:?}");
// Along the row: the menu filling its width turns the root's width Fixed; hugging it again
// turns the menu's width Fixed.
let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingH": "fill"}})).unwrap());
assert!(names(&w, root, "sizingH"), "{w:?}");
let w = warnings(s.execute("node.set", &json!({"id": root, "props": {"sizingH": "hug"}})).unwrap());
assert_eq!(sizing(&s, menu).0, Sizing::Fixed);
assert!(names(&w, menu, "sizingH") && !names(&w, root, "sizingH"), "the child that filled it: {w:?}");
}
#[test]
fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() {
let mut s = Session::new();
+4
View File
@@ -28,6 +28,7 @@ pub const NODE_KEYS: &[&str] = &[
"componentPropertyDefinitions",
"constraints",
"cornerRadius",
"cornerStyle",
"cornerSmoothing",
"dashCap",
"dashes",
@@ -304,6 +305,9 @@ fn paint_props(n: &Node, o: &mut serde_json::Map<String, Value>, options: &Inspe
if !n.effects.is_empty() {
insert_prop(o, options, "effects", || camel(serde_json::to_value(&n.effects).unwrap_or(Value::Null)));
}
if n.kind.has_independent_corners() && (!n.corners.style.is_round() || options.explicit("cornerStyle")) {
insert_prop(o, options, "cornerStyle", || json!(n.corners.style));
}
if n.corners.radii.iter().any(|r| *r > 0.0) {
insert_prop(o, options, "cornerRadius", || match n.corners.uniform() {
Some(r) => json!(r),
+15 -10
View File
@@ -56,14 +56,20 @@ pub(crate) enum VGesture {
start_angle: f64,
angle: f64,
},
/// Bend tool on a segment: a drag past the click slop from `start` (the press, on the page)
/// bends it.
BendSegment {
seg: usize,
t: f64,
start: Point,
moved: bool,
},
/// Bend tool on a point: drag pulls out handles, a click on a smooth point sharpens it.
/// Bend tool on a point: a drag past the click slop from `start` (the press, on the page)
/// pulls out handles; a click (wobble included) on a smooth point sharpens it.
BendVertex {
v: usize,
origin: Point,
start: Point,
moved: bool,
smooth: bool,
},
@@ -748,11 +754,11 @@ impl Session {
e.vertices = vec![index];
})?;
self.begin_interaction("Bend")?;
self.vgesture(VGesture::BendVertex { v: index, origin, moved: false, smooth });
self.vgesture(VGesture::BendVertex { v: index, origin, start: ev.p(), moved: false, smooth });
}
Some(VHit::Segment { seg, t }) => {
self.begin_interaction("Bend")?;
self.vgesture(VGesture::BendSegment { seg, t });
self.vgesture(VGesture::BendSegment { seg, t, start: ev.p(), moved: false });
}
None => self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift), leave: None }),
},
@@ -956,17 +962,16 @@ impl Session {
self.tool.overlay.cursor = Cursor::Rotate((ev.p() - c).atan2().to_degrees());
self.vgesture(VGesture::BoxRotate { b, start_angle, angle });
}
VGesture::BendSegment { seg, t } => {
// A hand's wobble during a click is not a drag (#2166): the same slop as other clicks.
VGesture::BendSegment { start, moved: false, .. } | VGesture::BendVertex { start, moved: false, .. } if within_slop(ev, start) => {}
VGesture::BendSegment { seg, t, start, .. } => {
self.preview(|doc, _| edit(doc, id, |net| ops::bend(net, seg, t, lp)))?;
self.vgesture(VGesture::BendSegment { seg, t, start, moved: true });
}
VGesture::BendVertex { v, origin, moved, smooth } => {
VGesture::BendVertex { v, origin, start, smooth, .. } => {
let d = lp - origin;
let page_d = (w * lp - w * origin).hypot() * ev.zoom;
if !moved && page_d < 2.0 {
return Ok(());
}
self.preview(|doc, _| edit(doc, id, |net| ops::make_smooth(net, v, d)))?;
self.vgesture(VGesture::BendVertex { v, origin, moved: true, smooth });
self.vgesture(VGesture::BendVertex { v, origin, start, moved: true, smooth });
}
VGesture::Marquee { start, base, .. } => {
let r = Rect::from_points(start, ev.p());
@@ -173,6 +173,46 @@ fn a_bend_click_curves_a_sharp_point_between_its_neighbours() {
assert!(n.incident(v).iter().all(|(sg, st)| n.handle(*sg, *st) == Some((0.0, 0.0))));
}
/// #2166: with the Bend tool, or Cmd/Ctrl with Move, a press that wobbles a pixel or two before
/// it lets go is a click: a sharp point curves between its neighbours as a still click does, and a
/// segment stays as it is. Past the click slop the drag pulls the point's handles towards it.
#[test]
fn a_bend_click_that_wobbles_is_still_a_click() {
for cmd in [false, true] {
let mut s = Session::new();
let r = ex(&mut s, "vector.create", json!({"points": [[0, 0], [50, 30], [100, 0]], "closed": false}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
if !cmd {
ex(&mut s, "vector.edit.tool", json!({"tool": "bend"}));
}
let v = vertex_at(&net(&s, id), 50.0, 30.0);
let gesture = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Move, to), (PointerKind::Up, to)] {
let mut e = ev(kind, x, y);
e.cmd = cmd;
s.pointer(&e).unwrap();
}
};
let handles = |s: &Session| {
let n = net(s, id);
n.incident(v).iter().map(|(sg, st)| n.handle(*sg, *st).unwrap()).collect::<Vec<_>>()
};
// A segment pressed and wobbled is not bent.
let before = net(&s, id);
gesture(&mut s, (25.0, 15.0), (26.0, 16.0));
assert_eq!(net(&s, id).segments, before.segments, "cmd={cmd}: a wobble doesn't bend the segment");
// Pressed beside the point and wobbled: the click's curve, along the neighbours' line.
gesture(&mut s, (51.0, 30.0), (52.0, 31.0));
let hs = handles(&s);
assert!(hs.iter().all(|h| h.0.abs() > 1.0 && h.1.abs() < 1e-6), "cmd={cmd}: the automatic curve, not a handle drag: {hs:?}");
// Dragged down past the slop: the handles follow the pointer.
gesture(&mut s, (50.0, 30.0), (50.0, 60.0));
let hs = handles(&s);
assert!(hs.iter().all(|h| h.1.abs() > h.0.abs()), "cmd={cmd}: pulled towards the pointer: {hs:?}");
}
}
/// Between a handle's end and a point both within reach, the nearer on the page wins, also under a
/// non-uniform scale (10× wide here), where local distances would pick the point.
#[test]
+28 -2
View File
@@ -294,10 +294,24 @@ fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_vari
if let Some(src) = foreign {
crate::library::adopt_pasted(doc, src, clip.source_path.as_deref(), &all)?;
}
drop_dangling_bindings(doc, all.values().copied());
crate::library::count_inserted(doc, &out);
Ok(out)
}
/// Pasted layers bound to variables this file doesn't have (copied from another file or app that
/// brought no variables along, or deleted since the copy) keep the values they showed, unbound: a
/// binding that names no variable here would dangle (#2524).
fn drop_dangling_bindings(doc: &mut Document, pasted: impl Iterator<Item = NodeId>) {
for id in pasted {
let Some(n) = doc.node(id).filter(|n| n.bound.values().any(|v| doc.variables.get_by_id(v).is_none())) else { continue };
let kept = n.bound.iter().filter(|(_, v)| doc.variables.get_by_id(v).is_some()).map(|(f, v)| (f.clone(), v.clone())).collect();
if let Ok(n) = doc.get_mut(id) {
n.bound = kept;
}
}
}
/// Lock the aspect ratio of a layer pasted into an auto layout frame when it shows an image cropped
/// to it and fills one axis while fixed on the other, so layout can't squash the image.
fn keep_a_cropped_images_proportions(doc: &mut Document, pasted: NodeId, parent: NodeId) {
@@ -524,6 +538,9 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
v["strokeStyle"] = json!(n.styles.stroke);
v["effectStyle"] = json!(n.styles.effect);
v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect());
if n.kind.has_independent_corners() {
v["cornerStyle"] = json!(n.corners.style);
}
if let NodeKind::Text(t) = &n.kind {
v["textStyle"] = json!(n.styles.text);
v["fontFamily"] = json!(t.style.font_family);
@@ -544,13 +561,19 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
Ok(v)
}
/// Whether copied property `k` links to a shared style: `fontStyle` and `cornerStyle` are values
/// (a font's style name; round, chamfer, concave).
fn is_style_link(k: &str) -> bool {
k.ends_with("Style") && !k.starts_with("font") && k != "cornerStyle"
}
/// Copied properties `props` without their style and variable links, for a paste into another
/// file: the copied ids name the source file's styles and variables, and the same ids here can
/// name unrelated ones. The values paste unlinked, and the layer's own links on them go.
fn without_links(mut props: Value) -> Value {
if let Some(m) = props.as_object_mut() {
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") {
if is_style_link(k) {
*v = Value::Null;
} else if k == "boundVariables" {
*v = json!({});
@@ -577,10 +600,13 @@ pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, prop
// values it gave are pasted without a link, so the layer's own link goes too.
let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some());
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") && !here(v) {
if is_style_link(k) && !here(v) {
*v = Value::Null;
}
}
if !doc.get(id)?.kind.has_independent_corners() {
m.remove("cornerStyle");
}
if let Some(Value::Object(copied)) = m.get_mut("boundVariables") {
copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some()));
}
+37 -3
View File
@@ -163,7 +163,7 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
names.join(", ")
));
}
let mut hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props);
let hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props);
let filling = crate::cmd::props::filling_children(&s.ds()?.doc, &ids, &props);
let targets = ids.clone();
let doc = s.doc_mut()?;
@@ -194,14 +194,48 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
for f in &targets {
figcraft_layout::coherent_sizing(doc, *f);
}
hugging.extend(filling);
}
if let Some(notice) = crate::cmd::props::fixed_notice(&s.ds()?.doc, &hugging) {
// The canvas shows the notice; a script reads the same side effects in `warnings` (#2178).
let doc = &s.ds()?.doc;
let parents = crate::cmd::props::turned_fixed(doc, &hugging);
let children = crate::cmd::props::turned_fixed(doc, &filling);
for ((n, horizontal), (was, why)) in parents
.iter()
.map(|f| (f, ("Hug", "a layer in it now fills it")))
.chain(children.iter().map(|f| (f, ("Fill", "the frame it is in now hugs it"))))
{
let key = if *horizontal { "sizingH" } else { "sizingV" };
warnings.push(format!("{} “{}” ({}): `{key}` {was} → Fixed, because {why}", n.id, n.name, n.kind.type_name()));
}
warnings.extend(clipped_variants(doc, &targets));
let notice = crate::cmd::props::fixed_notice(&[parents, children].concat());
if let Some(notice) = notice {
s.message = Some(notice);
}
if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) }
}
/// Variants among `ids` that reach past their component set while it clips them and has no auto
/// layout to grow with them: the set keeps its size, as it does on the canvas, so the cut-off part
/// is hidden (#2182).
fn clipped_variants(doc: &figcraft_doc::Document, ids: &[NodeId]) -> Vec<String> {
ids.iter()
.filter_map(|i| {
let n = doc.node(*i)?;
let set = doc.node(n.parent?).filter(|p| matches!(p.kind, NodeKind::ComponentSet { .. }) && p.clip && p.layout.is_none())?;
// The variant's box in the set's space, as `fit_set` measures it.
let b = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect());
let outside = b.x0 < -0.01 || b.y0 < -0.01 || b.x1 > set.width + 0.01 || b.y1 > set.height + 0.01;
outside.then(|| {
format!(
"{} “{}” reaches past its component set {} “{}”, which clips it: the part outside is hidden (`layout.add` on the set makes it grow with its variants)",
n.id, n.name, set.id, set.name
)
})
})
.collect()
}
/// A `fontStyle` draws in the family's face nearest to it, as a text layer resolves it. When that
/// face has another weight or slant than the name asks for ("Black" on a family whose heaviest is
/// Bold), say which face it is. Families that aren't installed, and names that match a style or a
+23 -2
View File
@@ -99,7 +99,7 @@ impl FileSnapshot {
/// as of the snapshot, and edits since stay unsaved. False (nothing written) when the document
/// was closed, saved, reverted or given another path since: the bytes are out of date.
pub fn save(self, s: &mut Session, bytes: &[u8]) -> Result<bool> {
let Some(ds) = s.docs.iter_mut().find(|d| d.uid == self.uid && d.path == self.path && Arc::ptr_eq(&d.saved_doc, &self.saved)) else {
let Some(ds) = self.tab(s) else {
return Ok(false);
};
let path = self.path.as_deref().ok_or(EngineError::NoDocument)?;
@@ -107,6 +107,27 @@ impl FileSnapshot {
refuse_overwriting_changes(ds, path)?;
write(path, bytes)?;
ds.note_on_disk();
Ok(self.saved_as_of(s))
}
/// The bytes of this snapshot reached their destination some time after it was taken (a page
/// hosting the browser build confirmed it stored them): the file is saved as of the snapshot,
/// and edits made since stay unsaved, as [`save`](Self::save) leaves them. False (nothing
/// changes) when the tab was closed, saved, reverted or given another path since.
pub fn delivered(self, s: &mut Session) -> bool {
self.saved_as_of(s)
}
/// The tab this snapshot was taken of, unless it was closed, saved, reverted or given another
/// path since.
fn tab<'a>(&self, s: &'a mut Session) -> Option<&'a mut DocState> {
s.docs.iter_mut().find(|d| d.uid == self.uid && d.path == self.path && Arc::ptr_eq(&d.saved_doc, &self.saved))
}
/// Mark the tab (and its branch tabs) saved as of this snapshot; false when [`tab`](Self::tab)
/// finds none.
fn saved_as_of(self, s: &mut Session) -> bool {
let Some(ds) = self.tab(s) else { return false };
// The history or branches may have changed since: then they still count as unsaved.
if ds.revision == self.revision {
ds.versions_changed = false;
@@ -114,7 +135,7 @@ impl FileSnapshot {
ds.saved_doc = self.doc;
ds.revision += 1;
branch_tabs_saved(s, self.uid);
Ok(true)
true
}
}
+29 -13
View File
@@ -18,7 +18,7 @@ pub const STROKE_SIDES: [&str; 4] = ["strokeTopWeight", "strokeRightWeight", "st
/// 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), 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, \
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]), cornerStyle (round|chamfer|concave), cornerSmoothing (0-1), effects, \
clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, padding (n or [t,r,b,l]), paddingTop/Right/Bottom/Left, \
mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \
columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \
@@ -728,6 +728,13 @@ fn apply_corners(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value)
*slot = r;
}
}
"cornerStyle" => {
let n = doc.get_mut(id)?;
if !n.kind.has_independent_corners() {
return Err(bad(cmd, "cornerStyle requires a rectangular layer"));
}
n.corners.style = serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "cornerStyle: round|chamfer|concave"))?;
}
"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)
}
@@ -1292,7 +1299,9 @@ pub fn override_group(k: &str) -> &'static str {
"characters" | "text" => "characters",
"features" | "fontFeatures" | "openTypeFeatures" | "listStyle" | "indentation" | "listSpacing" | "maxLines" | "variationSettings"
| "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" | "textDirection" | "direction" => "textStyle",
"cornerRadius" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "corners",
"cornerRadius" | "cornerStyle" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => {
"corners"
}
"width" | "height" | "w" | "h" => "size",
"sizingH" | "sizingV" | "layoutSizingHorizontal" | "layoutSizingVertical" | "minWidth" | "maxWidth" | "minHeight" | "maxHeight" => "resizing",
"gap" | "itemSpacing" | "columnGap" | "crossGap" | "counterAxisSpacing" | "rowGap" => "gap",
@@ -1548,7 +1557,7 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal:
}
/// The hugging parents that `props` setting Fill on `ids` may turn Fixed, as (parent, horizontal):
/// taken before the edit, for [`fixed_notice`].
/// taken before the edit, for [`turned_fixed`].
pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
@@ -1568,7 +1577,7 @@ pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map<String
}
/// The children, as (child, horizontal), that fill an axis of a frame in `ids` which `props` sets
/// to Hug: taken before the edit, for [`fixed_notice`] (the coherence pass turns them Fixed).
/// to Hug: taken before the edit, for [`turned_fixed`] (the coherence pass turns them Fixed).
pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
@@ -1587,17 +1596,24 @@ pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map<Strin
out
}
/// The notice for the layers of [`hugging_parents`] or [`filling_children`] that the edit turned
/// Fixed ("Height set to Fixed for Frame 1"), `None` when every one kept its sizing.
pub(crate) fn fixed_notice(doc: &Document, before: &[(NodeId, bool)]) -> Option<String> {
let notes: Vec<String> = before
/// The layers of [`hugging_parents`] or [`filling_children`] that the edit turned Fixed, as
/// (layer, horizontal).
pub(crate) fn turned_fixed<'a>(doc: &'a Document, before: &[(NodeId, bool)]) -> Vec<(&'a Node, bool)> {
before
.iter()
.filter_map(|(p, horizontal)| {
let p = doc.node(*p)?;
let now = if *horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v };
(now == Sizing::Fixed).then(|| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, p.name))
.filter_map(|(id, horizontal)| {
let n = doc.node(*id)?;
let now = if *horizontal { n.child_layout.sizing_h } else { n.child_layout.sizing_v };
(now == Sizing::Fixed).then_some((n, *horizontal))
})
.collect();
.collect()
}
/// The notice for the layers the edit turned Fixed ([`turned_fixed`]): "Height set to Fixed for
/// Frame 1", `None` when every one kept its sizing.
pub(crate) fn fixed_notice(fixed: &[(&Node, bool)]) -> Option<String> {
let notes: Vec<String> =
fixed.iter().map(|(n, horizontal)| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, n.name)).collect();
(!notes.is_empty()).then(|| notes.join("; "))
}
+1 -1
View File
@@ -114,7 +114,7 @@ fn every_command_edit_round_trips_through_its_changes() {
replica = d.replica;
}
assert!(edits > 50, "seed {seed}: only {edits} edits");
let back = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let back = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
assert_eq!(back, replica, "seed {seed}: snapshot");
}
}
+46
View File
@@ -0,0 +1,46 @@
//! A save confirmed some time after its bytes were taken (a page hosting the browser build stores
//! them, then answers): the file is saved as of those bytes, never as of edits made meanwhile.
use serde_json::json;
use crate::Session;
use crate::cmd::file::FileSnapshot;
fn rect(s: &mut Session, x: f64) {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap();
}
#[test]
fn a_confirmed_save_with_no_edits_since_clears_the_unsaved_changes() {
let mut s = Session::new();
rect(&mut s, 0.0);
let snapshot = FileSnapshot::of(s.ds().unwrap());
assert!(s.ds().unwrap().is_dirty());
assert!(snapshot.delivered(&mut s));
assert!(!s.ds().unwrap().is_dirty());
}
#[test]
fn edits_made_while_the_save_was_on_its_way_stay_unsaved() {
let mut s = Session::new();
rect(&mut s, 0.0);
let snapshot = FileSnapshot::of(s.ds().unwrap());
rect(&mut s, 20.0);
assert!(snapshot.delivered(&mut s));
assert!(s.ds().unwrap().is_dirty(), "the second rectangle never reached the host");
}
#[test]
fn a_confirmation_for_a_tab_saved_or_closed_since_changes_nothing() {
let mut s = Session::new();
rect(&mut s, 0.0);
let snapshot = FileSnapshot::of(s.ds().unwrap());
s.execute("file.markSaved", &json!({})).unwrap();
rect(&mut s, 20.0);
assert!(!snapshot.delivered(&mut s), "another save happened since");
assert!(s.ds().unwrap().is_dirty());
let snapshot = FileSnapshot::of(s.ds().unwrap());
s.execute("file.close", &json!({"force": true})).unwrap();
assert!(!snapshot.delivered(&mut s), "the tab is gone");
}
+21
View File
@@ -73,6 +73,27 @@ fn layers_paste_into_the_page_and_undo() {
assert!(ids.iter().all(|i| !s.doc().unwrap().contains(*i)));
}
/// Layers copied with a fill bound to a variable the copy doesn't bring along paste unbound, in
/// the colour they showed (#2524), rather than bound to a variable that isn't in the file.
#[test]
fn bindings_to_variables_the_file_lacks_paste_as_their_values() {
let mut src = Session::new();
let r = id(&src.execute("node.create", &json!({"type": "rectangle", "x": 0, "y": 0, "width": 40, "height": 20, "name": "Swatch"})).unwrap());
src.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
src.execute("variable.create", &json!({"collection": "Tokens", "name": "Brand", "type": "color", "value": "#3366FF"})).unwrap();
src.execute("variable.bind", &json!({"ids": [r], "field": "fill", "variable": "Brand"})).unwrap();
let file = B64.decode(src.execute("file.export", &json!({"format": "fig"})).unwrap()["data"].as_str().unwrap()).unwrap();
let mut s = Session::new();
let out = s.execute("edit.pasteDesignLayers", &json!({"html": clipboard_html(&file)})).unwrap();
let copied = s.clipboard.nodes[0].1[0].clone();
assert!(!copied.bound.is_empty(), "the copy is bound");
let doc = s.doc().unwrap();
let pasted = doc.node(params::id_of(&out["ids"][0]).unwrap()).unwrap();
assert!(copied.bound.values().all(|v| doc.variables.get_by_id(v).is_none()), "the file hasn't the variable");
assert!(pasted.bound.is_empty(), "no binding to a variable the file hasn't: {:?}", pasted.bound);
assert_eq!(pasted.fills, copied.fills, "the colour it showed");
}
#[test]
fn a_second_paste_repeats_the_copied_layers() {
let mut s = Session::new();
+11
View File
@@ -37,6 +37,17 @@ fn keys(v: &Value, allowed: &[&str]) {
}
}
#[test]
fn corner_style_is_sparse_and_can_be_requested_explicitly() {
let (mut s, frame, text) = tree();
let fields = json!({"fields": ["cornerStyle"]});
assert!(node(&s, frame, 0, json!({})).get("cornerStyle").is_none());
assert_eq!(node(&s, frame, 0, fields.clone())["cornerStyle"], "round");
assert!(node(&s, text, 0, fields).get("cornerStyle").is_none());
run(&mut s, "node.set", json!({"id": frame, "props": {"cornerStyle": "concave"}}));
assert_eq!(node(&s, frame, 0, json!({}))["cornerStyle"], "concave");
}
fn golden_tree() -> (Session, NodeId) {
let mut s = Session::new();
let frame = create(
+2 -2
View File
@@ -20,11 +20,11 @@ fn jam_file(tag: &str) -> std::path::PathBuf {
let mut member = from.by_index(i).unwrap();
let mut bytes = Vec::new();
member.read_to_end(&mut bytes).unwrap();
if member.name() == "canvas.fig" {
if member.name().expect("ZIP member name") == "canvas.fig" {
assert!(bytes.starts_with(b"fig-kiwi"));
bytes.splice(..8, *b"fig-jam.");
}
to.start_file(member.name(), zip::write::SimpleFileOptions::default()).unwrap();
to.start_file(member.name().expect("ZIP member name"), zip::write::SimpleFileOptions::default()).unwrap();
to.write_all(&bytes).unwrap();
}
let path = std::env::temp_dir().join(format!("figcraft-jam-{tag}-{}.jam", std::process::id()));
+96
View File
@@ -0,0 +1,96 @@
//! Join timings for a large shared file (#2041): the server's welcome, the sync client built from
//! it and the engine opening it as a tab, for the current catch-up and the older full snapshot.
//! Run in release:
//! `cargo test --release -p figcraft-engine --lib join_timings -- --ignored --nocapture`.
//!
//! `FIGCRAFT_JOIN_BENCH_LAYERS` sets the layer count (default 120000) and
//! `FIGCRAFT_JOIN_BENCH_CATCH_UP` which catch-ups to time (`delta,legacy` by default).
use std::time::Instant;
use figcraft_collab::message::{ClientMsg, ServerMsg};
use figcraft_collab::{Client, Limits, Outgoing, Server};
use figcraft_doc::color::{Color, Paint};
use figcraft_doc::{Document, NodeKind, TextData};
use serde_json::json;
use crate::live::{Event, Role};
use crate::live_tests::{info, push, session};
/// What a current client announces, minus the delta snapshot: a server sends it the full snapshot.
const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches";
/// A document of about `layers` layers over 15 pages: frames of eight children (text, rectangles
/// and ellipses with fills), like a large product file.
fn big_doc(layers: usize) -> Document {
let mut doc = Document::new("Big file");
let mut pages = vec![doc.first_page().unwrap()];
for p in 1..15 {
pages.push(doc.add_page(&format!("Page {p}")));
}
let per_page = layers / pages.len();
for (pi, page) in pages.into_iter().enumerate() {
let mut made = 0;
let mut f = 0;
while made < per_page {
let x = (f % 40) as f64 * 400.0;
let y = (f / 40) as f64 * 300.0;
let frame = doc.create(page, NodeKind::Frame, &format!("Card {pi}.{f}"), x, y, 360.0, 260.0).unwrap();
for c in 0..8 {
let kind = match c % 3 {
0 => NodeKind::Text(TextData::new(format!("Label {f} {c}")).into()),
1 => NodeKind::Rectangle,
_ => NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 },
};
let id = doc.create(frame, kind, &format!("Layer {c}"), 8.0 + c as f64 * 40.0, 8.0, 32.0, 32.0).unwrap();
doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::new(0.2, 0.4, c as f32 / 8.0, 1.0))];
}
made += 9;
f += 1;
}
}
doc.repair();
doc
}
/// The welcome `server` gives a newcomer announcing `client_version`, and its id.
fn welcome(server: &mut Server, client_version: &str) -> (u32, ServerMsg) {
let ClientMsg::Hello(mut h) = Client::hello("f", "", "Ada", "") else { panic!("no hello") };
h.client_version = client_version.to_string();
let (id, outs) = server.join(h).unwrap();
let w = outs.into_iter().find_map(|o| if let Outgoing::To(_, w @ ServerMsg::Welcome { .. }) = o { Some(w) } else { None }).unwrap();
(id, w)
}
fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
#[test]
#[ignore = "timing: run in release with --ignored --nocapture"]
fn join_timings() {
let layers: usize = std::env::var("FIGCRAFT_JOIN_BENCH_LAYERS").ok().and_then(|v| v.parse().ok()).unwrap_or(120_000);
let which = std::env::var("FIGCRAFT_JOIN_BENCH_CATCH_UP").unwrap_or_else(|_| "delta,legacy".into());
let doc = big_doc(layers);
println!("{} layers", doc.node_count());
let mut server = Server::new(doc, "", Limits::default());
for name in which.split(',').map(str::trim) {
let version = if name == "legacy" { LEGACY_CLIENT_VERSION.to_string() } else { figcraft_collab::message::client_version() };
let t = Instant::now();
let (id, w) = welcome(&mut server, &version);
let welcome_ms = ms(t);
let bytes = figcraft_collab::message::encode(&w).unwrap().len();
let t = Instant::now();
let client = Client::join(w.clone()).unwrap();
let client_ms = ms(t);
drop(client);
let (mut s, script) = session();
s.execute("collab.join", &json!({"link": "figcraft://join?host=a:1&file=f&token=t"})).unwrap();
push(&script, vec![Event::Welcome { info: info(Role::Guest, id), peers: vec![] }, Event::Sync(w)]);
let t = Instant::now();
s.live_poll();
let engine_ms = ms(t);
assert_eq!(s.doc().unwrap().name, "Big file");
println!("{name}: welcome {bytes} bytes in {welcome_ms:.0} ms; Client::join {client_ms:.0} ms; engine join (live_poll) {engine_ms:.0} ms");
}
}
+4
View File
@@ -298,6 +298,8 @@ mod datafill_tests;
#[cfg(test)]
mod default_props_tests;
#[cfg(test)]
mod delivered_save_tests;
#[cfg(test)]
mod design_context_tests;
#[cfg(test)]
mod design_paste_tests;
@@ -416,6 +418,8 @@ mod invite_links_tests;
#[cfg(test)]
mod jam_open_tests;
#[cfg(test)]
mod join_bench_tests;
#[cfg(test)]
mod jpg_export_tests;
#[cfg(test)]
mod keymap_tests;
+26 -1
View File
@@ -3,7 +3,7 @@
//! variants already (it used to put a set inside a set), and Add variant on a main component that
//! isn't in a set yet making it one.
use serde_json::json;
use serde_json::{Value, json};
use crate::Session;
use crate::cmd::component::{can_add_variant, can_combine_variants};
@@ -177,3 +177,28 @@ fn add_variant_on_a_lone_component_in_auto_layout_keeps_its_place() {
assert_eq!(kids(&s, set).len(), 2);
healthy(&s);
}
/// #2182: a set without auto layout keeps its size when a variant grows past it (it is sized only
/// when variants are combined or added) and clips it. `node.set` says so in `warnings`; with auto
/// layout on the set, it grows and there is nothing to say.
#[test]
fn a_variant_grown_past_its_clipping_set_is_warned_about() {
let mut s = Session::new();
let a = component(&mut s, "State=Default", 0.0);
let b = component(&mut s, "State=Hover", 200.0);
let set = idv(&ex(&mut s, "component.combineVariants", json!({"ids": [a, b]})));
let warns = |v: Value, id: NodeId| {
v["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with(&format!("{id} ")))))
};
let height = |s: &Session| node(s, set).height;
let before = height(&s);
let grown = s.execute("node.set", &json!({"id": a, "props": {"height": before * 3.0}})).unwrap();
assert_eq!(height(&s), before, "the set keeps its size");
assert!(warns(grown, a), "the clipped variant is named");
// Inside the set: nothing to say.
assert!(!warns(s.execute("node.set", &json!({"id": a, "props": {"height": 40}})).unwrap(), a));
// With auto layout the set grows with it.
ex(&mut s, "layout.add", json!({"ids": [set], "direction": "horizontal"}));
let grown = s.execute("node.set", &json!({"id": a, "props": {"height": before * 3.0}})).unwrap();
assert!(height(&s) > before && !warns(grown, a));
}
+3 -1
View File
@@ -14,7 +14,6 @@ figcraft-pathops = { workspace = true }
figcraft-layout = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
zip = { workspace = true }
flate2 = { workspace = true }
ruzstd = { workspace = true }
sha1 = { workspace = true }
@@ -32,3 +31,6 @@ craft-raw = { workspace = true }
craft-develop = { workspace = true }
craft-color-transform = { workspace = true }
craft-geom = { workspace = true }
[dev-dependencies]
zip = { workspace = true }
@@ -720,3 +720,74 @@ fn a_jam_shape_whose_text_only_the_outer_node_carries_keeps_it() {
assert!(frame.board.is_none(), "the generated layers keep the outer text");
assert!(frame.children.iter().filter_map(|id| doc.node(*id)?.kind.text()).any(|t| t.characters == "Outer saved text"));
}
/// A synthetic whiteboard of two boxes and connectors: one joining them by named and automatic
/// magnets, one from a box to a free point, and one inside a frame.
fn connected_board() -> Vec<u8> {
let box_at = |id, name: &str, x| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, 600.0))]);
let joined = |id, name: &str, parent: u64, start: Kv<'static>, finish: Kv<'static>| {
node(
id,
Some((parent, "+")),
"CONNECTOR",
name,
vec![
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
("connectorStart", start),
("connectorEnd", finish),
("connectorLineStyle", e("ELBOWED")),
],
)
};
let on = |node, magnet: &'static str| o(vec![("endpointNodeID", g(node)), ("magnet", e(magnet))]);
let message = o(vec![
(
"nodeChanges",
arr(vec![
node(0, None, "DOCUMENT", "Synthetic board", vec![]),
node(1, Some((0, "!")), "CANVAS", "Page", vec![]),
box_at(60, "A", 0.0),
box_at(61, "B", 300.0),
joined(62, "Joined", 1, on(60, "BOTTOM"), on(61, "AUTO")),
joined(63, "Loose", 1, on(60, "NONE"), o(vec![("position", xy(50.0, 900.0))])),
node(64, Some((1, "-")), "FRAME", "Frame", vec![("size", xy(400.0, 400.0)), ("transform", at(0.0, 0.0))]),
joined(65, "Framed", 64, on(60, "AUTO"), on(61, "AUTO")),
]),
),
("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(triangle_blob()))])])),
]);
let mut bytes = canvas(&board_schema(), &message);
bytes.splice(..8, *b"fig-jam.");
bytes
}
/// #1808: on a whiteboard a connector is a native board connector attached to the layers it joins,
/// so it follows them when they move; a free end keeps its point.
#[test]
fn a_jam_connector_is_attached_to_the_layers_it_joins() {
use figcraft_doc::{BoardItem, End, Routing, Side};
let (doc, warnings) = import(&connected_board(), "Synthetic board").unwrap();
let (a, b) = (named(&doc, "A").id, named(&doc, "B").id);
let Some(BoardItem::Connector(c)) = &named(&doc, "Joined").board else { panic!("{:?}", named(&doc, "Joined").board) };
assert!(matches!(c.from, End::Node { node, side: Side::Bottom, .. } if node == a), "{c:?}");
assert!(matches!(c.to, End::Node { node, side: Side::Auto, .. } if node == b), "{c:?}");
assert_eq!(c.routing, Routing::Elbow);
assert!(matches!(named(&doc, "Joined").kind, figcraft_doc::NodeKind::Vector { .. }), "it keeps the line it was drawn with");
let Some(BoardItem::Connector(loose)) = &named(&doc, "Loose").board else { panic!("the loose connector is attached too") };
assert!(matches!(loose.from, End::Node { node, .. } if node == a));
assert_eq!(loose.to, End::Point { x: 50.0, y: 900.0 }, "a free end keeps its point on the page");
assert!(named(&doc, "Framed").board.is_none(), "one inside a frame stays a plain line");
let note: Vec<_> = warnings.iter().filter(|w| w.starts_with("connector layers import as vectors")).collect();
assert_eq!(note, ["connector layers import as vectors"], "only the one left a line is reported: {warnings:?}");
}
/// In a `.fig` design file connectors stay plain lines.
#[test]
fn a_fig_connector_stays_a_line() {
let mut bytes = connected_board();
bytes.splice(..8, *b"fig-kiwi");
let (doc, _) = import(&bytes, "Synthetic design").unwrap();
assert!(doc.nodes().all(|n| n.board.is_none()));
}
+3
View File
@@ -188,6 +188,9 @@ impl<'d> Exporter<'d> {
_ => {}
}
let boxy = n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle | NodeKind::Section { .. });
if boxy && !n.corners.style.is_round() {
self.warn("chamfered and concave corners use outline geometry; .fig has no editable corner style");
}
if (boxy || matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Polygon { .. } | NodeKind::Star { .. }))
&& let Some(p) = figcraft_doc::geometry::shape_path(n)
{
+6 -1
View File
@@ -320,7 +320,12 @@ impl<'d> Exporter<'d> {
return;
}
let whole = matches!(n.kind, NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_doc::geom::full_sweep(sweep));
if boxy || whole {
if boxy && !n.corners.style.is_round() {
if let Some(path) = figcraft_doc::geometry::shape_path(n) {
let outline = figcraft_pathops::stroke_outline(&path, sp, true);
self.geometry("strokeGeometry", &outline, WindingRule::NonZero, f);
}
} else if boxy || whole {
let (out, inset) = match sp.align {
StrokeAlign::Inside => (0.0, weight),
StrokeAlign::Center => (weight / 2.0, weight / 2.0),
+3 -2
View File
@@ -819,7 +819,7 @@ fn a_boolean_groups_corner_radius_round_trips() {
doc.create(g, NodeKind::Rectangle, "A", 0.0, 0.0, 200.0, 100.0).unwrap();
doc.create(g, NodeKind::Rectangle, "B", 150.0, 0.0, 100.0, 200.0).unwrap();
doc.fit_to_children(g).unwrap();
doc.get_mut(g).unwrap().corners = Corners { radii: [20.0; 4], smoothing: 0.6 };
doc.get_mut(g).unwrap().corners = Corners { radii: [20.0; 4], smoothing: 0.6, ..Corners::default() };
let (back, _) = round_trip(&doc, "boolean radius");
let n = back.nodes().find(|n| matches!(n.kind, NodeKind::BooleanOp { .. })).unwrap();
assert!(n.corners.radii.iter().all(|r| (r - 20.0).abs() < 1e-4), "{:?}", n.corners);
@@ -1380,7 +1380,8 @@ fn images_are_named_by_the_sha1_of_their_bytes() {
assert_eq!(export::sha1_hex(&vec![b'a'; 1_000_000]), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
let (bytes, _) = export(&generate(3), None).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
let names: Vec<String> = z.file_names().filter(|n| n.starts_with("images/")).map(str::to_string).collect();
let names: Vec<String> =
z.file_names().map(|name| name.expect("ZIP member name")).filter(|n| n.starts_with("images/")).map(std::borrow::Cow::into_owned).collect();
assert!(!names.is_empty());
for name in names {
let data = crate::read_member(&mut z, &name, 1 << 26).unwrap();
+1 -1
View File
@@ -364,7 +364,7 @@ fn mask_types_round_trip() {
fn the_archive_lists_its_members_and_describes_the_file() {
let (bytes, _) = export(&sample(), Some(&super::tests::png())).unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().expect("ZIP member name").into_owned()).collect();
assert_eq!(names, ["canvas.fig", "thumbnail.png", "meta.json"]);
let meta: serde_json::Value = serde_json::from_slice(&crate::read_member(&mut z, "meta.json", 1 << 20).unwrap()).unwrap();
assert_eq!(meta["file_name"], "Interop");
+119
View File
@@ -78,6 +78,8 @@ pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) -
mapped.networks.into_iter().map(|n| serde_json::to_value(n?).ok().and_then(|v| crate::rest::network(&v))).collect();
if board {
native_board_shapes(msg, &mut mapped.json, &mut mapped.warnings);
let native = native_board_connectors(msg, &mut mapped.json);
uncount(&mut mapped.warnings, "connector layers import as vectors", native);
}
(mapped.json, mapped.warnings, networks)
}
@@ -199,6 +201,123 @@ fn apply_native_board_shape(rest_node: &mut Value, origin: &str, shape: BoardSha
}
}
/// A record's `guid` as the `session:local` origin the mapped layers carry.
fn origin(guid: &Kv) -> Option<String> {
let (session, local) = guid.get("sessionID").and_then(Kv::f64).zip(guid.get("localID").and_then(Kv::f64))?;
Some(format!("{}:{}", session as u64, local as u64))
}
/// Every mapped layer of `json` (bounded by `max_nodes` already), depth first.
fn each_layer(json: &mut Value, f: &mut impl FnMut(&mut Value)) {
if json.get(craft_fig::rest::FIG_SOURCE_FIELD).is_some() {
f(json);
}
match json {
Value::Object(fields) => fields.values_mut().for_each(|child| each_layer(child, f)),
Value::Array(items) => items.iter_mut().for_each(|child| each_layer(child, f)),
_ => {}
}
}
/// A mapped layer's source origin.
fn layer_origin(layer: &Value) -> Option<&str> {
layer.get(craft_fig::rest::FIG_SOURCE_FIELD)?.get("origin")?.as_str()
}
/// A whiteboard file's connectors are native board connectors: the line the shared mapper drew
/// stays, and the connector is attached to the layers it joins, so FigCraft routes it again when
/// they move. Only a connector drawn as one line on the page itself is adapted: a free end's
/// point is in its parent's space, the page's only there, and one with a label is a frame holding
/// its line and label, which stays as it is.
/// Returns how many it attached.
fn native_board_connectors(msg: &Kv, json: &mut Value) -> usize {
let Some(changes) = msg.get("nodeChanges") else { return 0 };
let ty = |n: &Kv| n.get("type").and_then(Kv::str).map(str::to_owned);
let pages: std::collections::HashSet<String> =
changes.list().iter().filter(|n| ty(n).as_deref() == Some("CANVAS")).filter_map(|n| origin(n.get("guid")?)).collect();
let mut connectors = std::collections::HashMap::new();
for node in changes.list() {
if ty(node).as_deref() != Some("CONNECTOR")
|| node.get("parentIndex").and_then(|p| p.get("guid")).and_then(origin).is_none_or(|p| !pages.contains(&p))
{
continue;
}
let Some(id) = node.get("guid").and_then(origin) else { continue };
let end = |key: &str| -> Option<Value> {
let e = node.get(key)?;
let Some(target) = e.get("endpointNodeID").and_then(origin) else {
let p = e.get("position")?;
return Some(serde_json::json!({"x": p.get("x").and_then(Kv::f64)?, "y": p.get("y").and_then(Kv::f64)?}));
};
let magnet = e.get("magnet").and_then(Kv::str);
let side = match magnet {
Some("TOP") => "top",
Some("RIGHT") => "right",
Some("BOTTOM") => "bottom",
Some("LEFT") => "left",
_ => "auto",
};
let mut out = serde_json::json!({"node": target, "side": side});
// Without a magnet the end sits where it was put on the layer.
if matches!(magnet, None | Some("NONE"))
&& let Some(r) = e.get("relativePosition")
&& let Some((x, y)) = r.get("x").and_then(Kv::f64).zip(r.get("y").and_then(Kv::f64))
{
out["at"] = serde_json::json!([x, y]);
}
Some(out)
};
let routing = match node.get("connectorLineStyle").and_then(Kv::str) {
Some("ELBOWED") => "elbow",
Some("CURVED") => "curved",
_ => "straight",
};
if let Some((from, to)) = end("connectorStart").zip(end("connectorEnd")) {
connectors.insert(id, serde_json::json!({"type": "connector", "from": from, "to": to, "routing": routing}));
}
}
if connectors.is_empty() {
return 0;
}
// The mapped layers' REST ids by origin: a connector's ends name the layers it joins by them.
let mut ids = std::collections::HashMap::new();
let mut attached = 0;
each_layer(json, &mut |layer| {
if let (Some(origin), Some(id)) = (layer_origin(layer), layer.get("id").and_then(Value::as_str)) {
ids.entry(origin.to_owned()).or_insert_with(|| id.to_owned());
}
});
each_layer(json, &mut |layer| {
if layer["type"] != "VECTOR" {
return;
}
let Some(mut board) = layer_origin(layer).and_then(|o| connectors.get(o)).cloned() else { return };
for key in ["from", "to"] {
if let Some(node) = board[key].get("node").and_then(Value::as_str) {
match ids.get(node) {
Some(id) => board[key]["node"] = Value::String(id.clone()),
// A layer left out (or not a layer here) leaves the connector a plain line.
None => return,
}
}
}
layer["board"] = board;
attached += 1;
});
attached
}
/// Take `n` off the count of warning `what` (`what (×count)`, or `what` once), dropping it at none.
fn uncount(warnings: &mut Vec<String>, what: &str, n: usize) {
let Some(i) = warnings.iter().position(|w| w.starts_with(what)) else { return };
let count = warnings[i].strip_prefix(what).and_then(|r| r.trim().strip_prefix("(×")?.strip_suffix(')')?.parse::<usize>().ok()).unwrap_or(1);
match count.saturating_sub(n) {
0 => _ = warnings.remove(i),
1 => warnings[i] = what.to_string(),
left => warnings[i] = format!("{what} (×{left})"),
}
}
/// The shared snapshot mapper omits a generated text child whose characters are empty. FigCraft
/// still keeps that empty child on a native shape, matching its prior mapper behavior.
fn generated_empty_body(node: &Kv) -> bool {
+1 -1
View File
@@ -31,7 +31,7 @@ fn file_with_images(n: u8) -> (Vec<u8>, Vec<String>, u64) {
/// `bytes` with one more member, `name` holding `data`.
fn with_member(bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let names: Vec<String> = z.file_names().map(str::to_string).collect();
let names: Vec<String> = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect();
let mut buf = std::io::Cursor::new(Vec::new());
let mut w = zip::ZipWriter::new(&mut buf);
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+13 -5
View File
@@ -25,7 +25,7 @@ fn doc_with_image() -> (Document, String) {
/// The archive of `d` rebuilt with `edit` applied to each member (None drops it).
fn rebuild(bytes: &[u8], edit: impl Fn(&str, Vec<u8>) -> Option<Vec<u8>>) -> Vec<u8> {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let names: Vec<String> = z.file_names().map(str::to_string).collect();
let names: Vec<String> = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect();
let mut buf = std::io::Cursor::new(Vec::new());
let mut w = zip::ZipWriter::new(&mut buf);
for n in names {
@@ -109,7 +109,11 @@ fn image_members_with_path_like_names_are_dropped_and_not_saved_back() {
assert!(!loaded.issues.is_empty());
let saved = save_bytes_with_history(&loaded.doc, None, &loaded.versions, &loaded.branches).unwrap();
let z = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap();
assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::<Vec<_>>());
assert!(
z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1),
"{:?}",
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
);
let _ = hash;
}
@@ -128,11 +132,15 @@ fn a_path_like_rest_image_ref_never_names_an_archive_member() {
assert!(doc.images.contains_key("rest-image-missing"), "the shared placeholder stores it instead: {:?}", doc.images.keys().collect::<Vec<_>>());
let bytes = save_bytes(&doc, None).unwrap();
let z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::<Vec<_>>());
assert!(
z.file_names().any(|n| n == "images/rest-image-missing"),
z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1),
"{:?}",
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
);
assert!(
z.file_names().map(|name| name.expect("ZIP member name")).any(|n| n == "images/rest-image-missing"),
"the placeholder is saved under its own name: {:?}",
z.file_names().collect::<Vec<_>>()
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
);
}
+1 -1
View File
@@ -81,7 +81,7 @@ fn replace_member(zip_bytes: &[u8], name: &str, bytes: Option<&[u8]>) -> Vec<u8>
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for i in 0..src.len() {
let mut f = src.by_index(i).unwrap();
let n = f.name().to_string();
let n = f.name().expect("ZIP member name").to_string();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
let data = if n == name { bytes.map(<[u8]>::to_vec) } else { Some(data) };
+83 -54
View File
@@ -8,6 +8,8 @@
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Cursor, Read};
use crate::{FormatError, add_image};
use craft_zip::{SeekableArchive, SeekableLimits};
use figcraft_doc::color::{BlendMode, Color, ColorStop, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind};
use figcraft_doc::geom::{Affine, BezPath, Shape};
use figcraft_doc::{
@@ -17,9 +19,8 @@ use figcraft_doc::{
Variable, VariableType, VariableValue, VectorNetwork,
};
use serde_json::Value;
use zip::ZipArchive;
use crate::{FormatError, add_image};
type PenpotArchive<'a> = SeekableArchive<Cursor<&'a [u8]>>;
mod embedded_fonts;
mod export;
@@ -135,11 +136,12 @@ impl<R: Read> Read for BudgetReader<'_, R> {
}
/// Read a JSON archive member within the per-member decompression limit.
fn json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudget) -> Result<Value, FormatError> {
let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?;
if entry.size() > MAX_JSON {
fn json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget) -> Result<Value, FormatError> {
let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
if declared > MAX_JSON {
return Err(corrupt(format!("JSON member too large: {path}")));
}
let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
let mut data = Vec::new();
BudgetReader { inner: entry, budget }.take(MAX_JSON + 1).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?;
if data.len() as u64 > MAX_JSON {
@@ -149,14 +151,15 @@ fn json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudge
}
/// Read a shape JSON member within member and per-page decompression limits.
fn shape_json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result<Value, FormatError> {
let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?;
if entry.size() > MAX_JSON {
fn shape_json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result<Value, FormatError> {
let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
if declared > MAX_JSON {
return Err(corrupt(format!("JSON member too large: {path}")));
}
if entry.size() > *page_budget {
if declared > *page_budget {
return Err(corrupt("page shapes exceed byte budget"));
}
let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
let mut data = Vec::new();
let max_read = (MAX_JSON + 1).min(*page_budget + 1);
BudgetReader { inner: entry, budget }.take(max_read).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?;
@@ -360,29 +363,35 @@ fn finish_masked_group(doc: &mut Document, group: NodeId, source: &Value, warnin
}
}
fn open_archive(bytes: &[u8]) -> Result<PenpotArchive<'_>, FormatError> {
let limits = SeekableLimits {
max_entries: MAX_ENTRIES as u64,
max_metadata_bytes: MAX_ARCHIVE as u64,
// The Penpot budget also charges partial reads (embedded font signatures) and
// remembers an overflow that an optional-member caller might otherwise swallow.
max_total_bytes: u64::MAX,
};
let z = SeekableArchive::open(Cursor::new(bytes), limits).map_err(|e| match e {
craft_zip::Error::TooManyEntries { .. } => corrupt("too many ZIP members"),
_ => corrupt(format!("invalid ZIP: {e}")),
})?;
if let Some(name) = z.duplicate_names().next() {
return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::<String>())));
}
Ok(z)
}
/// Read one exported `.penpot` archive without touching the filesystem or running a converter.
/// Returns native, editable FigCraft nodes plus notes about unsupported features.
pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
if bytes.len() > MAX_ARCHIVE {
return Err(corrupt("archive exceeds 512 MiB"));
}
let mut z = ZipArchive::new(Cursor::new(bytes)).map_err(|e| corrupt(format!("invalid ZIP: {e}")))?;
if z.len() > MAX_ENTRIES {
return Err(corrupt("too many ZIP members"));
}
// Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs
// whose compressed size is innocuous but whose advertised uncompressed size is enormous.
let mut z = open_archive(bytes)?;
// Check declared totals and member paths before decoding any JSON.
let mut expanded = 0_u64;
let mut names = BTreeSet::new();
for index in 0..z.len() {
let member = z.by_index(index).map_err(|e| corrupt(e.to_string()))?;
// An importer never extracts members to disk, but ambiguous ZIP names can
// cause one member to be inspected and another member to be read by name.
// Reject duplicates and traversal instead of guessing which version is real.
let name = member.name();
if !names.insert(name.to_owned()) {
return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::<String>())));
}
let name = z.entry_name(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
if name.starts_with('/')
|| name.contains('\\')
|| name.split('/').any(|part| part == "." || part == "..")
@@ -390,10 +399,14 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
{
return Err(corrupt("unsafe ZIP member path"));
}
expanded = expanded.saturating_add(member.size());
let (size, _) = z.entry_sizes(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
expanded = expanded.saturating_add(size);
if expanded > MAX_DECOMPRESSED {
return Err(corrupt("ZIP contents exceed 1 GiB"));
}
// The old indexing pass also rejected entries the decoder could not open,
// even when mapping the document would never request those members.
z.open_entry_index(index, MAX_DECOMPRESSED).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
}
let mut inflate_budget = InflateBudget::new();
let manifest = json(&mut z, "manifest.json", &mut inflate_budget)?;
@@ -447,12 +460,12 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
// The page index files are peers of the directories containing their layers.
let prefix = format!("{base}/pages/");
let page_names: Vec<String> = z
.file_names()
.names()
.filter(|name| {
name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))
})
.take(501)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect();
if page_names.len() > 500 {
return Err(corrupt("too many pages"));
@@ -508,13 +521,13 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
}
let page_prefix = format!("{prefix}{page_id}/");
let paths: Vec<String> = z
.file_names()
.names()
.filter(|name| {
name.strip_prefix(&page_prefix)
.is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))
})
.take(MAX_LAYERS + 1)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect();
if paths.len() > MAX_LAYERS {
return Err(corrupt("too many layers on a page"));
@@ -1439,13 +1452,13 @@ fn bind_applied_tokens(doc: &mut Document, active_modes: &BTreeMap<String, Strin
/// Import Penpot library colors as reusable native styles. Original design-token
/// references are handled separately by `bind_applied_tokens` after shape import.
fn import_document_colors(z: &mut ZipArchive<Cursor<&[u8]>>, base: &str, doc: &mut Document, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
fn import_document_colors(z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
let prefix = format!("{base}/colors/");
let paths = z
.file_names()
.names()
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
.take(2049)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect::<Vec<_>>();
if paths.len() > 2048 {
warn(warnings, "Penpot color library exceeds 2048 swatches; truncated".into());
@@ -1483,7 +1496,7 @@ fn import_document_colors(z: &mut ZipArchive<Cursor<&[u8]>>, base: &str, doc: &m
/// Keep original values on the text nodes: attaching a shared style automatically
/// would override local formatting unless the source explicitly links it.
fn import_typography_styles(
z: &mut ZipArchive<Cursor<&[u8]>>,
z: &mut PenpotArchive<'_>,
base: &str,
doc: &mut Document,
warnings: &mut Vec<String>,
@@ -1492,10 +1505,10 @@ fn import_typography_styles(
let mut custom_refs = Vec::new();
let prefix = format!("{base}/typographies/");
let paths: Vec<String> = z
.file_names()
.names()
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
.take(2049)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect();
if paths.len() > 2048 {
warn(warnings, "Penpot typography library exceeds 2048 entries; truncated".into());
@@ -2359,7 +2372,7 @@ fn import_themed_tokens(
/// Import supported scalar tokens and retain their original source.
fn import_token_variables(
z: &mut ZipArchive<Cursor<&[u8]>>,
z: &mut PenpotArchive<'_>,
base: &str,
doc: &mut Document,
active_modes: &mut BTreeMap<String, String>,
@@ -2367,7 +2380,9 @@ fn import_token_variables(
budget: &mut InflateBudget,
) -> Option<String> {
let path = format!("{base}/tokens.json");
z.index_for_name(&path)?;
if !z.contains(&path) {
return None;
}
let value = match json(z, &path, budget) {
Ok(v) => v,
Err(_) => {
@@ -2501,16 +2516,16 @@ fn report_design_system_limits(doc: &Document, warnings: &mut Vec<String>) {
/// that original into a native FigCraft component. Copies are still independent layers until the
/// Penpot override/source graph can be translated safely (see docs).
fn component_masters(
z: &mut ZipArchive<Cursor<&[u8]>>,
z: &mut PenpotArchive<'_>,
base: &str,
budget: &mut InflateBudget,
) -> (BTreeMap<String, String>, BTreeMap<String, String>, BTreeMap<String, String>) {
let prefix = format!("{base}/components/");
let paths = z
.file_names()
.names()
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
.take(10001)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect::<Vec<_>>();
let mut result = BTreeMap::new();
let mut variant_names = BTreeMap::new();
@@ -2971,7 +2986,7 @@ fn svg_paint_ref(text: &str) -> Option<&str> {
/// What importing a page's layers shares from layer to layer: the archive and the page's shapes,
/// and the document, budgets and warnings they add to.
struct LayerImport<'a, 'b> {
z: &'a mut ZipArchive<Cursor<&'b [u8]>>,
z: &'a mut PenpotArchive<'b>,
base: &'a str,
shapes: &'a BTreeMap<String, Value>,
children_by_parent: &'a BTreeMap<String, Vec<String>>,
@@ -4137,7 +4152,7 @@ fn effects(v: &Value, warnings: &mut Vec<String>) -> Vec<Effect> {
/// Resolve a Penpot image fill through `media/<id>.json` -> `objects/<mediaId>.png|jpg`.
fn paints(
z: &mut ZipArchive<Cursor<&[u8]>>,
z: &mut PenpotArchive<'_>,
base: &str,
shape: &Value,
key: &str,
@@ -4172,10 +4187,7 @@ fn paints(
};
if let Some(obj) = object_id {
let p = format!("objects/{obj}.{extension}");
let data = z.by_name(&p).ok().and_then(|f| {
if f.size() > MAX_IMAGE {
return None;
}
let data = z.open_entry(&p, MAX_IMAGE).ok().flatten().and_then(|f| {
let mut bytes = Vec::new();
BudgetReader { inner: f, budget: &mut *budget }.take(MAX_IMAGE + 1).read_to_end(&mut bytes).ok()?;
if bytes.len() as u64 > MAX_IMAGE || bytes.len() > MAX_TOTAL_IMAGES.saturating_sub(*image_bytes) {
@@ -4387,7 +4399,7 @@ mod tests {
writer.write_all(b"[0,0]").unwrap();
}
let bytes = writer.finish().unwrap().into_inner();
let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
let mut archive = open_archive(&bytes).unwrap();
let mut budget = InflateBudget { json_values: 6, ..InflateBudget::new() };
let mut page_bytes = MAX_PAGE_SHAPES_BYTES;
assert_eq!(json(&mut archive, "tokens.json", &mut budget).unwrap(), serde_json::json!([0, 0]));
@@ -4436,8 +4448,8 @@ mod tests {
assert!(dense.len() < MAX_JSON as usize);
for index in 0..source.len() {
let mut member = source.by_index(index).unwrap();
writer.start_file(member.name(), crate::json_options()).unwrap();
if member.name().ends_with(&format!("/{id}.json")) {
writer.start_file(member.name().expect("ZIP member name"), crate::json_options()).unwrap();
if member.name().expect("ZIP member name").ends_with(&format!("/{id}.json")) {
writer.write_all(dense.as_bytes()).unwrap();
} else {
io::copy(&mut member, &mut writer).unwrap();
@@ -4495,14 +4507,14 @@ mod tests {
z.start_file("shape.json", SimpleFileOptions::default()).unwrap();
z.write_all(br#"{"id":"00000000-0000-0000-0000-000000000001","type":"rect"}"#).unwrap();
let bytes = z.finish().unwrap().into_inner();
let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
let mut archive = open_archive(&bytes).unwrap();
let mut inflate_budget = InflateBudget::new();
let mut page_budget = 10u64; // Too small for the shape JSON (~60 bytes)
let res = shape_json(&mut archive, "shape.json", &mut inflate_budget, &mut page_budget);
assert!(res.is_err());
let mut archive2 = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
let mut archive2 = open_archive(&bytes).unwrap();
let mut inflate_budget2 = InflateBudget::new();
let mut page_budget2 = 1000u64;
let res2 = shape_json(&mut archive2, "shape.json", &mut inflate_budget2, &mut page_budget2);
@@ -4510,7 +4522,7 @@ mod tests {
assert!(page_budget2 < 1000);
}
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::{ZipArchive, write::SimpleFileOptions};
fn archive_with_shapes(shapes: &[(&str, Value)]) -> Vec<u8> {
archive_with_components(shapes, &[])
@@ -4548,6 +4560,23 @@ mod tests {
z.finish().unwrap().into_inner()
}
#[test]
fn import_allows_a_legacy_encoded_ancillary_zip_member() {
let id = "cccccccc-cccc-cccc-cccc-cccccccccccc";
let bytes = archive_with_shapes(&[(id, serde_json::json!({"id":id,"type":"rect","name":"Imported rectangle","width":40,"height":25}))]);
let mut writer = zip::ZipWriter::new_append(Cursor::new(bytes)).unwrap();
// Unflagged CP437, as written by legacy ZIP tools: 0x82 is é.
writer.start_file_with_options(SimpleFileOptions::default().name(b"caf\x82.txt")).unwrap();
writer.write_all(b"Ancillary archive note").unwrap();
let bytes = writer.finish().unwrap().into_inner();
let mut archive = open_archive(&bytes).unwrap();
assert!((0..archive.len()).any(|i| archive.entry_name(i).unwrap().as_deref() == Some("café.txt")));
let (doc, warnings) = import(&bytes).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
assert!(doc.nodes().any(|node| node.name == "Imported rectangle"));
}
#[test]
fn raw_svg_from_export_is_preserved_for_native_svg_expansion() {
let id = "cccccccc-cccc-cccc-cccc-cccccccccccc";
@@ -4931,12 +4960,12 @@ mod tests {
let mut e = z.by_index(i).unwrap();
let mut content = Vec::new();
e.read_to_end(&mut content).unwrap();
if e.name().ends_with(&format!("/{ROOT_ID}.json")) {
if e.name().expect("ZIP member name").ends_with(&format!("/{ROOT_ID}.json")) {
let mut v: Value = serde_json::from_slice(&content).unwrap();
v["shapes"] = serde_json::json!([one]);
content = serde_json::to_vec(&v).unwrap();
}
members.push((e.name().to_string(), content));
members.push((e.name().expect("ZIP member name").to_string(), content));
}
drop(z);
let cursor = Cursor::new(Vec::new());
+8 -9
View File
@@ -1,20 +1,19 @@
//! Embedded font detection without decoding or retaining unsupported binaries.
use super::{BudgetReader, InflateBudget, MAX_ENTRIES, warn};
use std::io::{Cursor, Read};
use zip::ZipArchive;
use super::{BudgetReader, InflateBudget, MAX_ENTRIES, PenpotArchive, warn};
use std::io::Read;
/// Identify unsupported fonts from signatures without decoding their payloads.
pub(super) fn report(z: &mut ZipArchive<Cursor<&[u8]>>, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
pub(super) fn report(z: &mut PenpotArchive<'_>, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
let names: Vec<String> = z
.file_names()
.names()
.filter(|n| n.starts_with("objects/") || n.starts_with("fonts/") || n.starts_with("assets/fonts/"))
.take(MAX_ENTRIES)
.map(str::to_owned)
.map(std::borrow::Cow::into_owned)
.collect();
let mut count = 0;
for name in names {
let Ok(member) = z.by_name(&name) else { continue };
let Ok(Some(member)) = z.open_entry(&name, u64::MAX) else { continue };
let mut header = [0; 4];
if (BudgetReader { inner: member, budget }).read_exact(&mut header).is_ok()
&& (matches!(&header, b"OTTO" | b"true" | b"ttcf" | b"wOFF" | b"wOF2") || header == [0, 1, 0, 0])
@@ -35,7 +34,7 @@ pub(super) fn report(z: &mut ZipArchive<Cursor<&[u8]>>, warnings: &mut Vec<Strin
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::io::{Cursor, Write};
use zip::{ZipWriter, write::SimpleFileOptions};
#[test]
@@ -45,7 +44,7 @@ mod tests {
z.write_all(b"wOF2").unwrap();
z.write_all(&vec![0; 100_000]).unwrap();
let bytes = z.finish().unwrap().into_inner();
let mut z = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
let mut z = super::super::open_archive(&bytes).unwrap();
let mut budget = InflateBudget::new();
let before = budget.remaining;
let mut warnings = Vec::new();
+3 -3
View File
@@ -18,7 +18,7 @@ fn entries(bytes: &[u8]) -> BTreeMap<String, Value> {
let mut out = BTreeMap::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let name = f.name().to_owned();
let name = f.name().expect("ZIP member name").into_owned();
if name.ends_with(".json") {
let mut text = String::new();
f.read_to_string(&mut text).unwrap();
@@ -684,7 +684,7 @@ fn imported_penpot_tokens_are_written_back_verbatim() {
doc.node_mut(p).unwrap().plugin_data.insert("penpot.fp.tokens".into(), fp);
let (bytes, warnings) = export(&doc).unwrap();
let mut z = zip::ZipArchive::new(Cursor::new(&bytes[..])).unwrap();
let path = z.file_names().find(|n| n.ends_with("tokens.json")).unwrap().to_owned();
let path = z.file_names().map(|name| name.expect("ZIP member name")).find(|n| n.ends_with("tokens.json")).unwrap().into_owned();
let mut text = String::new();
z.by_name(&path).unwrap().read_to_string(&mut text).unwrap();
assert_eq!(text, source);
@@ -1033,7 +1033,7 @@ fn shared_writer_keeps_manifest_first_and_deflated_members() {
let doc = Document::new("Shared container");
let (bytes, _) = export(&doc).unwrap();
let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json");
assert_eq!(zip.by_index(0).unwrap().name().expect("ZIP member name"), "manifest.json");
for index in 0..zip.len() {
assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated);
}
+35 -4
View File
@@ -767,10 +767,15 @@ impl<'a> Ctx<'a> {
}
/// The `board` field (a FigCraft extension): what the object is on a board. A sticky or shape
/// is set at once; anything else, or junk, is ignored with a warning.
/// is set at once, a connector (a vector) once every layer is in and its ends can be found;
/// anything else, or junk, is ignored with a warning.
fn board_item(&mut self, n: &mut Node, b: &'a Value) {
// A sticky or shape is a frame holding its layers: on anything else it is ignored.
let frame = n.kind.is_frame_like();
if text(b, "type") == Some("connector") && matches!(n.kind, NodeKind::Vector { .. }) {
self.pending_boards.push((n.id, b));
return;
}
let item = match text(b, "type") {
Some("sticky") if frame => {
let author = text(b, "author").unwrap_or("").trim();
@@ -789,10 +794,36 @@ impl<'a> Ctx<'a> {
/// Board items that name other layers (connector ends, a label's connector), once every
/// layer is imported and `ids` can resolve them.
/// A connector's `from` and `to` are each `{node: <REST id>, side?, at?: [x, y]}` (`at`: where
/// on the layer, as fractions of its box) or a page point `{x, y}`; `routing` is straight,
/// elbow or curved. One whose ends don't resolve is ignored with a warning (it stays a vector).
fn resolve_boards(&mut self) {
for (id, _) in std::mem::take(&mut self.pending_boards) {
let name = self.doc.node(id).map(|n| n.name.clone()).unwrap_or_default();
self.warn(format!("unknown board item on {name} was ignored"));
for (id, b) in std::mem::take(&mut self.pending_boards) {
let end = |e: &Value| -> Option<figcraft_doc::End> {
let Some(rest_id) = text(e, "node") else {
let (x, y) = (num(e, "x")?, num(e, "y")?);
let c = |v: f64| v.clamp(-MAX_COORD, MAX_COORD);
return (x.is_finite() && y.is_finite()).then(|| figcraft_doc::End::Point { x: c(x), y: c(y) });
};
let node = *self.ids.get(rest_id).filter(|node| **node != id)?;
let side = text(e, "side").and_then(figcraft_doc::Side::from_id).unwrap_or_default();
let at = list(e, "at").iter().map(Value::as_f64).collect::<Option<Vec<f64>>>().and_then(|v| match v.as_slice() {
[x, y] if x.is_finite() && y.is_finite() => Some([x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]),
_ => None,
});
Some(figcraft_doc::End::Node { node, side, at })
};
let ends = b.get("from").and_then(end).zip(b.get("to").and_then(end));
let routing = text(b, "routing").and_then(figcraft_doc::Routing::from_id).unwrap_or_default();
match (ends, self.doc.node_mut(id)) {
(Some((from, to)), Some(n)) => {
n.board = Some(figcraft_doc::BoardItem::Connector(figcraft_doc::Connector { from, to, routing, path: None, branch: false }));
}
(_, n) => {
let name = n.map(|n| n.name.clone()).unwrap_or_default();
self.warn(format!("unknown board item on {name} was ignored"));
}
}
}
}
+38 -3
View File
@@ -20,6 +20,22 @@ pub use transform::*;
/// Corner radii in clockwise order from the top-left: `[tl, tr, br, bl]`.
pub type Radii = [f64; 4];
/// How the outline joins two sides at a rectangle's corners.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CornerStyle {
#[default]
Round,
Chamfer,
Concave,
}
impl CornerStyle {
pub fn is_round(&self) -> bool {
*self == Self::Round
}
}
/// The largest magnitude a shape builder takes for a size, radius or angle. kurbo subdivides an
/// arc in proportion to the sixth root of its radius, so an uncapped radius means an unbounded
/// number of segments: 1e36 is about a million cubics and 1e60 never returns. Sizes come from
@@ -110,13 +126,18 @@ fn finite(v: f64) -> f64 {
/// Radii are clamped so adjacent corners never overlap; when smoothing doesn't fit, it is reduced
/// first, then the radius.
pub fn rounded_rect(width: f64, height: f64, radii: Radii, smoothing: f64) -> BezPath {
styled_rect(width, height, radii, smoothing, CornerStyle::Round)
}
/// A rectangle with editable corner cuts. Smoothing applies to round corners.
pub fn styled_rect(width: f64, height: f64, radii: Radii, smoothing: f64, style: CornerStyle) -> BezPath {
let w = bounded(width).max(0.0);
let h = bounded(height).max(0.0);
let mut path = BezPath::new();
if w <= 0.0 && h <= 0.0 {
return path;
}
let s = bounded(smoothing).clamp(0.0, 1.0);
let s = if style.is_round() { bounded(smoothing).clamp(0.0, 1.0) } else { 0.0 };
let max_r = w.min(h) / 2.0;
let radii = radii.map(|r| bounded(r).clamp(0.0, max_r));
if radii.iter().all(|r| *r <= 0.0) {
@@ -138,8 +159,22 @@ pub fn rounded_rect(width: f64, height: f64, radii: Radii, smoothing: f64) -> Be
// Start on the top edge just after the top-left corner.
path.move_to((first.p, 0.0));
for (c, din, dout, r) in corners {
let prof = corner_profile(r, s, max_r);
append_corner(&mut path, c, din, dout, &prof);
if style.is_round() {
append_corner(&mut path, c, din, dout, &corner_profile(r, s, max_r));
} else if r == 0.0 {
path.line_to(c);
} else {
let from = c - din * r;
let to = c + dout * r;
path.line_to(from);
if style == CornerStyle::Chamfer {
path.line_to(to);
} else {
// An inward quarter circle centred on the original corner.
let handle = 0.552_284_749_830_793_6 * r;
path.curve_to(from + dout * handle, to - din * handle, to);
}
}
}
path.close_path();
path
+18
View File
@@ -18,6 +18,24 @@ fn rounded_rect_area_matches_circle_corners() {
assert!((area(&p) - expected).abs() < 0.5, "{} vs {}", area(&p), expected);
}
#[test]
fn corner_styles_cut_each_corner_at_its_own_radius() {
let radii = [20.0, 8.0, 0.0, 4.0];
let cut = radii.iter().map(|r| r * r).sum::<f64>();
let rect = |style| styled_rect(100.0, 50.0, radii, 0.6, style);
let chamfer = rect(CornerStyle::Chamfer);
let concave = rect(CornerStyle::Concave);
assert!((area(&chamfer) - (5000.0 - cut / 2.0)).abs() < 1e-6);
assert!((area(&concave) - (5000.0 - PI * cut / 4.0)).abs() < 0.2);
assert!(chamfer.contains(Point::new(11.0, 11.0)));
assert!(!concave.contains(Point::new(11.0, 11.0)));
assert!(concave.contains(Point::new(99.0, 49.0)));
for style in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave] {
assert_eq!(styled_rect(100.0, 50.0, [0.0; 4], 0.6, style), rounded_rect(100.0, 50.0, [0.0; 4], 0.0));
assert_eq!(styled_rect(100.0, 50.0, [900.0; 4], 0.0, style), styled_rect(100.0, 50.0, [25.0; 4], 0.0, style));
}
}
#[test]
fn full_radius_is_capsule_and_bounds_hold() {
let p = rounded_rect(100.0, 40.0, [1000.0; 4], 0.0);
+61
View File
@@ -117,6 +117,32 @@ pub const PROMPTS: &[PromptDef] = &[
4. Stop after {minutes} minutes; summarize the threads you fixed and the ones still open (and why)."#,
defaults: &[("minutes", "5")],
},
PromptDef {
name: "implement_design",
title: "Implement the selected design",
description: "Build the design selected in FigCraft in this codebase from its stated values, real assets and connected components, then check the result against the design.",
args: &[PromptArg {
name: "destination",
description: "Where it goes in the code, e.g. a route or a component (default: ask if it isn't clear)",
required: false,
}],
template: r#"Implement the design selected in FigCraft in this codebase. Destination: {destination}.
Paths you pass are absolute, or relative to where the FigCraft MCP server runs, which may not be this project; they must be inside its automation roots when it has them.
1. Read the design with design_context {}. Check `target` first: if its `source` is `page`, nothing was selected and you have the whole page, so ask the designer which frame to build unless the whole page is meant. Where the tree stops, a layer has `childCount` instead of `children`; if the result has `truncated`, call design_context again with the `ids` of the parts you need.
2. Learn the project before writing code: its components, styling, tokens and where files go.
3. Reuse code that exists. A layer with `code` is connected to a code component: write its `code` snippet with its `importPath`, follow its `notes`, and don't build its children. component_mappings {"unmapped": true} lists the design's components with no code component yet: search the project for each before creating one. If the project has a figcraft.connect.json with mappings component_mappings doesn't show, ask the designer before running sync_mappings {"direction": "import"}: it changes the design (one undo step).
4. Use tokens over literal values. A layer's `tokens` name the variables and shared styles it uses: for a variable, use its `codeSyntax` from `variables` when it has one, else the project's matching token; for a style, the project's style of that `name`. Fall back to the resolved value only when the project has neither.
5. Treat `explicit` values as the specification. `derived` values are what layout worked out at this size: build the layout that produces them with the platform's own layout (flex or grid on the web, stacks natively), filling and hugging as the design does, instead of hard-coding them.
6. Bring in the real assets: export_assets {"ids": <the ids in target>, "dir": "<the project's asset folder>"} writes them as files and lists each one. Use those files, never screenshots or redrawn stand-ins. An asset whose `source` is `rendered` isn't the original image, each entry in its `adjustments` still has to be applied in code, and `skipped` says what couldn't be handed over. If the result has `truncated`, call export_assets again with the `ids` of the parts it left out. Fonts aren't exported: `fonts` lists them, and the project has to provide each one and check its licence.
7. For each `unsupported` entry, get as close as the platform allows and list it in your report. Never drop one silently.
8. Read what the design leaves open: `missing`, and the designer's annotations from run_command {"command": "annotation.list", "params": {"page": <the id of the page in document>}}, keeping those whose `id` is a layer in the tree: the rest belong to other designs. Don't invent behaviour the design doesn't state: ask, or report what you assumed.
9. For other screen sizes, follow `responsive`: its `versions` group the designs of one screen at each size, and its `rules` are the designer's instructions. Read the other sizes' `frames` with design_context {"ids": [...]} before building them. When its `explicit` is false the file states no breakpoints: keep to what constraints, sizing and annotations say, and say so instead of inventing breakpoints.
10. If a browser tool is available and the app runs, check the result. Size the browser to the frame's width and height in CSS pixels, capture the page to a file inside the project, and call compare_design {"id": <the frame's id>, "image": "<the capture>"}, one frame at a time; each result repeats the size as `viewport`. Fix the layers in `differences` and repeat. An empty list means no layer differs on 2% or more of its pixels, not that every pixel matches. Delete the captures afterwards. Without a browser tool, say the result wasn't checked against the design.
11. Finish with a report: the files you changed, the components you reused and created, what you approximated, what you assumed, what the design left missing, and whether the result was compared with the design."#,
defaults: &[("destination", "ask if it isn't clear")],
},
];
pub fn list() -> Value {
@@ -196,6 +222,41 @@ mod tests {
assert!(out.len() < 3 * bomb.len(), "{}", out.len());
}
/// Every tool and result field the instructions and prompts name exists: an agent told to call a
/// renamed tool, or to read a field that was renamed, follows a workflow that points at nothing.
#[test]
fn the_tools_and_fields_the_instructions_and_prompts_name_exist() {
let tools = crate::tool_definitions();
// Every name a tool's or command's documentation gives: its fields and arguments.
let documented: String = tools
.iter()
.map(Value::to_string)
.chain(figcraft_engine::all_commands().iter().map(|c| format!("{} {}", c.id, c.params)))
.collect::<Vec<_>>()
.join(" ");
let words: std::collections::HashSet<&str> =
documented.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')).map(|w| w.trim_matches('.')).collect();
let tool_names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
let prompt_names: Vec<&str> = PROMPTS.iter().map(|p| p.name).collect();
let texts = std::iter::once((crate::INSTRUCTIONS, &[][..])).chain(PROMPTS.iter().map(|p| (p.template, p.args)));
let (mut tools_named, mut fields_named) = (0, 0);
for (text, args) in texts {
for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| w.contains('_')) {
tools_named += 1;
let known = tool_names.contains(&word) || prompt_names.contains(&word) || args.iter().any(|a| a.name == word);
assert!(known, "`{word}` is neither a tool, a prompt nor one of the prompt's arguments");
}
for quoted in text.split('`').skip(1).step_by(2) {
if quoted.is_empty() || !quoted.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') {
continue;
}
fields_named += 1;
assert!(words.contains(quoted), "`{quoted}` is in no tool's or command's documentation");
}
}
assert!(tools_named > 10 && fields_named > 3, "the check found the names ({tools_named}, {fields_named})");
}
/// Every command the server's instructions and the prompts name exists: an agent told to run a
/// renamed or misspelt one gets an error instead of the workflow.
#[test]
+1 -1
View File
@@ -56,7 +56,7 @@ with severities; design.fix repairs the fixable ones as one undo step; design.ru
presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \
design.assert {failOn, minScore} is a read-only CI gate. \
Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \
prompts/list has workflows, including fix_comments and design_review.";
prompts/list has workflows, including fix_comments, design_review and implement_design (build the selected design in a codebase).";
/// An MCP server bound to one backend.
pub struct Server {
+24 -8
View File
@@ -195,7 +195,7 @@ fn tools() -> Vec<Value> {
tool(
"create_node",
"Create layer",
"Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face.",
"Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face. `fields` / `outline` shrink the returned layer as they do for get_node; the layer is created either way.",
obj(
json!({
"type": {"type": "string", "enum": ["frame", "rectangle", "ellipse", "polygon", "star", "line", "arrow", "text", "vector", "section", "component", "slice"], "description": "Layer type"},
@@ -212,6 +212,8 @@ fn tools() -> Vec<Value> {
"closed": boolean("For type vector: close the path"),
"select": boolean("Select the new layer (default true)"),
"props": {"type": "object", "description": "Any set_properties keys applied at creation, e.g. {\"fill\":\"#3366FF\",\"cornerRadius\":12,\"fontSize\":24,\"layout\":\"vertical\",\"gap\":8,\"padding\":16}"},
"fields": fields_schema(),
"outline": outline_schema(),
}),
&["type"],
),
@@ -220,9 +222,14 @@ fn tools() -> Vec<Value> {
tool(
"set_properties",
"Set properties",
"Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.",
"Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers (up to 20); `fields` / `outline` shrink them as they do for get_node.",
obj(
json!({"ids": ids_schema("Layer ids (default: the selection)"), "props": {"type": "object", "description": "Property values to set"}}),
json!({
"ids": ids_schema("Layer ids (default: the selection)"),
"props": {"type": "object", "description": "Property values to set"},
"fields": fields_schema(),
"outline": outline_schema(),
}),
&["props"],
),
false,
@@ -836,6 +843,8 @@ fn create_node(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult
{
return Err("`props` must be an object".into());
}
// Checked before the layer is made, so a bad option changes nothing.
let options = inspection_options(a)?;
let mut params = Map::new();
for k in ["type", "x", "y", "width", "height", "parent", "index", "name", "text", "path", "points", "closed", "props", "select"] {
if let Some(v) = a.get(k).filter(|v| !v.is_null()) {
@@ -848,7 +857,7 @@ fn create_node(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult
let r = exec(b, "node.create", Value::Object(params))?;
let id = r.get("id").cloned().ok_or("node.create returned no id")?;
let warnings = r.get("warnings").cloned();
let node = b.call("node.get", json!({"id": id, "depth": 0}))?;
let node = node_get(b, id_arg(&id)?, 0, &options)?;
let mut out = json!({"id": id, "node": node});
if let Some(w) = warnings {
out["warnings"] = w;
@@ -863,6 +872,8 @@ fn set_properties(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolRes
};
let mut props = props;
normalize_props(&mut props);
// Checked before anything is set, so a bad option changes nothing.
let options = inspection_options(a)?;
let mut params = json!({"props": props});
let ids = ids_arg(a, "ids")?;
if let Some(ids) = &ids {
@@ -881,7 +892,7 @@ fn set_properties(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolRes
.map(|a| a.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
};
let nodes: Vec<Value> = ids.iter().take(20).filter_map(|i| b.call("node.get", json!({"id": i, "depth": 0})).ok()).collect();
let nodes: Vec<Value> = ids.iter().take(20).filter_map(|&i| node_get(b, i, 0, &options).ok()).collect();
let mut out = json!({"ok": true, "nodes": nodes});
if let Some(w) = warnings {
out["warnings"] = w;
@@ -941,12 +952,17 @@ fn inspect_at(b: &mut dyn Backend, depth: u64, all: bool, options: &Value) -> Re
Ok((value, wire))
}
/// One layer's subtree at `depth`, and what its text block would take on the wire.
fn node_at(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result<(Value, usize), String> {
/// One layer's subtree at `depth`, with the `fields` / `outline` options applied.
fn node_get(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result<Value, String> {
let mut params = options.clone();
params["id"] = json!(id);
params["depth"] = json!(depth);
let value = b.call("node.get", params)?;
b.call("node.get", params)
}
/// One layer's subtree at `depth`, and what its text block would take on the wire.
fn node_at(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result<(Value, usize), String> {
let value = node_get(b, id, depth, options)?;
let wire = wire_size(&value);
Ok((value, wire))
}
+56 -1
View File
@@ -35,7 +35,7 @@ fn compact_keys(node: &Value, outline: bool) {
fn tool_schemas_describe_compact_inspection_options() {
let mut c = Client::new();
let tools = c.rpc("tools/list", json!({}));
for name in ["inspect_document", "get_node"] {
for name in ["inspect_document", "get_node", "create_node", "set_properties"] {
let tool = tools["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == name).unwrap();
let props = &tool["inputSchema"]["properties"];
assert_eq!(props["fields"]["type"], "array");
@@ -193,6 +193,61 @@ fn compact_examples_run_verbatim_from_the_docs() {
}
}
/// The mutation tools return the layers they touched; with `fields` or `outline` that echo is cut
/// down to what the agent asked for, and without them it stays complete.
#[test]
fn mutation_results_take_fields_and_outline() {
let mut c = Client::new();
let card = json!({"type": "frame", "name": "Card", "width": 280, "height": 160, "props": {"fill": "#F0F0F0", "cornerRadius": 12}});
let full = c.ok("create_node", card.clone());
let mut args = card.clone();
args["fields"] = json!(["name"]);
let picked = c.ok("create_node", args);
compact_keys(&picked["node"], false);
assert_eq!(picked["node"]["name"], "Card");
assert!(picked.to_string().len() < full.to_string().len(), "{picked} vs {full}");
let mut args = card;
args["outline"] = json!(true);
let outlined = c.ok("create_node", args);
compact_keys(&outlined["node"], true);
assert_eq!(outlined["node"]["type"], full["node"]["type"]);
let ids = json!([full["id"], picked["id"], outlined["id"]]);
let set = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 0.5}}));
let slim = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 0.4}, "fields": ["opacity"]}));
let (set, slim) = (set["nodes"].as_array().unwrap(), slim["nodes"].as_array().unwrap());
assert_eq!(slim.len(), set.len(), "every layer is still reported");
for (whole, cut) in set.iter().zip(slim) {
assert_eq!(cut["id"], whole["id"]);
assert!(cut["opacity"].as_f64().is_some_and(|o| (o - 0.4).abs() < 1e-6), "{cut}");
assert!(cut.as_object().unwrap().len() < whole.as_object().unwrap().len(), "{cut} vs {whole}");
}
let outlined = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 1}, "outline": true}));
for node in outlined["nodes"].as_array().unwrap() {
compact_keys(node, true);
}
}
/// A bad option is caught before the edit runs: the call fails and the document is as it was.
#[test]
fn a_bad_option_on_a_mutation_changes_nothing() {
let mut c = Client::new();
let id = c.create(json!({"type": "rectangle", "name": "Keep"}));
let before = c.doc();
for bad in [json!({"fields": ["Name"]}), json!({"outline": true, "fields": []}), json!({"outline": "yes"})] {
let mut create = json!({"type": "ellipse", "name": "Extra"});
let mut set = json!({"ids": [id], "props": {"name": "Changed"}});
for (k, v) in bad.as_object().unwrap() {
create[k] = v.clone();
set[k] = v.clone();
}
assert!(!c.err("create_node", create).is_empty());
assert!(!c.err("set_properties", set).is_empty());
}
let after = c.doc();
assert_eq!(after["pages"], before["pages"], "a rejected call left the layers as they were");
}
#[test]
fn invalid_compact_options_fail_in_tools_and_headless_control() {
let mut c = Client::new();
+4 -1
View File
@@ -219,7 +219,10 @@ fn prompts_list_and_get() {
let mut c = Client::new();
let r = c.rpc("prompts/list", json!({}));
let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect();
assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]);
assert_eq!(
names,
["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments", "implement_design"]
);
let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}}));
let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap();
assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}"));
+34 -3
View File
@@ -200,14 +200,16 @@ pub(crate) fn hash_path(p: &BezPath, h: &mut impl Hasher) {
fn side_strokes(n: &Node) -> Option<Arc<BezPath>> {
let props = &n.stroke;
let sides = props.sides?;
if !matches!(n.kind, NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. }) {
if !n.kind.has_independent_corners() {
return None;
}
let c = &n.corners;
Some(Arc::new(if c.uniform() == Some(0.0) {
figcraft_pathops::rect_side_strokes(n.width, n.height, sides, props.align)
} else {
} else if c.style.is_round() {
figcraft_pathops::rounded_side_strokes(n.width, n.height, c.radii, c.smoothing, sides, props.align)
} else {
cut_side_strokes(n, &figcraft_doc::geometry::shape_path(n)?, sides)
}))
}
@@ -239,7 +241,7 @@ fn ring(n: &Node, inset: f64) -> Option<BezPath> {
| NodeKind::ComponentSet { .. }
| NodeKind::Instance { .. }
| NodeKind::Section { .. }
if n.corners.smoothing == 0.0 =>
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
{
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
@@ -253,6 +255,35 @@ fn ring(n: &Node, inset: f64) -> Option<BezPath> {
}
}
/// Stroke each side at its own weight, meeting its neighbours on the corner bisectors.
fn cut_side_strokes(n: &Node, path: &BezPath, sides: [f64; 4]) -> BezPath {
let band = |weight| figcraft_pathops::stroke_outline(path, &figcraft_doc::StrokeProps { weight, sides: None, ..n.stroke.clone() }, true);
if sides.iter().all(|w| *w == sides[0]) {
return band(sides[0]);
}
let (w, h) = (n.width, n.height);
let mid = w.min(h) / 2.0;
let inner = [(mid, mid), (w - mid, mid), (w - mid, h - mid), (mid, h - mid)];
let mut out = BezPath::new();
for (i, weight) in sides.into_iter().enumerate().filter(|(_, weight)| *weight > 0.0) {
let stroke = band(weight);
let b = stroke.bounding_box();
let pad = 1.0 + (-b.x0).max(-b.y0).max(b.x1 - w).max(b.y1 - h).max(0.0);
let outer = [(-pad, -pad), (w + pad, -pad), (w + pad, h + pad), (-pad, h + pad)];
let next = (i + 1) % 4;
let mut side = BezPath::new();
side.move_to(outer[i]);
side.line_to(outer[next]);
side.line_to(inner[next]);
side.line_to(inner[i]);
side.close_path();
if let Ok(part) = figcraft_pathops::boolean_step(&stroke, &side, figcraft_doc::BoolOp::Intersect) {
out.extend(part.elements().iter().copied());
}
}
out
}
/// The stroke area of a node in local coordinates.
pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
if let Some(p) = side_strokes(n) {
+84 -1
View File
@@ -48,6 +48,32 @@ fn row_jobs(src: &[[u8; 4]], dst: &mut [[u8; 4]], w: usize, job: impl Fn(&[[u8;
src.chunks(n).zip(dst.chunks_mut(n)).for_each(|(s, d)| job(s, d));
}
/// Division by a box's width `d` as a multiply and a shift, exact for every sum of `d` bytes (at
/// most 255 × `d`, under `2^n` for `n` = 8 + ⌈log₂ d⌉): with `m` = ⌈2^(n + ⌈log₂ d⌉) / d⌉, the
/// product overshoots the quotient by less than 1/d, which never reaches the next whole number.
/// A divide per channel per pixel took about a third of a blur's time on one thread.
#[derive(Clone, Copy)]
struct ByWidth {
m: u64,
shift: u32,
}
impl ByWidth {
/// `None` for widths whose products could pass 64 bits (over 2^23 pixels: no box is that wide).
fn new(d: u32) -> Option<ByWidth> {
let log = u32::BITS - d.checked_sub(1)?.leading_zeros();
if log > 23 {
return None;
}
let shift = 8 + 2 * log;
Some(ByWidth { m: (1u64 << shift).div_ceil(u64::from(d)), shift })
}
fn of(self, sum: u32) -> u8 {
((u64::from(sum) * self.m) >> self.shift) as u8
}
}
/// One row box-blurred by radius `r` (transparent past its ends) into `dst`, the same length.
fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
if r == 0 {
@@ -55,6 +81,14 @@ fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
return;
}
let div = (2 * r + 1) as u32;
match ByWidth::new(div) {
Some(by) => box_sums(src, dst, r, |a| by.of(a)),
None => box_sums(src, dst, r, |a| (a / div) as u8),
}
}
/// [`box_blur_row`] with each window's sum divided by its width by `quotient`.
fn box_sums(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize, quotient: impl Fn(u32) -> u8) {
let mut acc = [0u32; 4];
for p in src.iter().take(r + 1) {
for (a, c) in acc.iter_mut().zip(p) {
@@ -62,7 +96,7 @@ fn box_blur_row(src: &[[u8; 4]], dst: &mut [[u8; 4]], r: usize) {
}
}
for (x, d) in dst.iter_mut().enumerate() {
*d = acc.map(|a| (a / div) as u8);
*d = acc.map(&quotient);
if let Some(p) = src.get(x + r + 1) {
for (a, c) in acc.iter_mut().zip(p) {
*a += u32::from(*c);
@@ -586,6 +620,55 @@ mod tests {
}
}
/// Blur timings, the best of several runs: in parallel (a full render's blur) and on one
/// thread (a band of a parallel render, the browser). Run in release:
/// `cargo test --release -p figcraft-render --lib blur_timings -- --ignored --nocapture`.
#[cfg(not(target_arch = "wasm32"))]
#[test]
#[ignore = "timing: run in release with --ignored --nocapture"]
fn blur_timings() {
let one = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
let best = |src: &Pixmap, sigma: f64, runs: u32, on_one: bool| {
(0..runs)
.map(|_| {
let mut p = src.clone();
let t = std::time::Instant::now();
if on_one {
one.install(|| blur(&mut p, sigma));
} else {
blur(&mut p, sigma);
}
t.elapsed().as_secs_f64() * 1000.0
})
.fold(f64::MAX, f64::min)
};
println!("| pixmap | sigma | parallel ms | one thread ms |\n|---|---:|---:|---:|");
for (w, h, sigma) in [(1700u32, 1200u32, 48.0), (1700, 1200, 12.0), (600, 400, 6.0)] {
let src = noise(w, h, 5);
println!("| {w} × {h} | {sigma} | {:.2} | {:.2} |", best(&src, sigma, 15, false), best(&src, sigma, 5, true));
}
}
/// The multiply and shift give every quotient a box's sums can have, for every box width up
/// to 4,001 pixels (radius 2,000) and for the widest ones.
#[test]
fn division_by_a_box_width_is_exact() {
let widths = (1..=4001u32).step_by(2).chain([65_535, 1_000_001, 2_000_001, (1 << 23) - 1, 1 << 23]);
for d in widths {
let by = ByWidth::new(d).unwrap();
let sums: Box<dyn Iterator<Item = u32>> = if d <= 4001 {
Box::new(0..=255 * d)
} else {
Box::new((0..=255u32).flat_map(move |q| [q * d, (q * d).saturating_sub(1), q * d + d - 1]).filter(move |s| *s <= 255 * d))
};
for s in sums {
assert_eq!(u32::from(by.of(s)), s / d, "{s} / {d}");
}
}
assert!(ByWidth::new((1 << 23) + 1).is_none());
assert!(ByWidth::new(0).is_none());
}
#[test]
fn blur_spreads_and_conserves() {
let mut p = Pixmap::new(64, 64).unwrap();
+1 -1
View File
@@ -790,7 +790,7 @@ impl RoundedRect {
| NodeKind::Section { .. }
);
let sized = n.width.is_finite() && n.height.is_finite() && n.width > 0.0 && n.height > 0.0;
(rect_like && sized && n.corners.smoothing == 0.0).then(|| {
(rect_like && sized && n.corners.style.is_round() && n.corners.smoothing == 0.0).then(|| {
// Clamped as `rounded_rect` clamps them: each radius to half the shorter side.
let most = n.width.min(n.height) / 2.0;
let radii = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, most) } else { 0.0 });
+271
View File
@@ -0,0 +1,271 @@
//! Navigation timings in a large file: five pages of 20,000 layers each (100,000 in the file), seen
//! through a 1600 × 1100 device-pixel view. Run in release:
//! `cargo test --release -p figcraft-render --lib large_doc_timings -- --ignored --nocapture`.
//!
//! Columns, by what the pages hold:
//! - "cards": 400 cards a page (frames with a drop shadow), each holding 49 rectangles;
//! - "blur here": the cards, and a background blur and a glass pane on the page shown;
//! - "blur elsewhere": the cards, and a background blur and a glass pane on another page;
//! - "flat": 20,000 rectangles straight on each page.
//!
//! Rows go through `Retained` as the canvas does: "scan" is what the retained renderer works out
//! about a page after an edit (the layers to redraw whole, the largest backdrop blur); "edit"
//! moves one rectangle each frame; "zoom" renders a new scale each frame; "pan" moves the view by
//! 60 device pixels each frame.
use std::sync::Arc;
use std::time::Instant;
use figcraft_color::{Color, Paint};
use figcraft_doc::{Blur, Document, Effect, EffectKind, Glass, NodeId, NodeKind, Shadow};
use figcraft_geom::Affine;
use crate::{Options, Retained, View, Work};
const PAGES: u32 = 5;
const RUNS: u32 = 12;
#[derive(Clone, Copy, PartialEq)]
enum Scene {
Cards,
BlurHere,
BlurElsewhere,
Flat,
}
/// The file, the page shown and a rectangle on it.
struct File {
doc: Document,
page: NodeId,
target: NodeId,
}
/// A background blur and a glass pane on `page`.
fn backdrops(d: &mut Document, page: NodeId) {
let pane = d.create(page, NodeKind::Rectangle, "Frosted", 1100.0, 1100.0, 500.0, 300.0).unwrap();
let n = d.get_mut(pane).unwrap();
n.fills = vec![Paint::solid(Color { a: 0.2, ..Color::WHITE })];
n.effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur { radius: 24.0, ..Blur::default() }), visible: true }];
let glass = d.create(page, NodeKind::Rectangle, "Glass", 1700.0, 1300.0, 400.0, 260.0).unwrap();
let n = d.get_mut(glass).unwrap();
n.corners.radii = [32.0; 4];
n.fills = vec![Paint::solid(Color { a: 0.1, ..Color::WHITE })];
n.effects = vec![Effect { kind: EffectKind::Glass(Glass::default()), visible: true }];
}
fn file(scene: Scene) -> File {
let mut d = Document::new("large file");
let first = d.first_page().unwrap();
let pages: Vec<NodeId> = std::iter::once(first).chain((1..PAGES).map(|i| d.add_page(&format!("Page {}", i + 1)))).collect();
let mut target = None;
let colour = |x: u32, y: u32, n: u32| Paint::solid(Color::new(x as f32 / n as f32, y as f32 / n as f32, 0.6, 1.0));
for &p in &pages {
if scene == Scene::Flat {
for y in 0..100u32 {
for x in 0..200u32 {
let r = d.create(p, NodeKind::Rectangle, "Cell", f64::from(x) * 30.0, f64::from(y) * 30.0, 26.0, 26.0).unwrap();
d.get_mut(r).unwrap().fills = vec![colour(x, y, 200)];
if p == first && x == 50 && y == 50 {
target = Some(r);
}
}
}
continue;
}
for cy in 0..20u32 {
for cx in 0..20u32 {
let card = d.create(p, NodeKind::Frame, "Card", f64::from(cx) * 400.0, f64::from(cy) * 400.0, 360.0, 360.0).unwrap();
let n = d.get_mut(card).unwrap();
n.fills = vec![Paint::solid(Color::WHITE)];
n.effects =
vec![Effect { kind: EffectKind::DropShadow(Shadow { radius: 12.0, offset: (0.0, 4.0), ..Shadow::default() }), visible: true }];
for y in 0..7u32 {
for x in 0..7u32 {
let r =
d.create(card, NodeKind::Rectangle, "Cell", 8.0 + f64::from(x) * 50.0, 8.0 + f64::from(y) * 50.0, 44.0, 44.0).unwrap();
d.get_mut(r).unwrap().fills = vec![colour(x, y, 7)];
if p == first && cx == 3 && cy == 3 && x == 3 && y == 3 {
target = Some(r);
}
}
}
}
}
}
match scene {
Scene::BlurHere => backdrops(&mut d, first),
Scene::BlurElsewhere => backdrops(&mut d, pages[2]),
Scene::Cards | Scene::Flat => {}
}
File { doc: d, page: first, target: target.unwrap() }
}
fn view(origin: (f64, f64), scale: f64) -> View {
View { origin, scale, width: 1600, height: 1100 }
}
fn opts() -> Options {
Options { lod: true, ..Options::default() }
}
fn mean_ms(t: Instant, runs: u32) -> f64 {
t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)
}
/// Move the target a unit right.
fn nudge(d: &mut Document, target: NodeId) {
let n = d.get_mut(target).unwrap();
let c = n.transform.as_coeffs();
n.transform = Affine::translate((c[4] + 1.0, c[5]));
}
/// Mean milliseconds of the retained renderer's look at the page after an edit.
fn scan(f: &File) -> f64 {
let mut doc = f.doc.clone();
let t = Instant::now();
for _ in 0..RUNS {
nudge(&mut doc, f.target);
std::hint::black_box(crate::retained::bench_scan(&doc, f.page));
}
mean_ms(t, RUNS)
}
/// Mean milliseconds of a canvas frame after moving the target a unit.
fn edits(f: &File) -> f64 {
let v = view((1000.0, 1000.0), 1.0);
let mut r = Retained::default();
let mut doc = Arc::new(f.doc.clone());
r.render(&doc, f.page, &v, &opts()).unwrap();
let t = Instant::now();
for _ in 0..RUNS {
let mut next = (*doc).clone();
nudge(&mut next, f.target);
doc = Arc::new(next);
let (_, _, work) = r.render(&doc, f.page, &v, &opts()).unwrap();
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
}
mean_ms(t, RUNS)
}
/// Mean milliseconds of a canvas frame at a new zoom around `scale`.
fn zooms(f: &File, scale: f64) -> f64 {
let doc = Arc::new(f.doc.clone());
let mut r = Retained::default();
r.render(&doc, f.page, &view((1000.0, 1000.0), scale), &opts()).unwrap();
let t = Instant::now();
for i in 1..=RUNS {
let (_, _, work) = r.render(&doc, f.page, &view((1000.0, 1000.0), scale * (1.0 + 0.02 * f64::from(i))), &opts()).unwrap();
assert_eq!(work, Work::Full);
}
mean_ms(t, RUNS)
}
/// Mean milliseconds of a canvas frame after a pan of 60 device pixels.
fn pans(f: &File) -> f64 {
let doc = Arc::new(f.doc.clone());
let mut r = Retained::default();
let mut at = (1000.0, 1000.0);
r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap();
let t = Instant::now();
for _ in 0..RUNS {
at.0 += 60.0;
let (_, _, work) = r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap();
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
}
mean_ms(t, RUNS)
}
#[test]
#[ignore = "timing: run in release with --ignored --nocapture"]
fn large_doc_timings() {
let scenes = [Scene::Cards, Scene::BlurHere, Scene::BlurElsewhere, Scene::Flat].map(file);
println!(
"large file timings ({} build, {} layers, 1600 × 1100 px, mean of {RUNS}, ms)",
if cfg!(debug_assertions) { "debug" } else { "release" },
scenes[0].doc.node_count()
);
println!("| frame | cards | blur here | blur elsewhere | flat |\n|---|---:|---:|---:|---:|");
let row = |name: &str, f: &dyn Fn(&File) -> f64| {
let cells: Vec<String> = scenes.iter().map(|s| format!("{:.2}", f(s))).collect();
println!("| {name} | {} |", cells.join(" | "));
};
row("scan after an edit", &scan);
row("edit one layer", &edits);
row("zoom (100%)", &|f| zooms(f, 1.0));
row("zoom (400%)", &|f| zooms(f, 4.0));
row("pan 60 px", &pans);
}
/// The cards with, on the page shown, a grainy card, a layer filled with a pattern whose source
/// lies on another page, a background blur and a glass pane.
fn mixed() -> File {
let mut f = file(Scene::BlurHere);
let d = &mut f.doc;
let other = d.pages[3];
let source = d.create(other, NodeKind::Frame, "Source", 0.0, 0.0, 30.0, 30.0).unwrap();
d.get_mut(source).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
let dot = d.create(source, NodeKind::Rectangle, "Dot", 8.0, 8.0, 12.0, 12.0).unwrap();
d.get_mut(dot).unwrap().fills = vec![Paint::solid(Color::from_hex("2040E0").unwrap())];
let filled = d.create(f.page, NodeKind::Rectangle, "Filled", 1300.0, 1500.0, 300.0, 200.0).unwrap();
let pt = figcraft_color::PatternPaint::new(source.0);
d.get_mut(filled).unwrap().fills = vec![Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }];
let grainy = d.create(f.page, NodeKind::Rectangle, "Grain", 1500.0, 1150.0, 200.0, 120.0).unwrap();
let n = d.get_mut(grainy).unwrap();
n.fills = vec![Paint::solid(Color::from_hex("20C060").unwrap())];
n.effects = vec![Effect {
kind: EffectKind::Noise(figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() }),
visible: true,
}];
f
}
/// Prints a digest of every frame of a run of pans, edits and zooms through `Retained`, to tell
/// that two builds draw the same pixels: run in release on each and compare.
#[test]
#[ignore = "digests: run in release with --ignored --nocapture on two builds and compare"]
fn large_doc_digests() {
use std::hash::{DefaultHasher, Hash, Hasher};
let scenes = [
("cards", file(Scene::Cards)),
("blur here", file(Scene::BlurHere)),
("blur elsewhere", file(Scene::BlurElsewhere)),
("flat", file(Scene::Flat)),
("mixed", mixed()),
];
let mut all = DefaultHasher::new();
for (name, f) in &scenes {
let mut r = Retained::default();
let mut doc = Arc::new(f.doc.clone());
let mut frames = Vec::new();
let mut at = (1000.0, 1000.0);
let mut scale = 1.0;
let steps = ["pan", "pan", "edit", "edit", "zoom 1.37", "pan", "edit", "zoom 4", "pan", "edit", "zoom 0.5", "pan"];
let mut draw = |r: &mut Retained, doc: &Arc<Document>, at: (f64, f64), scale: f64, frames: &mut Vec<String>| {
let (_, pix, work) = r.render(doc, f.page, &view(at, scale), &opts()).unwrap();
let mut h = DefaultHasher::new();
pix.data().hash(&mut h);
let w = match work {
Work::Full => "F",
Work::Partial { .. } => "P",
Work::Reused => "R",
};
frames.push(format!("{w}{:04x}", h.finish() & 0xffff));
pix.data().hash(&mut all);
};
draw(&mut r, &doc, at, scale, &mut frames);
for s in steps {
match s {
"pan" => at = (at.0 + 60.0 / scale, at.1 + 24.0 / scale),
"edit" => {
let mut next = (*doc).clone();
nudge(&mut next, f.target);
doc = Arc::new(next);
}
z => scale = z.trim_start_matches("zoom ").parse().unwrap(),
}
draw(&mut r, &doc, at, scale, &mut frames);
}
println!("{name}: {}", frames.join(" "));
}
println!("all: {:016x}", all.finish());
}
+57 -17
View File
@@ -123,6 +123,13 @@ pub(crate) fn render_number() -> u64 {
/// Render a page region, splitting it into horizontal bands rendered in parallel (desktop).
pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
render_view_with(doc, page, view, opts, max_backdrop_blur(doc))
}
/// [`render_view`], where `backdrop` is at least the largest backdrop radius of what it draws (a
/// retained render works it out for the page: a blur on another page then widens no band's
/// overlap).
pub(crate) fn render_view_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option<Pixmap> {
start_render();
#[cfg(not(target_arch = "wasm32"))]
if let Some(pool) = band_pool() {
@@ -130,43 +137,60 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) ->
let bands = threads.min(view.height / 96).max(1);
if bands > 1
&& view.width.saturating_mul(view.height) > 300_000
&& let Some(p) = pool.install(|| render_bands(doc, page, view, opts, bands))
&& let Some(p) = pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop))
{
return Some(p);
}
}
#[cfg(target_arch = "wasm32")]
let _ = backdrop;
render_one(doc, page, view, opts)
}
/// [`render_part_with`] for backdrop radii up to the file's largest.
#[cfg(test)]
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
render_part_with(doc, page, view, opts, max_backdrop_blur(doc))
}
/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the
/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a
/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is
/// drawn whole for a sliver of it), not its pixels.
pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
/// drawn whole for a sliver of it), not its pixels. `backdrop` is at least the largest backdrop
/// radius of what it draws.
pub(crate) fn render_part_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option<Pixmap> {
start_render();
#[cfg(not(target_arch = "wasm32"))]
if let Some(pool) = band_pool() {
let threads = pool.current_num_threads().clamp(1, 16) as u32;
let rendered = if view.height >= view.width {
let bands = threads.min(view.height / 96);
(bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten()
(bands > 1).then(|| pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop))).flatten()
} else {
let bands = threads.min(view.width / 96);
(bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten()
(bands > 1).then(|| pool.install(|| render_columns_with(doc, page, view, opts, bands, backdrop))).flatten()
};
if rendered.is_some() {
return rendered;
}
}
#[cfg(target_arch = "wasm32")]
let _ = backdrop;
render_one(doc, page, view, opts)
}
/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read.
#[cfg(not(target_arch = "wasm32"))]
/// [`render_columns_with`] for backdrop radii up to the file's largest.
#[cfg(all(test, not(target_arch = "wasm32")))]
fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
render_columns_with(doc, page, view, opts, bands, max_backdrop_blur(doc))
}
/// [`render_bands_with`] across: `bands` columns, overlapping by what background blurs read.
#[cfg(not(target_arch = "wasm32"))]
fn render_columns_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option<Pixmap> {
use rayon::prelude::*;
let band_w = view.width.div_ceil(bands.max(1));
let overlap = band_overlap(doc, view, band_w)?;
let overlap = overlap_for(backdrop, view, band_w)?;
let s = view.scale.max(1e-9);
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
.into_par_iter()
@@ -205,15 +229,21 @@ fn band_pool() -> Option<&'static rayon::ThreadPool> {
POOL.get_or_init(|| rayon::ThreadPoolBuilder::new().thread_name(|i| format!("figcraft-band-{i}")).stack_size(RENDER_STACK).build().ok()).as_ref()
}
/// Render `view` as `bands` horizontal bands in parallel. Bands overlap by what background blurs
/// read and each keeps only its own rows, so a backdrop never ends at a band's edge. `None` when a
/// blur reaches past a whole band (every band would render most of the view: render it in one
/// piece instead).
#[cfg(not(target_arch = "wasm32"))]
/// [`render_bands_with`] for backdrop radii up to the file's largest.
#[cfg(all(test, not(target_arch = "wasm32")))]
fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
render_bands_with(doc, page, view, opts, bands, max_backdrop_blur(doc))
}
/// Render `view` as `bands` horizontal bands in parallel. Bands overlap by what background blurs
/// read (`backdrop` is at least the largest backdrop radius of what they draw) and each keeps only
/// its own rows, so a backdrop never ends at a band's edge. `None` when a blur reaches past a whole
/// band (every band would render most of the view: render it in one piece instead).
#[cfg(not(target_arch = "wasm32"))]
fn render_bands_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option<Pixmap> {
use rayon::prelude::*;
let band_h = view.height.div_ceil(bands.max(1));
let overlap = band_overlap(doc, view, band_h)?;
let overlap = overlap_for(backdrop, view, band_h)?;
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
.into_par_iter()
.map(|i| {
@@ -230,10 +260,16 @@ fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands
Some(out)
}
/// How many rows bands of `band_h` rows of `view` overlap (what background blurs read); `None`
/// when that is more than a band.
/// [`overlap_for`] for backdrop radii up to the file's largest.
#[cfg(test)]
pub(crate) fn band_overlap(doc: &Document, view: &View, band_h: u32) -> Option<u32> {
let overlap = backdrop_reach(max_backdrop_blur(doc), view.scale).ceil();
overlap_for(max_backdrop_blur(doc), view, band_h)
}
/// How many rows bands of `band_h` rows of `view` overlap (what background blurs of radii up to
/// `backdrop` read); `None` when that is more than a band.
pub(crate) fn overlap_for(backdrop: f64, view: &View, band_h: u32) -> Option<u32> {
let overlap = backdrop_reach(backdrop, view.scale).ceil();
(overlap.is_finite() && overlap <= f64::from(band_h)).then_some(overlap as u32)
}
@@ -705,6 +741,8 @@ mod join_tests;
#[cfg(test)]
mod jpeg_sampling_tests;
#[cfg(test)]
mod large_doc_bench_tests;
#[cfg(test)]
mod large_image_tests;
#[cfg(test)]
mod lod_tests;
@@ -725,6 +763,8 @@ mod render_depth_tests;
#[cfg(test)]
mod retained_edit_tests;
#[cfg(test)]
mod retained_page_tests;
#[cfg(test)]
mod retained_tests;
#[cfg(test)]
mod rtl_list_tests;
+8 -3
View File
@@ -139,10 +139,15 @@ fn fill_share(n: &Node) -> f32 {
NodeKind::Polygon { .. } => 0.6,
NodeKind::Star { .. } | NodeKind::Vector { .. } | NodeKind::BooleanOp { .. } => 0.5,
_ => {
// Rounded corners cut (4 − π) r² from the box.
let r = (n.corners.radii.iter().sum::<f64>() / 4.0).clamp(0.0, w.min(h) / 2.0);
use figcraft_geom::CornerStyle;
let cut = match n.corners.style {
CornerStyle::Round => 1.0 - std::f64::consts::FRAC_PI_4,
CornerStyle::Chamfer => 0.5,
CornerStyle::Concave => std::f64::consts::FRAC_PI_4,
};
let squared_radii: f64 = n.corners.radii.iter().map(|r| r.clamp(0.0, w.min(h) / 2.0).powi(2)).sum();
let area = w * h;
if area > 0.0 { (1.0 - (4.0 - std::f64::consts::PI) * r * r / area).clamp(0.0, 1.0) as f32 } else { 1.0 }
if area > 0.0 { (1.0 - cut * squared_radii / area).clamp(0.0, 1.0) as f32 } else { 1.0 }
}
}
}
+134 -43
View File
@@ -4,15 +4,15 @@
//! Views are snapped to whole device pixels so that, at one zoom, the pixels of every render line
//! up and a pan is an integer shift of the previous image. Anything the partial path can't vouch
//! for (another zoom, page or set of options, new fonts, a page-level edit, a large change) is a
//! full render, the same as [`render_view`].
//! full render, the same as [`render_view`](crate::render_view).
use std::sync::Arc;
use figcraft_doc::{Document, EffectKind, NodeId, NodeKind};
use figcraft_doc::{Document, Effect, EffectKind, Node, NodeId, NodeKind};
use figcraft_geom::Rect;
use tiny_skia::Pixmap;
use crate::{Options, View, draw, render_view};
use crate::{Options, View, draw};
/// What a render had to do.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -68,19 +68,111 @@ struct Sensitive {
pattern_sources: Vec<NodeId>,
}
/// Grain effects (noise, texture) work on their layer's pixels, which end where a render cuts the
/// layer (texture scatters pixels from across the cut): grainy layers are redrawn whole.
fn sensitive(doc: &Document) -> Sensitive {
let noisy = doc.nodes().filter(|n| n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_))));
let pattern_sources = doc
.nodes()
.flat_map(|n| n.fills.iter().chain(&n.strokes))
.filter_map(|p| match &p.kind {
figcraft_color::PaintKind::Pattern(pt) => Some(NodeId(pt.source)),
_ => None,
})
.collect();
Sensitive { areas: noisy.filter_map(|n| draw::paint_bounds(doc, n.id)).collect(), backdrop_blur: crate::max_backdrop_blur(doc), pattern_sources }
/// The paints a vector's regions or a text's runs draw with besides the layer's own fills.
fn own_paints(n: &Node) -> impl Iterator<Item = &figcraft_color::Paint> {
let regions = match &n.kind {
NodeKind::Vector { network } => network.regions.as_slice(),
_ => &[],
};
let text = match &n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
};
let styles = text.into_iter().flat_map(|t| std::iter::once(&t.style).chain(t.runs.iter().map(|r| &r.style)));
regions.iter().filter_map(|r| r.fills.as_deref()).chain(styles.filter_map(|s| s.fills.as_deref())).flatten()
}
/// The pattern source `p` draws, when it is a pattern.
fn pattern_source(p: &figcraft_color::Paint) -> Option<NodeId> {
match &p.kind {
figcraft_color::PaintKind::Pattern(pt) => Some(NodeId(pt.source)),
_ => None,
}
}
/// The pattern sources of every paint `n` draws with: its fills and strokes, its vector regions'
/// own fills and its text runs' own fills.
fn pattern_sources_of(n: &Node) -> impl Iterator<Item = NodeId> + '_ {
let more = matches!(n.kind, NodeKind::Vector { .. } | NodeKind::Text(_)).then(|| own_paints(n));
n.fills.iter().chain(&n.strokes).filter_map(pattern_source).chain(more.into_iter().flatten().filter_map(pattern_source))
}
/// Whether `n`'s look depends on where a render cuts it: grain effects (noise, texture) work on
/// its pixels, which end at the cut (texture scatters pixels from across it).
fn grainy(n: &Node) -> bool {
n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_)))
}
/// What a render of `page` must know: grainy layers are redrawn whole, an edit inside a pattern
/// source shows wherever the pattern does, and backdrop blurs read around them.
///
/// Only what the page draws counts: its layers, and the pattern sources they fill with wherever
/// those are (and the sources those fill with in turn), whose edits show on the page and whose
/// backdrop blurs count too. A source's grain is drawn in its cells, not where the source lies, so
/// only the page's own grainy layers give areas. One walk down the page rather than passes over
/// every page of the file: in a large file those passes took most of an edit's frame, and a blur
/// on another page widened every pan's strips and every band's overlap.
fn sensitive(doc: &Document, page: NodeId) -> Sensitive {
page_walk(doc, page).unwrap_or_else(|| whole_file(doc))
}
/// [`sensitive`] from a walk down `page`; `None` when the walk runs out of its budget.
fn page_walk(doc: &Document, page: NodeId) -> Option<Sensitive> {
let mut noisy: Vec<(NodeId, Rect)> = Vec::new();
let mut backdrop_blur = 0.0f64;
let mut pattern_sources = Vec::new();
let mut sources = std::collections::BTreeSet::new();
// Layers walked as part of a source: sources inside sources are walked once.
let mut in_sources = std::collections::BTreeSet::new();
// A tree takes at most three visits a layer: on the page, in a source and as a source's root
// met again. Child lists that repeat (a hostile file) run out the budget: then what the page
// draws can't be told, and [`sensitive`] counts the whole file.
let mut left = doc.node_count().saturating_mul(3).saturating_add(8);
// Each layer with whether it is drawn where it lies on the page (a source's layers are drawn
// in its cells).
let mut stack = vec![(page, true)];
while let Some((id, on_page)) = stack.pop() {
left = left.checked_sub(1)?;
if !on_page && !in_sources.insert(id) {
continue;
}
let Some(n) = doc.node(id) else { continue };
if on_page
&& grainy(n)
&& let Some(r) = draw::paint_bounds(doc, id)
{
noisy.push((id, r));
}
backdrop_blur = n.effects.iter().map(Effect::backdrop_radius).fold(backdrop_blur, f64::max);
for src in pattern_sources_of(n) {
if sources.insert(src) {
pattern_sources.push(src);
// A page as a source draws nothing.
if doc.node(src).is_some_and(|s| !s.is_page()) {
stack.push((src, false));
}
}
}
stack.extend(n.children.iter().map(|c| (*c, on_page)));
}
// In id order, as a pass over the file finds them.
noisy.sort_by_key(|(id, _)| *id);
Some(Sensitive { areas: noisy.into_iter().map(|(_, r)| r).collect(), backdrop_blur, pattern_sources })
}
/// [`sensitive`] for every layer of the file, whatever page it is on.
fn whole_file(doc: &Document) -> Sensitive {
Sensitive {
areas: doc.nodes().filter(|n| grainy(n)).filter_map(|n| draw::paint_bounds(doc, n.id)).collect(),
backdrop_blur: crate::max_backdrop_blur(doc),
pattern_sources: doc.nodes().flat_map(pattern_sources_of).collect(),
}
}
/// [`sensitive`] for the large-file timings: how many areas it found.
#[cfg(test)]
pub(crate) fn bench_scan(doc: &Document, page: NodeId) -> usize {
sensitive(doc, page).areas.len()
}
/// Whether `id` is a pattern source or inside one in `doc`.
@@ -132,8 +224,8 @@ enum Prepared {
/// The previous render patched (or reused as is), now kept.
Patched(View, Work),
/// Only a full render will do: the snapped view, its top-left device pixel, the font
/// generation and what [`sensitive`] found when the previous render's document was checked.
Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Option<Arc<Sensitive>> },
/// generation and what [`sensitive`] finds on the page.
Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Arc<Sensitive> },
}
/// What [`Retained::begin`] did.
@@ -153,7 +245,7 @@ pub struct Steps {
px: (i64, i64),
fonts: u64,
opts: Options,
sensitive: Option<Arc<Sensitive>>,
sensitive: Arc<Sensitive>,
pix: Pixmap,
/// The first row not drawn yet.
next: u32,
@@ -225,9 +317,8 @@ impl Retained {
match self.prepare(doc, page, view, opts)? {
Prepared::Patched(snapped, work) => Some((snapped, &self.last.as_ref()?.pix, work)),
Prepared::Full { snapped, px, fonts, sensitive } => {
let pix = render_view(doc, page, &snapped, opts)?;
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc)));
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?;
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive);
Some((snapped, &frame.pix, Work::Full))
}
}
@@ -242,13 +333,12 @@ impl Retained {
Prepared::Full { snapped, px, fonts, sensitive } => {
// Bands at least twice what they overlap (each draws its overlap again both ways),
// so a background blur reaching past `band_h` makes the bands taller.
let overlap = crate::band_overlap(doc, &snapped, u32::MAX).map(|o| o.min(snapped.height));
let overlap = crate::overlap_for(sensitive.backdrop_blur, &snapped, u32::MAX).map(|o| o.min(snapped.height));
let band_h = band_h.max(1).max(overlap.unwrap_or(0).saturating_mul(2));
// A blur that can't be measured: one piece.
let Some(overlap) = overlap else {
let pix = render_view(doc, page, &snapped, opts)?;
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc)));
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?;
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive);
return Some(Begun::Done(snapped, &frame.pix, Work::Full));
};
let pix = crate::new_pixmap(snapped.width, snapped.height)?;
@@ -275,8 +365,7 @@ impl Retained {
/// Keep the image `steps` drew (all its bands: see [`Steps::step`]) as a full render.
pub fn finish(&mut self, steps: Steps) -> (View, &Pixmap) {
let Steps { doc, page, view, px, fonts, opts, sensitive, pix, .. } = steps;
let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(&doc)));
let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, s);
let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, sensitive);
(view, &frame.pix)
}
@@ -290,8 +379,12 @@ impl Retained {
return None;
};
let fonts = figcraft_text::layout_generation();
let mut sens = None;
if let Some(last) = self.last.take()
let last = self.last.take();
// What the previous render found on the page holds while the document, the page and the
// fonts (text's ink bounds) stay the same: a zoom works none of it out again.
let kept = last.as_ref().filter(|l| Arc::ptr_eq(&l.doc, doc) && l.page == page && l.fonts == fonts).map(|l| l.sensitive.clone());
let s = kept.unwrap_or_else(|| Arc::new(sensitive(doc, page)));
if let Some(last) = last
&& last.page == page
&& last.outline == opts.outline_mode
&& last.outline_extras == opts.outline
@@ -310,18 +403,14 @@ impl Retained {
&& last.fonts == fonts
// Images are decoded into the file's colour space: a new profile redraws everything.
&& last.doc.color_profile == doc.color_profile
&& let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s)
{
let same_doc = Arc::ptr_eq(&last.doc, doc);
let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) };
if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) {
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
self.patched = areas;
return Some(Prepared::Patched(snapped, work));
}
sens = Some(s);
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
self.patched = areas;
return Some(Prepared::Patched(snapped, work));
}
Some(Prepared::Full { snapped, px, fonts, sensitive: sens })
Some(Prepared::Full { snapped, px, fonts, sensitive: s })
}
/// Keep `pix`, the render of `at`: the snapped view, its top-left device pixel and the font
@@ -642,7 +731,7 @@ fn patch(
let mut pix = last.pix;
shift(&mut pix, dx, dy)?;
for d in &damage {
render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?;
render_into(FrameRender { doc, page, view, px, opts, backdrop: s.backdrop_blur }, d, margin, &mut pix)?;
}
let area =
|d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]);
@@ -706,13 +795,15 @@ struct FrameRender<'a> {
view: &'a View,
px: (i64, i64),
opts: &'a Options,
/// The largest backdrop radius on the page.
backdrop: f64,
}
/// Render the frame pixels `d` (with `margin` more around, discarded) into `pix`. The margin stops
/// at the frame's edge: background blurs and glass read what is drawn under them, and a full
/// render's backdrops end where the frame does.
fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> Option<()> {
let FrameRender { doc, page, view, px, opts } = frame;
let FrameRender { doc, page, view, px, opts, backdrop } = frame;
let s = view.scale;
let (w, h) = (i64::from(pix.width()), i64::from(pix.height()));
let (ox, oy) = ((d.x0 - margin).max(0), (d.y0 - margin).max(0));
@@ -720,7 +811,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) ->
let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?);
// The same pixel grid as the frame: origin (px + offset) / scale.
let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh };
let part = crate::render_part(doc, page, &sub, opts)?;
let part = crate::render_part_with(doc, page, &sub, opts, backdrop)?;
// The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the
// copy took longer than rendering a simple part).
let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?);
+268
View File
@@ -0,0 +1,268 @@
//! What the retained renderer works out about a page (grainy layers, pattern sources, the largest
//! backdrop blur) comes from that page and the pattern sources it draws, not from the whole file.
use std::sync::Arc;
use figcraft_color::{Color, Paint, PaintKind, PatternPaint};
use figcraft_doc::{Blur, Document, Effect, EffectKind, NodeId, NodeKind};
use figcraft_geom::Affine;
use crate::retained_tests::assert_same;
use crate::{Begun, Options, Pixmap, Retained, View, Work, render_view};
fn solid(d: &mut Document, id: NodeId, hex: &str) {
d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())];
}
fn pattern(d: &mut Document, id: NodeId, source: NodeId) {
let pt = PatternPaint::new(source.0);
d.get_mut(id).unwrap().fills = vec![Paint { kind: PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }];
}
fn edit(doc: &Arc<Document>, f: impl FnOnce(&mut Document)) -> Arc<Document> {
let mut d = (**doc).clone();
f(&mut d);
Arc::new(d)
}
/// Render through `r`; the image, the view drawn and what it took.
fn render(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View) -> (Pixmap, View, Work) {
let (shown, pix, work) = r.render(doc, page, v, &Options::default()).unwrap();
(pix.clone(), shown, work)
}
/// Render through `r` and check the image against a full render of the same view: the same
/// pixels for a full render, the same up to anti-aliasing for a patched one.
fn check(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View) -> Work {
let (pix, shown, work) = render(r, doc, page, v);
let full = render_view(doc, page, &shown, &Options::default()).unwrap();
if work == Work::Full {
assert!(pix.data() == full.data(), "a full retained render differs from render_view");
} else {
assert_same(&pix, &full, &format!("{work:?}"));
}
work
}
/// Shapes on the first page, and a background blur reaching far past any patch's margin on the
/// second: (document, first page, a shape on it).
fn blur_elsewhere() -> (Arc<Document>, NodeId, NodeId) {
let mut d = Document::new("blur elsewhere");
let p = d.first_page().unwrap();
let mut shape = None;
for i in 0..12u32 {
let r = d.create(p, NodeKind::Rectangle, "R", f64::from(i % 4) * 160.0 + 20.0, f64::from(i / 4) * 150.0 + 20.0, 120.0, 100.0).unwrap();
solid(&mut d, r, ["E03030", "2040E0", "20C060", "F0C830"][i as usize % 4]);
shape.get_or_insert(r);
}
let other = d.add_page("Other");
let frosted = d.create(other, NodeKind::Rectangle, "Frosted", 0.0, 0.0, 400.0, 300.0).unwrap();
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }];
(Arc::new(d), p, shape.unwrap())
}
#[test]
fn a_blur_on_another_page_leaves_pans_and_edits_partial() {
let (doc, p, shape) = blur_elsewhere();
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 700, height: 500 };
let mut r = Retained::default();
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
assert!(matches!(check(&mut r, &doc, p, &v(30.0)), Work::Partial { .. }), "a pan");
let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0)));
assert!(matches!(check(&mut r, &moved, p, &v(30.0)), Work::Partial { .. }), "an edit");
// A new zoom renders in bands as wide apart as the page's own blurs need (none here).
assert_eq!(check(&mut r, &moved, p, &View { scale: 1.5, ..v(30.0) }), Work::Full);
}
#[test]
fn a_blur_on_the_page_still_renders_full_when_it_reaches_past_a_patch() {
let (doc, p, shape) = blur_elsewhere();
// The same blur on the page shown.
let doc = edit(&doc, |d| {
let frosted = d.create(p, NodeKind::Rectangle, "Frosted", 300.0, 200.0, 200.0, 150.0).unwrap();
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }];
});
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 700, height: 500 };
let mut r = Retained::default();
check(&mut r, &doc, p, &v);
let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0)));
assert_eq!(check(&mut r, &moved, p, &v), Work::Full);
}
/// A rectangle on the first page filled with a pattern whose source is a frame on the second
/// page; inside the source, a child and a layer filled with a second pattern, whose source is on
/// a third page. (document, first page, filled rectangle, source, child, nested source)
fn patterns() -> (Arc<Document>, NodeId, [NodeId; 4]) {
let mut d = Document::new("patterns");
let p = d.first_page().unwrap();
let filled = d.create(p, NodeKind::Rectangle, "Filled", 20.0, 20.0, 260.0, 200.0).unwrap();
let plain = d.create(p, NodeKind::Rectangle, "Plain", 300.0, 40.0, 60.0, 60.0).unwrap();
solid(&mut d, plain, "202020");
let second = d.add_page("Sources");
let source = d.create(second, NodeKind::Frame, "Source", 0.0, 0.0, 40.0, 40.0).unwrap();
solid(&mut d, source, "E03030");
let child = d.create(source, NodeKind::Rectangle, "Child", 4.0, 4.0, 14.0, 14.0).unwrap();
solid(&mut d, child, "2040E0");
let inner = d.create(source, NodeKind::Rectangle, "Inner", 20.0, 20.0, 18.0, 18.0).unwrap();
let third = d.add_page("More sources");
let nested = d.create(third, NodeKind::Rectangle, "Nested", 0.0, 0.0, 6.0, 6.0).unwrap();
solid(&mut d, nested, "20C060");
pattern(&mut d, inner, nested);
pattern(&mut d, filled, source);
(Arc::new(d), p, [filled, source, child, nested])
}
#[test]
fn edits_to_pattern_sources_on_other_pages_show_on_the_page() {
let (doc, p, [_, source, child, nested]) = patterns();
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 400, height: 260 };
let mut r = Retained::default();
check(&mut r, &doc, p, &v);
let mut doc = doc;
for (what, id, hex) in
[("the source", source, "F0C830"), ("a layer in the source", child, "FFFFFF"), ("a source the source fills with", nested, "000000")]
{
doc = edit(&doc, |d| solid(d, id, hex));
assert_ne!(check(&mut r, &doc, p, &v), Work::Reused, "{what}");
}
}
#[test]
fn a_grainy_layer_patches_as_it_renders_after_a_zoom() {
let mut d = Document::new("grain");
let p = d.first_page().unwrap();
let grainy = d.create(p, NodeKind::Rectangle, "Grain", 60.0, 50.0, 120.0, 90.0).unwrap();
solid(&mut d, grainy, "E03030");
let noise = figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() };
d.get_mut(grainy).unwrap().effects = vec![Effect { kind: EffectKind::Noise(noise), visible: true }];
let other = d.add_page("Other");
let far = d.create(other, NodeKind::Rectangle, "Far", 0.0, 0.0, 10.0, 10.0).unwrap();
solid(&mut d, far, "2040E0");
let doc = Arc::new(d);
let v = |x: f64, scale: f64| View { origin: (x, 0.0), scale, width: 400, height: 300 };
let mut r = Retained::default();
check(&mut r, &doc, p, &v(0.0, 1.0));
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.7)), Work::Full);
// Pans across the grainy layer at the new zoom: it is redrawn whole each time.
for i in 1..=4 {
let (pix, shown, work) = render(&mut r, &doc, p, &v(f64::from(i) * 13.0, 1.7));
let full = render_view(&doc, p, &shown, &Options::default()).unwrap();
let worst = pix.data().iter().zip(full.data()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
assert!(matches!(work, Work::Partial { .. }), "{work:?}");
assert!(worst <= 2, "pan {i}: {worst} levels off a full render");
}
}
#[test]
fn a_page_shown_again_after_another_matches() {
let (doc, p, [filled, ..]) = patterns();
let other = doc.pages[1];
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 400, height: 260 };
let mut r = Retained::default();
check(&mut r, &doc, p, &v(0.0));
assert_eq!(check(&mut r, &doc, other, &v(0.0)), Work::Full);
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
assert!(matches!(check(&mut r, &doc, p, &v(24.0)), Work::Partial { .. }));
let moved = edit(&doc, |d| d.get_mut(filled).unwrap().transform = Affine::translate((40.0, 30.0)));
assert!(matches!(check(&mut r, &moved, p, &v(24.0)), Work::Partial { .. }));
}
/// A render drawn band by band through [`Retained::begin`], kept with [`Retained::finish`].
fn stepped(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View, band_h: u32) -> (Pixmap, View) {
match r.begin(doc, page, v, &Options::default(), band_h).unwrap() {
Begun::Done(shown, pix, _) => (pix.clone(), shown),
Begun::Steps(mut steps) => {
while !steps.step() {}
let (shown, pix) = r.finish(*steps);
(pix.clone(), shown)
}
}
}
/// Stripes under a glass pane and a background blur on the first page, a much wider blur on the
/// second: (document, first page, a stripe beside the pane).
fn backdrops_here_and_wider_elsewhere() -> (Arc<Document>, NodeId, NodeId) {
let mut d = Document::new("backdrops");
let p = d.first_page().unwrap();
let mut stripes = Vec::new();
for i in 0..16u32 {
let s = d.create(p, NodeKind::Rectangle, "Stripe", f64::from(i) * 40.0, 0.0, 40.0, 500.0).unwrap();
solid(&mut d, s, ["E03030", "2040E0", "20C060", "F0C830"][i as usize % 4]);
stripes.push(s);
}
let pane = d.create(p, NodeKind::Rectangle, "Glass", 120.0, 100.0, 240.0, 160.0).unwrap();
let n = d.get_mut(pane).unwrap();
n.corners.radii = [24.0; 4];
n.fills = vec![Paint::solid(Color { a: 0.1, ..Color::WHITE })];
n.effects = vec![Effect { kind: EffectKind::Glass(figcraft_doc::Glass::default()), visible: true }];
let frosted = d.create(p, NodeKind::Rectangle, "Frosted", 420.0, 260.0, 160.0, 120.0).unwrap();
d.get_mut(frosted).unwrap().fills = vec![Paint::solid(Color { a: 0.2, ..Color::WHITE })];
d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(6.0)), visible: true }];
let other = d.add_page("Other");
let wide = d.create(other, NodeKind::Rectangle, "Wide", 0.0, 0.0, 300.0, 200.0).unwrap();
d.get_mut(wide).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(400.0)), visible: true }];
(Arc::new(d), p, stripes[9])
}
#[test]
fn backdrops_on_the_page_draw_as_render_view_does_with_a_wider_blur_elsewhere() {
let (doc, p, beside) = backdrops_here_and_wider_elsewhere();
let v = |x: f64, scale: f64| View { origin: (x, 0.0), scale, width: 640, height: 480 };
let mut r = Retained::default();
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.0)), Work::Full);
// A new zoom: bands overlapping by the page's own blurs, the same pixels as render_view's
// (whose bands overlap by the other page's blur).
assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.5)), Work::Full);
assert!(matches!(check(&mut r, &doc, p, &v(30.0, 1.5)), Work::Partial { .. }), "a pan");
let moved = edit(&doc, |d| d.get_mut(beside).unwrap().transform = Affine::translate((372.0, 12.0)));
assert!(matches!(check(&mut r, &moved, p, &v(30.0, 1.5)), Work::Partial { .. }), "an edit beside the glass");
// The browser's render, a band at a time.
for band_h in [24, 64, 200] {
let mut r = Retained::default();
let (pix, shown) = stepped(&mut r, &moved, p, &v(10.0, 1.37), band_h);
let full = render_view(&moved, p, &shown, &Options::default()).unwrap();
assert!(pix.data() == full.data(), "bands of {band_h} rows");
}
}
#[test]
fn a_child_list_that_loops_counts_the_whole_file() {
let (doc, p, _) = backdrops_here_and_wider_elsewhere();
// On top of the page: a frame listed as its own child, whose walk never ends. The blurs
// under it are still counted.
let doc = edit(&doc, |d| {
let f = d.create(p, NodeKind::Frame, "Loop", 600.0, 420.0, 20.0, 20.0).unwrap();
solid(d, f, "202020");
d.get_mut(f).unwrap().children.push(f);
});
let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 640, height: 480 };
let mut r = Retained::default();
assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full);
for i in 1..=3 {
check(&mut r, &doc, p, &v(f64::from(i) * 50.0));
}
}
#[test]
fn edits_to_a_pattern_a_vector_region_fills_with_show_on_the_page() {
use figcraft_doc::{Region, Segment, VectorNetwork, Vertex, WindingRule};
let mut d = Document::new("region pattern");
let p = d.first_page().unwrap();
let other = d.add_page("Sources");
let source = d.create(other, NodeKind::Rectangle, "Source", 0.0, 0.0, 20.0, 20.0).unwrap();
solid(&mut d, source, "E03030");
let tile = Paint { kind: PaintKind::Pattern(PatternPaint::new(source.0)), ..Paint::solid(Color::BLACK) };
let network = VectorNetwork {
vertices: [(0.0, 0.0), (200.0, 0.0), (200.0, 160.0), (0.0, 160.0)].into_iter().map(|(x, y)| Vertex::new(x, y)).collect(),
segments: (0..4).map(|i| Segment::line(i, (i + 1) % 4)).collect(),
regions: vec![Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(vec![tile]), ..Default::default() }],
};
let v = d.create(p, NodeKind::Vector { network: network.into() }, "V", 20.0, 20.0, 200.0, 160.0).unwrap();
d.get_mut(v).unwrap().fills.clear();
let doc = Arc::new(d);
let view = View { origin: (0.0, 0.0), scale: 1.0, width: 260, height: 220 };
let mut r = Retained::default();
check(&mut r, &doc, p, &view);
let recoloured = edit(&doc, |d| solid(d, source, "2040E0"));
assert_ne!(check(&mut r, &recoloured, p, &view), Work::Reused);
}
+24
View File
@@ -300,6 +300,30 @@ fn strokes_align() {
assert_eq!(px(&pix, 30, 8)[0], 0xF5);
}
#[test]
fn cut_corners_clip_children_and_follow_individual_stroke_weights() {
use figcraft_geom::CornerStyle;
let mut d = figcraft_doc::Document::new("cut corners");
let p = d.first_page().unwrap();
let f = d.create(p, NodeKind::Frame, "Frame", 0.0, 0.0, 80.0, 80.0).unwrap();
let child = d.create(f, NodeKind::Rectangle, "Child", 0.0, 0.0, 80.0, 80.0).unwrap();
d.get_mut(child).unwrap().fills = vec![Paint::solid(Color::WHITE)];
for (style, inside) in [(CornerStyle::Chamfer, true), (CornerStyle::Concave, false)] {
let n = d.get_mut(f).unwrap();
n.clip = true;
n.corners.style = style;
n.corners.radii = [24.0; 4];
n.strokes = vec![Paint::solid(Color::BLACK)];
n.stroke.align = StrokeAlign::Inside;
n.stroke.sides = Some([4.0, 0.0, 0.0, 2.0]);
let pix = render_view(&d, p, &view(80, 80), &Options::default()).unwrap();
assert_eq!(px(&pix, 14, 14)[0] != 0xF5, inside);
assert_eq!(px(&pix, 40, 2), [0, 0, 0, 255]);
assert_eq!(px(&pix, 1, 40), [0, 0, 0, 255]);
assert_eq!(px(&pix, 40, 78), [255, 255, 255, 255]);
}
}
#[test]
fn side_strokes_follow_rounded_corners() {
// border-l-4 rounded-r-lg: a straight 4 px bar on the left, nothing on the other edges.
+3 -1
View File
@@ -873,7 +873,9 @@ impl W<'_> {
NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_geom::full_sweep(sweep) => {
figcraft_geom::kurbo::Shape::to_path(&figcraft_geom::kurbo::Ellipse::from_rect(r), 0.1)
}
NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. } if n.corners.smoothing == 0.0 => {
NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. }
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
{
// A rounded corner keeps a radius only while the shifted radius stays positive.
let radii = n.corners.radii.map(|c| if c > 0.0 { c + d } else { 0.0 });
if n.corners.radii.iter().zip(radii).any(|(c, r)| *c > 0.0 && r <= 0.0) {
+29 -1
View File
@@ -1084,6 +1084,14 @@ impl FontDb {
faces.into_iter().min_by_key(|f| cost(f)).cloned()
}
/// The face to draw `family` + `style` with: the family's own, else for a well-known family
/// that isn't installed a close stand-in in the same style ([`stand_ins`]), else the default.
pub fn find_or_stand_in(&mut self, family: &str, style: &str) -> Option<Arc<Face>> {
self.find(family, style)
.or_else(|| stand_ins(&family.trim().to_lowercase()).iter().find_map(|f| self.find(f, style)))
.or_else(|| self.default_face())
}
/// The default face (Inter Regular if embedded, else any system sans).
pub fn default_face(&mut self) -> Option<Arc<Face>> {
for fam in ["Inter", "Helvetica Neue", "Helvetica", "Arial", "Segoe UI", "Roboto", "DejaVu Sans", "Liberation Sans", "Noto Sans"] {
@@ -1534,6 +1542,26 @@ pub fn apple_alias(key: &str) -> Option<&'static str> {
})
}
/// Installed families of similar design and width to draw a well-known UI family with when it
/// isn't installed (`key` lowercase), best first (#1237): the platform UI and code families that
/// designs use most and other systems lack. Text still names the family it asked for, which stays
/// reported as missing.
fn stand_ins(key: &str) -> &'static [&'static str] {
const MONO: &[&str] = &["Cascadia Mono", "Consolas", "SF Mono", "Menlo", "DejaVu Sans Mono", "Liberation Mono", "Courier New"];
let key = key.trim_start_matches('.');
if ["sf mono", "menlo", "monaco"].iter().any(|m| key.starts_with(m)) {
MONO
} else if key.starts_with("sf pro") || key.starts_with("sf compact") || apple_alias(key).is_some() {
&["Inter", "Pretendard"]
} else if key.starts_with("google sans") {
&["Roboto", "Inter"]
} else if key.starts_with("euclid") {
&["DM Sans", "Inter"]
} else {
&[]
}
}
/// Convenience: find a face with the global db.
/// The family and style of the installed face whose PostScript name is `ps`.
pub fn postscript_face(ps: &str) -> Option<(String, String)> {
@@ -1545,7 +1573,7 @@ pub fn postscript_face(ps: &str) -> Option<(String, String)> {
pub fn find_face(family: &str, style: &str) -> Option<Arc<Face>> {
let mut db = db().write().unwrap_or_else(std::sync::PoisonError::into_inner);
db.find(family, style).or_else(|| db.default_face())
db.find_or_stand_in(family, style)
}
/// All family names known to the global db.
+19
View File
@@ -145,3 +145,22 @@ fn a_family_per_weight_offers_its_italics_too() {
db.add(face("Synthetic Slab Semi Light", "Italic", 350, true));
assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)]));
}
#[test]
fn a_well_known_family_that_isnt_installed_draws_with_a_close_stand_in_in_its_style() {
// #1237: the default face (the first of Inter, Helvetica…, in Regular) stood in for every
// missing family, so code set in Menlo came out proportional and SF Pro Bold came out regular.
let Some(f) = CRAFT_FONTS.first() else { return };
let face = |family: &str, style: &str| Face::from_bytes(FontBytes::Static(f.bytes), 0, Some(family), Some(style)).unwrap();
let mut db = FontDb::default();
let inter = db.add(face("Inter", "Regular"));
let inter_bold = db.add(face("Inter", "Bold"));
let roboto = db.add(face("Roboto", "Regular"));
let consolas = db.add(face("Consolas", "Regular"));
assert!(Arc::ptr_eq(&db.find_or_stand_in("Menlo", "Regular").unwrap(), &consolas), "a code font for a code font");
assert!(Arc::ptr_eq(&db.find_or_stand_in("Google Sans", "Regular").unwrap(), &roboto), "ahead of the default");
assert!(Arc::ptr_eq(&db.find_or_stand_in("SF Pro Display", "Bold").unwrap(), &inter_bold), "the style asked for");
assert!(Arc::ptr_eq(&db.find_or_stand_in("Synthetic Unknown", "Bold").unwrap(), &inter), "others keep the default");
// The stand-in only draws: the family itself is still missing.
assert!(!db.has_family("Menlo") && !db.has_family("Google Sans"));
}
+1 -1
View File
@@ -510,7 +510,7 @@ fn shape_text(text: &TextData) -> ShapedText {
let mut faces: Vec<Option<Arc<Face>>> = Vec::with_capacity(styles.len());
let mut style_fallbacks: Vec<Vec<Arc<Face>>> = Vec::with_capacity(styles.len());
for s in &styles {
faces.push(dbw.find(&s.font_family, &s.font_style).or_else(|| dbw.default_face()));
faces.push(dbw.find_or_stand_in(&s.font_family, &s.font_style));
style_fallbacks.push(dbw.fallbacks_for(&s.font_style));
}
// Colour emoji are their own, large faces (Apple Color Emoji is ~180 MB): they are read only
+10
View File
@@ -373,6 +373,10 @@ name = "English"
"Copy the {label}" = "Copy the {label}"
"Copy {value}" = "Copy {value}"
"Corner radius" = "Corner radius"
"Corner style" = "Corner style"
"Round|corner" = "Round"
"Chamfered|corner" = "Chamfered"
"Concave|corner" = "Concave"
"Corner smoothing" = "Corner smoothing"
"Couldn't download the variables" = "Couldn't download the variables"
"Couldn't download {name}" = "Couldn't download {name}"
@@ -462,6 +466,8 @@ name = "English"
"Default content" = "Default content"
"Default value (the top-left variant)" = "Default value (the top-left variant)"
"This variant's value" = "This variant's value"
"Current variant" = "Current variant"
"Select component set" = "Select component set"
"Delay" = "Delay"
"Delete" = "Delete"
"Delete category (its annotations stay)" = "Delete category (its annotations stay)"
@@ -1382,6 +1388,7 @@ name = "English"
"Save version {key}" = "Save version {key}"
"Saved" = "Saved"
"Saved {name}" = "Saved {name}"
"Saving {name}…" = "Saving {name}…"
"Say something" = "Say something"
"Scale" = "Scale"
"Scatter" = "Scatter"
@@ -1949,6 +1956,8 @@ name = "English"
"text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered"
"text style overrides refer to missing table entries" = "text style overrides refer to missing table entries"
"the file has no pages" = "the file has no pages"
"the page hosting FigCraft opened another file before confirming it" = "the page hosting FigCraft opened another file before confirming it"
"the page hosting FigCraft didn't confirm it within {n} seconds" = { one = "the page hosting FigCraft didn't confirm it within {n} second", other = "the page hosting FigCraft didn't confirm it within {n} seconds" }
"the plugin" = "the plugin"
"the variables JSON has no `variableCollections` (expected the local variables response) and was ignored" = "the variables JSON has no `variableCollections` (expected the local variables response) and was ignored"
"this session only" = "this session only"
@@ -1996,6 +2005,7 @@ name = "English"
"{name} ({tag}): {min} – {max}, default {default}. Double-click the slider to go back to the style's value; Escape while dragging cancels." = "{name} ({tag}): {min} – {max}, default {default}. Double-click the slider to go back to the style's value; Escape while dragging cancels."
"{name} from {path}" = "{name} from {path}"
"{name} was removed from the server" = "{name} was removed from the server"
"{name} wasn't saved: {why}" = "{name} wasn't saved: {why}"
"{name} · deleted on main" = "{name} · deleted on main"
"{name} · deleted on the branch" = "{name} · deleted on the branch"
"{name} · not published" = "{name} · not published"
+44 -6
View File
@@ -2,6 +2,8 @@ use super::{
AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OsStr, Path, PathBuf, PendingDialog, PickFuture, Picked, Poll,
RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows,
};
use crate::Delivery;
use figcraft_engine::cmd::file::FileSnapshot;
impl FigApp {
pub fn save_as_dialog(&mut self) {
@@ -39,16 +41,52 @@ impl FigApp {
}
/// Save by handing the file over as a download. `keep`: the name a Save of a host-opened
/// document keeps; `None` is a Save As, under the document's own name.
/// document keeps; `None` is a Save As, under the document's own name. A host that confirms
/// what it stores leaves the file unsaved until it answers ([`Delivery::Pending`]).
fn save_download(&mut self, keep: Option<&str>) {
if let Some(r) = self.run("file.saveAs", json!({"data": true}))
&& self.download(keep.unwrap_or_else(|| r["name"].as_str().unwrap_or_default()), &r)
{
self.run("file.markSaved", json!({}));
dialogs::file_saved(self, &r);
let Some(r) = self.run("file.saveAs", json!({"data": true})) else { return };
let name = keep.unwrap_or_else(|| r["name"].as_str().unwrap_or_default()).to_string();
match self.deliver_document(&name, &r) {
Delivery::Saved => {
self.run("file.markSaved", json!({}));
dialogs::file_saved(self, &r);
}
Delivery::Pending => self.toast(i18n::trf("Saving {name}…", &[("name", &name)])),
Delivery::Refused => {}
}
}
/// [`download`](Self::download) for the document's own file (`file.saveAs {data: true}`'s
/// result), through [`Services::deliver_document`] with the file as it is now.
fn deliver_document(&mut self, name: &str, result: &Value) -> Delivery {
use base64::Engine as _;
let bytes = result["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok());
let file = self.session.docs.get(figcraft_engine::branches::file_tab(&self.session)).map(FileSnapshot::of);
let delivery = match (bytes, file) {
(Some(bytes), Some(file)) => self.services.deliver_document(name, &bytes, file),
_ => Delivery::Refused,
};
if delivery == Delivery::Refused {
self.toast(i18n::trf("Couldn't download {name}", &[("name", &name)]));
}
delivery
}
/// The host stored the document file handed over as `file` under `name`
/// ([`Delivery::Pending`]): the document is saved as of then, and edits made since stay
/// unsaved. Nothing changes for a tab closed, saved or reverted meanwhile.
pub fn document_stored(&mut self, name: &str, file: FileSnapshot) {
if file.delivered(&mut self.session) {
self.toast(i18n::trf("Saved {name}", &[("name", &name)]));
}
}
/// The host didn't store the document file handed over under `name` ([`Delivery::Pending`]),
/// for the reason `why`: the document keeps its unsaved changes, and the user is told.
pub fn document_not_stored(&mut self, name: &str, why: &str) {
self.show_error(i18n::trf("{name} wasn't saved: {why}", &[("name", &name), ("why", &why)]));
}
pub fn save(&mut self) {
// A branch tab saves its main file.
let tab = figcraft_engine::branches::file_tab(&self.session);
+8
View File
@@ -72,6 +72,14 @@ impl FigApp {
}
}
/// Whether the canvas hides the selection's frame and a text's coloured selection right now:
/// while a field is scrubbed ([`crate::widgets::scrubbing`]) or the colour picker is used on
/// the selection ([`Self::picker_hides_selection`]), so the value being changed shows on the
/// layer itself.
pub(crate) fn hides_selection(&self, ctx: &egui::Context) -> bool {
crate::widgets::scrubbing(ctx) || self.picker_hides_selection(ctx)
}
/// Whether the colour picker is being used right now for the selected layers' own look (a
/// paint, an effect, a text range or Selection colors): a drag on its value controls (the
/// palette, the hue and alpha sliders, a number field, the gradient bar and its stops), the
+5
View File
@@ -120,6 +120,11 @@ impl CanvasState {
self.submitted.as_ref().map(|k| k.skip.as_slice())
}
/// Whether the canvas shows a finished render that leaves no layer out.
pub(crate) fn shows_whole_render(&self) -> bool {
self.texture.is_some() && !self.tex_skipped
}
/// The file and page the texture shows.
pub(crate) fn tex_of(&self) -> Option<(u64, NodeId)> {
self.tex_of
+8 -8
View File
@@ -124,10 +124,10 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
}
// Selection.
let editing = ds.text_edit.clone();
// While the colour picker is being used on the selection, hide its frame and handles so the
// colour being picked shows on the layer itself (a text's coloured selection would hide it
// too).
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.picker_hides_selection(painter.ctx()) {
// While a field is scrubbed or the colour picker is used on the selection, hide its frame and
// handles so the value being changed shows on the layer itself (a text's coloured selection
// would hide it too).
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.hides_selection(painter.ctx()) {
size_label = selection_overlay(app, painter, ds, &doc, &sel, zoom);
}
if app.session.tool.tool == ToolId::ShapeBuilder
@@ -276,10 +276,10 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do
let preedit = app.preedit_view();
let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc);
let Some(text) = TextOnScreen::of(edoc, te.id) else { return };
// While the colour picker is being used on this text, its frame and coloured selection hide
// too: the selection colour tinted the very characters whose colour is being chosen. The
// caret stays.
let picking = app.picker_hides_selection(painter.ctx());
// While a field is scrubbed or the colour picker is used on this text, its frame and coloured
// selection hide too: the selection colour tinted the very characters being changed. The caret
// stays.
let picking = app.hides_selection(painter.ctx());
let layout = &text.layout;
if !picking && let Some(q) = node_quad(app, edoc, te.id) {
quad(painter, q, stroke(accent(painter), 1.0));
+4 -2
View File
@@ -176,7 +176,8 @@ fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() {
u.button(p + vec2(90.0, 40.0), false);
u.frame(vec![]);
assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the whole document is rendered again");
assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown");
// The render can already be on screen by the end of this frame; until it is, the sprite stays.
assert!(u.app.canvas.sprite_rect(&u.app).is_some() || u.app.canvas.shows_whole_render(), "the sprite stays until that render is shown");
settle(&mut u);
u.frame(vec![]);
assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "the sprite goes once that render is shown");
@@ -245,7 +246,8 @@ fn a_cancelled_drag_keeps_its_sprite_until_the_restored_document_shows_and_the_n
u.app.session.cancel_interaction().unwrap();
u.frame(vec![]);
assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the restored document is rendered whole");
assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown");
// The render can already be on screen by the end of this frame; until it is, the sprite stays.
assert!(u.app.canvas.sprite_rect(&u.app).is_some() || u.app.canvas.shows_whole_render(), "the sprite stays until that render is shown");
u.button(p, false);
settle(&mut u);
u.frame(vec![]);
@@ -541,3 +541,27 @@ fn a_focused_palette_square_does_not_hide_the_selection() {
}
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "focus on a palette square leaves the frame in view");
}
// Scrubbing a field changes the layer live (#1319): its frame and handles step aside meanwhile, as
// they do for the colour picker, so the new value shows on the layer itself.
#[test]
fn scrubbing_a_field_hides_the_selections_frame_until_let_go() {
let mut s = Session::new();
let text = selected_text(&mut s);
let mut u = Ui::new(s);
let area = text_area(&u, text);
let accent = crate::theme::canvas_accent(&u.ctx);
u.ctx.enable_accesskit();
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the selected text's frame shows");
let from = crate::field_tests::label(&mut u, "Rotation");
u.button(from, true);
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "a press on the label alone leaves the frame");
let mut to = from;
for _ in 0..4 {
to += egui::vec2(6.0, 0.0);
u.frame(vec![egui::Event::PointerMoved(to)]);
}
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "scrubbing hides the frame");
u.button(to, false);
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "letting go brings the frame back");
}
+26 -1
View File
@@ -41,11 +41,15 @@ fn enter(u: &mut Ui) {
/// The middle of the toggle button named `label`, found in the AccessKit tree.
fn named_button(u: &mut Ui, label: &str) -> Pos2 {
named_control(u, Role::Button, label)
}
fn named_control(u: &mut Ui, role: Role, label: &str) -> Pos2 {
u.ctx.enable_accesskit();
u.frame(vec![]);
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::Button && n.label() == Some(label)).expect(label);
let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == role && (n.label() == Some(label) || n.value() == Some(label))).expect(label);
let b = n.bounds().expect("bounds");
pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
}
@@ -55,6 +59,27 @@ fn field(u: &Ui, k: usize) -> Rect {
u.ctx.read_response(Id::unique(("corner", k)).with("field")).expect("corner field shows").rect
}
#[test]
fn corner_style_menu_changes_the_outline_without_losing_individual_radii() {
use figcraft_doc::geom::CornerStyle;
let (mut u, r) = scene();
let toggle = named_button(&mut u, "Individual corners");
click(&mut u, toggle);
for (current, choice, expected) in
[("Round", "Chamfered", CornerStyle::Chamfer), ("Chamfered", "Concave", CornerStyle::Concave), ("Concave", "Round", CornerStyle::Round)]
{
let dropdown = named_control(&mut u, Role::ComboBox, current);
click(&mut u, dropdown);
let action = named_control(&mut u, Role::MenuItemCheckBox, choice);
let history = u.app.session.undo_depth().0;
click(&mut u, action);
let corners = u.app.session.doc().unwrap().node(r).unwrap().corners;
assert_eq!(corners.style, expected);
assert_eq!(corners.radii, [30.0, 0.0, 0.0, 30.0]);
assert_eq!(u.app.session.undo_depth().0, history + 1);
}
}
/// The iOS button next to Corner smoothing sets 60% in one undo step, as the help page's "click
/// iOS to set corner smoothing to 60%" describes.
#[test]
+1 -1
View File
@@ -204,7 +204,7 @@ pub(crate) fn field(u: &mut Ui, name: &str) -> (Pos2, String) {
}
/// The middle of field `name`'s label (what scrubs): just left of its value.
fn label(u: &mut Ui, name: &str) -> Pos2 {
pub(crate) fn label(u: &mut Ui, name: &str) -> Pos2 {
u.frame(vec![]);
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
+84 -1
View File
@@ -1,5 +1,6 @@
//! In a page host the browser hands files to the host: a Save of the document the host opened goes
//! out under the host's file name, a Save As under the document's own name.
//! out under the host's file name, a Save As under the document's own name. A host that confirms
//! what it stores leaves the document unsaved until it answers.
use std::sync::{Arc, Mutex};
@@ -58,3 +59,85 @@ fn without_a_host_file_or_for_a_copy_format_save_is_a_save_as() {
assert_eq!(got.lock().unwrap().as_slice(), ["Original.figcraft"], "{file:?}");
}
}
/// A host that answers later whether it stored a document file ([`crate::Delivery::Pending`]):
/// the files it was handed wait here; exports still arrive as plain downloads.
#[derive(Default)]
struct Confirming {
documents: std::rc::Rc<std::cell::RefCell<Vec<(String, figcraft_engine::cmd::file::FileSnapshot)>>>,
downloads: Saved,
}
impl Services for Confirming {
fn downloads(&self) -> bool {
true
}
fn download(&mut self, name: &str, _bytes: &[u8]) -> bool {
self.downloads.lock().unwrap().push(name.to_string());
true
}
fn deliver_document(&mut self, name: &str, _bytes: &[u8], file: figcraft_engine::cmd::file::FileSnapshot) -> crate::Delivery {
self.documents.borrow_mut().push((name.to_string(), file));
crate::Delivery::Pending
}
}
type Documents = std::rc::Rc<std::cell::RefCell<Vec<(String, figcraft_engine::cmd::file::FileSnapshot)>>>;
fn confirming() -> (FigApp, Documents, Saved) {
let host = Confirming::default();
let (documents, downloads) = (host.documents.clone(), host.downloads.clone());
let mut app = FigApp::new(Session::empty(), Box::new(host));
app.session.execute("file.new", &json!({"name": "Original"})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
(app, documents, downloads)
}
fn toast(app: &FigApp) -> String {
app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default()
}
#[test]
fn a_save_the_host_has_not_confirmed_keeps_the_unsaved_changes() {
let (mut app, documents, downloads) = confirming();
app.save_as_dialog();
assert_eq!(documents.borrow().len(), 1, "the document file went to the host");
assert!(downloads.lock().unwrap().is_empty(), "not as a plain download");
assert!(app.session.ds().unwrap().is_dirty(), "nothing is saved until the host says so");
assert!(!toast(&app).starts_with("Saved"), "the user isn't told it is saved yet: {}", toast(&app));
let (name, file) = documents.borrow_mut().remove(0);
app.document_stored(&name, file);
assert!(!app.session.ds().unwrap().is_dirty());
assert_eq!(toast(&app), "Saved Original.figcraft");
}
#[test]
fn edits_made_before_the_host_confirms_stay_unsaved() {
let (mut app, documents, _) = confirming();
app.save_as_dialog();
app.session.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap();
let (name, file) = documents.borrow_mut().remove(0);
app.document_stored(&name, file);
assert!(app.session.ds().unwrap().is_dirty(), "the second rectangle never reached the host");
}
#[test]
fn a_save_the_host_did_not_store_stays_unsaved_and_says_why() {
let (mut app, documents, _) = confirming();
app.save_as_dialog();
let (name, _file) = documents.borrow_mut().remove(0);
app.document_not_stored(&name, "you can only view this file");
assert!(app.session.ds().unwrap().is_dirty());
let error = app.ui.last_error.clone().unwrap_or_default();
assert!(error.contains("Original.figcraft") && error.contains("you can only view this file"), "{error}");
}
#[test]
fn exports_are_never_document_saves() {
let (mut app, documents, downloads) = confirming();
let id = app.session.ds().unwrap().selection[0];
crate::export_panel::save_one(&mut app, &[id], &figcraft_doc::ExportSetting::default(), "Rectangle.png");
assert!(documents.borrow().is_empty());
assert_eq!(downloads.lock().unwrap().as_slice(), ["Rectangle.png"]);
assert!(app.session.ds().unwrap().is_dirty(), "an export saves nothing");
}
+2 -2
View File
@@ -426,8 +426,8 @@ pub(crate) use clock::repaint_in;
pub use clock::{AUTO_SAVE_SECS, AUTOSAVE_SECS, FrameClock, ToastClock};
pub(crate) use open::{drop_overlay, dropped_bytes, is_document, opens};
pub use services::{
ContentsFuture, DialogFuture, MAX_CLIPBOARD_PNG_BYTES, NoServices, ReadFuture, Services, browser_can_read, browser_stopped, egui_copy_png,
egui_copy_text, unreadable,
ContentsFuture, Delivery, DialogFuture, MAX_CLIPBOARD_PNG_BYTES, NoServices, ReadFuture, Services, browser_can_read, browser_stopped,
egui_copy_png, egui_copy_text, save_forgotten_on_open, save_unconfirmed, unreadable,
};
use services::{DialogDone, PickFuture, Picked, RepaintWaker};
pub use state::{
+45 -21
View File
@@ -38,12 +38,14 @@ pub fn instance_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[No
match &n.kind {
NodeKind::Instance { .. } => instance_ui(app, ui, doc, n),
NodeKind::ComponentSet { description } => {
properties_ui(app, ui, doc, n.id, None);
properties_ui(app, ui, doc, n.id);
description_ui(app, ui, n.id, description);
}
NodeKind::Component { description, .. } => {
let set = variant_set(doc, n.id);
properties_ui(app, ui, doc, set.unwrap_or(n.id), set.map(|_| n.id));
match variant_set(doc, n.id) {
Some(set) => current_variant_ui(app, ui, doc, n, set),
None => properties_ui(app, ui, doc, n.id),
}
description_ui(app, ui, n.id, description);
}
_ => {}
@@ -226,8 +228,43 @@ fn name_width(ui: &Ui, default_w: f32, max: f32) -> f32 {
(ui.available_width() - default_w - BUTTON - 2.0 * widgets::GUTTER).clamp(48.0, max)
}
/// Properties of a component or component set (`variant`: the set's variant that is selected).
fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, variant: Option<NodeId>) {
/// One variant of a set selected: a Current variant section, a dropdown of each variant property
/// set to this variant's value; choosing another renames this variant only, so nothing moves
/// (#2349). The set's properties are edited on the set, which the section's button selects (#2346).
fn current_variant_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, variant: &Node, set: NodeId) {
let t = Tokens::get(ui.ctx());
widgets::separator(ui);
if widgets::section_header(ui, tr("Current variant"), &[(Icon::ComponentSet, tr("Select component set"))], false) == Some(0) {
app.run("select.set", json!({"ids": [set]}));
}
let pairs = variant_props(&variant.name);
let options = variant_options(doc, set);
let order: Vec<String> = options.iter().map(|(k, _)| k.clone()).collect();
for (k, vals) in &options {
let cur = pairs.get(k).cloned().unwrap_or_default();
row(ui, 32.0, |ui| {
prop_label(ui, k, Icon::ComponentSet);
let w = ui.available_width().max(60.0);
let resp = widgets::dropdown(ui, &cur, w, None).on_hover_text(tr("This variant's value"));
menu_popup(&resp).show(|ui| {
for v in vals {
if menu_item(ui, v, "") {
let mut pairs = pairs.clone();
pairs.insert(k.clone(), v.clone());
app.run("node.set", json!({"ids": [variant.id], "props": {"name": variant_name(&pairs, &order)}}));
ui.close();
}
}
});
});
}
if variant_conflicts(doc, set).iter().any(|g| g.contains(&variant.id)) {
widgets::note(ui, tr("Some variants have the same property values: give each one a unique combination"), t.warning);
}
}
/// Properties of a component or component set.
fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) {
let t = Tokens::get(ui.ctx());
let is_set = matches!(doc.node(owner).map(|n| &n.kind), Some(NodeKind::ComponentSet { .. }));
// Shared (non-variant) properties live on every variant; read them from the first.
@@ -273,9 +310,6 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, v
} else {
Default::default()
};
// A selected variant's dropdowns show and set its own values (#2349); the set's, its default.
let own = variant.and_then(|v| doc.node(v)).map(|n| (n.id, variant_props(&n.name)));
let order: Vec<String> = variants.iter().map(|(k, _)| k.clone()).collect();
// Variant properties: name, values (the matrix), add value, delete. Dragged by their left
// margin to reorder them (only among themselves: the shared ones keep the engine's order).
let mut drag = ListDrag::in_order(ui, ("variant_props", owner));
@@ -291,22 +325,12 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, v
if let Some(nn) = widgets::text_field(ui, Id::unique(("vprop_name", owner, k.as_str())), k, name_w, tr("Name")) {
app.run("component.editProperty", json!({"id": owner, "name": k, "newName": nn}));
}
let def = own.as_ref().map_or(&defaults, |(_, pairs)| pairs).get(k).or(vals.first()).cloned().unwrap_or_default();
let hint = if own.is_some() { tr("This variant's value") } else { tr("Default value (the top-left variant)") };
let resp = widgets::dropdown(ui, &def, DEFAULT_W, None).on_hover_text(hint);
let def = defaults.get(k).or(vals.first()).cloned().unwrap_or_default();
let resp = widgets::dropdown(ui, &def, DEFAULT_W, None).on_hover_text(tr("Default value (the top-left variant)"));
menu_popup(&resp).show(|ui| {
for v in vals {
if menu_item(ui, v, "") {
match &own {
Some((id, pairs)) => {
let mut pairs = pairs.clone();
pairs.insert(k.clone(), v.clone());
app.run("node.set", json!({"ids": [id], "props": {"name": variant_name(&pairs, &order)}}));
}
None => {
app.run("component.editProperty", json!({"id": owner, "name": k, "default": v}));
}
}
app.run("component.editProperty", json!({"id": owner, "name": k, "default": v}));
ui.close();
}
}
+34 -9
View File
@@ -1,3 +1,5 @@
use figcraft_doc::geom::CornerStyle;
use super::menu::{blend_menu, context_popup, menu_check, menu_item, menu_popup, preview_blend, row, row_context_menu, row_target};
use super::stroke::stroke_settings;
use super::{
@@ -93,6 +95,26 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N
}
});
if smooth_ok && ui.data(|d| d.get_temp::<bool>(Id::unique("indep_corners"))).unwrap_or(false) {
if indep_ok {
let style = common(doc, sel, |n| n.corners.style);
let label = |style| match style {
CornerStyle::Round => tr("Round|corner"),
CornerStyle::Chamfer => tr("Chamfered|corner"),
CornerStyle::Concave => tr("Concave|corner"),
};
widgets::sublabels(ui, tr("Corner style"), None);
row(ui, 32.0, |ui| {
let resp = widgets::dropdown(ui, style.map(label).unwrap_or(tr("Mixed")), col * 2.0 + 8.0, Some(Icon::CornerRadius));
menu_popup(&resp).show(|ui| {
for choice in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave] {
if menu_check(ui, style == Some(choice), label(choice), "") {
app.set_props(&ids, json!({"cornerStyle": choice}));
ui.close();
}
}
});
});
}
let radii = common(doc, sel, |n| n.corners.radii);
// `k` indexes `radii` ([top left, top right, bottom right, bottom left]); the fields sit
// where their corners are: top left, top right / bottom left, bottom right.
@@ -121,15 +143,18 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N
}
});
}
let sm = common(doc, sel, |n| n.corners.smoothing * 100.0);
widgets::sublabels(ui, tr("Corner smoothing"), None);
row(ui, 32.0, |ui| {
let e = widgets::number_field(ui, Id::unique("smoothing"), Lead::Icon(Icon::CornerSmoothing, tr("Corner smoothing")), sm, "%", col, 1.0);
app.field(&ids, "cornerSmoothing", e, |v| json!((v / 100.0).clamp(0.0, 1.0)));
if widgets::button(ui, tr("iOS"), false, true).on_hover_text(tr("Set corner smoothing to 60%")).clicked() {
app.set_props(&ids, json!({"cornerSmoothing": 0.6}));
}
});
if crate::selection_cache::every(doc, sel, |n| n.corners.style.is_round()) {
let sm = common(doc, sel, |n| n.corners.smoothing * 100.0);
widgets::sublabels(ui, tr("Corner smoothing"), None);
row(ui, 32.0, |ui| {
let e =
widgets::number_field(ui, Id::unique("smoothing"), Lead::Icon(Icon::CornerSmoothing, tr("Corner smoothing")), sm, "%", col, 1.0);
app.field(&ids, "cornerSmoothing", e, |v| json!((v / 100.0).clamp(0.0, 1.0)));
if widgets::button(ui, tr("iOS"), false, true).on_hover_text(tr("Set corner smoothing to 60%")).clicked() {
app.set_props(&ids, json!({"cornerSmoothing": 0.6}));
}
});
}
}
let blend = common(doc, sel, |n| n.blend);
let show_blend = ui.data(|d| d.get_temp::<bool>(Id::unique("blend_open"))).unwrap_or(false)
+4
View File
@@ -295,6 +295,9 @@ pub struct Presenter {
/// The part of the presented frame in view, drawn at device scale over the (capped) whole-frame
/// texture; `bounds` is the page area it covers.
detail: Option<(NodeId, FrameTex)>,
/// The page area in view and the pixel scale it was drawn at last frame: a change is motion,
/// which the detail waits out.
last_view: Option<(figcraft_geom::Rect, f64)>,
/// Small current-screen preview in the full-window bar, cached until its content changes.
bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>,
arrived: f64,
@@ -382,6 +385,7 @@ impl Presenter {
temp: None,
textures: HashMap::new(),
detail: None,
last_view: None,
bar_thumb: None,
arrived: -1.0,
delays_fired: HashSet::new(),
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more