Merge main into #1548

This commit is contained in:
bflatastic
2026-10-30 00:31:50 +07:00
31 changed files with 938 additions and 144 deletions
+1 -1
View File
@@ -27,7 +27,7 @@ permissions:
jobs:
windows-arm64:
# Immutable supporting workflow revision until the new install contract lands upstream.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@fa5ef18780cf5e7d5d3b8de068de56cffc83cac5
with:
app-name: figcraft
app-dir: FigCraft
+2 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
@@ -356,6 +356,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | minor | M4, #1219: Thai, Lao, Khmer and Burmese text, written without spaces between words, wraps between words instead of where a line overflows (`พัฒนาซอ|ฟต์แวร์` → `พัฒนา|ซอฟต์แวร์`). `figcraft_text::breaks::word_breaks` finds the word starts inside each run of these scripts with ICU4X's line segmenter (`icu_segmenter` 2.3): its dictionaries on desktop, its LSTM models in the browser (about 0.39 MB of wasm instead of 1.86 MB, which the 24 MiB gate can't take; they split a few compounds the dictionaries keep whole). Where a run meets spaces, Latin or CJK the UAX #14 rules decide as before, and a word wider than its box still takes #1400's emergency break. Text without these scripts does no extra work. Grade unchanged. Evidence: `breaks::tests::thai_lines_break_between_words`, `lao_khmer_and_burmese_lines_break_between_words`, `word_breaks_survive_junk`, `behaviour_tests::thai_lines_break_between_words` (fails on main). |
| 2026-10-29 | minor | M9, #1075: `figcraft-server` gives requests that change its files (join codes, links, renames, removals, blocks, publishing with the key) a budget of 60 a minute per address, with the server key and owner tokens alike (100 renames in a row from one address: 100 served before, 60 now; another address is unaffected), and finds join codes through an index of their hashes instead of opening every link's code. Same results, same protocol. Tests: `admin_budget_tests`. Numbers unchanged |
| 2026-10-29 | minor | M8, #1080: SVG import draws a pattern's tile once per pattern and scale and reuses it for every other layer it fills (1,000 rectangles filled with one pattern: 1,000 tile drawings before, 1 now, same image fill), and the layers inside a tile count in the import's 100,000-layer budget instead of each tile starting a fresh one, so patterns nested in patterns stop at the budget. Tests: `tile_tests` (svg). Numbers unchanged |
| 2026-10-29 | patch | M4, #1478: a letter and its combining marks are shaped with one font that has them all. Text typed decomposed (NFD, `E` + U+0302 + U+0309 for Ể) in a font with the letters but not the marks drew missing-glyph boxes beside and above the letter, while the precomposed form fell back to a font that has it; each grapheme cluster now takes the first face (the style's own, then the fallbacks) that covers every char in it (joiners and variation selectors need no glyph), else the letter's own face as before. Fonts that cover Vietnamese were already right: mark positioning (GPOS `mark`/`mkmk`) stacks the marks over the letter on the canvas, in PNG, SVG and PDF. Tests in `crates/text/src/vietnamese_tests.rs`. Numbers unchanged |
| 2026-10-29 | minor | M9, #1415: `comment.list` (CLI, MCP `run_command`, the `figcraft://comments` resource) gives every message, the first and each reply, its `mentions`: `{name, known, you}` for each name it @mentions, by the rule the thread view highlights them with (`figcraft_doc::mentions`, which the highlighting now shares). A name resolves against the file's people and you, as the file spells it. An unknown name is reported with `known: false`. `a@b.com` mentions nobody. Filtering threads by a mentioned name and listing mentioned names in `comment.people` stay open. Numbers unchanged |
+11 -1
View File
@@ -1,5 +1,6 @@
//! What one address may do how often: new connections, publishing without the key and messages
//! (only on a server open to the public), and reports and downloads (always). Each is a token
//! (only on a server open to the public), and reports, downloads and requests that change the
//! server's files (always, with the server key too). Each is a token
//! bucket per block an address counts in ([`ip_blocks`]: an IPv4 address, or an IPv6 /64 and its
//! /56 and /48 with 2 and 4 times the rate), so a tunnel's /48 doesn't get 65,536 /64s' worth. Publishing has a budget for
//! everyone besides ([`PUBLISHES_ALL`] times one address's). The table keeps at most
@@ -34,6 +35,10 @@ pub const DOWNLOAD_BURST: f64 = (16u64 << 20) as f64;
/// times what the widest block (an IPv6 /48, four addresses' worth) may, so no block takes it all.
pub const PUBLISHES_ALL: f64 = 32.0;
/// Requests that change the server's files (join codes, links, renames, removals, blocks,
/// publishing with the key) one address may make a minute, with the server key or an owner token.
pub const ADMIN_PER_MINUTE: f64 = 60.0;
/// Join codes one address may try a minute (right or wrong).
pub const CODES_PER_MINUTE: f64 = 10.0;
/// Wrong codes in a row (within [`CODE_LOCKOUT`] of each other) that lock an address out of codes.
@@ -66,6 +71,8 @@ pub enum Action {
Download(usize),
/// Trying a join code.
Code,
/// A request that changes the server's files ([`ADMIN_PER_MINUTE`]).
Admin,
}
struct Address {
@@ -76,6 +83,7 @@ struct Address {
reports: Bucket,
downloads: Bucket,
codes: Bucket,
admin: Bucket,
/// Wrong join codes in a row, and when the last one was.
wrong: u32,
wrong_at: Instant,
@@ -177,6 +185,7 @@ impl Abuse {
reports: bucket(REPORTS_PER_HOUR * times, 3600.0),
downloads: Bucket::new(DOWNLOAD_RATE * times, DOWNLOAD_BURST * times),
codes: bucket(CODES_PER_MINUTE * times, 60.0),
admin: bucket(ADMIN_PER_MINUTE * times, 60.0),
wrong: 0,
wrong_at: now,
locked: None,
@@ -195,6 +204,7 @@ impl Abuse {
Action::Report => (&mut a.reports, 1.0),
Action::Download(n) => (&mut a.downloads, n as f64),
Action::Code => (&mut a.codes, 1.0),
Action::Admin => (&mut a.admin, 1.0),
}
}
@@ -0,0 +1,75 @@
//! Requests that change the server's files have a budget per address, with the server key or an
//! owner token too; join codes are found through an index of their hashes, with the same results
//! as comparing every link.
use std::net::IpAddr;
use figcraft_collab::message::{Admin, AdminReply};
use figcraft_collab_net::hub::Backend;
use crate::abuse::ADMIN_PER_MINUTE;
use crate::store::{BUSY_ADMIN, CODE_GONE, Store};
use crate::test_util::{TempDir, config, ip, snapshot};
fn rename(store: &mut Store, from: IpAddr, file: &str) -> AdminReply {
Backend::admin(store, from, Admin::Rename { file: file.into(), name: "Renamed".into() }, &|_| None).reply
}
#[test]
fn a_flood_of_changes_from_one_address_is_held_back_and_others_are_not() {
let dir = TempDir::new("admin-budget");
let mut store = Store::open(dir.path(), config(dir.path()).store()).unwrap();
let (file, ..) = store.publish("Poster", &snapshot("Poster")).unwrap();
let flooder = ip("198.51.100.1");
let done = (0..100).filter(|_| rename(&mut store, flooder, &file.id) == AdminReply::Done).count();
assert_eq!(done, ADMIN_PER_MINUTE as usize, "a minute's worth, then wait");
assert_eq!(rename(&mut store, flooder, &file.id), AdminReply::Failed { reason: BUSY_ADMIN.into() });
// An owner token's requests share the address's budget.
let hosted = store.hosted(flooder, Some(&file.id), Admin::Rename { file: file.id.clone(), name: "Mine".into() }, &|_| None).reply;
assert_eq!(hosted, AdminReply::Failed { reason: BUSY_ADMIN.into() });
// Looking costs nothing, and another address has its own budget.
assert!(matches!(Backend::admin(&mut store, flooder, Admin::Files, &|_| None).reply, AdminReply::Files(_)));
assert_eq!(rename(&mut store, ip("198.51.100.2"), &file.id), AdminReply::Done);
}
#[test]
fn codes_are_found_through_the_index_as_before() {
let dir = TempDir::new("code-index");
let files_dir = dir.path().join("files");
let (files, codes) = {
let mut store = Store::open(dir.path(), config(dir.path()).store()).unwrap();
let mut files = Vec::new();
let mut codes = Vec::new();
for n in 0..12 {
let (file, edit, _view) = store.publish(&format!("File {n}"), &snapshot("File")).unwrap();
codes.push(store.set_code(&file.id, &edit.token).unwrap());
files.push((file.id, edit.token, edit.link.id));
}
(files, codes)
};
// A copy of a file's folder holds the same code (the last file by id wins, as before).
let copy = "zzzzzzzzzzzzzzzz";
std::fs::create_dir_all(files_dir.join(copy)).unwrap();
for f in std::fs::read_dir(files_dir.join(&files[0].0)).unwrap() {
let f = f.unwrap();
std::fs::copy(f.path(), files_dir.join(copy).join(f.file_name())).unwrap();
}
let mut store = Store::open(dir.path(), config(dir.path()).store()).unwrap();
let who = |n: usize| ip(&format!("192.0.2.{n}"));
for (n, ((id, token, _), code)) in files.iter().zip(&codes).enumerate().skip(1) {
assert_eq!(store.resolve_code(who(n), code).unwrap(), (id.clone(), token.clone()), "file {n}");
}
assert_eq!(store.resolve_code(who(100), &codes[0]).unwrap().0, copy);
// Revoking the copy's link leaves the original's code working; revoking that one ends it.
store.revoke(copy, &files[0].2).unwrap();
assert_eq!(store.resolve_code(who(101), &codes[0]).unwrap(), (files[0].0.clone(), files[0].1.clone()));
store.revoke(&files[0].0, &files[0].2).unwrap();
assert_eq!(store.resolve_code(who(102), &codes[0]).unwrap_err(), CODE_GONE);
// A new code replaces the old in the index; a removed file's code is gone.
let newer = store.set_code(&files[1].0, &files[1].1).unwrap();
assert_eq!(store.resolve_code(who(103), &codes[1]).unwrap_err(), CODE_GONE);
assert_eq!(store.resolve_code(who(104), &newer).unwrap().0, files[1].0);
store.remove(&files[2].0).unwrap();
assert_eq!(store.resolve_code(who(105), &codes[2]).unwrap_err(), CODE_GONE);
assert_eq!(store.resolve_code(who(106), &codes[3]).unwrap().0, files[3].0);
}
+2 -1
View File
@@ -316,7 +316,8 @@ fn running(data: &Path) -> Result<SocketAddr, String> {
/// Do one request: through the running server, or on the data directory.
fn admin(cfg: &Config, req: Admin) -> Result<AdminReply, String> {
match Store::try_open(&cfg.data, cfg.store())? {
Some(mut store) => Ok(store.admin(req, &|_| None).reply),
// On this machine, one request per command: never over the address's budget.
Some(mut store) => Ok(store.admin(std::net::Ipv4Addr::LOCALHOST.into(), req, &|_| None).reply),
None => {
let addr = running(&cfg.data)?;
let key = std::fs::read_to_string(cfg.data.join(KEY)).map_err(|e| format!("can't read the server key: {e}"))?;
+1 -15
View File
@@ -7,11 +7,9 @@
use std::net::IpAddr;
use std::time::{Duration, Instant};
use figcraft_collab::Replica;
use figcraft_collab::code;
use figcraft_collab::message::{Admin, AdminReply, ClientMsg, Hello, OpenHosting, PROTOCOL, Resolve, ServerMsg};
use figcraft_collab_net::hub::Backend;
use figcraft_doc::{Document, NodeKind};
use figcraft_engine::Session;
use figcraft_engine::live::Status;
use serde_json::{Value, json};
@@ -20,24 +18,12 @@ use crate::abuse::{Abuse, AbuseConfig, Action, CODE_LOCKOUT, CODES_PER_MINUTE, W
use crate::codes::Key;
use crate::config::Config;
use crate::store::{CODE_GONE, CODES_BUSY, NO_CODE, Store};
use crate::test_util::{Raw, TempDir, config, live, pump, session};
use crate::test_util::{Raw, TempDir, config, ip, live, pump, session, snapshot};
fn open(dir: &std::path::Path) -> Config {
Config { open_publish: true, operator_contact: "abuse@example.com".into(), terms_url: "https://example.com/terms".into(), ..config(dir) }
}
fn snapshot(name: &str) -> Vec<figcraft_collab::Change> {
let mut d = Document::new(name);
let page = d.first_page().unwrap();
d.create(page, NodeKind::Rectangle, "Card", 0.0, 0.0, 100.0, 60.0).unwrap();
d.repair();
Replica::new(d).snapshot().unwrap()
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
+1 -13
View File
@@ -25,24 +25,12 @@ use crate::abuse::{Abuse, AbuseConfig, Action, DOWNLOAD_BURST};
use crate::config::Config;
use crate::public_tests::via_proxy;
use crate::store::{BUSY_DOWNLOADS, NO_PUBLIC_LIBRARY, Store};
use crate::test_util::{Raw, TempDir, config};
use crate::test_util::{Raw, TempDir, config, ip, snapshot};
fn open(dir: &std::path::Path) -> Config {
Config { open_publish: true, operator_contact: "abuse@example.com".into(), ..config(dir) }
}
fn snapshot(name: &str) -> Vec<figcraft_collab::Change> {
let mut d = Document::new(name);
let page = d.first_page().unwrap();
d.create(page, NodeKind::Rectangle, "Card", 0.0, 0.0, 100.0, 60.0).unwrap();
d.repair();
Replica::new(d).snapshot().unwrap()
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
/// A team library archive as the app makes it; with `bomb` bytes of spaces as its snapshot
/// (deflated: a few KiB) and `padding` incompressible bytes stored beside it.
fn archive(bomb: usize, padding: usize) -> Vec<u8> {
+2
View File
@@ -86,6 +86,8 @@ pub fn start(cfg: &Config) -> Result<Running, String> {
Ok(Running { hosting })
}
#[cfg(test)]
mod admin_budget_tests;
#[cfg(test)]
mod background_tests;
#[cfg(test)]
+1 -15
View File
@@ -6,10 +6,8 @@ use std::io::{Read, Write};
use std::net::{IpAddr, SocketAddr, TcpStream};
use std::time::{Duration, Instant};
use figcraft_collab::Replica;
use figcraft_collab::message::{self, Admin, AdminReply, ClientMsg, OpenHosting, PROTOCOL, ServerMsg};
use figcraft_collab_net::{Endpoint, Invite, NetLimits, manage};
use figcraft_doc::{Document, NodeKind};
use serde_json::{Value, json};
use tungstenite::client::IntoClientRequest;
use tungstenite::{Bytes, Message};
@@ -18,24 +16,12 @@ use crate::abuse::{Abuse, AbuseConfig, Action, MAX_ADDRESSES};
use crate::cli::{self, Cli, Command, Sort};
use crate::config::Config;
use crate::store::{KEY_ONLY, Store};
use crate::test_util::{Raw, TempDir, config, join, key, live, pump, session};
use crate::test_util::{Raw, TempDir, config, ip, join, key, live, pump, session, snapshot};
fn open(dir: &std::path::Path) -> Config {
Config { open_publish: true, operator_contact: "abuse@example.com".into(), terms_url: "https://example.com/terms".into(), ..config(dir) }
}
fn snapshot(name: &str) -> Vec<figcraft_collab::Change> {
let mut d = Document::new(name);
let page = d.first_page().unwrap();
d.create(page, NodeKind::Rectangle, "Card", 0.0, 0.0, 100.0, 60.0).unwrap();
d.repair();
Replica::new(d).snapshot().unwrap()
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
fn ex(s: &mut figcraft_engine::Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
+11 -1
View File
@@ -30,7 +30,7 @@
//! hashes and compared in constant time. Whatever is damaged at startup is skipped and reported,
//! never deleted.
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{Cursor, Write};
use std::net::IpAddr;
@@ -88,6 +88,9 @@ const MAX_PROBLEMS: usize = 200;
/// Why a download is turned away (an address's share, or everyone's, is used up for now).
pub const BUSY_DOWNLOADS: &str = "too many downloads from your address or from everyone right now: try again in a minute";
/// Why a request that changes the server's files is turned away (the address's share is used up).
pub const BUSY_ADMIN: &str = "too many changes to this server's files from your address: wait a minute and try again";
/// Why publishing without the key is refused on a server that isn't open to the public.
pub const KEY_ONLY: &str = "this server takes files only from people who have its key: add ?key=… to the address (its operator has the key)";
@@ -270,6 +273,9 @@ pub struct Store {
// shortcut: in memory only, so after a restart such a code reads as unknown; keep them in the
// data directory if people ask why their code "never existed".
gone_codes: VecDeque<String>,
/// The files whose links hold each join code, by the code's hash ([`Sealed::hash`]): a typed
/// code is looked up here instead of against every link.
codes: HashMap<String, BTreeSet<String>>,
/// When idle files are looked for next (seconds since 1970).
next_sweep: u64,
/// Compactions so far (tests count them).
@@ -396,6 +402,7 @@ impl Store {
blocked: BTreeSet::new(),
reports: Vec::new(),
gone_codes: VecDeque::new(),
codes: HashMap::new(),
next_sweep: 0,
compactions: 0,
cut_short: Vec::new(),
@@ -448,6 +455,9 @@ impl Store {
}
match self.check(&path) {
Ok(entry) => {
for c in entry.links.iter().filter_map(|l| l.code.as_ref()) {
self.codes.entry(c.hash.clone()).or_default().insert(id.clone());
}
self.files.insert(id, entry);
}
Err(why) => self.note(format!("skipped file {id}: {why}")),
+17 -4
View File
@@ -1,9 +1,18 @@
use super::journal::flush_log;
use super::{
Access, Action, Admin, AdminReply, Admission, BUSY_DOWNLOADS, Backend, ClientMsg, Closing, Handled, HostInfo, Instant, IpAddr, LibraryReply,
LibraryReq, OpenFile, PluginReply, PluginReq, Server, Store, disk, now, same_secret,
Access, Action, Admin, AdminReply, Admission, BUSY_ADMIN, BUSY_DOWNLOADS, Backend, ClientMsg, Closing, Handled, HostInfo, Instant, IpAddr,
LibraryReply, LibraryReq, OpenFile, PluginReply, PluginReq, Server, Store, disk, now, same_secret,
};
/// Whether `req` changes the server's files (a write, a removal or a join code's stretching):
/// such requests count against the address's budget ([`Action::Admin`]); looking doesn't.
fn changes_files(req: &Admin) -> bool {
!matches!(
req,
Admin::Files | Admin::Links { .. } | Admin::Listing | Admin::Reports | Admin::Blocked | Admin::Owned { .. } | Admin::RemovePeer { .. }
)
}
impl Backend for Store {
fn admit(&mut self, file: &str, token: &str) -> Result<Admission, String> {
let entry = self.entry(file)?;
@@ -156,15 +165,19 @@ impl Backend for Store {
if owns != Some(file.as_str()) {
return failed("an owner token manages only its own file");
}
self.admin(req, open)
self.admin(ip, req, open)
}
fn report(&mut self, file: &str, link: Option<&str>, ip: IpAddr, reason: &str) -> Result<(), String> {
self.keep_report(file, link, ip, reason)
}
fn admin(&mut self, req: Admin, open: &dyn Fn(&str) -> Option<OpenFile>) -> Handled {
fn admin(&mut self, ip: IpAddr, req: Admin, open: &dyn Fn(&str) -> Option<OpenFile>) -> Handled {
let failed = |reason: String| Handled::from(AdminReply::Failed { reason });
if changes_files(&req) && !self.abuse.allow(ip, Action::Admin, Instant::now()) {
log::info!("event=refused ip={ip} reason=admin_per_address");
return failed(BUSY_ADMIN.into());
}
match req {
Admin::Publish { name, snapshot } => match self.publish(&name, &snapshot) {
Ok((file, edit, view)) => AdminReply::Published { file, edit, view }.into(),
+22 -8
View File
@@ -44,18 +44,30 @@ impl Store {
found
}
/// These join codes no longer open anything: typing one says so.
fn forget_codes(&mut self, codes: impl IntoIterator<Item = Sealed>) {
self.gone_codes.extend(codes.into_iter().map(|c| c.hash));
/// These join codes of `file` no longer open anything: typing one says so. A code is dropped
/// from the index once none of `file`'s links holds it.
fn forget_codes(&mut self, file: &str, codes: impl IntoIterator<Item = Sealed>) {
for c in codes {
let held = self.files.get(file).is_some_and(|e| e.links.iter().any(|l| l.code.as_ref().is_some_and(|k| k.hash == c.hash)));
if !held && let Some(files) = self.codes.get_mut(&c.hash) {
files.remove(file);
if files.is_empty() {
self.codes.remove(&c.hash);
}
}
self.gone_codes.push_back(c.hash);
}
let extra = self.gone_codes.len().saturating_sub(MAX_GONE_CODES);
self.gone_codes.drain(..extra);
}
/// Where the link with the join code `key` is: its file, its place among the file's links
/// and its token (every code is compared, so timing doesn't tell which one matched).
/// and its token. Only the files the index names for the code's hash are looked at; their
/// links are each compared, in constant time.
fn find_code(&self, key: &codes::Key) -> Option<(String, usize, String)> {
let mut found = None;
for (id, e) in &self.files {
for id in self.codes.get(key.hash())? {
let Some(e) = self.files.get(id) else { continue };
for (i, l) in e.links.iter().enumerate() {
if let Some(token) = l.code.as_ref().and_then(|c| key.open(c)) {
found = Some((id.clone(), i, token));
@@ -78,6 +90,7 @@ impl Store {
}
};
let sealed = key.seal(token)?;
let found_by = sealed.hash.clone();
let path = self.dir(file).join(LINKS);
let entry = self.entry(file)?;
let link = entry.links.get_mut(at).ok_or("that file has no such link")?;
@@ -89,7 +102,8 @@ impl Store {
}
return Err(format!("couldn't keep the join code: {e}"));
}
self.forget_codes(before);
self.codes.entry(found_by).or_default().insert(file.to_string());
self.forget_codes(file, before);
log::info!("event=code file={file} link={id}");
Ok(code)
}
@@ -137,7 +151,7 @@ impl Store {
return Err(format!("couldn't revoke the link: {e}"));
}
log::info!("revoked link {link} of file {file}");
self.forget_codes(gone.code);
self.forget_codes(file, gone.code);
Ok(())
}
@@ -146,7 +160,7 @@ impl Store {
pub fn remove(&mut self, file: &str) -> Result<(), String> {
// Closed first: an open log would keep the folder from being deleted on Windows.
let entry = self.files.remove(file).ok_or("this file isn't on the server (it may have been removed)")?;
self.forget_codes(entry.links.iter().filter_map(|l| l.code.clone()));
self.forget_codes(file, entry.links.iter().filter_map(|l| l.code.clone()));
drop(entry);
let dir = self.dir(file);
fs::remove_dir_all(&dir)
+14
View File
@@ -170,3 +170,17 @@ impl Raw {
}
}
}
/// A one-page file with one rectangle, named `name`, as a snapshot to publish.
pub fn snapshot(name: &str) -> Vec<figcraft_collab::Change> {
let mut d = figcraft_doc::Document::new(name);
let page = d.first_page().unwrap();
d.create(page, figcraft_doc::NodeKind::Rectangle, "Card", 0.0, 0.0, 100.0, 60.0).unwrap();
d.repair();
figcraft_collab::Replica::new(d).snapshot().unwrap()
}
/// An address from text.
pub fn ip(s: &str) -> std::net::IpAddr {
s.parse().unwrap()
}
+3 -3
View File
@@ -305,7 +305,7 @@ impl<B: Backend> Hub<B> {
let reply = self.removed_reply(&file, client);
self.answer(conn, &ServerMsg::Admin(Box::new(reply)));
}
ClientMsg::Admin(req) => self.admin(conn, req),
ClientMsg::Admin(req) => self.admin(conn, ip, req),
ClientMsg::Ping => self.answer(conn, &ServerMsg::Pong),
_ => self.kick(&[conn], "only requests to manage files are spoken on this connection"),
},
@@ -538,10 +538,10 @@ impl<B: Backend> Hub<B> {
}
}
fn admin(&mut self, conn: u64, req: Admin) {
fn admin(&mut self, conn: u64, ip: IpAddr, req: Admin) {
let rooms = &self.rooms;
let open = |file: &str| rooms.get(file).map(Room::info);
let handled = self.backend.admin(req, &open);
let handled = self.backend.admin(ip, req, &open);
self.handled(conn, handled);
}
+3 -2
View File
@@ -76,8 +76,9 @@ pub trait Backend: Send + 'static {
Err("this session is hosted by an app: it has no files to manage".into())
}
/// A request on a managing connection; `open` tells about a file that is open.
fn admin(&mut self, _req: Admin, _open: &dyn Fn(&str) -> Option<OpenFile>) -> Handled {
/// A request on a managing connection from `ip` ([`ip_key`]); `open` tells about a file that
/// is open.
fn admin(&mut self, _ip: IpAddr, _req: Admin, _open: &dyn Fn(&str) -> Option<OpenFile>) -> Handled {
AdminReply::Failed { reason: "nothing to manage here".into() }.into()
}
+6 -5
View File
@@ -1337,13 +1337,14 @@ impl ExportSize {
(value.is_finite() && value > 0.0 && value <= max).then_some(self)
}
/// "2x", "512w", "512h".
/// "2x", "0.125x", "512w", "512h". Not rounded, so `parse` reads it back as the same size.
pub fn label(self) -> String {
let n = |v: f64| crate::text::trim_num(v);
// `{}` prints the shortest text that parses back to the same `f64`, and whole numbers
// without a fraction ("2", not "2.0").
match self {
ExportSize::Scale { value } => format!("{}x", n(value)),
ExportSize::Width { value } => format!("{}w", n(value)),
ExportSize::Height { value } => format!("{}h", n(value)),
ExportSize::Scale { value } => format!("{value}x"),
ExportSize::Width { value } => format!("{value}w"),
ExportSize::Height { value } => format!("{value}h"),
}
}
+18
View File
@@ -232,3 +232,21 @@ fn export_sizes_parse_and_label() {
assert_eq!(e(ExportSize::Scale { value: 2.0 }, "-big", ExportFormat::Png).file_suffix(), "-big");
assert_eq!(e(ExportSize::Width { value: 64.0 }, "", ExportFormat::Png).file_suffix(), "");
}
#[test]
fn export_size_label_parses_back_exactly() {
for want in [
ExportSize::Scale { value: 0.125 },
ExportSize::Scale { value: 0.004 },
ExportSize::Scale { value: 0.001 },
ExportSize::Scale { value: 63.99 },
ExportSize::Scale { value: 1.0 / 3.0 },
ExportSize::Width { value: 512.125 },
ExportSize::Height { value: 0.005 },
] {
assert_eq!(ExportSize::parse(&want.label()), Some(want), "{}", want.label());
}
assert_eq!(ExportSize::Scale { value: 0.125 }.label(), "0.125x");
assert_eq!(ExportSize::Scale { value: 2.0 }.label(), "2x");
assert_eq!(ExportSize::Width { value: 512.0 }.label(), "512w");
}
+45 -26
View File
@@ -26,7 +26,7 @@ pub mod shadow;
pub use dots::Dots;
pub use draw::{node_outline, paint_bounds, stroke_fill, subtree_outline, ts_path};
pub use export_depth::{ExportDepthError, MAX_EXPORT_DEPTH, check_export_depth};
pub use retained::{Retained, Work};
pub use retained::{Begun, Retained, Steps, Work};
pub use tiny_skia::{FillRule, Pixmap};
use figcraft_color::{Color, ColorProfile};
@@ -89,7 +89,7 @@ pub struct Options {
pub dots: Option<Dots>,
}
fn new_pixmap(w: u32, h: u32) -> Option<Pixmap> {
pub(crate) fn new_pixmap(w: u32, h: u32) -> Option<Pixmap> {
let w = w.clamp(1, 16_384);
let h = h.clamp(1, 16_384);
Pixmap::new(w, h)
@@ -112,7 +112,7 @@ pub(crate) fn backdrop_reach(radius: f64, scale: f64) -> f64 {
static RENDERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// The number of the render that just started.
fn start_render() -> u64 {
pub(crate) fn start_render() -> u64 {
RENDERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
}
@@ -146,42 +146,61 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) ->
fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option<Pixmap> {
use rayon::prelude::*;
let band_h = view.height.div_ceil(bands.max(1));
let overlap = backdrop_reach(max_backdrop_blur(doc), view.scale).ceil();
if !overlap.is_finite() || overlap > f64::from(band_h) {
return None;
}
let overlap = overlap as u32;
let s = view.scale.max(1e-9);
let overlap = band_overlap(doc, view, band_h)?;
let parts: Vec<(u32, Option<Pixmap>)> = (0..bands)
.into_par_iter()
.map(|i| {
let y0 = i * band_h;
let h = band_h.min(view.height.saturating_sub(y0)).max(1);
let top = y0.saturating_sub(overlap);
let bottom = (y0 + h + overlap).min(view.height).max(y0 + h);
let v = View { origin: (view.origin.0, view.origin.1 + f64::from(top) / s), scale: view.scale, width: view.width, height: bottom - top };
let part = render_one(doc, page, &v, opts);
let own = tiny_skia::IntRect::from_xywh(0, (y0 - top) as i32, view.width.clamp(1, 16_384), h);
(y0, if overlap == 0 { part } else { part.zip(own).and_then(|(p, r)| p.clone_rect(r)) })
(y0, render_band(doc, page, view, opts, y0, band_h, overlap))
})
.collect();
let mut out = new_pixmap(view.width, view.height)?;
let row = out.width() as usize * 4;
for (y0, part) in parts {
let Some(part) = part else { continue };
// Bands are as wide as the view: their rows go straight into place.
let start = y0 as usize * row;
let dst = out.data_mut();
let n = part.data().len().min(dst.len().saturating_sub(start));
if part.width() == view.width.clamp(1, 16_384)
&& let (Some(d), Some(s)) = (dst.get_mut(start..start + n), part.data().get(..n))
{
d.copy_from_slice(s);
if let Some(part) = part {
put_band(&mut out, y0, &part);
}
}
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.
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.is_finite() && overlap <= f64::from(band_h)).then_some(overlap as u32)
}
/// The rows `y0 .. y0 + band_h` of `view` (fewer at the bottom), rendered with `overlap` rows
/// more each way and cut back to their own.
pub(crate) fn render_band(doc: &Document, page: NodeId, view: &View, opts: &Options, y0: u32, band_h: u32, overlap: u32) -> Option<Pixmap> {
let s = view.scale.max(1e-9);
let h = band_h.min(view.height.saturating_sub(y0)).max(1);
let top = y0.saturating_sub(overlap);
let bottom = (y0 + h + overlap).min(view.height).max(y0 + h);
let v = View { origin: (view.origin.0, view.origin.1 + f64::from(top) / s), scale: view.scale, width: view.width, height: bottom - top };
let part = render_one(doc, page, &v, opts);
if overlap == 0 {
return part;
}
let own = tiny_skia::IntRect::from_xywh(0, (y0 - top) as i32, view.width.clamp(1, 16_384), h);
part.zip(own).and_then(|(p, r)| p.clone_rect(r))
}
/// Copy a band's rows into `out` at row `y0` (bands are as wide as the view: their rows go
/// straight into place).
pub(crate) fn put_band(out: &mut Pixmap, y0: u32, part: &Pixmap) {
let row = out.width() as usize * 4;
let start = y0 as usize * row;
let width = out.width();
let dst = out.data_mut();
let n = part.data().len().min(dst.len().saturating_sub(start));
if part.width() == width
&& let (Some(d), Some(s)) = (dst.get_mut(start..start + n), part.data().get(..n))
{
d.copy_from_slice(s);
}
}
/// Render a page region on the calling thread.
pub fn render_view_single(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option<Pixmap> {
start_render();
+129 -8
View File
@@ -127,6 +127,70 @@ impl Px {
}
}
/// What [`Retained::prepare`] found.
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>> },
}
/// What [`Retained::begin`] did.
pub enum Begun<'a> {
/// The view drawn, its image and what it took.
Done(View, &'a Pixmap, Work),
/// A full render to draw band by band (boxed: it holds the image).
Steps(Box<Steps>),
}
/// A full render drawn a band at a time ([`Retained::begin`]): bands overlap by what background
/// blurs read and keep only their own rows, as the desktop's parallel bands do.
pub struct Steps {
doc: Arc<Document>,
page: NodeId,
view: View,
px: (i64, i64),
fonts: u64,
opts: Options,
sensitive: Option<Arc<Sensitive>>,
pix: Pixmap,
/// The first row not drawn yet.
next: u32,
band_h: u32,
overlap: u32,
}
impl Steps {
/// Draw the next band; `true` once every row is drawn.
pub fn step(&mut self) -> bool {
if self.done() {
return true;
}
let y0 = self.next;
if let Some(part) = crate::render_band(&self.doc, self.page, &self.view, &self.opts, y0, self.band_h, self.overlap) {
crate::put_band(&mut self.pix, y0, &part);
}
self.next = y0.saturating_add(self.band_h);
self.done()
}
/// Whether every row is drawn.
pub fn done(&self) -> bool {
self.next >= self.view.height
}
/// The view drawn (snapped to device pixels).
pub fn view(&self) -> &View {
&self.view
}
/// The page drawn.
pub fn page(&self) -> NodeId {
self.page
}
}
/// Keeps the last rendered view; see the module docs.
#[derive(Default)]
pub struct Retained {
@@ -142,13 +206,73 @@ impl Retained {
/// Render `view` of `page`, reusing the previous render where nothing changed. Returns the
/// view actually drawn (snapped to device pixels, see [`snap`]), the image and what it took.
pub fn render(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options) -> Option<(View, &Pixmap, Work)> {
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);
Some((snapped, &frame.pix, Work::Full))
}
}
}
/// [`Self::render`], except that a full render comes back as [`Steps`] to draw `band_h` rows
/// at a time (the browser, whose renders block the page: input is handled between bands) and
/// keep with [`Self::finish`]. A render that is reused or patched is done at once.
pub fn begin(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options, band_h: u32) -> Option<Begun<'_>> {
match self.prepare(doc, page, view, opts)? {
Prepared::Patched(snapped, work) => Some(Begun::Done(snapped, &self.last.as_ref()?.pix, work)),
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 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);
return Some(Begun::Done(snapped, &frame.pix, Work::Full));
};
let pix = crate::new_pixmap(snapped.width, snapped.height)?;
// One render, as the desktop's parallel bands are: glass keeps the shapes a
// later render asks for again, and the bands of this one are not later renders.
crate::start_render();
Some(Begun::Steps(Box::new(Steps {
doc: doc.clone(),
page,
view: snapped,
px,
fonts,
opts: opts.clone(),
sensitive,
pix,
next: 0,
band_h,
overlap,
})))
}
}
}
/// 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);
(view, &frame.pix)
}
/// The previous render patched where it could be (kept, see [`Self::keep`]), or what a full
/// render of `view` needs.
fn prepare(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options) -> Option<Prepared> {
// A view that can't be put on a pixel grid (non-finite or absurd) draws nothing.
let Some((snapped, px)) = snap(view) else {
self.last = None;
return None;
};
let fonts = figcraft_text::layout_generation();
let mut work = Work::Full;
let mut sens = None;
if let Some(last) = self.last.take()
&& last.page == page
@@ -173,16 +297,13 @@ impl Retained {
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)) = patch(last, doc, page, &snapped, px, opts, &s) {
work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
return Some((snapped, &frame.pix, work));
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
return Some(Prepared::Patched(snapped, work));
}
sens = Some(s);
}
let pix = render_view(doc, page, &snapped, opts)?;
let s = sens.unwrap_or_else(|| Arc::new(sensitive(doc)));
let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
Some((snapped, &frame.pix, work))
Some(Prepared::Full { snapped, px, fonts, sensitive: sens })
}
/// Keep `pix`, the render of `at`: the snapped view, its top-left device pixel and the font
+86
View File
@@ -287,3 +287,89 @@ fn overflowing_text_is_drawn_while_its_box_is_out_of_view() {
let dark = pix.data().as_chunks::<4>().0.iter().filter(|c| c[0] < 128).count();
assert!(dark > 20, "glyphs drawn: {dark}");
}
/// Draw a full render through [`Retained::begin`] `band_h` rows at a time; how many steps it took.
fn stepped(r: &mut Retained, doc: &Arc<Document>, page: NodeId, v: &View, band_h: u32) -> (View, Pixmap, usize) {
match r.begin(doc, page, v, &Options::default(), band_h).unwrap() {
crate::Begun::Done(shown, pix, work) => {
assert_eq!(work, Work::Full, "one piece only when a blur can't be measured");
(shown, pix.clone(), 0)
}
crate::Begun::Steps(mut steps) => {
let mut n = 1;
while !steps.step() {
n += 1;
assert!(n < 1000, "steps end");
}
let (shown, pix) = r.finish(*steps);
(shown, pix.clone(), n)
}
}
}
#[test]
fn a_render_drawn_band_by_band_matches_one_in_one_piece() {
for cut_sensitive in [false, true] {
let s = scene(cut_sensitive);
// The whole scene in view, so the glass's backdrop is never cut by the view.
let v = View { origin: (-10.0, -10.0), scale: 1.0, width: 380, height: 360 };
let mut r = Retained::default();
let (shown, pix, n) = stepped(&mut r, &s.doc, s.page, &v, 40);
assert_eq!(n, shown.height.div_ceil(40) as usize, "a band a step");
let full = render_view(&s.doc, s.page, &shown, &Options::default()).unwrap();
assert_same(&pix, &full, "bands");
// Kept as a full render: the next pan patches it.
assert!(partial(check(&mut r, &s.doc, s.page, &View { origin: (0.0, -10.0), ..v })));
}
}
#[test]
fn bands_thinner_than_a_blur_reaches_grow_to_twice_its_reach() {
let s = scene(true);
let v = View { origin: (-10.0, -10.0), scale: 4.0, width: 380, height: 360 };
let reach = crate::band_overlap(&s.doc, &v, u32::MAX).unwrap();
assert!(reach > 4, "the blur reaches past the bands asked for");
let mut r = Retained::default();
let (shown, pix, n) = stepped(&mut r, &s.doc, s.page, &v, 4);
assert_eq!(n, shown.height.div_ceil(4.max(reach.min(shown.height) * 2)) as usize, "bands twice the reach");
assert_same(&pix, &render_view(&s.doc, s.page, &shown, &Options::default()).unwrap(), "taller bands");
}
#[test]
fn a_reused_or_patched_render_needs_no_steps() {
let s = scene(false);
let v = view(0.0, 0.0, 1.0);
let mut r = Retained::default();
check(&mut r, &s.doc, s.page, &v);
assert!(matches!(r.begin(&s.doc, s.page, &v, &Options::default(), 40), Some(crate::Begun::Done(_, _, Work::Reused))));
let panned = View { origin: (12.0, 0.0), ..v };
assert!(matches!(r.begin(&s.doc, s.page, &panned, &Options::default(), 40), Some(crate::Begun::Done(_, _, Work::Partial { .. }))));
}
/// Background blurs stacked on each other (the upper reads the lower's blurred pixels) across the
/// band boundaries: the bands' overlap, the reach of the largest blur, is enough for the image to
/// match one drawn in one piece, as it is for the desktop's parallel bands.
#[test]
fn stacked_backdrop_blurs_draw_the_same_in_bands() {
fonts();
let mut d = Document::new("stacked");
let page = d.first_page().unwrap();
// Stripes to blur, then three translucent blurred panels overlapping each other.
for i in 0..40 {
let r = d.create(page, NodeKind::Rectangle, "S", 0.0, f64::from(i) * 10.0, 400.0, 5.0).unwrap();
solid(d.get_mut(r).unwrap(), if i % 2 == 0 { "E03030" } else { "3070E0" });
}
for (x, y) in [(40.0, 60.0), (120.0, 120.0), (60.0, 200.0)] {
let b = d.create(page, NodeKind::Rectangle, "B", x, y, 220.0, 160.0).unwrap();
d.get_mut(b).unwrap().fills = vec![Paint::solid(Color::new(1.0, 1.0, 1.0, 0.25))];
d.get_mut(b).unwrap().effects.push(Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(24.0)), visible: true });
}
let doc = Arc::new(d);
let v = View { origin: (0.0, 0.0), scale: 1.0, width: 400, height: 400 };
for band_h in [64, 100, 200] {
let mut r = Retained::default();
let (shown, pix, n) = stepped(&mut r, &doc, page, &v, band_h);
assert!(n >= 3, "{n} bands of {band_h} rows");
assert_same(&pix, &render_view(&doc, page, &shown, &Options::default()).unwrap(), &format!("bands of {band_h} rows"));
}
}
+207 -16
View File
@@ -15,13 +15,16 @@
//! The browser renders on the UI thread, so a zoom's full render blocks the page: there a preview
//! is refined only once no newer request has come for [`SETTLE_MS`] (the zoom has paused), or for
//! as long as the last full render took when that is shorter (a wait never costs more than the
//! render it may save).
//! render it may save), and the full render is then drawn a band at a time
//! ([`figcraft_render::Steps`]), at least a band a frame and more while they fit in [`STEP_MS`],
//! so input is handled while it draws (on a page whose render takes seconds, a band is a
//! fraction of that: eight at most).
use std::sync::Arc;
use figcraft_color::ColorProfile;
use figcraft_doc::{Document, NodeId};
use figcraft_render::{Pixmap, Retained, View, Work};
use figcraft_render::{Begun, Pixmap, Retained, Steps, View, Work};
// A monotonic clock in the browser too: preview decisions rest on how long renders take there.
use web_time::Instant;
@@ -33,6 +36,17 @@ pub const PREVIEW_AFTER_MS: f64 = 12.0;
/// long as the last full render took, when shorter): a full render there blocks the page, and one
/// between every two wheel steps of a zoom held it up for seconds.
pub const SETTLE_MS: u64 = 120;
/// The browser draws a full render a band at a time ([`figcraft_render::Steps`]): at least one
/// band a frame, and more while they fit in this long, so input is handled while it draws. A
/// band of a render that takes seconds takes a fraction of that (see [`MAX_BANDS`]).
pub const STEP_MS: f64 = 24.0;
/// Bands are at least this many rows ...
const MIN_BAND_ROWS: u32 = 64;
/// ... and a view has at most this many: a frame draws at least one band, so the longest frame of
/// a render drawn in steps is about a band's time, a part of the render rather than the whole of it
/// (0.7–1.4 s where the render took 3.7–4.0 s, measured for #1496; more bands would repeat more of
/// the overlap and of the per-band work).
const MAX_BANDS: u32 = 8;
#[derive(Clone)]
pub struct Job {
@@ -100,11 +114,9 @@ fn mark_outside_srgb(image: &mut egui::ColorImage, pix: &Pixmap, profile: ColorP
}
}
/// Render `view` of the job (its own view, or the coarse one standing in for it).
fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option<Done> {
let t0 = Instant::now();
// The canvas is a preview: what's too small to see in detail at this zoom is approximated.
let opts = figcraft_render::Options {
/// The canvas is a preview: what's too small to see in detail at this zoom is approximated.
fn options(job: &Job) -> figcraft_render::Options {
figcraft_render::Options {
outline_mode: job.outline,
outline: job.outline_extras,
outlined: job.outlined.clone(),
@@ -114,14 +126,23 @@ fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option<
magnified_image_pixels: true,
dots: job.dots,
..Default::default()
};
let (view, pix, work) = retained.render(&job.doc, job.page, view, &opts)?;
}
}
/// Render `view` of the job (its own view, or the coarse one standing in for it).
fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option<Done> {
let t0 = Instant::now();
let (view, pix, work) = retained.render(&job.doc, job.page, view, &options(job))?;
Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse))
}
/// The image `pix` of `view`, rendered for `job` in `ms`.
fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) -> Done {
let mut image = screen_image(pix, job.doc.color_profile);
if job.proof {
mark_outside_srgb(&mut image, pix, job.doc.color_profile);
}
let ms = t0.elapsed().as_secs_f64() * 1000.0;
Some(Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 })
Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 }
}
/// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area.
@@ -141,6 +162,56 @@ pub struct Renders {
full_ms: f64,
/// Previews come first only when renders from scratch take at least this long.
preview_after_ms: f64,
/// A full render being drawn band by band (the browser): the job it was started for, the
/// font generation then, the bands and the time they took so far.
steps: Option<Stepping>,
}
/// A full render drawn in steps and what it is of: a newer job of the same file, page, zoom, size
/// and render options keeps it going (its image is then patched to the job, as a pan or an edit
/// is), any other drops it.
struct Stepping {
job: Job,
fonts: u64,
steps: Box<Steps>,
spent: f64,
}
/// Whether `a` and `b` are drawn the same way: the same file, page, zoom, size and options (the
/// view may be elsewhere and the document edited: a render of one is patched to the other).
fn same_settings(a: &Job, b: &Job) -> bool {
a.uid == b.uid
&& a.page == b.page
&& a.view.scale.to_bits() == b.view.scale.to_bits()
&& (a.view.width, a.view.height) == (b.view.width, b.view.height)
&& a.outline == b.outline
&& a.outline_extras == b.outline_extras
&& a.outlined == b.outlined
&& a.skip == b.skip
&& a.solo == b.solo
&& a.proof == b.proof
&& a.dots == b.dots
}
/// Whether a render drawn for `a` (with fonts of generation `fonts`) is `b`'s image as it is:
/// the same settings, document and view, and no fonts arrived meanwhile.
fn same_request(a: &Job, fonts: u64, b: &Job) -> bool {
same_settings(a, b)
&& Arc::ptr_eq(&a.doc, &b.doc)
&& a.view.origin.0.to_bits() == b.view.origin.0.to_bits()
&& a.view.origin.1.to_bits() == b.view.origin.1.to_bits()
&& figcraft_text::layout_generation() == fonts
}
/// What [`Renders::refine_for`] got to.
pub enum Refined {
/// The image (`None`: nothing could be drawn).
Done(Option<Done>),
/// Bands remain: call again (next frame).
More,
/// A full render drawn for what has changed since (an edit, a pan or images that came while
/// it was drawn), shown meanwhile; it is drawn again: call again.
Shown(Done),
}
impl Default for Renders {
@@ -152,7 +223,7 @@ impl Default for Renders {
impl Renders {
/// Previews when renders from scratch take at least `ms` (tests: 0, always).
pub fn with_threshold(ms: f64) -> Self {
Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms }
Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None }
}
/// Whether `job` is a render from scratch: the kept image is of another zoom, page or file, or
@@ -164,7 +235,13 @@ impl Renders {
/// Whether `job` gets a preview first: it renders from scratch and those have been slow on a
/// page already drawn (the first render has no measure).
fn wants_preview(&self, job: &Job) -> bool {
job.zoom_preview && self.last.is_some() && self.full_ms >= self.preview_after_ms && self.starts_over(job)
job.zoom_preview && self.last.is_some() && self.full_ms_so_far() >= self.preview_after_ms && self.starts_over(job)
}
/// How long the last render from scratch took, or what the one being drawn in steps has taken
/// so far when that is more: a render dropped mid-way (a zoom going on) leaves a measure too.
pub fn full_ms_so_far(&self) -> f64 {
self.full_ms.max(self.steps.as_ref().map_or(0.0, |s| s.spent))
}
/// Whether `job` should get a preview should its render run long: from scratch, with none first.
@@ -191,6 +268,107 @@ impl Renders {
}
done
}
/// [`Self::refine`] for about `budget_ms` at a time (the browser): a full render is drawn band by
/// band over several calls, the kept image (re-projected) or the preview showing meanwhile.
pub fn refine_for(&mut self, job: &Job, budget_ms: f64) -> Refined {
let t0 = Instant::now();
if let Some(s) = self.steps.as_ref()
&& !same_settings(&s.job, job)
{
// Dropped for a render of the new view. What its bands took is at least what a full
// render takes: enough for the next zoom to get its preview and its wait.
self.full_ms = self.full_ms.max(s.spent);
self.steps = None;
}
if self.steps.is_none()
&& let Some(r) = self.begin(job, t0, None)
{
return r;
}
let Some(s) = self.steps.as_mut() else { return Refined::Done(None) };
let steps = &mut s.steps;
let stepped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
loop {
if steps.step() {
return true;
}
if t0.elapsed().as_secs_f64() * 1000.0 >= budget_ms {
return false;
}
}
}));
s.spent += t0.elapsed().as_secs_f64() * 1000.0;
match stepped {
Ok(false) => Refined::More,
Ok(true) => {
let Some(Stepping { job: drawn_for, fonts, steps, spent }) = self.steps.take() else { return Refined::Done(None) };
let (view, pix) = self.full.finish(*steps);
self.full_ms = spent;
// The image of the job it was started for: its document's colour profile, its
// proof setting and its request time.
let drawn = done(&drawn_for, view, pix, Work::Full, spent, false);
// Drawn for this very request: shown, done. Otherwise kept, then started on like
// any render: an edit, a pan or images that came meanwhile are patched in, or it
// is drawn again in steps (never all at once here), this one shown till then.
if same_request(&drawn_for, fonts, job) {
return Refined::Done(self.finished(job, Some(drawn)));
}
self.begin(job, t0, Some(drawn)).unwrap_or(Refined::More)
}
Err(_) => {
self.steps = None;
self.full.clear();
Refined::Done(None)
}
}
}
/// Start `job` on the kept image: done when it is reused or patched, `None` when a full render
/// is now drawn in steps. `drawn` is the kept image just drawn in steps: what a reuse shows,
/// else shown while it is drawn again.
fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option<Done>) -> Option<Refined> {
// The snapped view may be a row taller.
let rows = job.view.height.saturating_add(1).div_ceil(MAX_BANDS).max(MIN_BAND_ROWS);
let begun =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match self.full.begin(&job.doc, job.page, &job.view, &options(job), rows) {
Some(Begun::Done(view, pix, work)) => Err(Box::new(match drawn.take() {
Some(d) if work == Work::Reused => Some(d),
_ => Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false)),
})),
Some(Begun::Steps(steps)) => Ok(steps),
None => Err(Box::new(None)),
}));
match begun {
Ok(Ok(steps)) => {
// A pan or an edit at this zoom builds on this render: no preview for it.
self.last = Some((job.uid, job.page, job.view.scale));
self.steps = Some(Stepping { job: job.clone(), fonts: figcraft_text::layout_generation(), steps, spent: 0.0 });
drawn.map(Refined::Shown)
}
Ok(Err(d)) => Some(Refined::Done(self.finished(job, *d))),
Err(_) => {
self.full.clear();
Some(Refined::Done(None))
}
}
}
/// Record a render done at once in [`Self::refine_for`].
fn finished(&mut self, job: &Job, d: Option<Done>) -> Option<Done> {
if let Some(d) = &d {
self.last = Some((job.uid, job.page, job.view.scale));
if d.work == Work::Full {
self.full_ms = d.ms;
}
}
d
}
/// Whether a full render is being drawn band by band.
pub fn stepping(&self) -> bool {
self.steps.is_some()
}
}
/// The coarse preview of the whole of `job`'s view, kept in `retained`.
@@ -401,7 +579,7 @@ impl Inline {
if let Some(d) = self.pending.as_ref().and_then(|job| self.renders.preview(job)) {
self.preview_shown = true;
self.since = Instant::now();
let full = std::time::Duration::try_from_secs_f64(self.renders.full_ms / 1000.0);
let full = std::time::Duration::try_from_secs_f64(self.renders.full_ms_so_far() / 1000.0);
self.wait = full.map_or(self.settle, |full| full.min(self.settle));
self.ctx.request_repaint_after(self.wait);
return Some(answering(d, self.submitted));
@@ -414,8 +592,21 @@ impl Inline {
return None;
}
}
let job = self.pending.take()?;
self.renders.refine(&job).map(|d| answering(d, self.submitted))
let job = self.pending.as_ref()?;
match self.renders.refine_for(job, STEP_MS) {
Refined::Done(d) => {
self.pending = None;
d.map(|d| answering(d, self.submitted))
}
Refined::More => {
self.ctx.request_repaint();
None
}
Refined::Shown(d) => {
self.ctx.request_repaint();
Some(answering(d, self.submitted))
}
}
}
}
+179 -16
View File
@@ -18,7 +18,7 @@ use super::{CanvasState, shows};
use figcraft_render::Retained;
use crate::render_worker::{
Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now,
Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now,
};
/// A page of ellipses with a rectangle on top; the session and the rectangle.
@@ -90,6 +90,45 @@ fn same_pixels(a: &Done, b: &Done) -> bool {
a.image.size == b.image.size && a.image.pixels == b.image.pixels
}
/// The same image up to where render bands meet ([`figcraft_render::Steps`] and the desktop's
/// parallel bands cut the view in different places): on each row, under a quarter of a level on
/// average and at most one pixel in twenty off.
fn close_pixels(a: &Done, b: &Done) -> bool {
let [w, h] = a.image.size;
a.image.size == b.image.size
&& (0..h).all(|y| {
let row = |d: &Done| d.image.pixels[y * w..(y + 1) * w].to_vec();
let (ra, rb) = (row(a), row(b));
let diffs: Vec<u32> =
ra.iter().zip(&rb).map(|(p, q)| p.to_array().iter().zip(q.to_array()).map(|(x, y)| u32::from(x.abs_diff(y))).sum()).collect();
let sum: u32 = diffs.iter().sum();
f64::from(sum) / (w as f64 * 4.0) < 0.25 && diffs.iter().filter(|d| **d > 0).count() * 20 <= w
})
}
/// Poll the browser's worker until it shows the full image (drawn band by band over polls).
fn refined(w: &mut Inline) -> Option<Done> {
for _ in 0..1000 {
match w.poll() {
Some(d) => return Some(d),
None if !w.in_flight() => return None,
None => {}
}
}
None
}
/// Refine `job` through `r` with no time to spare (a band a call); the image and how many calls.
fn stepped(r: &mut Renders, job: &Job) -> (Option<Done>, usize) {
for n in 1..1000 {
match r.refine_for(job, 0.0) {
Refined::Done(d) => return (d, n),
Refined::Shown(_) | Refined::More => {}
}
}
(None, 1000)
}
fn covers(outer: &View, inner: &View) -> bool {
let (o, i) = (outer.page_rect(), inner.page_rect());
let eps = 1e-6;
@@ -397,23 +436,23 @@ fn the_browser_worker_previews_by_measured_render_time_then_refines_the_next_fra
// The production threshold, as the browser has it; refined the next frame (settling: below).
let mut w = Inline::with_settle(egui::Context::default(), std::time::Duration::ZERO);
w.submit(at(2.0));
let first = w.poll().expect("the first image");
let first = refined(&mut w).expect("the first image");
assert!(!first.coarse && !w.in_flight(), "the first render has no measure to preview by");
assert!(first.ms >= PREVIEW_AFTER_MS, "renders are timed in the browser worker too (and this one is slow): {} ms", first.ms);
// A new zoom: the preview this frame, the refined image the next.
// A new zoom: the preview this frame, the refined image over the next (a band each).
w.submit(at(1.0));
let p = w.poll().expect("a preview");
assert!(p.coarse && w.in_flight());
let d = w.poll().expect("the refined image");
let d = refined(&mut w).expect("the refined image");
assert!(!d.coarse && !w.in_flight());
assert!(same_pixels(&d, &render_now(&at(1.0)).unwrap()));
assert!(close_pixels(&d, &render_now(&at(1.0)).unwrap()), "drawn band by band");
// A newer request before the refinement: refining the old one is skipped.
w.submit(at(0.5));
assert!(w.poll().is_some_and(|d| d.coarse));
w.submit(at(0.25));
let p = w.poll().expect("the newer one's preview");
assert!(p.coarse && (p.view.scale - 0.25 / PREVIEW_FACTOR).abs() < 1e-12);
assert!(w.poll().is_some_and(|d| !d.coarse && d.view.scale == 0.25));
assert!(refined(&mut w).is_some_and(|d| !d.coarse && d.view.scale == 0.25));
assert!(w.poll().is_none() && !w.in_flight());
}
@@ -426,7 +465,7 @@ fn the_browser_worker_refines_a_zoom_only_once_it_settles() {
let settle = std::time::Duration::from_millis(SETTLE_MS);
let mut w = Inline::with_settle(egui::Context::default(), settle);
w.submit(at(2.0));
assert!(w.poll().is_some_and(|d| !d.coarse), "the first render: no preview, no wait");
assert!(refined(&mut w).is_some_and(|d| !d.coarse), "the first render: no preview, no wait");
// Zooming: each step shows its preview, never a full render in between.
for scale in [1.5, 1.0] {
w.submit(at(scale));
@@ -434,11 +473,11 @@ fn the_browser_worker_refines_a_zoom_only_once_it_settles() {
assert!(w.poll().is_none() && w.in_flight(), "not refined while the zoom may go on");
}
std::thread::sleep(settle);
let d = w.poll().expect("refined once it settled");
let d = refined(&mut w).expect("refined once it settled");
assert!(!d.coarse && d.view.scale == 1.0 && !w.in_flight());
// A pan at the same zoom has no preview and is refined at once.
w.submit(job(&ds.doc, ds.page, ds.uid, view_at((340.0, 200.0), 1.0, 1200, 1200)));
assert!(w.poll().is_some_and(|d| !d.coarse));
assert!(refined(&mut w).is_some_and(|d| !d.coarse));
}
/// The wait counts from the preview being shown, not from the request: rendering the preview can
@@ -455,13 +494,13 @@ fn the_wait_counts_from_the_preview_not_from_the_request() {
let settle = std::time::Duration::from_millis(SETTLE_MS);
let mut w = Inline::with_settle(egui::Context::default(), settle);
w.submit(at(2.0));
assert!(w.poll().is_some_and(|d| !d.coarse));
assert!(refined(&mut w).is_some_and(|d| !d.coarse));
w.submit(at(1.0));
std::thread::sleep(settle + std::time::Duration::from_millis(30));
assert!(w.poll().is_some_and(|d| d.coarse), "the preview, longer after the request than the wait");
assert!(w.poll().is_none() && w.in_flight(), "the wait starts only now");
std::thread::sleep(settle);
assert!(w.poll().is_some_and(|d| !d.coarse && d.view.scale == 1.0));
assert!(refined(&mut w).is_some_and(|d| !d.coarse && d.view.scale == 1.0));
}
/// Until the zoom's full render has run, the kept image is of the old zoom, so a pan or an edit
@@ -477,7 +516,7 @@ fn same_zoom_requests_before_the_zoom_refines_keep_waiting_and_refine_at_once_af
let settle = std::time::Duration::from_millis(SETTLE_MS);
let mut w = Inline::with_settle(egui::Context::default(), settle);
w.submit(at((300.0, 200.0), 2.0));
assert!(w.poll().is_some_and(|d| !d.coarse), "the first render: no preview, no wait");
assert!(refined(&mut w).is_some_and(|d| !d.coarse), "the first render: no preview, no wait");
// A zoom step, then a pan at the new zoom before the pause: a preview each, no full render.
w.submit(at((300.0, 200.0), 1.0));
assert!(w.poll().is_some_and(|d| d.coarse));
@@ -486,11 +525,11 @@ fn same_zoom_requests_before_the_zoom_refines_keep_waiting_and_refine_at_once_af
assert!(w.poll().is_some_and(|d| d.coarse), "from scratch still: the kept image is of the old zoom");
assert!(w.poll().is_none() && w.in_flight(), "the wait starts over");
std::thread::sleep(settle);
let d = w.poll().expect("refined once it settled");
let d = refined(&mut w).expect("refined once it settled");
assert!(!d.coarse && d.view.scale == 1.0 && !w.in_flight());
// From then on a pan at this zoom builds on the kept image: no preview, refined at once.
w.submit(at((380.0, 200.0), 1.0));
let d = w.poll().expect("the refined image");
let d = refined(&mut w).expect("the refined image");
assert!(!d.coarse && !w.in_flight());
}
@@ -507,12 +546,136 @@ fn the_wait_is_capped_by_the_time_of_the_last_full_render() {
let settle = std::time::Duration::from_secs(10);
let mut w = Inline::with_settle(egui::Context::default(), settle);
w.submit(at(2.0));
let first = w.poll().expect("the first image");
let first = refined(&mut w).expect("the first image");
assert!(!first.coarse && first.ms >= PREVIEW_AFTER_MS, "slow enough to preview: {} ms", first.ms);
w.submit(at(1.0));
assert!(w.poll().is_some_and(|d| d.coarse));
assert!(w.poll().is_none() && w.in_flight(), "not refined in the very next frame");
std::thread::sleep(std::time::Duration::from_secs_f64(first.ms / 1000.0));
let d = w.poll().expect("refined once the last full render's time has passed, not the settle");
let d = refined(&mut w).expect("refined once the last full render's time has passed, not the settle");
assert!(!d.coarse && d.view.scale == 1.0 && !w.in_flight());
}
#[test]
fn the_browser_draws_a_full_render_band_by_band() {
let view = |x| view_at((x, 200.0), 1.0, 600, 600);
let s = slow_scene(&[view(300.0)], 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let at = |x| job(&ds.doc, ds.page, ds.uid, view(x));
let mut r = Renders::default();
let (d, n) = stepped(&mut r, &at(300.0));
let d = d.expect("drawn");
assert!(n > 2 && !r.stepping(), "several calls, then done ({n})");
assert!(close_pixels(&d, &render_now(&at(300.0)).unwrap()));
// Kept: a pan now patches it at once.
assert!(matches!(r.refine_for(&at(320.0), 0.0), Refined::Done(Some(d)) if d.work != Work::Full));
}
#[test]
fn a_pan_while_drawing_finishes_the_render_then_patches_it_and_a_zoom_drops_it() {
let view = |x, scale| view_at((x, 200.0), scale, 600, 600);
let s = slow_scene(&[view(300.0, 1.0)], 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let at = |x, scale| job(&ds.doc, ds.page, ds.uid, view(x, scale));
let mut r = Renders::default();
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More));
// Panned meanwhile: the same render goes on, and what comes is the panned view.
let (d, _) = stepped(&mut r, &at(330.0, 1.0));
let d = d.expect("drawn");
assert!(close_pixels(&d, &render_now(&at(330.0, 1.0)).unwrap()), "the panned view");
// Zoomed meanwhile: the render under way is dropped for one of the new zoom.
let mut r = Renders::default();
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More));
let (d, _) = stepped(&mut r, &at(300.0, 2.0));
assert_eq!(d.expect("drawn").view.scale, 2.0);
}
#[test]
fn an_edit_while_drawing_shows_in_what_comes() {
let v = view_at((300.0, 200.0), 1.0, 600, 600);
let mut s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS);
let (doc, page, uid) = {
let ds = s.ds().unwrap();
(ds.doc.clone(), ds.page, ds.uid)
};
let mut r = Renders::default();
assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0), Refined::More));
// Edited meanwhile, the view unchanged: the render goes on and what comes shows the edit.
s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 400, "height": 400})).unwrap();
let edited = job(&s.ds().unwrap().doc, page, uid, v);
let (d, _) = stepped(&mut r, &edited);
assert!(close_pixels(&d.expect("drawn"), &render_now(&edited).unwrap()), "the edit shows");
}
#[test]
fn a_render_overtaken_by_a_long_pan_is_shown_then_drawn_again() {
let v = view_at((300.0, 200.0), 1.0, 600, 600);
let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let mut r = Renders::default();
assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0), Refined::More));
// Panned more than a view meanwhile: nothing to patch. What was drawn shows, then the new view.
let far = job(&ds.doc, ds.page, ds.uid, view_at((1500.0, 200.0), 1.0, 600, 600));
let mut shown = vec![];
let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0) {
Refined::More => None,
Refined::Shown(d) => {
shown.push(d);
None
}
Refined::Done(d) => Some(d),
});
assert_eq!(shown.len(), 1, "the render drawn shows once");
assert!(close_pixels(&shown[0], &render_now(&job(&ds.doc, ds.page, ds.uid, v)).unwrap()), "the view it was drawn for");
assert!(close_pixels(&last.flatten().expect("drawn"), &render_now(&far).unwrap()), "then the new view");
}
/// Drawn for the very request, the render is done: it is not started on again, even where the
/// kept image can never be patched (outline mode drawing hidden layers), which drew it again
/// and again, the page never idle.
#[test]
fn a_render_drawn_for_the_request_is_done_even_where_it_could_never_be_patched() {
let v = view_at((300.0, 200.0), 1.0, 600, 600);
let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let mut hidden = job(&ds.doc, ds.page, ds.uid, v);
hidden.outline = true;
hidden.outline_extras.hidden = true;
let mut r = Renders::default();
let (d, n) = stepped(&mut r, &hidden);
assert!(d.is_some_and(|d| !d.coarse && d.work == Work::Full) && !r.stepping(), "done after {n} calls");
assert!(n < 100, "drawn once, not over and over ({n} calls)");
}
/// A change of render options (outline mode here) mid-way drops the render, as a zoom does: the
/// bands of the old one are not drawn to the end first.
#[test]
fn a_change_of_options_while_drawing_drops_the_render() {
let v = view_at((300.0, 200.0), 1.0, 600, 600);
let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let plain = job(&ds.doc, ds.page, ds.uid, v.clone());
let mut outlined = plain.clone();
outlined.outline = true;
let (_, alone) = stepped(&mut Renders::default(), &outlined);
let mut r = Renders::default();
assert!(matches!(r.refine_for(&plain, 0.0), Refined::More));
let (d, n) = stepped(&mut r, &outlined);
assert!(d.is_some_and(|d| !d.coarse));
assert!(n <= alone + 1, "the old render's bands are dropped: {n} calls against {alone} alone");
}
/// A render dropped mid-way leaves a measure behind: what its bands took is at least what a full
/// render takes, so the next zoom gets its preview (and, in the browser, its wait) instead of
/// starting from scratch at once, as many times as the zoom goes on.
#[test]
fn a_render_dropped_while_drawing_leaves_its_time_as_the_measure() {
let view = |scale| view_at((300.0, 200.0), scale, 600, 600);
let s = slow_scene(&[view(1.0)], 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let at = |scale| job(&ds.doc, ds.page, ds.uid, view(scale));
// Previews once renders have taken any time at all: a band has, where no measure (0 ms) hasn't.
let mut r = Renders::with_threshold(1e-9);
assert!(matches!(r.refine_for(&at(1.0), 0.0), Refined::More));
assert!(r.preview(&at(2.0)).is_some(), "the zoom gets a preview by the dropped render's measure");
}
@@ -70,6 +70,75 @@ fn ios_button_sets_corner_smoothing_to_60_percent() {
assert_eq!(u.app.session.undo_depth().0, history + 1);
}
/// The visible smoothing icon uses the same scrub gesture, cursor and modifier rates as the
/// other numeric fields; the whole drag is one undo step, including when clamped at either end.
#[test]
fn corner_smoothing_icon_scrubs_with_modifiers_and_one_undo_step() {
for (dx, modifiers, want) in
[(16.0, Modifiers::NONE, 0.66), (8.0, Modifiers::SHIFT, 1.0), (16.0, Modifiers::ALT, 0.516), (-80.0, Modifiers::NONE, 0.0)]
{
let (mut u, r) = scene();
u.app.run("node.set", json!({"ids": [r], "props": {"cornerSmoothing": 0.5}}));
let toggle = named_button(&mut u, "Individual corners");
click(&mut u, toggle);
let lead = u.ctx.read_response(Id::unique("smoothing").with("lead")).expect("smoothing icon").rect;
assert_eq!(lead.width(), 24.0, "the icon has the same drag target as other fields");
let from = lead.center();
let out = u.frame_output(vec![Event::PointerMoved(from)]);
assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal);
let history = u.app.session.undo_depth().0;
u.frame_with(vec![Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }], modifiers);
for step in 1..=4 {
u.frame_with(vec![Event::PointerMoved(pos2(from.x + dx * step as f32 / 4.0, from.y))], modifiers);
}
let smoothing = |u: &Ui| u.app.session.doc().unwrap().node(r).unwrap().corners.smoothing;
assert!((smoothing(&u) - want).abs() < 1e-9, "the drag updates the canvas before release");
u.frame_with(
vec![Event::PointerButton { pos: pos2(from.x + dx, from.y), button: egui::PointerButton::Primary, pressed: false, modifiers }],
modifiers,
);
u.frame(vec![]);
assert!((smoothing(&u) - want).abs() < 1e-9, "release keeps the scrubbed value");
assert_eq!(u.app.session.undo_depth().0, history + 1);
u.app.session.undo().unwrap();
assert_eq!(smoothing(&u), 0.5);
u.app.session.redo().unwrap();
assert!((smoothing(&u) - want).abs() < 1e-9);
}
}
/// Fine drags keep their fractional baseline across gestures, including a later plain drag.
#[test]
fn consecutive_smoothing_drags_preserve_fractional_percentages() {
let (mut u, r) = scene();
u.app.run("node.set", json!({"ids": [r], "props": {"cornerSmoothing": 0.5}}));
let toggle = named_button(&mut u, "Individual corners");
click(&mut u, toggle);
let history = u.app.session.undo_depth().0;
let smoothing = |u: &Ui| u.app.session.doc().unwrap().node(r).unwrap().corners.smoothing;
for (step, (dx, modifiers, want)) in
[(16.0, Modifiers::ALT, 0.516), (16.0, Modifiers::ALT, 0.532), (8.0, Modifiers::NONE, 0.612)].into_iter().enumerate()
{
let from = u.ctx.read_response(Id::unique("smoothing").with("lead")).unwrap().rect.center();
u.frame_with(vec![Event::PointerMoved(from)], modifiers);
u.frame_with(vec![Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }], modifiers);
for k in 1..=4 {
u.frame_with(vec![Event::PointerMoved(pos2(from.x + dx * k as f32 / 4.0, from.y))], modifiers);
}
u.frame_with(
vec![Event::PointerButton { pos: pos2(from.x + dx, from.y), button: egui::PointerButton::Primary, pressed: false, modifiers }],
modifiers,
);
u.frame(vec![]);
assert!((smoothing(&u) - want).abs() < 1e-9, "gesture {step}: expected {want}, got {}", smoothing(&u));
assert_eq!(u.app.session.undo_depth().0, history + step + 1);
}
for want in [0.532, 0.516, 0.5] {
u.app.session.undo().unwrap();
assert!((smoothing(&u) - want).abs() < 1e-9, "undo restores the precise value");
}
}
/// The fields sit at their corners, and typing in the bottom right one sets only that corner in a
/// single undo step (#1002: the bottom row showed bottom right on the left).
#[test]
+2
View File
@@ -89,6 +89,8 @@ icons! {
FlipH,
FlipV,
CornerRadius,
/// A smooth corner with its two tangent endpoints.
CornerSmoothing,
/// Individual corners: the rounded corner each field sets.
CornerTopLeft,
CornerTopRight,
+12
View File
@@ -510,6 +510,18 @@ fn draw(p: &P, icon: Icon) {
p.fill(&[(3.0, 9.0), (13.0, 9.0), (13.0, 14.0)]);
}
CornerRadius | CornerTopLeft => p.corner(2.5, 2.5, 1.0, 1.0, 11.5, 6.0),
CornerSmoothing => {
// An original superellipse corner, with dots marking its tangent endpoints.
let points: Vec<_> = (0..=24)
.map(|i| {
let a = i as f32 / 24.0 * FRAC_PI_2;
(2.5 + 11.0 * (1.0 - a.cos().max(0.0).sqrt()), 2.5 + 11.0 * (1.0 - a.sin().max(0.0).sqrt()))
})
.collect();
p.path(&points, false);
p.dot(2.5, 13.5, 1.0);
p.dot(13.5, 2.5, 1.0);
}
CornerTopRight => p.corner(13.5, 2.5, -1.0, 1.0, 11.5, 6.0),
CornerBottomRight => p.corner(13.5, 13.5, -1.0, -1.0, 11.5, 6.0),
CornerBottomLeft => p.corner(2.5, 13.5, 1.0, -1.0, 11.5, 6.0),
+2 -2
View File
@@ -113,10 +113,10 @@ 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).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::None, sm, "%", col, 1.0);
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}));
+2 -1
View File
@@ -1,6 +1,6 @@
# Collaboration parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (comment.list reports each message's @mentions (#1415); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); a refused batch's fixes take time linear in the batch (#1063); image entries are checked as they apply; branches in live sessions and branch history entries; server message limits follow `max_file_mb`; a damaged log generation field keeps flushed edits; the web build joins from a `#join=` link; removing someone from a live session; live-session revert guard; live sessions per document; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; cursor chat and spotlight in live sessions; branch version history and finer list merges; comments and version history behaviour suite and fixes; hosting the server: `wss://` in the desktop app, server releases, deployment guide; team libraries on the server and swap library; branches: create, update from main, review and merge; wording: the standalone server with share links to edit or view; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); comment.list reports each message's @mentions (#1415); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); a refused batch's fixes take time linear in the batch (#1063); image entries are checked as they apply; branches in live sessions and branch history entries; server message limits follow `max_file_mb`; a damaged log generation field keeps flushed edits; the web build joins from a `#join=` link; removing someone from a live session; live-session revert guard; live sessions per document; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; cursor chat and spotlight in live sessions; branch version history and finer list merges; comments and version history behaviour suite and fixes; hosting the server: `wss://` in the desktop app, server releases, deployment guide; team libraries on the server and swap library; branches: create, update from main, review and merge; wording: the standalone server with share links to edit or view; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7)
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
@@ -28,6 +28,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | minor | M9, #1075: `figcraft-server` gives requests that change its files (join codes, links, renames, removals, blocks, publishing with the key) a budget of 60 a minute per address and block (`Action::Admin`), on every server, with the server key and with an owner token alike; listing and looking aren't counted. Before, a managing connection with the key had no limit at all and an owner token only the message rate, so one address could ask for hundreds of 10,000-round code stretches and `links.json` writes a second (100 renames in a row: 100 served before, 60 now, then "too many changes to this server's files from your address…"; another address is unaffected). A typed or new join code is found through an index of code hashes to the files holding them, instead of opening every link's code on the server; results are the same, a copied file folder holding the same code included. The protocol is unchanged. Tests: `admin_budget_tests`. Numbers unchanged |
| 2026-10-29 | minor | M9, #1415: `comment.list` (CLI, MCP `run_command`, the `figcraft://comments` resource) gives every message, the first and each reply, its `mentions`: `{name, known, you}` for each name it @mentions, by the rule the thread view highlights them with (`figcraft_doc::mentions`, which the highlighting now shares). A name resolves against the file's people and you, as the file spells it. An unknown name is reported with `known: false`. `a@b.com` mentions nobody. Filtering threads by a mentioned name and listing mentioned names in `comment.people` stay open. Numbers unchanged |
| 2026-10-29 | minor | Bounded replay log (#1069, from a security audit): the batches a session keeps for apps that reconnect were bounded only by count (10,000 batches, 1,000,000 changes) on a desktop host and a private `figcraft-server`, so a long busy session could hold any number of bytes. `Limits::max_log_bytes` now defaults to 64 MiB, and `figcraft-server` takes it from a new `max_log_mb` setting (default 64; open to the public, also at most a quarter of `max_file_mb`, as before). An app further behind than the trimmed log catches up with the whole file, as it already did past the count limits. Nine 8 MiB renames with default limits kept all 75.5 MB before; now 58.7 MB, and a client that missed them gets a snapshot. The protocol is unchanged. |
| 2026-10-29 | minor | Sibling placement in live sessions (#1065, from a security audit): every replica (the server's and each app's) placed a created, moved or reordered layer by counting each sibling that sorts before it, so a batch of many layers under one parent took quadratic time, on the server's single hub thread too. It now binary-searches the siblings' `(key, id)` order on each side of the layer's old place. The order is unchanged, ties and fractional positions included: a test replays 5,000 creations and 2,500 moves against the counting rule. 20,000 creations and 10,000 moves under two parents took 20 s in a debug build; they now take 0.3 s. |
+9 -1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -1,6 +1,6 @@
# FigCraft roadmap: milestones and what's next
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (Thai, Lao, Khmer and Burmese lines break between words (#1219); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and
[`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours
@@ -76,6 +76,7 @@ blockers.
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | minor | M4, #1219: Thai, Lao, Khmer and Burmese text, written without spaces between words, wraps between words instead of where a line overflows (`พัฒนาซอ|ฟต์แวร์` → `พัฒนา|ซอฟต์แวร์`). `figcraft_text::breaks::word_breaks` finds the word starts inside each run of these scripts with ICU4X's line segmenter (`icu_segmenter` 2.3): its dictionaries on desktop, its LSTM models in the browser (about 0.39 MB of wasm instead of 1.86 MB, which the 24 MiB gate can't take; they split a few compounds the dictionaries keep whole). Where a run meets spaces, Latin or CJK the UAX #14 rules decide as before, and a word wider than its box still takes #1400's emergency break. Text without these scripts does no extra work. Grade unchanged. Evidence: `breaks::tests::thai_lines_break_between_words`, `lao_khmer_and_burmese_lines_break_between_words`, `word_breaks_survive_junk`, `behaviour_tests::thai_lines_break_between_words` (fails on main). |
| 2026-10-29 | minor | M9, #1075: `figcraft-server` gives requests that change its files a budget of 60 a minute per address, with the server key and owner tokens alike, and finds join codes through an index of their hashes. Tests: `admin_budget_tests` |
| 2026-10-29 | minor | M8, #1080: SVG import draws a pattern's tile once per pattern and scale and reuses it for every other layer it fills, and the layers inside a tile count in the import's 100,000-layer budget instead of each tile starting a fresh one. Tests: `tile_tests` (svg) |
| 2026-10-29 | patch | M4, #1478: a letter and its combining marks are shaped with one font that has them all. Text typed decomposed (NFD, `E` + U+0302 + U+0309 for Ể) in a font with the letters but not the marks drew missing-glyph boxes beside and above the letter, while the precomposed form fell back to a font that has it; each grapheme cluster now takes the first face (the style's own, then the fallbacks) that covers every char in it (joiners and variation selectors need no glyph), else the letter's own face as before. Fonts that cover Vietnamese were already right: mark positioning (GPOS `mark`/`mkmk`) stacks the marks over the letter on the canvas, in PNG, SVG and PDF. Tests in `crates/text/src/vietnamese_tests.rs`. Numbers unchanged |
| 2026-10-29 | minor | M9, #1415: `comment.list` (CLI, MCP `run_command`, the `figcraft://comments` resource) gives every message, the first and each reply, its `mentions`: `{name, known, you}` for each name it @mentions, by the rule the thread view highlights them with (`figcraft_doc::mentions`, which the highlighting now shares). A name resolves against the file's people and you, as the file spells it. An unknown name is reported with `known: false`. `a@b.com` mentions nobody. Filtering threads by a mentioned name and listing mentioned names in `comment.people` stay open. Numbers unchanged |
+1 -1
View File
@@ -498,7 +498,7 @@ are larger.
| Bytes being read | Messages not yet whole: the largest message and 1 MiB per block, 192 MiB for everyone; past everyone's budget the readers holding the most are cut off until it fits (their bytes count as free at once), and a reader is refused only when it is the biggest |
| Bytes waiting for the server | 128 MiB of read messages not handled yet: past it a connection is dropped as busy |
| Connections | `max_connections` (512) in all (*always*); `max_connections_per_ip` (32) per address, ×2 per IPv6 /56 (at most a sixteenth of all), ×4 per /48 (at most an eighth of all), joins included, so no block can take every connection; one-shot requests (asking about hosting, libraries, browsing plugins) can't take the last eighth, which stays for people joining files, and are dropped after 20 idle seconds |
| Rates | Per address and block: `connects_per_minute`, `publishes_per_hour` (and 32 addresses' worth for everyone), `messages_per_second` (cursors, selections, cursor chat and pings have their own budget beside it, twice that, so an office moving its cursors together doesn't trip it); reports, ten an hour (*always*); downloads of libraries and plugins, 1 MiB a second with bursts of 16 MiB per address (*always*), checked before anything is read, within 32 MiB a second (512 MiB at once) for libraries and for plugins, everyone together |
| Rates | Per address and block: `connects_per_minute`, `publishes_per_hour` (and 32 addresses' worth for everyone), `messages_per_second` (cursors, selections, cursor chat and pings have their own budget beside it, twice that, so an office moving its cursors together doesn't trip it); reports, ten an hour (*always*); requests that change files (join codes, links, renames, removals, blocks, publishing with the key), sixty a minute, with the server key or an owner token too ("too many changes to this server's files from your address…"; listing and looking aren't counted) (*always*); downloads of libraries and plugins, 1 MiB a second with bursts of 16 MiB per address (*always*), checked before anything is read, within 32 MiB a second (512 MiB at once) for libraries and for plugins, everyone together |
| Team libraries | Only files published with the key hold one on a public server; an archive is at most `max_file_mb` and everything it unpacks to counts against the same cap (*always*), so a zip bomb is refused before it expands |
| Usage reports | Kept in memory, written at most once a minute per library and when the server stops; at most 1,000 components per file and 200 files per library (*always*) |
| Disk writes | A batch is confirmed only once it is on disk; when its log can't be written, nobody hears it was accepted: the file closes, everyone in it reconnects and their apps send again what wasn't confirmed. Below 1 GiB (or two of the largest files) free, changes and new files are refused with "the server's disk is nearly full" instead (*always*, where the free space can be told: Unix). The server keeps the last 200 problems for the operator |
+3 -2
View File
File diff suppressed because one or more lines are too long