Merge main into release

This commit is contained in:
Dylan M. Taylor
2026-11-09 00:26:08 -05:00
397 changed files with 20233 additions and 1725 deletions
+8
View File
@@ -19,7 +19,14 @@ concurrency:
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
needs: credits
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
@@ -33,6 +40,7 @@ jobs:
# crates/text/build.rs keeps the web allowlist small (Inter and Georgian).
web-craft-fonts: true
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
Generated
+14 -3
View File
@@ -1134,7 +1134,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -1157,10 +1157,21 @@ dependencies = [
"zip 9.1.1",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"js-sys",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"wasm-bindgen",
"web-sys",
@@ -2130,6 +2141,7 @@ name = "figcraft-web"
version = "0.16.0"
dependencies = [
"base64 0.22.1",
"craft-web-api",
"craft-web-host",
"eframe",
"egui",
@@ -7008,7 +7020,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
+1 -1
View File
@@ -43,7 +43,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
# pull a second egui family version).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto
# indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
+23 -7
View File
File diff suppressed because one or more lines are too long
+40 -7
View File
@@ -10,6 +10,12 @@ use serde_json::{Value, json};
use crate::{CliError, CliResult};
/// A document's or plugin's text as a terminal should show it: control characters escaped, and
/// everything else (quotes, backslashes in paths) left as it is.
fn plain(text: &str) -> String {
text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect()
}
pub fn load(path: &str) -> CliResult<Document> {
let (doc, notes) = load_noted(path)?;
if ext(path) == "penpot" {
@@ -199,26 +205,33 @@ pub fn info(path: &str, as_json: bool) -> CliResult<ExitCode> {
return Ok(ExitCode::SUCCESS);
}
for n in &notes {
eprintln!("note: {n}");
eprintln!("note: {}", plain(&n.to_string()));
}
println!(
"{} — {} ({} nodes, {} styles, {} variables, {} images)",
path,
doc.name,
plain(path),
plain(&doc.name),
doc.node_count(),
doc.styles.len(),
doc.variables.variables.len(),
doc.images.len()
);
for p in &pages {
println!("page {} \"{}\": {} nodes, {} top-level", p["id"], p["name"].as_str().unwrap_or(""), p["nodes"], p["topLevel"]);
println!("page {} \"{}\": {} nodes, {} top-level", p["id"], plain(p["name"].as_str().unwrap_or("")), p["nodes"], p["topLevel"]);
for f in p["frames"].as_array().into_iter().flatten() {
println!(" {} {} \"{}\" {}×{}", f["id"], f["type"].as_str().unwrap_or(""), f["name"].as_str().unwrap_or(""), f["width"], f["height"]);
println!(
" {} {} \"{}\" {}×{}",
f["id"],
f["type"].as_str().unwrap_or(""),
plain(f["name"].as_str().unwrap_or("")),
f["width"],
f["height"]
);
}
}
for m in &missing {
let layers = if m.layers == 1 { "text layer" } else { "text layers" };
println!("missing font \"{}\": {} {layers} (drawn in a fallback font)", m.family, m.layers);
println!("missing font \"{}\": {} {layers} (drawn in a fallback font)", plain(&m.family), m.layers);
}
Ok(ExitCode::SUCCESS)
}
@@ -438,7 +451,8 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliRe
let cmd = steps.get(failed_at).map_or("", |step| step.command.as_str());
let i = failed_at;
println!("{}", json!({"step": i, "command": cmd, "ok": false, "error": e.to_string(), "rolledBack": true}));
eprintln!("error: step {i} ({cmd}) failed: {e}");
// Plugin-supplied text: escape terminal controls and line breaks.
eprintln!("error: step {i} ({}) failed: {}", plain(cmd), plain(&e.to_string()));
eprintln!("the script's document changes were rolled back");
return Ok(ExitCode::from(1));
}
@@ -491,6 +505,25 @@ pub fn connect_publish(file: &str, mappings: &str, dry_run: bool) -> CliResult<E
mod tests {
use super::*;
/// `info` and a script's failure print what a file and its steps name, controls escaped.
#[test]
fn info_and_a_failed_script_print_what_they_were_given() {
let dir = std::env::temp_dir().join(format!("figcraft-cli-plain-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (svg, script) = (dir.join("a.svg"), dir.join("s.json"));
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>"#).unwrap();
std::fs::write(&script, r#"[{"command":"no.such\u001b"}]"#).unwrap();
assert_eq!(info(svg.to_str().unwrap(), false).unwrap(), ExitCode::SUCCESS);
assert_eq!(run_script(script.to_str().unwrap(), None, None).unwrap(), ExitCode::from(1));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn plain_escapes_controls_and_leaves_quotes_and_paths() {
assert_eq!(plain("a\u{1b}[31m\nb"), r"a\u{1b}[31m\nb");
assert_eq!(plain(r"Bob's C:\files"), r"Bob's C:\files");
}
#[test]
fn script_formats() {
assert_eq!(parse_script(r#"[{"command":"a"},{"command":"b","params":{"x":1}}]"#).unwrap().len(), 2);
+1 -1
View File
@@ -118,7 +118,7 @@ fn a_file_shared_online_is_joined_by_its_codes() {
});
for guest in [&b, &c] {
assert!(guest.message.as_deref().unwrap_or_default().contains("Sharing was stopped"), "{:?}", guest.message);
assert_eq!(guest.live().status, Status::Off, "over, not failed: nothing retries");
assert!(guest.live().rejoinable() && !guest.live().status.active(), "over: nothing retries, and the tab says so");
}
assert_eq!(layers(&b), before + 2, "Bo keeps the copy");
let folder = dir.path().join("files").join(&p.file);
+1 -1
View File
@@ -160,7 +160,7 @@ fn revoked_links_stop_working_at_once() {
assert_eq!((files.len(), files[0].people), (1, 3));
// Revoked: Cy is out at once, the others stay.
assert_eq!(ask(Admin::Revoke { file: file.clone(), link: review.link.id.clone() }), AdminReply::Done);
pump(&mut [&mut a, &mut b, &mut c], "Cy out", |s| s[2].live().status == Status::Off && s[0].live().peers.len() == 1);
pump(&mut [&mut a, &mut b, &mut c], "Cy out", |s| s[2].live().rejoinable() && s[0].live().peers.len() == 1);
// Told as when a host stops: the session is over for Cy, whose copy stays open (no retries).
assert!(c.message.as_deref().unwrap_or_default().contains("Sharing was stopped"), "{:?}", c.message);
assert!(live(&b));
+3 -1
View File
@@ -68,7 +68,9 @@ impl Backend for Store {
Err(err) => log::error!("file {file}: a change couldn't be logged: {err}"),
}
}
log.entries += journal.len();
// A refusal changes nothing in the document: it counts toward the log's size (bytes), but
// not toward the entries that make a snapshot rewrite worthwhile.
log.entries += journal.iter().filter(|j| !matches!(j, figcraft_collab::Journal::Refused { .. })).count();
log.dirty = true;
e.meta.updated = now();
if log.entries >= after || log.bytes + log.pending.len() as u64 >= max_bytes {
+18
View File
@@ -155,6 +155,24 @@ fn read_only_sessions_keep_client_ids_without_rewriting_the_snapshot() {
}
}
#[test]
fn a_viewers_refused_batches_do_not_rewrite_the_snapshot() {
let dir = TempDir::new("refusals");
let c = StoreConfig { compact_after: 3, ..cfg(dir.path()) };
let mut store = Store::open(dir.path(), c).unwrap();
let (id, _, _) = publish(&mut store, "Busy");
let mut server = store.open(&id).unwrap();
let mut v = join(&mut server, Access::View);
store.changed(&id, &mut server);
let generation = || disk::check_snapshot(&fs::read(dir.path().join(FILES).join(&id).join(SNAPSHOT)).unwrap()).unwrap();
assert_eq!(generation(), 1);
for i in 0..10 {
rename(&mut server, &mut v, &format!("P{i}"));
store.changed(&id, &mut server);
}
assert_eq!(generation(), 1, "refusals are logged, not compacted");
}
#[test]
fn a_long_log_is_compacted_while_open() {
let dir = TempDir::new("compact");
+3 -1
View File
@@ -20,7 +20,9 @@ figcraft-ui-egui = { workspace = true }
figcraft-collab-net = { workspace = true }
figcraft-text = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.figcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
base64 = { workspace = true }
egui = { workspace = true }
log = { workspace = true }
+103 -63
View File
@@ -1,36 +1,54 @@
//! `window.figcraft`: the control channel for the page, as promises.
//! `window.figcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) plus FigCraft's
//! own file functions.
//!
//! The same JSON methods as the desktop control server (`docs/control-protocol.md`), so an agent
//! driving FigCraft in a browser tab (or an `<iframe>` in another app) uses the same commands as
//! the CLI and the MCP server:
//! The crate installs `request`, `execute`, `commands`, `docInspect`, `uiInspect` and `screenshot`
//! over the same JSON methods as the desktop control server (`docs/control-protocol.md`), as
//! promises with a timeout, so an agent driving FigCraft in a browser tab (or an `<iframe>` in
//! another app) uses the same commands as the CLI and the MCP server:
//!
//! ```js
//! await figcraft.execute("node.create", {kind: "frame", name: "Home"}) // engine command → its result
//! await figcraft.execute("node.create", {type: "frame", name: "Home"}) // engine command → its result
//! await figcraft.request("document.inspect") // control method → its result
//! await figcraft.commands() // command list
//! const {data} = await figcraft.screenshot() // the canvas as PNG (base64)
//! ```
//!
//! FigCraft adds, on the same object:
//!
//! ```js
//! await figcraft.openFile("home.fig", bytes) // `file.open` with the bytes
//! figcraft.captureDownloads(true) // saves stay in the page…
//! figcraft.files(); await figcraft.readFile("home.figcraft") // …to be read back
//! await figcraft.inspect() // `document.inspect`
//! ```
//!
//! Results resolve with the method's `result`; errors reject with an `Error`.
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError};
use base64::Engine as _;
use figcraft_ui_egui::{ControlReply, ControlRequest};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate};
use serde_json::{Value, json};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, future_to_promise};
use crate::saved_files::SavedFiles;
type Waiting = (Receiver<ControlReply>, js_sys::Function, js_sys::Function);
/// The app id in `window.<app>`.
const APP: &str = "figcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
thread_local! {
static QUEUE: RefCell<Vec<ControlRequest>> = const { RefCell::new(Vec::new()) };
static WAITING: RefCell<Vec<Waiting>> = const { RefCell::new(Vec::new()) };
static NEXT_ID: Cell<u64> = const { Cell::new(0) };
static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
static CAPTURE: Cell<bool> = const { Cell::new(false) };
@@ -59,88 +77,112 @@ fn to_js(v: &Value) -> JsValue {
js_sys::JSON::parse(&v.to_string()).unwrap_or(JsValue::NULL)
}
fn from_js(v: &JsValue) -> Value {
if v.is_undefined() || v.is_null() {
return json!({});
}
js_sys::JSON::stringify(v).ok().and_then(|s| s.as_string()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))
/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's
/// timeout fired) cancels the request if the app has not started it: the page was told it failed,
/// so the app must not run it late.
struct Waiting {
reply: Receiver<ControlReply>,
gate: RequestGate,
answered: bool,
}
/// Settle the promises of answered requests (called every frame).
pub fn poll_replies() {
WAITING.with(|w| {
w.borrow_mut().retain(|(rx, resolve, reject)| match rx.try_recv() {
Ok(ControlReply { result: Ok(v), .. }) => {
let _ = resolve.call1(&JsValue::NULL, &to_js(&v));
false
impl Waiting {
/// The reply as the protocol's object once the app has answered or gone away; `None` while the
/// request is still waiting.
fn poll(&mut self) -> Option<Value> {
match self.reply.try_recv() {
Ok(ControlReply { result, .. }) => {
self.answered = true;
Some(match result {
Ok(value) => json!({"ok": true, "result": value}),
Err(error) => json!({"ok": false, "error": error}),
})
}
Ok(ControlReply { result: Err(e), .. }) => {
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new(&e));
false
}
Err(TryRecvError::Empty) => true,
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new("request dropped"));
false
self.answered = true;
Some(json!({"ok": false, "error": "request dropped"}))
}
});
});
}
}
}
fn request(method: &str, params: Value) -> js_sys::Promise {
let method = method.to_string();
let p = js_sys::Promise::new(&mut |resolve, reject| {
let (reply, rx) = std::sync::mpsc::channel();
let id = NEXT_ID.with(|n| {
n.set(n.get() + 1);
n.get()
});
let req = ControlRequest { id: json!(id), method: method.clone(), params: params.clone(), reply, state: Default::default() };
QUEUE.with(|q| q.borrow_mut().push(req));
WAITING.with(|w| w.borrow_mut().push((rx, resolve, reject)));
impl Drop for Waiting {
fn drop(&mut self) {
if !self.answered {
self.gate.cancel_if_open();
}
}
}
/// Queue a control request for the next frame and wait for the app's reply, as the protocol's
/// `{ok, result}` / `{ok: false, error}` object.
fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
let (reply, rx) = std::sync::mpsc::channel();
let id = NEXT_ID.with(|n| {
n.set(n.get() + 1);
n.get()
});
let gate = RequestGate::new();
QUEUE.with(|q| q.borrow_mut().push(ControlRequest { id: json!(id), method: method.to_string(), params, reply, state: gate.clone() }));
CTX.with(|c| {
if let Some(ctx) = c.borrow().as_ref() {
ctx.request_repaint();
}
});
p
let mut waiting = Waiting { reply: rx, gate, answered: false };
Box::pin(async move {
loop {
if let Some(reply) = waiting.poll() {
return reply;
}
sleep(POLL_MS).await;
}
})
}
async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
}
});
let _ = JsFuture::from(promise).await;
}
/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`.
fn outcome(reply: &Value) -> Result<JsValue, JsValue> {
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(to_js(reply.get("result").unwrap_or(&Value::Null)))
} else {
Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into())
}
}
fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> {
js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ())
}
/// Install `window.figcraft`.
/// Install `window.figcraft`: the crate's functions, then FigCraft's own.
pub fn install() -> Result<(), JsValue> {
let obj = js_sys::Object::new();
let request: Request = Rc::new(|method, params| send(&method, params));
Rc::new(PageApi::new(APP, Methods::default(), request)).install()?;
let window = web_sys::window().ok_or("no window")?;
let obj: js_sys::Object = js_sys::Reflect::get(&window, &APP.into())?.unchecked_into();
set_fn(
&obj,
"request",
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|method: String, params: JsValue| request(&method, from_js(&params)))
"inspect",
Closure::<dyn Fn() -> js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("document.inspect", json!({})).await) }))
.into_js_value(),
)?;
set_fn(
&obj,
"execute",
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|command: String, params: JsValue| {
request("engine.execute", json!({"command": command, "params": from_js(&params)}))
})
.into_js_value(),
)?;
set_fn(&obj, "commands", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("engine.commands", json!({}))).into_js_value())?;
set_fn(&obj, "inspect", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("document.inspect", json!({}))).into_js_value())?;
set_fn(
&obj,
"screenshot",
Closure::<dyn Fn(JsValue) -> js_sys::Promise>::new(|params: JsValue| request("ui.screenshot", from_js(&params))).into_js_value(),
)?;
set_fn(
&obj,
"openFile",
Closure::<dyn Fn(String, js_sys::Uint8Array) -> js_sys::Promise>::new(|name: String, bytes: js_sys::Uint8Array| {
let data = base64::engine::general_purpose::STANDARD.encode(bytes.to_vec());
request("engine.execute", json!({"command": "file.open", "params": {"name": name, "data": data}}))
future_to_promise(async move {
outcome(&send("engine.execute", json!({"command": "file.open", "params": {"name": name, "data": data}})).await)
})
})
.into_js_value(),
)?;
@@ -166,7 +208,5 @@ pub fn install() -> Result<(), JsValue> {
})
.into_js_value(),
)?;
let w = web_sys::window().ok_or("no window")?;
js_sys::Reflect::set(&w, &"figcraft".into(), &obj)?;
Ok(())
}
-1
View File
@@ -225,7 +225,6 @@ impl eframe::App for WebShell {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.fig.control_queue.extend(crate::api::take_requests());
self.fig.ui(ui);
crate::api::poll_replies();
// The fonts on this computer that text asked for this frame are read; once one is in,
// auto-sizing text measured in a fallback fits it.
crate::local_fonts::load_wanted(ui.ctx());
+6 -1
View File
@@ -126,7 +126,12 @@ impl eframe::App for App {
fn on_exit(&mut self) {
// With the app out of reach (busy), its recovery copies stay for the next start.
let copies = recovery::lock(&self.recovery).take();
with_app(|fig| services::shutdown(fig, services::config_dir().as_deref(), copies));
with_app(|fig| {
services::shutdown(fig, services::config_dir().as_deref(), copies);
// An update that waits for the app to close installs now: the app lives in a
// thread-local, and the process can end without dropping it.
fig.start_pending_update();
});
// Everything is kept: end before the windows' teardown, where AppKit's Touch Bar support
// throws on the content view AccessKit restores (craft-libs#3, #781).
#[cfg(target_os = "macos")]
+17 -11
View File
@@ -217,7 +217,8 @@ impl Recovery {
return false;
}
let _ = match online {
Some(text) => std::fs::write(&note, text),
// The note holds the secret the client resumes with: owner-only, as the copy.
Some(text) => write_private(&note, text.as_bytes()),
None => std::fs::remove_file(&note),
};
true
@@ -326,24 +327,29 @@ fn rejoin_online(file: &Path, s: &mut Session) -> Option<u64> {
fn write_atomic(path: &Path, doc: &figcraft_engine::doc::Document, versions: &[Version], branches: &[Branch]) -> bool {
let Ok(bytes) = figcraft_format::save_bytes_with_history(doc, None, versions, branches) else { return false };
let tmp = path.with_extension("tmp");
if write_private(&tmp, &bytes).is_err() {
let _ = std::fs::remove_file(&tmp);
return false;
}
std::fs::rename(&tmp, path).is_ok()
}
/// Write `bytes` to `path`, created (or cut back) readable by its owner only on Unix.
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true).mode(0o600);
let Ok(mut f) = opts.open(&tmp) else { return false };
if std::io::Write::write_all(&mut f, &bytes).is_err() {
let _ = std::fs::remove_file(&tmp);
return false;
}
let mut f = opts.open(path)?;
// `mode` applies to a new file only: one that was there keeps its mode unless set.
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
std::io::Write::write_all(&mut f, bytes)
}
#[cfg(not(unix))]
{
if std::fs::write(&tmp, bytes).is_err() {
return false;
}
std::fs::write(path, bytes)
}
std::fs::rename(&tmp, path).is_ok()
}
/// [`recover_all`], for a start that keeps nothing waiting: how many documents came back as
@@ -77,6 +77,7 @@ fn root(name: &str) -> PathBuf {
r
}
/// What the scripted link says about the session it is in.
fn info() -> SessionInfo {
SessionInfo {
role: Role::Guest,
@@ -90,6 +91,7 @@ fn info() -> SessionInfo {
address: SERVER.into(),
network: true,
access: Access::Edit,
view: None,
}
}
+11
View File
@@ -104,3 +104,14 @@ real_name = "Oleksii Sukholita"
[people.helenkwok]
real_name = "Helen Kwok"
[people.denisg0mes]
real_name = "Denis Gomes"
display_name = "Denis Gomes"
[people.Hamza0101]
real_name = "Hamza Naveed"
display_name = "Hamza0101"
[people.ashokram-si]
real_name = "Ashok Ram"
+126 -7
View File
@@ -1,9 +1,9 @@
//! Join codes over the network: a file shared on the local network joined by its code (two
//! engine sessions over loopback), what the browser's driver does with an online code, a server
//! Join codes over the network: a file shared on the local network joined by its code, and by
//! its view-only code to look without editing (engine sessions over loopback), what the browser's driver does with an online code, a server
//! older than join codes, and the links that name a code. (A `figcraft-server` handing codes out
//! and resolving them is tested in its own crate, with the same link.)
use std::net::{Ipv4Addr, TcpListener};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -18,8 +18,9 @@ use crate::driver::{Driver, Socket};
use crate::guest::GuestConfig;
use crate::inbox::Inbox;
use crate::invite::{Endpoint, Invite, Lookup};
use crate::link::reachable;
use crate::loopback_tests::{fast_limits, quick};
use crate::{NetLink, manage};
use crate::{NetLink, lan_ip, manage};
fn session(name: &str) -> Session {
let mut s = Session::new();
@@ -53,6 +54,7 @@ fn layers(s: &Session) -> usize {
s.doc().map_or(0, |d| d.node_count())
}
/// A local network share's code joins its session from another app, and edits sync both ways.
#[test]
fn a_local_share_is_joined_by_its_code_and_edits_sync() {
let (mut host, mut guest) = (session("Hana"), session("Ada"));
@@ -65,7 +67,13 @@ fn a_local_share_is_joined_by_its_code_and_edits_sync() {
assert_eq!(local.ip, Ipv4Addr::LOCALHOST);
assert_eq!(shared["address"], format!("127.0.0.1:{}", local.port));
assert_eq!(shared["link"], local.link(), "the code and the invite link name the same session");
assert!(shared["share"]["viewCode"].is_null(), "everyone edits on the local network");
// A view-only code too, with its own secret, and no comment code.
let view = shared["share"]["viewCode"].as_str().unwrap();
let Code::Local(viewing) = code::parse(view).unwrap() else { panic!("not a local code") };
assert_eq!((viewing.ip, viewing.port), (local.ip, local.port), "the same session");
assert_ne!(viewing.secret, local.secret, "a secret of its own");
assert_eq!(shared["share"]["viewLink"], viewing.link());
assert!(shared["share"]["commentCode"].is_null());
// Typed the way people type: lower case, spaces for the dashes.
let typed = shown.to_lowercase().replace('-', " ");
assert_eq!(guest.execute("collab.join", &json!({"code": typed})).unwrap()["status"], "connecting");
@@ -93,6 +101,8 @@ fn a_local_share_is_joined_by_its_code_and_edits_sync() {
assert!(label.contains("Couldn't join") || label.contains("The host refused"), "{label}");
}
/// A well-formed code with the wrong secret is refused by the host, a mistyped one never connects,
/// and there is no comment code on the local network.
#[test]
fn a_local_code_with_the_wrong_secret_or_a_typo_doesnt_join() {
let (mut host, mut guest) = (session("Hana"), session("Ada"));
@@ -112,11 +122,120 @@ fn a_local_code_with_the_wrong_secret_or_a_typo_doesnt_join() {
*last = if *last == 'A' { 'B' } else { 'A' };
let e = guest.execute("collab.join", &json!({"code": typo.iter().collect::<String>()})).unwrap_err().to_string();
assert!(e.contains("typing mistake"), "{e}");
// A view-only code doesn't exist here, and says where it does.
let e = host.execute("collab.share", &json!({"access": "view"})).unwrap_err().to_string();
// A comment code doesn't exist here, and says where it does.
let e = host.execute("collab.share", &json!({"access": "comment"})).unwrap_err().to_string();
assert!(e.contains("share it online"), "{e}");
}
/// A local network share started for looking only shows its view code: whoever joins with it sees
/// every change and can't make one, the edit code (picked later) still edits, and stopping ends
/// both.
#[test]
fn a_local_view_code_lets_people_look_and_not_edit() {
let (mut host, mut viewer, mut editor) = (session("Hana"), session("Ada"), session("Bo"));
let shared = host.execute("collab.share", &json!({"via": "local", "bind": "local", "access": "view"})).unwrap();
assert_eq!(shared["share"]["access"], "view");
let (shown, edit) = (shared["code"].as_str().unwrap().to_string(), shared["share"]["editCode"].as_str().unwrap().to_string());
assert_eq!(shared["share"]["viewCode"], shown, "the code shown is the view code");
assert_ne!(shown, edit);
viewer.execute("collab.join", &json!({"code": shown})).unwrap();
pump(&mut [&mut host, &mut viewer], "the viewer's join", |s| live(s[1]) && s[0].live().peers.len() == 1);
let summary = viewer.live_summary();
assert_eq!((&summary["access"], &summary["readOnly"]), (&json!("view"), &json!(true)));
// The host's edit reaches the viewer; the viewer's is refused before it leaves.
let before = layers(&host);
host.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
pump(&mut [&mut host, &mut viewer], "the host's edit", |s| layers(s[1]) == before + 1);
let e = viewer.execute("shape.ellipse", &json!({"x": 80, "y": 10, "width": 40, "height": 30})).unwrap_err().to_string();
assert!(e.contains("View only"), "{e}");
// The edit code, picked now, still edits, and the viewer sees it.
assert_eq!(host.execute("collab.share", &json!({"access": "edit"})).unwrap()["code"], edit);
editor.execute("collab.join", &json!({"code": edit})).unwrap();
pump(&mut [&mut host, &mut viewer, &mut editor], "the editor's join", |s| live(s[2]) && s[0].live().peers.len() == 2);
assert_eq!(editor.live_summary()["access"], "edit");
editor.execute("shape.ellipse", &json!({"x": 80, "y": 10, "width": 40, "height": 30})).unwrap();
pump(&mut [&mut host, &mut viewer, &mut editor], "the editor's edit", |s| layers(s[0]) == before + 2 && layers(s[1]) == before + 2);
assert_eq!(viewer.live_summary()["readOnly"], true, "picking the edit code changes nothing for who joined to look");
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
pump(&mut [&mut host, &mut viewer, &mut editor], "the end", |s| !s[1].live().status.active() && !s[2].live().status.active());
}
/// A local network share's `link` and `url` are the ones that go with the code shown: started for
/// looking only, whoever joins through either can't edit, and the session's line in `sessions`
/// says the same.
#[test]
fn a_local_view_share_s_link_and_url_only_let_people_look() {
let mut host = session("Hana");
let shared = host.execute("collab.share", &json!({"via": "local", "bind": "local", "access": "view"})).unwrap();
for key in ["link", "url"] {
let way = shared[key].as_str().unwrap().to_string();
let mut viewer = session("Ada");
viewer.execute("collab.join", &json!({"link": way})).unwrap();
pump(&mut [&mut host, &mut viewer], "the join", |s| live(s[1]) && s[0].live().peers.len() == 1);
let summary = viewer.live_summary();
assert_eq!((&summary["access"], &summary["readOnly"]), (&json!("view"), &json!(true)), "joined with {key} {way}");
let before = layers(&host);
let e = viewer.execute("shape.ellipse", &json!({"x": 80, "y": 10, "width": 40, "height": 30})).unwrap_err().to_string();
assert!(e.contains("View only"), "{key}: {e}");
host.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
pump(&mut [&mut host, &mut viewer], "the host's edit", |s| layers(s[1]) == before + 1);
assert_eq!(layers(&host), before + 1, "nothing of the viewer's reached the host ({key})");
viewer.execute("collab.leave", &json!({})).unwrap();
pump(&mut [&mut host, &mut viewer], "the leave", |s| s[0].live().peers.is_empty());
}
// The link, the URL and the code name the same way in, wherever the session is listed.
let Code::Local(local) = code::parse(shared["code"].as_str().unwrap()).unwrap() else { panic!("not a local code") };
assert_eq!((&shared["link"], &shared["share"]["viewLink"]), (&json!(local.link()), &json!(local.link())));
let url = shared["url"].as_str().unwrap();
assert!(url.starts_with("ws://") && url.ends_with(&format!("&token={}", local.token())), "{url}");
assert_eq!(shared["sessions"][0]["link"], shared["link"]);
// Picking the edit code makes them the edit ones too.
let edit = host.execute("collab.share", &json!({"access": "edit"})).unwrap();
assert_eq!((&edit["link"], &edit["sessions"][0]["link"]), (&edit["share"]["editLink"], &edit["share"]["editLink"]));
let edit_token = edit["link"].as_str().unwrap().rsplit("token=").next().unwrap();
assert!(edit["url"].as_str().unwrap().ends_with(&format!("&token={edit_token}")), "{}", edit["url"]);
assert_ne!((&edit["link"], &edit["url"]), (&shared["link"], &shared["url"]));
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
}
/// A share listening on every interface (`bind` 0.0.0.0) names where others reach it, never
/// 0.0.0.0: this machine's local network address (loopback without one) in its codes, links, URL
/// and address, and its view code and edit link both join it.
#[test]
fn a_share_on_every_interface_names_an_address_others_reach() {
let (mut host, mut viewer, mut editor) = (session("Hana"), session("Ada"), session("Bo"));
let shared = host.execute("collab.share", &json!({"via": "local", "bind": "0.0.0.0", "access": "view"})).unwrap();
let Code::Local(viewing) = code::parse(shared["code"].as_str().unwrap()).unwrap() else { panic!("not a local code") };
let at = lan_ip().unwrap_or(Ipv4Addr::LOCALHOST.into());
assert_eq!(IpAddr::from(viewing.ip), at);
let address = format!("{at}:{}", viewing.port);
assert_eq!(shared["address"], address);
let Code::Local(editing) = code::parse(shared["share"]["editCode"].as_str().unwrap()).unwrap() else { panic!("not a local code") };
assert_eq!((editing.ip, editing.port), (viewing.ip, viewing.port));
for way in [&shared["link"], &shared["url"], &shared["share"]["viewLink"], &shared["share"]["editLink"], &shared["sessions"][0]["link"]] {
let way = way.as_str().unwrap_or_default();
assert!(way.contains(&address) && !way.contains("0.0.0.0"), "{way}");
}
viewer.execute("collab.join", &json!({"code": shared["code"]})).unwrap();
editor.execute("collab.join", &json!({"link": shared["share"]["editLink"]})).unwrap();
pump(&mut [&mut host, &mut viewer, &mut editor], "the joins", |s| live(s[1]) && live(s[2]) && s[0].live().peers.len() == 2);
assert_eq!((&viewer.live_summary()["access"], &editor.live_summary()["access"]), (&json!("view"), &json!("edit")));
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
}
/// A listener on one address is reached at it; one on every interface at an address of its own
/// family, on its port.
#[test]
fn a_listener_on_every_interface_is_reached_at_an_address_of_its_family() {
let one: SocketAddr = "192.168.1.20:47900".parse().unwrap();
assert_eq!(reachable(one), one);
for any in ["0.0.0.0:47900", "[::]:47901"] {
let any: SocketAddr = any.parse().unwrap();
let at = reachable(any);
assert!(!at.ip().is_unspecified() && at.is_ipv4() == any.is_ipv4() && at.port() == any.port(), "{any}: {at}");
}
}
/// An invite naming only `server` (what a join code is asked at).
fn code_at(server: &Endpoint) -> Invite {
Invite { server: server.clone(), file: String::new(), token: String::new() }
+37 -8
View File
@@ -28,7 +28,7 @@ use crate::invite::Endpoint;
use crate::join::{GuestConfig, Next, Outcome, Resuming, Seen, Taken, after, ask, closed, hello, resolved, take, too_large, unresolved};
use crate::limits::NetLimits;
use crate::requests::Publish;
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
use crate::throttle::{PRESENCE_INTERVAL, Paced, Throttle, earliest};
/// A WebSocket the driver opens, writes and closes; what it receives comes back through the
/// driver's event methods.
@@ -79,6 +79,8 @@ pub(crate) struct Driver<S: Socket> {
/// Your latest presence while not welcomed (sent with the welcome).
pending: Option<Presence>,
throttle: Throttle<Presence>,
/// Sync messages waiting their turn (a long queue from while offline).
paced: Paced<ClientMsg>,
reconnect_at: Option<Instant>,
/// What this connection asks a server (a managing one), and what follows its answers.
asking: Option<(Box<Exchange>, Then)>,
@@ -86,7 +88,7 @@ pub(crate) struct Driver<S: Socket> {
}
impl<S: Socket> Driver<S> {
fn new(sock: S, cfg: GuestConfig, inbox: Inbox) -> Self {
fn new(sock: S, cfg: GuestConfig, inbox: Inbox, now: Instant) -> Self {
Self {
sock,
cfg,
@@ -97,6 +99,7 @@ impl<S: Socket> Driver<S> {
resume: Resuming::default(),
pending: None,
throttle: Throttle::new(PRESENCE_INTERVAL),
paced: Paced::new(now),
reconnect_at: None,
asking: None,
done: false,
@@ -105,7 +108,7 @@ impl<S: Socket> Driver<S> {
/// Start joining (progress arrives in `inbox`).
pub(crate) fn start(sock: S, cfg: GuestConfig, inbox: Inbox, now: Instant) -> Self {
let mut d = Self::new(sock, cfg, inbox);
let mut d = Self::new(sock, cfg, inbox, now);
d.inbox.push(Event::Status(Status::Connecting));
d.connect(now);
d
@@ -114,7 +117,7 @@ impl<S: Socket> Driver<S> {
/// Start with what `next` asks a server (a background request): the events it ends in go to
/// `inbox`, then the join it ends in, if any, as `cfg` says.
pub(crate) fn asking(sock: S, cfg: GuestConfig, next: exchange::Next, inbox: Inbox, now: Instant) -> Self {
let mut d = Self::new(sock, cfg, inbox);
let mut d = Self::new(sock, cfg, inbox, now);
d.follow(next, now);
d
}
@@ -159,6 +162,8 @@ impl<S: Socket> Driver<S> {
fn connect(&mut self, now: Instant) {
self.reconnect_at = None;
// A server counts per connection, and these were made for the last one.
self.paced = Paced::new(now);
self.conn = Some(Conn::new(now));
if let Err(e) = self.sock.open(&self.server().url()) {
self.dropped(e, now);
@@ -303,13 +308,35 @@ impl<S: Socket> Driver<S> {
if !self.conn.as_ref().is_some_and(|c| c.welcomed) {
return;
}
if !self.write(&msg) {
self.paced.push(msg);
if !self.send_paced(now) {
self.end(Outcome::Retry("the connection dropped".into()), now);
}
}
/// Send the sync messages whose turn has come; false when one couldn't go.
fn send_paced(&mut self, now: Instant) -> bool {
while let Some(msg) = self.paced.take_due(now) {
if !self.write(&msg) {
return false;
}
}
true
}
/// Reconnect now, if it is waiting to: the pauses grow from the beginning again.
pub(crate) fn retry(&mut self, now: Instant) {
if !self.done && self.reconnect_at.is_some() {
self.attempt = 0;
self.connect(now);
}
}
/// Leave the session.
pub(crate) fn leave(&mut self, now: Instant) {
// What may go now still reaches the others. The rest would get the connection refused, and
// a page can't wait: the sync client says so when you leave.
let _ = self.send_paced(now);
self.end(Outcome::Left, now);
}
@@ -327,7 +354,7 @@ impl<S: Socket> Driver<S> {
[Some(c.last_ping + l.keepalive), Some(c.last_heard + c.silence_limit(l)), if c.welcomed { self.throttle.due() } else { None }]
}
});
earliest(conn.into_iter().flatten().chain([self.reconnect_at]))
earliest(conn.into_iter().flatten().chain([self.reconnect_at, self.paced.due()]))
}
/// Do what's due at `now`: reconnect, send held presence or a ping, give up on a connection
@@ -357,7 +384,7 @@ impl<S: Socket> Driver<S> {
if now >= last_heard + silence {
return self.end(Outcome::Retry("the host stopped answering".into()), now);
}
let ok = self.throttle.take_due(now).is_none_or(|p| self.write(&ClientMsg::Presence(p)));
let ok = self.send_paced(now) && self.throttle.take_due(now).is_none_or(|p| self.write(&ClientMsg::Presence(p)));
let ok = ok && (now < last_ping + l.keepalive || self.ping(now));
if !ok {
self.end(Outcome::Retry("the connection dropped".into()), now);
@@ -388,10 +415,12 @@ impl<S: Socket> Driver<S> {
self.sock.close();
}
self.throttle = Throttle::new(PRESENCE_INTERVAL);
// Made for this connection: the sync client sends again what the server didn't get.
self.paced = Paced::new(now);
match after(outcome, &self.cfg, self.was_live, &mut self.attempt, &self.inbox) {
Next::Stop(e) => {
if let Some(e) = e {
self.inbox.push(e);
self.inbox.push(*e);
}
self.done = true;
}
+181 -6
View File
@@ -252,7 +252,7 @@ fn a_silent_host_counts_as_dropped_and_the_client_reconnects() {
}
#[test]
fn reconnects_back_off_then_give_up() {
fn a_live_connection_reconnects_in_rounds_and_never_gives_up() {
let t0 = Instant::now();
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
@@ -260,7 +260,7 @@ fn reconnects_back_off_then_give_up() {
let mut now = t0;
let mut pauses = Vec::new();
d.closed(1006, "", now);
while !d.done() {
for _ in 0..26 {
let next = d.deadline().unwrap();
pauses.push(next - now);
now = next;
@@ -269,11 +269,183 @@ fn reconnects_back_off_then_give_up() {
d.closed(1006, "", now);
}
let secs: Vec<f64> = pauses.iter().map(Duration::as_secs_f64).collect();
assert_eq!(secs, [0.5, 1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0]);
let round = [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0];
assert_eq!(secs[0], 0.5);
assert_eq!(secs[1..12], round);
assert_eq!(secs[12], 60.0, "a longer pause after a round");
assert_eq!(secs[13..24], round, "then as many again");
assert_eq!(secs[24], 60.0);
assert!(!d.done());
let st = statuses(&inbox.drain());
assert_eq!(st.len(), 14, "connecting, 12 reconnects, then failed");
assert!(matches!(st.last(), Some(Status::Failed { reason }) if reason.starts_with("Lost the connection to the host")), "{st:?}");
assert_eq!(d.deadline(), None);
assert!(!st.iter().any(|s| matches!(s, Status::Failed { .. })), "{st:?}");
assert!(matches!(st.last(), Some(Status::Reconnecting { attempt: 27 })), "{st:?}");
}
#[test]
fn retry_now_skips_the_pause_and_starts_the_round_over() {
let t0 = Instant::now();
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
d.closed(1006, "", t0);
let mut now = t0;
for _ in 0..12 {
now = d.deadline().unwrap();
d.tick(now);
d.closed(1006, "", now);
}
assert_eq!(d.deadline().unwrap() - now, Duration::from_secs(60));
let opened = d.sock.opened.len();
d.retry(now);
assert_eq!(d.sock.opened.len(), opened + 1, "connects at once");
inbox.drain();
d.closed(1006, "", now);
assert_eq!(statuses(&inbox.drain()), vec![Status::Reconnecting { attempt: 1 }]);
assert_eq!(d.deadline().unwrap() - now, ms(500), "the pauses grow from the beginning again");
}
#[test]
fn a_session_that_was_live_only_stops_for_a_refusal_that_is_for_good() {
let t0 = Instant::now();
// The words servers turn a session away with for now.
for reason in [
"too many messages",
"the server is busy: try again in a moment",
"the session is full",
"no hello in time",
"this file can't be opened on the server (its data is damaged); tell the server's owner",
"too many connections from your address lately: wait a minute and try again",
] {
for frame in [false, true] {
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
inbox.drain();
if frame {
d.closed(1008, reason, t0);
} else {
d.message(&encode(&ServerMsg::Refused { reason: reason.into() }), t0);
}
assert!(!d.done(), "{reason}");
assert_eq!(statuses(&inbox.drain()), vec![Status::Reconnecting { attempt: 1 }], "{reason}");
}
}
// And the words for good.
for reason in [
"this link isn't valid (it may have been revoked)",
"this file isn't on the server (it may have been removed)",
"this file was removed from the server",
"you were removed from this session",
"this server no longer accepts connections from your address",
"this server doesn't accept connections from your address",
"wrong session token",
"protocol 9 isn't supported",
"message too large: this server takes at most 64 MiB at once (a change that big can't be kept here)",
] {
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
d.closed(1008, reason, t0);
assert!(d.done(), "{reason}");
assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { reason: r }) if r.contains(reason)), "{reason}");
}
// What this end finds it can't talk to: a text frame, or a message it can't read.
for text in [true, false] {
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
if text {
d.text(t0);
} else {
d.message(&[0xFF, 1, 2, 3], t0);
}
assert!(d.done(), "text: {text}");
assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { .. })));
}
}
#[test]
fn a_long_queue_goes_out_paced_and_in_order() {
let t0 = Instant::now();
let (mut d, _inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
let before = d.sock.sent.len();
for seq in 0..500 {
d.send(ClientMsg::Ack { seq }, t0);
}
let at_once = d.sock.sent.len() - before;
assert!((1..=200).contains(&at_once), "{at_once} at once: a server drops a connection past 400");
let mut now = t0;
while d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count() < 500 {
now = d.deadline().unwrap();
d.tick(now);
}
let seqs: Vec<u64> = d.sock.sent.iter().filter_map(|m| if let ClientMsg::Ack { seq } = m { Some(*seq) } else { None }).collect();
assert_eq!(seqs, (0..500).collect::<Vec<u64>>());
assert!(now - t0 >= Duration::from_secs(4), "the rest take their time: {:?}", now - t0);
// Unsent ones were made for this connection: the sync client sends them again.
for seq in 0..500 {
d.send(ClientMsg::Ack { seq }, now);
}
d.closed(1006, "", now);
assert_eq!(d.deadline().unwrap() - now, ms(500), "nothing left to send but the reconnect");
}
#[test]
fn messages_held_up_by_a_stall_dont_leave_together() {
let t0 = Instant::now();
let (mut d, _inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
for seq in 0..700 {
d.send(ClientMsg::Ack { seq }, t0);
}
let acks = |d: &Driver<Script>| d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count();
let first = acks(&d);
// Nothing ran for 8 s.
d.tick(t0 + Duration::from_secs(8));
assert!(acks(&d) - first <= 200, "{} at once: a server drops a connection past 400", acks(&d) - first);
}
#[test]
fn a_new_connection_starts_with_a_fresh_pace() {
let t0 = Instant::now();
let (mut d, _inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
for seq in 0..500 {
d.send(ClientMsg::Ack { seq }, t0);
}
d.closed(1006, "", t0);
let back = d.deadline().unwrap();
d.tick(back);
d.opened(back);
d.message(&welcome(), back);
d.send(ClientMsg::Ack { seq: 900 }, back);
assert!(d.sock.sent.iter().any(|m| matches!(m, ClientMsg::Ack { seq: 900 })), "sent at once");
}
#[test]
fn leaving_sends_what_may_go_at_its_pace() {
let t0 = Instant::now();
let (mut d, _inbox) = start(Script::default(), t0);
d.opened(t0);
d.message(&welcome(), t0);
for seq in 0..150 {
d.send(ClientMsg::Ack { seq }, t0);
}
let later = t0 + Duration::from_secs(1);
for seq in 150..600 {
d.send(ClientMsg::Ack { seq }, later);
}
let before = d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count();
d.leave(later + Duration::from_secs(1));
let seqs: Vec<u64> = d.sock.sent.iter().filter_map(|m| if let ClientMsg::Ack { seq } = m { Some(*seq) } else { None }).collect();
assert!(seqs.len() > before, "more goes on leaving");
assert!(seqs.len() - before <= 200, "{} at once: a server drops a connection past 400", seqs.len() - before);
assert_eq!(seqs, (0..seqs.len() as u64).collect::<Vec<u64>>(), "in order");
assert!(d.done());
}
#[test]
@@ -419,6 +591,8 @@ fn pump(d: &mut Driver<Loopback>) {
}
}
/// The browser's driver joins a real host over loopback, edits with it, sends presence and hears
/// the session end.
#[test]
fn joins_a_real_host_and_edits_with_it() {
let host_probe = Inbox::new(Arc::new(|| {}));
@@ -428,6 +602,7 @@ fn joins_a_real_host_and_edits_with_it() {
any_port_if_taken: false,
file: FILE.into(),
token: TOKEN.into(),
view_token: None,
doc: shared(),
name: "Hana".into(),
limits: fast_limits(),
+52 -9
View File
@@ -31,7 +31,7 @@ use crate::manage;
use crate::net::{Duplex, NetLimits, config, open, shutdown};
use crate::requests;
pub use crate::requests::Publish;
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
use crate::throttle::{PRESENCE_INTERVAL, Paced, Throttle, earliest};
/// A joined (or joining) session. Dropping it leaves.
pub struct Guest {
@@ -44,6 +44,8 @@ enum Cmd {
/// For the server, in order (document changes).
Send(ClientMsg),
Leave,
/// Try now rather than after the pause under way (reconnecting).
Retry,
/// The reader of connection `epoch` got its welcome.
Welcomed(u64),
/// Connection `epoch` ended.
@@ -67,7 +69,7 @@ impl Guest {
});
if let Err(o) = asked.and_then(|(file, token)| resolved(&mut cfg, file, token)) {
if let Next::Stop(Some(e)) = after(unresolved(&cfg, o), &cfg, false, &mut 0, &inbox) {
inbox.push(e);
inbox.push(*e);
}
return;
}
@@ -133,6 +135,11 @@ impl Guest {
let _ = self.cmd.send(Cmd::Send(msg));
}
/// Reconnect now, if it is waiting to.
pub fn retry(&self) {
let _ = self.cmd.send(Cmd::Retry);
}
/// Leave (returns at once: a connection attempt in progress ends on its own).
pub fn leave(&mut self) {
let _ = self.cmd.send(Cmd::Leave);
@@ -155,6 +162,9 @@ impl Drop for Guest {
}
}
/// How long leaving keeps sending what was waiting its turn.
const LEAVE_DRAIN: Duration = Duration::from_secs(10);
/// A connected socket: reader and writer ends.
struct Conn {
reader: WebSocket<Duplex>,
@@ -217,7 +227,7 @@ fn supervise(cfg: &GuestConfig, inbox: &Inbox, rx: &Receiver<Cmd>, me: &Sender<C
match after(outcome, cfg, was_live, &mut attempt, inbox) {
Next::Stop(e) => {
if let Some(e) = e {
inbox.push(e);
inbox.push(*e);
}
return;
}
@@ -227,6 +237,11 @@ fn supervise(cfg: &GuestConfig, inbox: &Inbox, rx: &Receiver<Cmd>, me: &Sender<C
match rx.recv_timeout(until.saturating_duration_since(Instant::now())) {
Ok(Cmd::Leave) | Err(RecvTimeoutError::Disconnected) => return,
Ok(Cmd::Presence(p)) => pending = Some(p),
// A fresh start: the pauses grow from the beginning again.
Ok(Cmd::Retry) => {
attempt = 0;
break;
}
// From the old connection's client: the next welcome starts over.
Ok(_) => {}
Err(RecvTimeoutError::Timeout) => break,
@@ -267,14 +282,15 @@ fn session(
let hello = hello(cfg, resume);
let mut welcomed = false;
let mut throttle = Throttle::new(PRESENCE_INTERVAL);
// Sync messages waiting their turn (a long queue from while offline).
let mut paced: Paced<ClientMsg> = Paced::new(Instant::now());
let outcome = if send(&mut writer, &hello) {
loop {
let ping_at = last_ping + cfg.limits.keepalive;
let wake = earliest([throttle.due(), Some(ping_at)]).unwrap_or(ping_at);
let wake = earliest([throttle.due(), Some(ping_at), paced.due()]).unwrap_or(ping_at);
let mut out = None;
let mut now_send = Vec::new();
match rx.recv_timeout(wake.saturating_duration_since(Instant::now())) {
Ok(Cmd::Send(m)) if welcomed => now_send.push(m),
Ok(Cmd::Send(m)) if welcomed => paced.push(m),
// Made for the previous connection (the sync client sends again what the server
// didn't get once it has caught up with this connection's welcome).
Ok(Cmd::Send(_)) => {}
@@ -288,17 +304,22 @@ fn session(
}
Ok(Cmd::Lost(e, o)) if e == epoch => break o,
Ok(Cmd::Leave) | Err(RecvTimeoutError::Disconnected) => {
leave_paced(&mut writer, &mut paced);
let _ = writer.close(Some(CloseFrame { code: CloseCode::Normal, reason: "".into() }));
break Outcome::Left;
}
// From an earlier connection.
Ok(Cmd::Welcomed(_) | Cmd::Lost(..)) => {}
Ok(Cmd::Welcomed(_) | Cmd::Lost(..) | Cmd::Retry) => {}
Err(RecvTimeoutError::Timeout) => {}
}
if !now_send.iter().all(|m| send(&mut writer, m)) {
let now = Instant::now();
let mut sent = true;
while sent && let Some(m) = paced.take_due(now) {
sent = send(&mut writer, &m);
}
if !sent {
break Outcome::Retry("the connection dropped".into());
}
let now = Instant::now();
let out = out.or_else(|| throttle.take_due(now));
let ok = out.is_none_or(|p| send(&mut writer, &ClientMsg::Presence(p)));
let ok = ok
@@ -318,6 +339,28 @@ fn session(
outcome
}
/// Send what was waiting its turn before leaving, at its pace, for at most [`LEAVE_DRAIN`]: nothing
/// waits for this thread (the app has moved on), and going faster would get the rest refused. What
/// doesn't go is left to the sync client, which says so when you leave.
fn leave_paced(writer: &mut WebSocket<Duplex>, paced: &mut Paced<ClientMsg>) {
let give_up = Instant::now() + LEAVE_DRAIN;
loop {
let now = Instant::now();
if now >= give_up {
return;
}
if let Some(m) = paced.take_due(now) {
if !send(writer, &m) {
return;
}
} else if let Some(at) = paced.due().filter(|at| *at < give_up) {
std::thread::sleep(at.saturating_duration_since(now));
} else {
return;
}
}
}
/// Send one message; false when the connection is gone.
fn send(ws: &mut WebSocket<Duplex>, msg: &ClientMsg) -> bool {
message::encode(msg).is_ok_and(|b| ws.send(Message::Binary(Bytes::from(b))).is_ok())
+23 -8
View File
@@ -1,7 +1,8 @@
//! The session host the app embeds: the shared [hub](crate::hub) serving one file, the one the
//! app shares, with the session's single token. The person hosting is in it without a socket:
//! their presence goes in with [`Host::presence`], their edits with [`Host::send`], what others do
//! comes out through their [`Inbox`]. When the host stops, the session ends for everyone.
//! app shares, with the session's edit token and, for a share that has one, its view token. The
//! person hosting is in it without a socket: their presence goes in with [`Host::presence`], their
//! edits with [`Host::send`], what others do comes out through their [`Inbox`]. When the host
//! stops, the session ends for everyone.
use std::io;
use std::net::{SocketAddr, TcpListener};
@@ -26,6 +27,9 @@ pub struct HostConfig {
/// The file's session id and secret (both in the invite).
pub file: String,
pub token: String,
/// A second secret that lets its holders look and not edit (`None`: everyone who gets in
/// edits). It must differ from `token`.
pub view_token: Option<String>,
/// The shared document (the session's authoritative copy starts from it).
pub doc: Document,
/// The host's own name (empty: "Host").
@@ -40,21 +44,28 @@ pub struct Host {
me: Peer,
}
/// The app's one file and its token: everyone with the invite edits.
/// The app's one file and its tokens: whoever has the edit token edits, whoever has the view
/// token only looks (the server refuses their changes).
struct OneFile {
file: String,
token: String,
view: Option<String>,
}
impl Backend for OneFile {
/// Let in a hello for `file` with `token`, with what its token allows.
fn admit(&mut self, file: &str, token: &str) -> Result<Admission, String> {
if file != self.file {
return Err("this invite is for another file or an earlier session".into());
}
if !same_secret(token, &self.token) {
return Err("wrong session token".into());
// Both tokens are compared, whichever matches, so the time taken doesn't tell them apart.
let edit = same_secret(token, &self.token);
let view = self.view.as_deref().is_some_and(|v| same_secret(token, v));
match (edit, view) {
(true, _) => Ok(Admission { access: Access::Edit, link: None }),
(false, true) => Ok(Admission { access: Access::View, link: None }),
(false, false) => Err("wrong session token".into()),
}
Ok(Admission { access: Access::Edit, link: None })
}
fn open(&mut self, _: &str) -> Result<Server, String> {
@@ -69,6 +80,10 @@ impl Backend for OneFile {
impl Host {
/// Listen and start the hub; the host joins its own session as the first person.
pub fn start(cfg: HostConfig, inbox: Inbox) -> io::Result<Host> {
// A view token equal to the edit token would let its holders edit: nobody gets in with it.
if cfg.view_token.as_deref().is_some_and(|v| same_secret(v, &cfg.token)) {
return Err(io::Error::other("the view-only secret is the same as the edit secret"));
}
let listener = match TcpListener::bind(cfg.addr) {
Ok(l) => l,
Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?,
@@ -99,7 +114,7 @@ impl Host {
}
}
let me = server.peers().find(|p| p.client_id == me).cloned().ok_or_else(|| io::Error::other("the host didn't join its own session"))?;
let backend = OneFile { file: cfg.file.clone(), token: cfg.token };
let backend = OneFile { file: cfg.file.clone(), token: cfg.token, view: cfg.view_token };
let local = Local { file: cfg.file, server, id: me.client_id, inbox };
let hosting = Hosting::start(listener, backend, cfg.limits, Some(local))?;
Ok(Host { hosting, me })
+3
View File
@@ -737,6 +737,9 @@ impl<B: Backend> Hub<B> {
continue;
}
let Some(&conn) = room.ids.get(&id) else { continue };
if matches!(msg, ServerMsg::Presence { .. }) && self.conns.get(&conn).is_some_and(|c| !c.out.takes_presence()) {
continue;
}
let Some(b) = bytes.get_or_insert_with(|| encode(&msg)).clone() else { continue };
if !deliver(&self.conns, conn, &b, &mut held, &mut stuck) {
stuck.push(conn);
@@ -74,6 +74,8 @@ fn a_kicked_connection_with_a_full_queue_is_shut() {
let out = Line {
tx,
queued: Arc::default(),
waiting: Arc::default(),
max_presence: 32,
block: Arc::new(AtomicUsize::new(0)),
all: Arc::new(AtomicUsize::new(0)),
max: 1 << 20,
+36
View File
@@ -51,6 +51,12 @@ fn health_check(stream: &mut TcpStream, until: Instant) -> bool {
let mut req = Vec::new();
let mut chunk = [0u8; 1024];
while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 << 10 {
// The same deadline as the request line: a peer dripping header bytes would otherwise
// hold this thread and its connection slot for as long as it liked.
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() {
break;
}
match stream.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(chunk.get(..n).unwrap_or_default()),
@@ -235,6 +241,8 @@ fn serve(mut stream: TcpStream, conn: u64, hub: &Sender<HubIn>, limits: NetLimit
let out = Line {
tx,
queued: Arc::default(),
waiting: Arc::default(),
max_presence: limits.queue.max(4) / 2,
block: block.queued.clone(),
all: shared.queued.clone(),
max: limits.max_queued_bytes,
@@ -407,3 +415,31 @@ fn linger(ws: &mut WebSocket<Duplex>) {
}
}
}
#[cfg(test)]
mod health_check_tests {
use super::*;
#[test]
fn a_health_check_dripping_headers_ends_at_the_deadline() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let client = std::thread::spawn(move || {
let mut c = TcpStream::connect(addr).unwrap();
c.write_all(b"GET /healthz HTTP/1.1\r\n").unwrap();
// One header byte every 20 ms, far past the deadline, until the server hangs up.
for _ in 0..200 {
if c.write_all(b"X").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
});
let (mut stream, _) = listener.accept().unwrap();
let start = Instant::now();
assert!(health_check(&mut stream, start + Duration::from_millis(300)));
assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed());
drop(stream);
client.join().unwrap();
}
}
+17 -1
View File
@@ -48,6 +48,7 @@ pub(crate) struct Charges {
pub(super) struct Charge {
n: usize,
mine: Arc<AtomicUsize>,
waiting: Arc<AtomicUsize>,
_all: Arc<Held>,
_block: Option<Arc<Held>>,
}
@@ -55,6 +56,7 @@ pub(super) struct Charge {
impl Drop for Charge {
fn drop(&mut self) {
self.mine.fetch_sub(self.n, Ordering::Relaxed);
self.waiting.fetch_sub(1, Ordering::Relaxed);
}
}
@@ -76,6 +78,10 @@ pub(crate) enum Push {
pub(crate) struct Line {
pub(crate) tx: SyncSender<Out>,
pub(crate) queued: Arc<AtomicUsize>,
/// Messages waiting in the queue.
pub(crate) waiting: Arc<AtomicUsize>,
/// With this many waiting, presence is left out (see [`Line::takes_presence`]).
pub(crate) max_presence: usize,
pub(crate) block: Arc<AtomicUsize>,
pub(crate) all: Arc<AtomicUsize>,
pub(crate) max: usize,
@@ -84,6 +90,15 @@ pub(crate) struct Line {
}
impl Line {
/// Whether presence goes in the queue now. A client still taking in a long message (the welcome
/// of a large file on a slow link) would otherwise have its queue filled by everyone's cursors
/// and be dropped, again on every try. Presence is latest-wins, so what's left out is made up
/// for by the next update, and this keeps room for what can't be: other people's edits. A client
/// that reads nothing at all still ends at the write timeout.
pub(crate) fn takes_presence(&self) -> bool {
self.waiting.load(Ordering::Relaxed) < self.max_presence
}
/// Queue `b`. One message always fits an empty queue (a welcome as large as the largest file
/// gets out). `charges` is what the message counts against, shared by its recipients;
/// `over_budget` lets it past the server's budget (the hub just dropped the biggest consumer
@@ -118,7 +133,8 @@ impl Line {
}
};
self.queued.fetch_add(n, Ordering::Relaxed);
let charge = Charge { n, mine: self.queued.clone(), _all: all, _block: block };
self.waiting.fetch_add(1, Ordering::Relaxed);
let charge = Charge { n, mine: self.queued.clone(), waiting: self.waiting.clone(), _all: all, _block: block };
self.tx.try_send(Out::Bytes(b.clone(), Some(charge))).map_err(|e| match e {
TrySendError::Full(_) => Push::Full,
TrySendError::Disconnected(_) => Push::Gone,
+38 -2
View File
@@ -1,7 +1,8 @@
//! The hub's send queues (no writers: nothing is ever sent, so what is queued stays queued): a
//! broadcast counts once against the server's budget however many copies are queued, a block of
//! addresses can't take more than its share, and when the server's budget is used up the
//! connection holding the most is shed, not the next client that needs a little.
//! connection holding the most is shed, not the next client that needs a little. Presence stays out
//! of a busy queue.
use std::collections::HashMap;
use std::net::{IpAddr, TcpListener, TcpStream};
@@ -16,7 +17,20 @@ use super::{BlockUse, Blocks, Charges, Conn, Kind, Line, Out, Push, deliver};
/// A line with its own queue counter, the given block counter and the server's.
fn line(block: &Arc<AtomicUsize>, all: &Arc<AtomicUsize>, max_block: usize, max_all: usize) -> (Line, Receiver<Out>) {
let (tx, rx) = sync_channel(64);
(Line { tx, queued: Arc::default(), block: block.clone(), all: all.clone(), max: 1 << 20, max_block, max_all }, rx)
(
Line {
tx,
queued: Arc::default(),
waiting: Arc::default(),
max_presence: 32,
block: block.clone(),
all: all.clone(),
max: 1 << 20,
max_block,
max_all,
},
rx,
)
}
fn socket() -> TcpStream {
@@ -120,3 +134,25 @@ fn blocks_nobody_uses_are_forgotten() {
let _c = blocks.get("203.0.113.3".parse().unwrap());
assert_eq!(blocks.len(), 2, "203.0.113.1 went");
}
#[test]
fn a_busy_queue_leaves_presence_out_and_keeps_room_for_edits() {
let (l, rx) = line(&Arc::default(), &Arc::default(), usize::MAX, usize::MAX);
let msg = Bytes::from_static(b"x");
for _ in 0..32 {
assert!(l.takes_presence());
l.push(&msg, &mut Charges::default(), false).unwrap();
}
assert!(!l.takes_presence(), "half full");
// Edits still fit in the half kept for them.
for _ in 0..32 {
l.push(&msg, &mut Charges::default(), false).unwrap();
}
assert_eq!(l.push(&msg, &mut Charges::default(), false), Err(Push::Full), "a client that takes in nothing still ends");
// It catches up: presence goes in again.
for _ in 0..33 {
drop(rx.recv().unwrap());
}
assert!(l.takes_presence());
assert_eq!(l.waiting.load(Ordering::Relaxed), 31);
}
+51 -13
View File
@@ -39,8 +39,10 @@ pub struct GuestConfig {
/// The pause before the first reconnect; it doubles each time up to `max_backoff`.
pub backoff: Duration,
pub max_backoff: Duration,
/// Reconnect attempts before giving up.
/// Reconnect attempts in a row before the longer pause (`round_pause`), after which it tries
/// as many again: a connection that was live is never given up on by itself.
pub attempts: u32,
pub round_pause: Duration,
/// Join as the client you were (an app that starts over after a crash): the first hello
/// carries it, and a server that still knows the id gives it back.
pub resume: Option<Resume>,
@@ -57,6 +59,7 @@ impl GuestConfig {
backoff: Duration::from_millis(500),
max_backoff: Duration::from_secs(10),
attempts: 12,
round_pause: Duration::from_secs(60),
resume: None,
}
}
@@ -65,6 +68,14 @@ impl GuestConfig {
pub(crate) fn backoff(&self, attempt: u32) -> Duration {
self.backoff.saturating_mul(1u32 << attempt.saturating_sub(1).min(16)).min(self.max_backoff)
}
/// The pause before reconnect attempt `attempt` (from 1): growing within a round of
/// [`attempts`](Self::attempts), and [`round_pause`](Self::round_pause) between rounds.
pub(crate) fn pause(&self, attempt: u32) -> Duration {
let round = self.attempts.max(1);
let into_round = attempt.saturating_sub(1) % round;
if into_round == 0 && attempt > round { self.round_pause } else { self.backoff(into_round + 1) }
}
}
/// How a connection ended.
@@ -137,31 +148,57 @@ pub(crate) fn closed(code: u16, reason: &str) -> Outcome {
/// What a guest does after a connection ended.
pub(crate) enum Next {
/// Done: tell the UI this (nothing when you left).
Stop(Option<Event>),
/// Done: tell the UI this (nothing when you left). Boxed: an event can be large (a welcome),
/// and this one is only ever a status or the end of the session.
Stop(Option<Box<Event>>),
/// Connect again after this pause (the UI has been told: `Reconnecting`).
Reconnect(Duration),
}
/// After `outcome`: a refusal or the end of the session is final, and so is a first join that
/// can't reach the host; a live connection that dropped tries again with growing pauses until the
/// attempts run out.
/// What a server refuses for good, whenever you ask: the link, the file or your place in it is
/// gone, or the two versions can't talk. Anything else a server refuses a session with (it is
/// busy, a limit was hit, the file couldn't be read just now) may pass, and servers of any version
/// say so in these words, so a reason not listed here means try again.
const FINAL_REFUSALS: [&str; 12] = [
"isn't valid",
"isn't on the server",
"was removed from the server",
"were removed from this session",
"no longer accepts connections",
"doesn't accept connections",
"wrong session token",
"isn't supported",
"couldn't be read",
"message too large",
"this version can't read",
"sent a text message",
];
/// Whether `reason`, from a server refusing a session that was live, is for good.
pub(crate) fn final_refusal(reason: &str) -> bool {
FINAL_REFUSALS.iter().any(|f| reason.contains(f))
}
/// After `outcome`: the end of the session is final, and so are a refusal for good and a first
/// join that can't reach the host. A live connection that dropped or was turned away for now tries
/// again until you leave: with growing pauses, and a longer one between rounds.
pub(crate) fn after(outcome: Outcome, cfg: &GuestConfig, was_live: bool, attempt: &mut u32, inbox: &Inbox) -> Next {
let failed = |reason: String| Next::Stop(Some(Event::Status(Status::Failed { reason })));
let failed = |reason: String| Next::Stop(Some(Box::new(Event::Status(Status::Failed { reason }))));
let outcome = match outcome {
Outcome::Refused(why) if was_live && !final_refusal(&why) => Outcome::Retry(why),
o => o,
};
match outcome {
Outcome::Left => Next::Stop(None),
Outcome::Refused(why) => failed(format!("The host refused: {why}")),
Outcome::Failed(why) => failed(why),
Outcome::Ended(reason) => Next::Stop(Some(Event::Ended { reason })),
Outcome::Ended(reason) => Next::Stop(Some(Box::new(Event::Ended { reason }))),
Outcome::Retry(why) if !was_live => failed(format!("Couldn't join the live session: {why}")),
Outcome::Retry(why) => {
*attempt += 1;
if *attempt > cfg.attempts {
return failed(format!("Lost the connection to the host ({why})"));
}
*attempt = attempt.saturating_add(1);
log::info!("live session: connection lost ({why}); reconnecting, attempt {attempt}");
inbox.push(Event::Status(Status::Reconnecting { attempt: *attempt }));
Next::Reconnect(cfg.backoff(*attempt))
Next::Reconnect(cfg.pause(*attempt))
}
}
}
@@ -228,6 +265,7 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
address: inv.server.display(),
network: !inv.loopback(),
access,
view: None,
};
seen.peers = peers.clone();
seen.info = Some(info.clone());
+68 -20
View File
@@ -1,6 +1,6 @@
//! [`NetLink`]: the engine's [`LiveLink`] over the network.
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
@@ -9,7 +9,7 @@ use figcraft_collab::code;
use figcraft_collab::message::{Access, Admin, AdminReply, ClientMsg, LibraryReply, LibraryReq, PluginReply, PluginReq};
use figcraft_engine::live::{
Bind, Event, HostInfo, HostOptions, LiveLink, NO_SESSION, NetReply, NetRequest, PageInfo, Presence, PublishOptions, Published, Resume, Role,
SessionId, SessionInfo, Shared,
SessionId, SessionInfo, Shared, WayIn,
};
use crate::guest::{Guest, GuestConfig, Publish, upload_file};
@@ -97,24 +97,62 @@ impl NetLink {
}
}
/// A new secret for a hosted session: one a join code can carry (`short`: 44 bits, see
/// `figcraft_collab::code`), else a full one.
fn session_secret(short: bool) -> Result<String, String> {
match short {
true => Ok(code::Local::new(Ipv4Addr::UNSPECIFIED, 0, token::random()?).token()),
false => token::secret(),
}
}
/// A view-only secret for a session whose edit secret is `edit`: of the same kind, never the same.
fn view_secret(short: bool, edit: &str) -> Result<String, String> {
for _ in 0..3 {
let view = session_secret(short)?;
if view != edit {
return Ok(view);
}
}
Err("couldn't make a view-only secret".into())
}
/// This machine's address on the local network: the interface the default route leaves by (no
/// packet is sent).
pub fn lan_ip() -> Option<IpAddr> {
let sock = UdpSocket::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))).ok()?;
// Documentation and private ranges: only the route matters.
for probe in ["192.0.2.1:9", "10.255.255.255:9"] {
if sock.connect(probe).is_ok()
&& let Ok(a) = sock.local_addr()
&& !a.ip().is_loopback()
&& !a.ip().is_unspecified()
{
return Some(a.ip());
}
}
None
route_ip(Ipv4Addr::UNSPECIFIED.into(), &["192.0.2.1:9", "10.255.255.255:9"])
}
/// The address of `any`'s family that the route to the first of `probes` that has one leaves by
/// (no packet is sent): never a loopback, unspecified or IPv6 link-local one, which others can't
/// reach this machine at.
fn route_ip(any: IpAddr, probes: &[&str]) -> Option<IpAddr> {
let sock = UdpSocket::bind(SocketAddr::new(any, 0)).ok()?;
probes.iter().find_map(|probe| {
sock.connect(probe).ok()?;
let ip = sock.local_addr().ok()?.ip();
let link_local = matches!(ip, IpAddr::V6(v6) if v6.is_unicast_link_local());
(!ip.is_loopback() && !ip.is_unspecified() && !link_local).then_some(ip)
})
}
/// Where others reach a session listening on `addr`: `addr` itself, or for a listener on every
/// interface (`0.0.0.0`, `::`) this machine's local network address of the same family (its
/// loopback without one), on the same port. Links name it; the listener keeps every interface.
pub(crate) fn reachable(addr: SocketAddr) -> SocketAddr {
let ip = match addr.ip() {
ip if !ip.is_unspecified() => ip,
IpAddr::V4(_) => lan_ip().unwrap_or(Ipv4Addr::LOCALHOST.into()),
// Documentation and unique local ranges, as for IPv4.
IpAddr::V6(_) => route_ip(Ipv6Addr::UNSPECIFIED.into(), &["[2001:db8::1]:9", "[fd00::1]:9"]).unwrap_or(Ipv6Addr::LOCALHOST.into()),
};
SocketAddr::new(ip, addr.port())
}
impl LiveLink for NetLink {
/// Host the open file on `o.bind`: a join code's short secret when `o.short`, and a second,
/// view-only secret with its invite link when `o.view`.
fn host(&mut self, session: SessionId, o: HostOptions) -> Result<SessionInfo, String> {
let ip = match o.bind {
Bind::Local => IpAddr::V4(Ipv4Addr::LOCALHOST),
@@ -123,11 +161,10 @@ impl LiveLink for NetLink {
};
// A session shared with a join code: its secret is short enough to be typed with the
// address (see `figcraft_collab::code`); the code and the invite link name the same session.
let (file, token) = if o.short {
(code::LOCAL_FILE.to_string(), code::Local::new(Ipv4Addr::UNSPECIFIED, 0, token::random()?).token())
} else {
(token::file_id()?, token::secret()?)
};
let file = if o.short { code::LOCAL_FILE.to_string() } else { token::file_id()? };
let token = session_secret(o.short)?;
// A way in for looking only: a second secret of the same kind, never the edit one.
let view_token = o.view.then(|| view_secret(o.short, &token)).transpose()?;
let inbox = self.sessions.inbox();
let doc = (*o.doc).clone();
let pages = doc.pages.iter().map(|p| PageInfo { id: p.0, name: doc.node(*p).map(|n| n.name.clone()).unwrap_or_default() }).collect();
@@ -137,13 +174,17 @@ impl LiveLink for NetLink {
any_port_if_taken: o.port.is_none(),
file: file.clone(),
token: token.clone(),
view_token: view_token.clone(),
doc,
name: o.name,
limits: self.limits,
core: figcraft_collab::Limits::default(),
};
let host = Host::start(cfg, inbox.clone()).map_err(|e| format!("can't listen on {ip}: {e}"))?;
let invite = Invite::new(host.addr().to_string(), file, token);
// Listening on every interface (`0.0.0.0`, `::`), the links name an address others reach.
let at = reachable(host.addr()).to_string();
let view = view_token.map(|v| Invite::new(at.clone(), file.clone(), v)).map(|v| WayIn { link: v.link(), url: v.url() });
let invite = Invite::new(at.clone(), file, token);
let info = SessionInfo {
role: Role::Host,
me: host.me().client_id,
@@ -153,9 +194,10 @@ impl LiveLink for NetLink {
pages,
link: invite.link(),
url: invite.url(),
address: host.addr().to_string(),
address: at,
network: !ip.is_loopback(),
access: Access::Edit,
view,
};
self.started(session, Active::Host(host), inbox);
Ok(info)
@@ -266,6 +308,12 @@ impl LiveLink for NetLink {
}
}
fn retry(&mut self, session: SessionId) {
if let Some(Active::Guest(g)) = self.sessions.get(session) {
g.retry();
}
}
fn presence(&mut self, session: SessionId, p: &Presence) {
match self.sessions.get(session) {
Some(Active::Host(h)) => h.presence(p.clone()),
+57 -1
View File
@@ -7,7 +7,7 @@ use std::net::{SocketAddr, TcpStream};
use std::sync::Arc;
use std::time::{Duration, Instant};
use figcraft_collab::message::{self, CatchUp, ClientMsg, Hello, Presence, ServerMsg, Signal};
use figcraft_collab::message::{self, Access, CatchUp, ClientMsg, Hello, Presence, ServerMsg, Signal};
use figcraft_collab::{Client, Limits};
use figcraft_doc::{Document, NodeId};
use figcraft_engine::live::{Event, PEOPLE, Status, TOO_LARGE_TO_JOIN};
@@ -78,6 +78,7 @@ pub(crate) fn fast_limits() -> NetLimits {
NetLimits { hello_timeout: Duration::from_secs(5), ..NetLimits::default() }
}
/// A host on a free loopback port with these limits, a probe of what it is told, and its invite.
fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
let probe = Probe::new();
let mut doc = Document::new("Shared file");
@@ -87,6 +88,7 @@ fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
any_port_if_taken: false,
file: FILE.into(),
token: TOKEN.into(),
view_token: None,
doc,
name: "Hana".into(),
limits,
@@ -214,6 +216,7 @@ fn guests_join_and_see_each_other() {
assert_eq!(host.connections(), 0);
}
/// A guest with the wrong token or for another file is refused, and the secret never shows.
#[test]
fn a_wrong_token_or_file_is_refused() {
let (mut host, mut hp, invite) = start();
@@ -236,6 +239,57 @@ fn a_wrong_token_or_file_is_refused() {
host.stop();
}
/// Join `addr` with `token` over a bare socket and make an edit: what the welcome allowed, and
/// whether the host took the edit (`Changes`) or rejected it (`Reject`).
fn join_and_edit(addr: SocketAddr, token: &str) -> (Access, ServerMsg) {
let mut raw = Raw::hello(addr, token);
let mut welcome = std::iter::from_fn(|| raw.next()).find(|m| matches!(m, ServerMsg::Welcome { .. })).expect("a welcome");
message::unpack(&mut welcome, 64 << 20).unwrap();
let ServerMsg::Welcome { access, .. } = welcome else { panic!("not a welcome: {welcome:?}") };
let mut client = Client::join(welcome).unwrap();
let mut doc = client.document().clone();
doc.add_page("Mine");
assert!(raw.send(&client.edit(&doc).unwrap().unwrap()));
let answer = std::iter::from_fn(|| raw.next()).find(|m| matches!(m, ServerMsg::Changes(_) | ServerMsg::Reject { .. })).expect("an answer");
(access, answer)
}
/// A session hosted with a view token as well (a local network share's view-only code): whoever
/// joins with it is welcomed as a viewer and their edits are rejected, the edit token still edits,
/// any other token is still refused, and a view token equal to the edit token isn't hosted.
#[test]
fn a_view_token_lets_people_look_and_not_edit() {
const VIEW: &str = "ViewOnlyViewOnlyView00";
let probe = Probe::new();
let cfg = |view: &str| {
let mut doc = Document::new("Shared file");
doc.repair();
HostConfig {
addr: SocketAddr::from(([127, 0, 0, 1], 0)),
any_port_if_taken: false,
file: FILE.into(),
token: TOKEN.into(),
view_token: Some(view.into()),
doc,
name: "Hana".into(),
limits: fast_limits(),
core: Limits::default(),
}
};
let same = Host::start(cfg(TOKEN), probe.inbox.clone()).err().expect("a view token equal to the edit token is refused");
assert!(same.to_string().contains("view-only"), "{same}");
let mut host = Host::start(cfg(VIEW), probe.inbox.clone()).unwrap();
let (access, answer) = join_and_edit(host.addr(), VIEW);
assert_eq!(access, Access::View);
assert!(matches!(&answer, ServerMsg::Reject { reason, .. } if reason.contains("view")), "{answer:?}");
let (access, answer) = join_and_edit(host.addr(), TOKEN);
assert_eq!(access, Access::Edit);
assert!(matches!(answer, ServerMsg::Changes(_)), "{answer:?}");
let refusal = Raw::hello(host.addr(), "WrongWrongWrongWrong00").refusal();
assert!(refusal.as_deref().is_some_and(|r| r.contains("token")), "{refusal:?}");
host.stop();
}
#[test]
fn unreachable_hosts_fail_at_once() {
// A port nothing listens on.
@@ -677,6 +731,7 @@ fn the_host_removes_someone_and_they_cant_come_back() {
assert_eq!(host.connections(), 0);
}
/// A welcome larger than the guest takes says the file is too large to join.
#[test]
fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
let mut doc = Document::new("B".repeat(1 << 20));
@@ -687,6 +742,7 @@ fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
any_port_if_taken: false,
file: FILE.into(),
token: TOKEN.into(),
view_token: None,
doc,
name: "Hana".into(),
limits: fast_limits(),
+31
View File
@@ -206,7 +206,17 @@ fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> {
/// The next answer `pick` takes, or why there is none.
fn reply<T>(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option<T>) -> Result<T, String> {
// One deadline for the whole answer: pings, pongs and a message trickling in each renew the
// read timeout, so without it a server could keep a request (and the refresh permit the
// caller holds) waiting for as long as it liked.
// The request-reply bound, not the session idle one: a publish uploads a whole file and can
// legitimately take minutes to be answered (see `connect`).
let until = std::time::Instant::now() + limits.request_reply_timeout;
ws.get_mut().read_until(Some(until));
loop {
if std::time::Instant::now() >= until {
return Err("no answer from the server (it took too long)".into());
}
return match ws.read() {
Ok(Message::Binary(b)) => match message::decode::<ServerMsg>(&b, limits.max_server_message) {
Ok(ServerMsg::Refused { reason }) => Err(format!("{REFUSED}{reason}")),
@@ -251,6 +261,27 @@ mod tests {
rx.recv_timeout(Duration::from_secs(3)).is_ok()
}
/// A server that keeps pinging and never answers ends the wait at the request-reply bound.
#[test]
fn reply_gives_up_at_the_request_reply_deadline_against_a_pinging_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
if let Ok(mut ws) = tungstenite::accept(s) {
while ws.send(Message::Ping(Bytes::new())).is_ok() {
std::thread::sleep(Duration::from_millis(10));
}
}
});
let limits = NetLimits { request_reply_timeout: Duration::from_millis(400), ..NetLimits::default() };
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
let mut ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
let started = std::time::Instant::now();
assert!(reply::<()>(&mut ws, &limits, |_| None).is_err());
assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
}
/// A server that keeps pinging and never answers the close must not pin `close` forever.
#[test]
fn close_returns_against_a_server_that_keeps_pinging() {
+3 -2
View File
@@ -124,8 +124,9 @@ fn following_a_viewport_until_you_move() {
fn the_host_stopping_ends_the_session_for_guests() {
let (mut host, mut guest, _, _) = host_and_join();
host.execute("collab.stop", &json!({})).unwrap();
pump(&mut host, &mut guest, "the end", |_, g| g.live().status == Status::Off);
assert!(guest.live().peers.is_empty());
pump(&mut host, &mut guest, "the end", |_, g| g.live().rejoinable());
assert!(guest.live().peers.is_empty() && !guest.live().syncing());
assert!(guest.live().disconnected(), "the tab says so");
assert_eq!(guest.message.as_deref(), Some(crate::host::ENDED));
}
+2 -2
View File
@@ -158,8 +158,8 @@ fn two_files_are_hosted_and_joined_independently() {
assert!(host.live_of(hb).presence.get(&ada(&host, hb)).is_none_or(|p| p.cursor.is_none()), "no cursor in the file that isn't in front");
// The host closes B: its session ends for everyone, A's goes on.
host.execute("file.close", &json!({"index": 1, "force": true})).unwrap();
pump(&mut [&mut host, &mut guest], "B's session ending", |s| s[0].live.iter().count() == 1 && s[1].live.iter().count() == 1);
assert_eq!(guest.live_of(gb).status, Status::Off);
pump(&mut [&mut host, &mut guest], "B's session ending", |s| s[0].live.iter().count() == 1 && s[1].live_of(gb).rejoinable());
assert!(guest.live_of(gb).disconnected(), "the guest's tab says so");
assert_eq!(guest.docs.len(), 3, "the guest keeps its copy of B");
assert_eq!((host.live_of(ha).status.clone(), host.live_of(ha).peers.len()), (Status::Live, 1));
assert_eq!(guest.live_of(ga).status, Status::Live);
+49
View File
@@ -2,6 +2,7 @@
//! (replacing any older waiting value) until the interval has passed, so the last one is never
//! lost. Used for presence on both ends (about 30 updates a second).
use std::collections::VecDeque;
use std::time::Duration;
// `std::time::Instant` on native builds; the browser's clock in the web build.
@@ -10,6 +11,54 @@ use web_time::Instant;
/// How often presence goes out at most.
pub const PRESENCE_INTERVAL: Duration = Duration::from_millis(33);
/// How many messages other than presence go out at once, and per second after that: with presence
/// and pings that stays under what a server takes from a connection before it drops it.
const PACE_BURST: f64 = 200.0;
const PACE_RATE: f64 = 60.0;
/// Messages that must all go out, in order, at a pace (everything queued while offline leaves at
/// once when the connection comes back). The pace is counted when they go, so messages held up by
/// a stalled connection don't leave together afterwards.
#[derive(Debug)]
pub struct Paced<T> {
tokens: f64,
last: Instant,
queue: VecDeque<T>,
}
impl<T> Paced<T> {
pub fn new(now: Instant) -> Self {
Self { tokens: PACE_BURST, last: now, queue: VecDeque::new() }
}
pub fn push(&mut self, v: T) {
self.queue.push_back(v);
}
/// The next message, if its turn has come at `now`.
pub fn take_due(&mut self, now: Instant) -> Option<T> {
if self.queue.is_empty() {
return None;
}
self.tokens = (self.tokens + now.saturating_duration_since(self.last).as_secs_f64() * PACE_RATE).min(PACE_BURST);
self.last = now;
// Within rounding of a whole turn counts as one: the time `due` gave has come.
if self.tokens < 1.0 - 1e-6 {
return None;
}
self.tokens -= 1.0;
self.queue.pop_front()
}
/// When the next message's turn comes (`None`: there's none).
pub fn due(&self) -> Option<Instant> {
self.queue.front()?;
// Rounded up to whole microseconds, so a timer set for this always finds the turn come.
let wait = ((1.0 - self.tokens).max(0.0) / PACE_RATE * 1e6).ceil() as u64;
Some(self.last + Duration::from_micros(wait))
}
}
#[derive(Debug)]
pub struct Throttle<T> {
interval: Duration,
+4
View File
@@ -242,6 +242,10 @@ impl LiveLink for NetLink {
}
}
fn retry(&mut self, session: SessionId) {
self.with(session, |d, now| d.retry(now));
}
fn presence(&mut self, session: SessionId, p: &Presence) {
self.with(session, |d, now| d.presence(p.clone(), now));
}
+204 -13
View File
@@ -9,16 +9,20 @@
//! interactions, accessibility annotations, Dev Mode resources and measurements) merge item by
//! item: both sides changing different items of the list (or one adding items at its end) is no
//! conflict, only the same item changed both ways or the list shortened on a side while the other
//! changed it. Nothing that conflicts is merged until it is resolved: each conflict is resolved for
//! one side, and the other side's changes to it are left out. Everything else from both sides is
//! kept.
//! changed it. Auto layout settings (a frame's and a child's) merge field by field: each field
//! changed both ways is a conflict of its own, and the other fields merge. Values a file works out
//! for itself (a size or place auto layout gives a layer, text sizing to its characters, a value a
//! layer in an instance takes from its main component) never conflict: the merged file works them
//! out again from what they follow. Nothing that conflicts is merged until it is resolved: each
//! conflict is resolved for one side, and the other side's changes to it are left out. Everything
//! else from both sides is kept.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use figcraft_doc::{Document, NodeId};
use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, TextAutoResize};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::{Map, Value};
use crate::change::{Change, DocProp, Entry, Json, Prop};
use crate::replica::{Mode, Positions, Replica, create_change};
@@ -33,6 +37,7 @@ pub enum Side {
}
impl Side {
/// The side that isn't `self`.
pub fn other(self) -> Side {
match self {
Side::Branch => Side::Main,
@@ -48,6 +53,7 @@ impl Side {
}
}
/// The side `"branch"` or `"main"` names (`None` for anything else).
pub fn parse(s: &str) -> Option<Side> {
match s {
"branch" => Some(Side::Branch),
@@ -62,6 +68,9 @@ impl Side {
pub enum Key {
/// A layer property. A layer's parent and position are one property (where it is).
Node(NodeId, Prop),
/// One field of a layer property that merges field by field ([`PER_FIELD`]): `padding` of
/// `layout`, `sizing_h` of `childLayout`…
Field(NodeId, Prop, String),
/// A layer deleted on one side and edited (it or what's inside it) on the other.
Layer(NodeId),
/// A document-level property.
@@ -78,11 +87,13 @@ fn camel<T: Serialize>(v: &T) -> String {
}
}
/// `12/fills`, `12/layer`, `doc/styleOrder`, `style/S:3`, `comment/7`… (the keys resolutions use).
/// `12/fills`, `12/layout.padding`, `12/layer`, `doc/styleOrder`, `style/S:3`, `comment/7`… (the
/// keys resolutions use).
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::Node(id, prop) => write!(f, "{id}/{}", camel(prop)),
Key::Field(id, prop, field) => write!(f, "{id}/{}.{field}", camel(prop)),
Key::Layer(id) => write!(f, "{id}/layer"),
Key::Doc(prop) => write!(f, "doc/{}", camel(prop)),
Key::Entry(e) => match e {
@@ -129,10 +140,25 @@ pub struct Plan {
/// The main file's changes since the base.
pub main: Vec<Change>,
pub conflicts: Vec<Conflict>,
/// Layer properties changed both ways to values both files work out for themselves
/// ([`computed`]): no conflict, and a merge leaves the file merged into its own value.
derived: BTreeSet<Key>,
/// Layer properties ([`Key::Node`]) merged field by field with fields in conflict.
fields: BTreeMap<Key, Fields>,
branch_positions: Positions,
main_positions: Positions,
}
/// A layer property merged field by field ([`merge_fields`]): the value with every field changed
/// one way (or the same way on both sides) merged, and each side's values of the fields changed
/// both ways (`Null` for a field a side left out).
#[derive(Clone, Debug, Default, PartialEq)]
struct Fields {
merged: Map<String, Value>,
branch: Map<String, Value>,
main: Map<String, Value>,
}
/// Document-level properties that belong to each copy, not to the work: the file name (a branch
/// is named after itself) and the page it opens on.
fn merges(c: &Change) -> bool {
@@ -152,6 +178,7 @@ fn key_of(c: &Change) -> Option<Key> {
})
}
/// The changes (indexes) in `changes` grouped by what they write ([`key_of`]).
fn by_key(changes: &[Change]) -> BTreeMap<Key, Vec<usize>> {
let mut out: BTreeMap<Key, Vec<usize>> = BTreeMap::new();
for (i, c) in changes.iter().enumerate() {
@@ -193,6 +220,108 @@ fn merged_list(base: &Document, key: &Key, b: Option<&Change>, m: Option<&Change
merge_items(o.0.as_array()?, bv.0.as_array()?, mv.0.as_array()?).map(|v| Json(Value::Array(v)))
}
/// Layer properties whose fields merge one by one: auto layout settings, a frame's (`layout`) and
/// a child's (`childLayout`). Changing the padding on one side and the gap on the other is no
/// conflict, and each field changed both ways is a conflict of its own ([`Key::Field`]).
const PER_FIELD: &[Prop] = &[Prop::Layout, Prop::ChildLayout];
/// Three-way merge of object `o` changed to `b` on one side and `m` on the other, field by field:
/// a field changed on one side takes that side's value, and one changed both ways (differently)
/// is in conflict. `None` when any of them isn't an object (auto layout added or removed).
fn merge_fields(o: &Value, b: &Value, m: &Value) -> Option<Fields> {
let (o, b, m) = (o.as_object()?, b.as_object()?, m.as_object()?);
let names: BTreeSet<&String> = o.keys().chain(b.keys()).chain(m.keys()).collect();
let mut out = Fields::default();
for name in names {
let (base, x, y) = (o.get(name), b.get(name), m.get(name));
let kept = if x == base {
y
} else if y == base || x == y {
x
} else {
out.branch.insert(name.clone(), x.cloned().unwrap_or(Value::Null));
out.main.insert(name.clone(), y.cloned().unwrap_or(Value::Null));
base
};
if let Some(v) = kept {
out.merged.insert(name.clone(), v.clone());
}
}
Some(out)
}
/// Both sides' writes `b` and `m` of property `key` (one of [`PER_FIELD`]) merged field by field
/// against the base; `None` when `key` isn't such a property or a value isn't an object.
fn merged_fields(base: &Document, key: &Key, b: Option<&Change>, m: Option<&Change>) -> Option<Fields> {
let Key::Node(id, prop) = key else { return None };
let (Some(Change::Set { value: bv, .. }), Some(Change::Set { value: mv, .. })) = (b, m) else { return None };
if !PER_FIELD.contains(prop) {
return None;
}
let o = prop.get(base.node(*id)?).ok()?;
merge_fields(&o.0, &bv.0, &mv.0)
}
/// Whether layer `n` of `doc` is placed by its parent's auto layout (not absolute).
fn in_flow(doc: &Document, n: &Node) -> bool {
!n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
}
/// Whether auto layout or text works out layer `n`'s width (`horizontal`) or height: an auto layout
/// frame hugging its contents, a child filling its auto layout parent, or text sizing to its
/// characters.
fn sized_for_itself(doc: &Document, n: &Node, horizontal: bool) -> bool {
let sizing = if horizontal { n.child_layout.sizing_h } else { n.child_layout.sizing_v };
let by_layout = match sizing {
Sizing::Hug => n.layout.is_some(),
Sizing::Fill => in_flow(doc, n),
Sizing::Fixed => false,
};
let by_text = match &n.kind {
NodeKind::Text(t) => t.auto_resize == TextAutoResize::WidthAndHeight || (!horizontal && t.auto_resize == TextAutoResize::Height),
_ => false,
};
by_layout || by_text
}
/// Whether layer `n` of `doc` (an instance, or a layer inside one) has property `prop` as its main
/// component's layer has it: it follows the main rather than overriding it.
fn follows_main(doc: &Document, n: &Node, prop: Prop) -> bool {
let main = match &n.kind {
NodeKind::Instance { component, .. } => Some(*component),
_ => n.source,
};
Prop::FIELDS.contains(&prop) && main.and_then(|m| doc.node(m)).is_some_and(|m| !prop.differs(n, m))
}
/// Whether layer property `key` holds a value `doc` works out for itself rather than one set on
/// the layer: a size auto layout or text gives it ([`sized_for_itself`]), its place in an auto
/// layout parent, or a value it takes from its main component ([`follows_main`]).
fn computed(doc: &Document, key: &Key) -> bool {
let Key::Node(id, prop) = key else { return false };
let Some(n) = doc.node(*id) else { return false };
let by_layout = match prop {
Prop::Width => sized_for_itself(doc, n, true),
Prop::Height => sized_for_itself(doc, n, false),
Prop::Transform => in_flow(doc, n),
_ => false,
};
by_layout || follows_main(doc, n, *prop)
}
/// Whether property `key`, changed both ways, is one both files work out for themselves
/// ([`computed`]), so neither side's value is a choice to make. A place given by auto layout is
/// only that when both sides also turn and scale the layer the same way (a rotation is set on the
/// layer, not worked out).
fn derived_on_both(branch: &Document, main: &Document, key: &Key) -> bool {
if !(computed(branch, key) && computed(main, key)) {
return false;
}
let Key::Node(id, Prop::Transform) = key else { return true };
let linear = |doc: &Document| doc.node(*id).map(|n| n.transform.as_coeffs()).map(|c| [c[0], c[1], c[2], c[3]]);
linear(branch) == linear(main)
}
/// The change at the only index in `c`.
fn only<'a>(c: &[usize], all: &'a [Change]) -> Option<&'a Change> {
match c {
@@ -265,6 +394,8 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
let mut mc: Vec<Change> = m.changes.into_iter().filter(merges).collect();
let mut conflicts = Vec::new();
let mut lists = Vec::new();
let mut derived = BTreeSet::new();
let mut fields = BTreeMap::new();
let km = by_key(&mc);
for (k, bi) in by_key(&bc) {
// Deletions conflict with edits (below); images are content-addressed, so never differ.
@@ -279,13 +410,28 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
if same {
continue;
}
match merged_list(base, &k, only(&bi, &bc), only(mi, &mc)) {
Some(value) => lists.push((bi, mi.clone(), value)),
None => conflicts.push(Conflict { key: k, deleted_by: None, branch: bi, main: mi.clone() }),
if derived_on_both(branch, main, &k) {
derived.insert(k);
continue;
}
if let Some(value) = merged_list(base, &k, only(&bi, &bc), only(mi, &mc)) {
lists.push((bi, mi.clone(), value));
continue;
}
match (&k, merged_fields(base, &k, only(&bi, &bc), only(mi, &mc))) {
(_, Some(f)) if f.branch.is_empty() => lists.push((bi, mi.clone(), Json(Value::Object(f.merged)))),
(Key::Node(id, prop), Some(f)) => {
for name in f.branch.keys() {
let key = Key::Field(*id, *prop, name.clone());
conflicts.push(Conflict { key, deleted_by: None, branch: bi.clone(), main: mi.clone() });
}
fields.insert(k, f);
}
_ => conflicts.push(Conflict { key: k, deleted_by: None, branch: bi, main: mi.clone() }),
}
}
// Both sides' writes of a list merged item by item become the merged list, so merging either
// way writes it.
// Both sides' writes of a list merged item by item (or of auto layout settings merged field by
// field) become the merged value, so merging either way writes it.
for (bi, mi, value) in lists {
for (changes, at) in [(&mut bc, bi), (&mut mc, mi)] {
for i in at {
@@ -313,6 +459,8 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
branch: bc,
main: mc,
conflicts,
derived,
fields,
branch_positions: b.replica.positions().clone(),
main_positions: m.replica.positions().clone(),
})
@@ -332,6 +480,42 @@ impl Plan {
}
}
/// Layer properties both sides changed to values both files work out for themselves (a size or
/// place auto layout gives, a value an instance takes from its main): not conflicts, and
/// merging leaves the file merged into its own value for the merged file to work out again.
pub fn derived(&self) -> &BTreeSet<Key> {
&self.derived
}
/// The branch's and main's values of field conflict `key` ([`Key::Field`]); `None` for other
/// keys.
pub fn field_values(&self, key: &Key) -> Option<(&Value, &Value)> {
let Key::Field(id, prop, name) = key else { return None };
let f = self.fields.get(&Key::Node(*id, *prop))?;
Some((f.branch.get(name)?, f.main.get(name)?))
}
/// The side `pick` chose for each field in conflict of every property merged field by field,
/// written into the value merged from the other fields: the writes that replace both sides'
/// own writes of those properties.
fn field_writes(&self, pick: &dyn Fn(&Key) -> Option<Side>) -> Vec<Change> {
let mut out = Vec::new();
for (key, f) in &self.fields {
let Key::Node(id, prop) = key else { continue };
let mut value = f.merged.clone();
for name in f.branch.keys() {
let won = if pick(&Key::Field(*id, *prop, name.clone())) == Some(Side::Branch) { &f.branch } else { &f.main };
match won.get(name) {
Some(Value::Null) | None => value.remove(name),
Some(v) => value.insert(name.clone(), v.clone()),
};
}
out.push(Change::Set { id: *id, prop: *prop, value: Json(Value::Object(value)) });
}
out
}
/// `side`'s positions (fractional keys) of the layers, for applying its changes elsewhere.
fn positions(&self, side: Side) -> &Positions {
match side {
Side::Branch => &self.branch_positions,
@@ -355,7 +539,10 @@ impl Plan {
let mut skip: BTreeSet<usize> = BTreeSet::new();
let mut batch = Vec::new();
for c in &self.conflicts {
if pick(&c.key) != Some(from) {
if matches!(c.key, Key::Field(..)) {
// Written whole below, each field from the side picked for it.
skip.extend(c.changes(from));
} else if pick(&c.key) != Some(from) {
skip.extend(c.changes(from));
} else if let (Key::Layer(id), Some(by)) = (&c.key, c.deleted_by)
&& by != from
@@ -372,7 +559,11 @@ impl Plan {
// shortcut: images a side stopped using are kept (unused ones cost file size only); drop
// them if files grow.
let kept = |c: &Change| !matches!(c, Change::Remove { entry: Entry::Image(_) });
batch.extend(self.changes(from).iter().enumerate().filter(|(i, c)| !skip.contains(i) && kept(c)).map(|(_, c)| c.clone()));
// Values both files work out for themselves stay as `into` has them; normalising the merged
// file works them out again from what changed.
let own = |c: &Change| key_of(c).is_some_and(|k| self.derived.contains(&k));
batch.extend(self.changes(from).iter().enumerate().filter(|(i, c)| !skip.contains(i) && kept(c) && !own(c)).map(|(_, c)| c.clone()));
batch.extend(self.field_writes(pick));
let mut r = Replica::from_parts(into.clone(), self.positions(from.other()).clone());
let applied = r.apply(&batch, Mode::Strict)?;
Ok((r.document().clone(), applied.touched))
+4 -1
View File
@@ -73,7 +73,10 @@ fn css_hue_units_and_none() {
assert_eq!(Color::parse_css(&format!("oklch(0.6 0.2 {h})")).unwrap().to_hex(), blue.to_hex(), "{h}");
}
assert_eq!(Color::parse_css("lch(50 none none)").unwrap().to_hex(), Color::parse_css("lch(50 0 0)").unwrap().to_hex());
assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 255]);
// A missing alpha is zero like any other missing component (CSS Color 4 §4.4), so it is
// transparent; only an *omitted* alpha defaults to opaque.
assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 0]);
assert_eq!(Color::parse_css("oklch(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]);
}
#[test]
+55 -24
View File
@@ -158,14 +158,9 @@ impl Color {
}
if let Some(inner) = t.strip_prefix("rgba(").or_else(|| t.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')) {
let parts = css_args(inner)?;
let num = |i: usize| -> Option<f32> {
let p = parts.get(i)?;
if let Some(pc) = p.strip_suffix('%') {
pc.trim().parse::<f32>().ok().map(|v| v / 100.0)
} else {
p.parse::<f32>().ok().map(|v| v / 255.0)
}
};
// A channel is a number of 255, a percentage or `none`; out-of-range values (a number
// too big for f32 included) clamp in `Color::new`, as CSS Color 4 §5.1 asks.
let num = |i: usize| css_fraction(parts.get(i)?, 255.0);
let alpha = match parts.get(3) {
Some(a) => parse_alpha(a)?,
None => 1.0,
@@ -177,10 +172,12 @@ impl Color {
}
if let Some(inner) = t.strip_prefix("hsla(").or_else(|| t.strip_prefix("hsl(")).and_then(|r| r.strip_suffix(')')) {
let parts = css_args(inner)?;
let h = parts.first()?.trim_end_matches("deg").parse::<f32>().ok()?;
let s = parts.get(1)?.trim_end_matches('%').parse::<f32>().ok()? / 100.0;
let l = parts.get(2)?.trim_end_matches('%').parse::<f32>().ok()? / 100.0;
if !(h.is_finite() && s.is_finite() && l.is_finite()) {
// The hue takes every CSS angle unit; saturation and lightness are percentages, numbers
// read as percentages (CSS Color 4 §7) or `none`.
let h = css_hue(parts.first()?)?;
let s = css_fraction(parts.get(1)?, 100.0)?;
let l = css_fraction(parts.get(2)?, 100.0)?;
if !(s.is_finite() && l.is_finite()) {
return None;
}
let alpha = match parts.get(3) {
@@ -209,14 +206,23 @@ impl Color {
/// CSS `rgba(...)` / hex text for copy-as-CSS.
pub fn to_css(self) -> String {
let [r, g, b, _] = self.to_rgba8();
if self.a >= 0.999 {
let [r, g, b, a8] = self.to_rgba8();
let a = clamp01(self.a);
if a >= 0.999 {
return self.to_css_hex();
}
// Two decimals when they keep the 8-bit alpha, three otherwise (near-transparent colours).
let a8 = |a: f32| (a.clamp(0.0, 1.0) * 255.0).round() as u8;
let short = format!("{:.2}", self.a);
let alpha = if short.parse::<f32>().is_ok_and(|v| a8(v) == a8(self.a)) { short } else { format!("{:.3}", self.a) };
// The fewest decimals that read back as the same 8-bit alpha: two, else three, else three
// of the 8-bit value itself (within half a step of it, so it always reads back).
let keeps = |s: &str| s.parse::<f32>().is_ok_and(|v| (v * 255.0).round() as u8 == a8);
let two = format!("{a:.2}");
let three = format!("{a:.3}");
let alpha = if keeps(&two) {
two
} else if keeps(&three) {
three
} else {
format!("{:.3}", f32::from(a8) / 255.0)
};
format!("rgba({r}, {g}, {b}, {alpha})")
}
@@ -268,19 +274,42 @@ fn css_polar(inner: &str, l_full: f32, c_full: f32) -> Option<([f32; 3], f32)> {
let l = css_number(parts.first()?, l_full)?;
let c = css_number(parts.get(1)?, c_full)?;
let h = css_hue(parts.get(2)?)?;
let alpha = match parts.get(3).map(String::as_str) {
None | Some("none") => 1.0,
let alpha = match parts.get(3) {
None => 1.0,
Some(a) => parse_alpha(a)?,
};
Some(([l, c, h], alpha))
}
/// A CSS `<number>` as f32: a sign, digits, a decimal point and an exponent only. Rust's float
/// parser also reads `inf`, `infinity` and `nan`, which are identifiers in CSS, not numbers. A
/// value too big for f32 comes back as an infinity for the caller to clamp or refuse.
fn css_f32(s: &str) -> Option<f32> {
if !s.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E')) {
return None;
}
s.parse::<f32>().ok()
}
/// A CSS number, percentage or `none` as a fraction of one: a percentage is of 100, a bare number
/// of `number_full` (255 for an rgb() channel, 100 for hsl() saturation and lightness, 1 for
/// alpha) and `none` is 0 (CSS Color 4 §4.4).
fn css_fraction(p: &str, number_full: f32) -> Option<f32> {
if p == "none" {
return Some(0.0);
}
match p.strip_suffix('%') {
Some(pc) => Some(css_f32(pc)? / 100.0),
None => Some(css_f32(p)? / number_full),
}
}
/// A CSS number, a percentage of `full` or `none` (0); finite only.
fn css_number(p: &str, full: f32) -> Option<f32> {
let v = match p.strip_suffix('%') {
_ if p == "none" => 0.0,
Some(pc) => pc.trim().parse::<f32>().ok()? / 100.0 * full,
None => p.parse::<f32>().ok()?,
Some(pc) => css_f32(pc)? / 100.0 * full,
None => css_f32(p)?,
};
v.is_finite().then_some(v)
}
@@ -294,12 +323,14 @@ fn css_hue(p: &str) -> Option<f32> {
.into_iter()
.find_map(|(unit, k)| p.strip_suffix(unit).map(|n| (n, k)))
.unwrap_or((p, 1.0));
let v = num.parse::<f32>().ok()? / per_degree;
let v = css_f32(num)? / per_degree;
v.is_finite().then_some(v)
}
/// A CSS `<alpha-value>`: a number, a percentage or `none` (0: a missing alpha is transparent, CSS
/// Color 4 §4.4); finite only. An *omitted* alpha is the caller's default of 1.
fn parse_alpha(a: &str) -> Option<f32> {
let v = if let Some(pc) = a.strip_suffix('%') { pc.parse::<f32>().ok().map(|v| v / 100.0) } else { a.parse::<f32>().ok() }?;
let v = css_fraction(a, 1.0)?;
v.is_finite().then_some(v)
}
+99
View File
@@ -195,3 +195,102 @@ fn css_rejects_empty_arguments() {
assert!(Color::parse_css("rgb(255 0 0 / 50%)").is_some());
assert!(Color::parse_css("hsl(120deg 50% 50%)").is_some());
}
#[test]
fn css_rgb_rejects_non_numeric_channels() {
// `nan`, `inf` and `infinity` are identifiers, not CSS numbers; the hsl(), lch() and oklch()
// branches and the alpha already refuse them, and so must rgb() channels (which previously read
// `rgb(nan, 0, 0)` as black and `rgb(inf, 0, 0)` as red).
for s in ["rgb(nan, 0, 0)", "rgb(inf, 0, 0)", "rgb(0, 0, infinity)", "rgb(-inf, 0, 0)", "rgb(nan%, 0, 0)", "rgb(NaN 0 0)", "rgba(0, 0, 0, inf)"] {
assert_eq!(Color::parse_css(s), None, "{s}");
}
// A genuine number that overflows f32 is still a number and clamps (CSS Color 4 §5.1).
assert_eq!(Color::parse_css("rgb(1e40, -1e40, 0)").unwrap().to_rgba8(), [255, 0, 0, 255]);
assert_eq!(Color::parse_css("rgb(+255, .5%, 1E2)").unwrap().to_rgba8(), [255, 1, 100, 255]);
}
#[test]
fn css_hsl_takes_every_hue_unit() {
// CSS Color 4 §4.3: `<hue> = <number> | <angle>`, so turn, grad and rad are as valid as deg.
let cyan = Color::parse_css("hsl(180, 100%, 50%)").unwrap();
assert_eq!(cyan.to_hex(), "00FFFF");
let units =
["hsl(0.5turn, 100%, 50%)", "hsl(200grad 100% 50%)", "hsl(3.1415927rad 100% 50%)", "hsl(180deg 100% 50%)", "hsla(-0.5turn, 100%, 50%, 1)"];
for s in units {
assert_eq!(Color::parse_css(s).map(|c| c.to_hex()), Some(cyan.to_hex()), "{s}");
}
// One unit only: a repeated or stray unit is not a dimension.
for s in ["hsl(120degdeg, 100%, 50%)", "hsl(120, 100%%, 50%)", "hsl(0.5turndeg 100% 50%)", "hsl(deg 100% 50%)"] {
assert_eq!(Color::parse_css(s), None, "{s}");
}
}
#[test]
fn css_none_is_zero_in_every_function() {
// CSS Color 4 §4.4: every modern-syntax component may be `none`, and outside interpolation a
// missing component "behaves as a zero value" -- including a missing alpha, which renders
// fully transparent.
assert_eq!(Color::parse_css("rgb(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]);
assert_eq!(Color::parse_css("rgb(255 none none)").unwrap().to_rgba8(), [255, 0, 0, 255]);
assert_eq!(Color::parse_css("rgb(255 0 0 / none)").unwrap().to_rgba8(), [255, 0, 0, 0]);
assert_eq!(Color::parse_css("hsl(none 100% 50%)").unwrap().to_hex(), "FF0000");
assert_eq!(Color::parse_css("hsl(120 none 50%)").unwrap().to_hex(), "808080");
assert_eq!(Color::parse_css("hsl(120 100% none)").unwrap().to_hex(), "000000");
assert_eq!(Color::parse_css("hsl(120 100% 50% / none)").unwrap().to_rgba8(), [0, 255, 0, 0]);
assert_eq!(Color::parse_css("oklch(0.5 0.1 20 / none)").unwrap().a, 0.0);
assert_eq!(Color::parse_css("lch(50 50 50 / none)").unwrap().a, 0.0);
// An omitted alpha still defaults to opaque.
assert_eq!(Color::parse_css("rgb(none none none)").unwrap().a, 1.0);
}
#[test]
fn to_css_keeps_the_8_bit_alpha_for_any_alpha() {
// Three decimals of the alpha can still round across an 8-bit step (0.0055 -> "0.006" reads
// back as 2/255, not 1/255); the text must always read back to the same 8-bit alpha.
for i in 0..=10_000u32 {
let a = i as f32 / 10_000.0;
let c = Color::new(0.1, 0.2, 0.3, a);
let css = c.to_css();
assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some(c.to_rgba8()), "alpha {a}: {css}");
}
let c = Color::new(0.1, 0.2, 0.3, 0.0055);
assert_eq!(Color::parse_css(&c.to_css()).unwrap().to_rgba8()[3], 1, "{}", c.to_css());
// Still the short forms where they are exact.
assert_eq!(Color::new(1.0, 0.0, 0.0, 0.5).to_css(), "rgba(255, 0, 0, 0.50)");
assert_eq!(Color::from_rgba8(255, 0, 0, 85).to_css(), "rgba(255, 0, 0, 0.333)");
}
#[test]
fn to_css_sanitizes_an_unclamped_alpha() {
// The RGB channels go through `to_rgba8` and are sanitized; the alpha must be too, or a colour
// built field-by-field prints `rgba(0, 0, 0, NaN)` / `rgba(0, 0, 0, -0.50)`, which is not CSS.
for a in [f32::NAN, -0.5, f32::NEG_INFINITY] {
let c = Color { r: 0.0, g: 0.0, b: 0.0, a };
let css = c.to_css();
assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some([0, 0, 0, 0]), "alpha {a}: {css}");
}
assert_eq!(Color { r: 1.0, g: 0.0, b: 0.0, a: f32::INFINITY }.to_css(), "#FF0000");
}
#[test]
fn css_hue_wraps_a_whole_turn_and_calc_is_not_a_number() {
// A hue is an angle (CSS Color 4 §4.3): a whole turn (360, 1turn, 400grad, 2 pi rad) is 0 and a
// negative hue counts back from it, in hsl() and in the polar spaces alike. `calc()` is not
// read, so `calc(NaN)` and `calc(infinity)` are refused like any other non-number rather than
// read as 0 or clamped.
let red = Color::parse_css("hsl(0 100% 50%)").unwrap().to_rgba8();
for s in ["hsl(360 100% 50%)", "hsl(1turn 100% 50%)", "hsl(400grad 100% 50%)", "hsl(6.2831855rad 100% 50%)", "hsl(-1turn 100% 50%)"] {
assert_eq!(Color::parse_css(s).map(|c| c.to_rgba8()), Some(red), "{s}");
}
let violet = Color::parse_css("hsl(270 100% 50%)").unwrap().to_rgba8();
for s in ["hsl(-90deg 100% 50%)", "hsl(-0.25turn 100% 50%)", "hsl(-100grad 100% 50%)", "hsl(630 100% 50%)"] {
assert_eq!(Color::parse_css(s).map(|c| c.to_rgba8()), Some(violet), "{s}");
}
assert_eq!(Color::parse_css("oklch(0.5 0.1 1turn)").map(|c| c.to_rgba8()), Color::parse_css("oklch(0.5 0.1 0)").map(|c| c.to_rgba8()));
assert_eq!(Color::parse_css("lch(50 50 400grad)").map(|c| c.to_rgba8()), Color::parse_css("lch(50 50 0)").map(|c| c.to_rgba8()));
assert_eq!(Color::parse_css("oklch(0.5 0.1 -90deg)").map(|c| c.to_rgba8()), Color::parse_css("oklch(0.5 0.1 270)").map(|c| c.to_rgba8()));
for s in ["hsl(calc(NaN) 100% 50%)", "rgb(calc(infinity) 0 0)", "rgb(0 0 0 / calc(1))", "oklch(0.5 0.1 calc(20deg))", "hsl(calc(1turn) 100% 50%)"]
{
assert_eq!(Color::parse_css(s), None, "{s}");
}
}
+20 -6
View File
@@ -28,9 +28,15 @@ impl RouteEnd {
/// How far an elbow connector going around the objects it joins keeps from them.
const ROOM: f64 = 24.0;
/// The points a connector runs through from `from` to `to`: from the middle of the side of each
/// box facing the other end (or the side it names), straight, in right angles, or (curved) its two
/// ends with the curve's two control points between them. `None` when a point isn't finite.
/// How far outside the border a connector attached to a side starts and ends (#1916): the stroke's
/// round cap never lies on the fill, and elbows leaving one side share their first run along the
/// side's normal (curves leave tangent to it), as FigJam's connectors do.
pub const END_GAP: f64 = 4.0;
/// The points a connector runs through from `from` to `to`: from [`END_GAP`] outside the middle of
/// the side of each box facing the other end (or the side it names), straight, in right angles, or
/// (curved) its two ends with the curve's two control points between them. `None` when a point isn't
/// finite.
pub fn route_points(from: RouteEnd, to: RouteEnd, routing: Routing) -> Option<Vec<Point>> {
let (p0, s0) = attach(from, to.centre());
let (p1, s1) = attach(to, from.centre());
@@ -66,6 +72,12 @@ pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option<Side>, Option<Sid
(attach(from, to.centre()).1, attach(to, from.centre()).1)
}
/// Where a connector's ends attach, as routed now: the points [`ConnectorPath::Runs`] is measured
/// from the middle of.
pub fn attach_points(from: RouteEnd, to: RouteEnd) -> (Point, Point) {
(attach(from, to.centre()).0, attach(to, from.centre()).0)
}
/// The route's path handles: one for each run of an elbow and one for a curve, with the portion
/// of the path each moves and where it sits.
pub fn path_handles(pts: &[Point], routing: Routing) -> Vec<(usize, Point)> {
@@ -90,8 +102,9 @@ pub fn reshaped(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&Co
}
}
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another.
const MAX_RUNS: usize = 64;
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another, and an
/// importer leaves a saved one to the router.
pub const MAX_RUNS: usize = 64;
/// The runs of the right-angled route `pts` with run `portion` moved to `p`.
fn reshaped_runs(pts: &[Point], portion: usize, p: Point) -> Option<ConnectorPath> {
@@ -169,8 +182,9 @@ fn attach(e: RouteEnd, other: Point) -> (Point, Option<Side>) {
RouteEnd::Point(p) => (p, None),
RouteEnd::Box(b, side) => {
let side = named_or_facing(b, side, other);
(side.point(b), Some(side))
(side.point(b) + side.normal() * END_GAP, Some(side))
}
// Placed by hand: the point is the user's, gap or not.
RouteEnd::On(b, side, p) => (p, Some(named_or_facing(b, side, other))),
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Connector routes (`board_route`): where an end attached to a side starts (#1916).
use figcraft_geom::{Point, Rect};
use crate::board::{Routing, Side};
use crate::board_route::{END_GAP, RouteEnd, route_points};
fn shape(x: f64, y: f64) -> Rect {
Rect::new(x, y, x + 100.0, y + 60.0)
}
/// An end attached to a side starts `END_GAP` outside the middle of that side, not on the border,
/// so the stroke never lies on the fill (#1916: FigJam starts the line a few pixels outside).
#[test]
fn an_attached_end_starts_outside_the_border() {
let (a, b) = (shape(0.0, 0.0), shape(300.0, 0.0));
for routing in [Routing::Straight, Routing::Elbow, Routing::Curved] {
let pts = route_points(RouteEnd::Box(a, Side::Auto), RouteEnd::Box(b, Side::Auto), routing).unwrap();
assert_eq!(pts.first().copied(), Some(Point::new(100.0 + END_GAP, 30.0)), "{routing:?}: leaves the right side");
assert_eq!(pts.last().copied(), Some(Point::new(300.0 - END_GAP, 30.0)), "{routing:?}: arrives at the left side");
}
// A named side, and the gap along its own normal.
let pts = route_points(RouteEnd::Box(a, Side::Bottom), RouteEnd::Point(Point::new(50.0, 200.0)), Routing::Straight).unwrap();
assert_eq!(pts.first().copied(), Some(Point::new(50.0, 60.0 + END_GAP)));
}
/// Elbows leaving one side share their first run along its normal, and curves leave tangent to it:
/// the second point of each lies straight out of the side.
#[test]
fn connectors_from_one_side_leave_together() {
let a = shape(0.0, 0.0);
let (up, down) = (RouteEnd::Box(shape(300.0, -200.0), Side::Auto), RouteEnd::Box(shape(300.0, 200.0), Side::Auto));
for routing in [Routing::Elbow, Routing::Curved] {
let p = route_points(RouteEnd::Box(a, Side::Right), up, routing).unwrap();
let q = route_points(RouteEnd::Box(a, Side::Right), down, routing).unwrap();
assert_eq!(p[0], q[0], "{routing:?}: the same start");
assert_eq!(p[1].y, p[0].y, "{routing:?}: out along the side's normal first");
assert_eq!(q[1].y, q[0].y, "{routing:?}: out along the side's normal first");
}
}
/// A point placed by hand on the object (`RouteEnd::On`) is the user's: no gap is added.
#[test]
fn a_hand_placed_end_keeps_its_point() {
let a = shape(0.0, 0.0);
let on = Point::new(80.0, 60.0);
let pts = route_points(RouteEnd::On(a, Side::Bottom, on), RouteEnd::Point(Point::new(80.0, 200.0)), Routing::Straight).unwrap();
assert_eq!(pts.first().copied(), Some(on));
}
+1 -1
View File
@@ -79,7 +79,7 @@ impl Style {
pub fn for_each_color_mut(&mut self, f: &mut ColorVisitor) {
match &mut self.kind {
StyleKind::Paint { paints } => paints.iter_mut().for_each(|p| p.for_each_color_mut(f)),
StyleKind::Text { style } => style.for_each_color_mut(f),
StyleKind::Text { style, .. } => style.for_each_color_mut(f),
StyleKind::Effect { effects } => effects.iter_mut().for_each(|e| e.for_each_color_mut(f)),
StyleKind::Grid { grids } => grids.iter_mut().for_each(|g| f(&mut g.color)),
}
+20 -2
View File
@@ -75,10 +75,10 @@ fn glass_fields_take_bound_numbers_as_the_panel_shows_them() {
}
assert_eq!((g.light_angle, g.light_intensity, g.refraction, g.depth, g.dispersion, g.frost, g.splay), (30.0, 0.25, 0.4, 12.0, 0.1, 8.0, 0.5));
// Out of range: clamped to the field's range.
for (field, x) in [("lightAngle", 270.0), ("lightIntensity", 250.0), ("depth", 0.0), ("radius", 150.0), ("splay", -5.0)] {
for (field, x) in [("lightIntensity", 250.0), ("depth", 0.0), ("radius", 150.0), ("splay", -5.0)] {
assert!(g.set_bound(field, x), "{field}");
}
assert_eq!((g.light_angle, g.light_intensity, g.depth, g.frost, g.splay), (180.0, 1.0, 1.0, Glass::MAX_FROST, 0.0));
assert_eq!((g.light_intensity, g.depth, g.frost, g.splay), (1.0, 1.0, Glass::MAX_FROST, 0.0));
// A field glass doesn't have, or a value that isn't a number, changes nothing.
let before = g.clone();
assert!(!g.set_bound("spread", 3.0));
@@ -90,6 +90,24 @@ fn glass_fields_take_bound_numbers_as_the_panel_shows_them() {
}
}
#[test]
fn a_bound_light_angle_turns_round_instead_of_stopping() {
// An angle past ±180 is the same direction a turn away (270 is -90), not the end of the range.
for (x, want) in [(270.0, -90.0), (-270.0, 90.0), (540.0, 180.0), (-180.0, 180.0), (180.0, 180.0), (720.5, 0.5), (-360.0, 0.0), (-45.0, -45.0)] {
let mut g = Glass::default();
assert!(g.set_bound("lightAngle", x), "{x}");
assert_eq!(g.light_angle, want, "{x}");
}
// A whole turn back is 0, not -0, so a saved file says 0.
let mut g = Glass::default();
assert!(g.set_bound("lightAngle", -360.0));
assert!(g.light_angle == 0.0 && g.light_angle.is_sign_positive());
// A huge angle still lands in range.
let mut g = Glass::default();
assert!(g.set_bound("lightAngle", 1e300));
assert!((-180.0..=180.0).contains(&g.light_angle) && g.light_angle != -180.0);
}
#[test]
fn effect_colours() {
let mut e = Effect::noise();
+19 -7
View File
@@ -28,8 +28,9 @@ pub fn shape_path(n: &Node) -> Option<BezPath> {
p
}
NodeKind::Vector { network } => {
let f = network.fill_path();
if f.elements().is_empty() { network.stroke_path() } else { f }
let net = drawn_network(network, c.smoothing);
let f = net.fill_path();
if f.elements().is_empty() { net.stroke_path() } else { f }
}
NodeKind::Text(_) => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0),
NodeKind::Page { .. } | NodeKind::Group | NodeKind::BooleanOp { .. } => return None,
@@ -39,11 +40,21 @@ pub fn shape_path(n: &Node) -> Option<BezPath> {
/// The open/closed path strokes follow (vector networks stroke every segment, filled or not).
pub fn stroke_geometry(n: &Node) -> Option<BezPath> {
match &n.kind {
NodeKind::Vector { network } => Some(network.stroke_path()),
NodeKind::Vector { network } => Some(drawn_network(network, n.corners.smoothing).stroke_path()),
_ => shape_path(n),
}
}
/// A vector's `network` as the layer draws it: rounded points drawn in with the layer's corner
/// `smoothing` (see [`VectorNetwork::rounded_smoothed`](crate::VectorNetwork::rounded_smoothed)),
/// or the network itself when no point is rounded.
pub fn drawn_network(network: &crate::VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, crate::VectorNetwork> {
match network.rounded_smoothed(smoothing) {
Some(r) => std::borrow::Cow::Owned(r),
None => std::borrow::Cow::Borrowed(network),
}
}
/// Whether the shape's path is closed (fills apply).
pub fn is_closed(n: &Node) -> bool {
match &n.kind {
@@ -75,8 +86,8 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
n.local_rect().inflate(tol_l, tol_l).contains(lp)
}
NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => {
let rounded = network.rounded();
let net = rounded.as_ref().unwrap_or(network);
let drawn = drawn_network(network, n.corners.smoothing);
let net = drawn.as_ref();
if !outline {
for (i, region) in net.regions.iter().enumerate().rev() {
let paints = region.fills.as_deref().unwrap_or(&n.fills);
@@ -96,10 +107,11 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
}
/// Whether the fill of `n`, drawn as `path`, covers `lp` (vectors follow the rule of
/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains): even-odd when any region asks for it).
/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains) on the network as drawn: even-odd when any
/// region asks for it).
fn fills_point(n: &Node, path: &BezPath, lp: Point) -> bool {
match &n.kind {
NodeKind::Vector { network } => network.fill_contains(lp),
NodeKind::Vector { network } => drawn_network(network, n.corners.smoothing).fill_contains(lp),
_ => path.winding(lp) != 0,
}
}
+23 -4
View File
@@ -14,6 +14,8 @@
//! space 0. The session server accepts a new object only with an id in its creator's space or
//! space 0, so two people never make the same id.
use std::collections::BTreeSet;
use crate::{CollectionId, Document, ModeId, NodeId, StyleId, VariableId};
/// What style ids start with.
@@ -74,25 +76,42 @@ impl Document {
/// A new style id.
pub fn new_style_id(&mut self) -> StyleId {
let taken: Vec<u64> = self.styles.iter().filter_map(|s| id_number(&s.id, STYLE_ID_PREFIX)).collect();
self.new_style_id_avoiding(&BTreeSet::new())
}
/// A new style id that is none of `avoid` either: ids of styles about to come in with a file
/// being imported.
pub fn new_style_id_avoiding(&mut self, avoid: &BTreeSet<StyleId>) -> StyleId {
let taken: Vec<u64> = self.styles.iter().map(|s| &s.id).chain(avoid).filter_map(|id| id_number(id, STYLE_ID_PREFIX)).collect();
if let Some(n) = self.session_number(taken) {
return format!("{STYLE_ID_PREFIX}{n}");
}
(self.styles.len() + 1..)
.map(|k| format!("{STYLE_ID_PREFIX}{k}"))
.find(|id| self.style(id).is_none())
.find(|id| self.style(id).is_none() && !avoid.contains(id))
.unwrap_or_else(|| format!("{STYLE_ID_PREFIX}0"))
}
/// A new variable id.
pub fn new_variable_id(&mut self) -> VariableId {
let taken: Vec<u64> = self.variables.variables.iter().filter_map(|v| id_number(&v.id, VARIABLE_ID_PREFIX)).collect();
self.new_variable_id_avoiding(&BTreeSet::new())
}
/// A new variable id that is none of `avoid` either (see [`Self::new_style_id_avoiding`]).
pub fn new_variable_id_avoiding(&mut self, avoid: &BTreeSet<VariableId>) -> VariableId {
let taken = self.variables.variables.iter().map(|v| &v.id).chain(avoid).filter_map(|id| id_number(id, VARIABLE_ID_PREFIX)).collect();
self.new_numbered_id(VARIABLE_ID_PREFIX, taken)
}
/// A new variable collection id.
pub fn new_collection_id(&mut self) -> CollectionId {
let taken: Vec<u64> = self.variables.collections.iter().filter_map(|c| id_number(&c.id, COLLECTION_ID_PREFIX)).collect();
self.new_collection_id_avoiding(&BTreeSet::new())
}
/// A new variable collection id that is none of `avoid` either (see
/// [`Self::new_style_id_avoiding`]).
pub fn new_collection_id_avoiding(&mut self, avoid: &BTreeSet<CollectionId>) -> CollectionId {
let taken = self.variables.collections.iter().map(|c| &c.id).chain(avoid).filter_map(|id| id_number(id, COLLECTION_ID_PREFIX)).collect();
self.new_numbered_id(COLLECTION_ID_PREFIX, taken)
}
+16
View File
@@ -1,6 +1,8 @@
//! Ids of styles, variables, collections, modes and comments: unchanged outside a live session,
//! from the client's own space during one.
use std::collections::BTreeSet;
use crate::ids::{COLLECTION_ID_PREFIX, id_number, id_space, mode_number, space_of};
use crate::{Collection, Comment, Document, Message, Mode, NodeId, NodeKind, Style, StyleKind};
@@ -93,6 +95,20 @@ fn ids_of_the_space_already_in_the_document_stay_taken() {
assert_eq!(e.new_style_id(), format!("S:{}", C3 | 1));
}
#[test]
fn new_ids_can_avoid_ids_about_to_come_in() {
let mut d = Document::new("a");
d.styles.push(style("S:1"));
let avoid: BTreeSet<String> = ["S:2", "S:3", "VariableID:4", "VariableCollectionId:2", "lib:VariableID:9"].map(String::from).into();
assert_eq!(d.new_style_id_avoiding(&avoid), "S:4");
assert_eq!(d.new_variable_id_avoiding(&avoid), "VariableID:5");
assert_eq!(d.new_collection_id_avoiding(&avoid), "VariableCollectionId:3");
// In a session the numbers come from the client's space, above those of it to avoid.
let avoid: BTreeSet<String> = [format!("VariableID:{}", C3 | 7)].into();
d.set_client_id(3);
assert_eq!(d.new_variable_id_avoiding(&avoid), format!("VariableID:{}", C3 | 8));
}
#[test]
fn the_highest_space_counts_every_kind_of_id() {
let mut d = Document::new("a");
+22 -9
View File
@@ -27,7 +27,7 @@ pub mod vector_faces;
pub mod vector_regions;
pub use board::*;
pub use board_route::{RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
pub use colors::*;
pub use comments::*;
pub use facilitation::*;
@@ -598,7 +598,14 @@ impl Document {
let Some(n) = self.node(id) else { return Affine::IDENTITY };
let mut t = n.transform;
let mut parent = n.parent;
// More hops than nodes means the parent chain loops (a restored snapshot can leave one):
// stop rather than spin.
let mut hops = 0;
while let Some(p) = parent.and_then(|p| self.node(p)).filter(|p| p.kind.bounds_follow_children()) {
hops += 1;
if hops > self.nodes.len() {
break;
}
t = p.transform * t;
parent = p.parent;
}
@@ -760,16 +767,20 @@ impl Document {
/// children only within their mask). A group, or an unclipped frame past its box, is what its
/// children show grown by its effects, which apply to all of it.
pub fn world_render_bounds(&self, id: NodeId) -> Option<Rect> {
self.render_bounds_at(id, 0)
// A tree visits each node once; a child list deserialized with repeats (a graph) is cut off
// after twice the document's node count rather than walked in full.
self.render_bounds_at(id, 0, &std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8)))
}
fn render_bounds_at(&self, id: NodeId, depth: usize) -> Option<Rect> {
fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell<usize>) -> Option<Rect> {
let n = self.node(id)?;
let own = n.own_paint_bounds(self.world_transform(id));
if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH {
let visit = left.get();
left.set(visit.saturating_sub(1));
if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH || visit == 0 {
return Some(own);
}
Some(match (self.children_render_bounds(n, depth + 1), &n.kind) {
Some(match (self.children_render_bounds(n, depth + 1, left), &n.kind) {
(Some(kids), NodeKind::Group) => n.grow_by_effects(kids),
// An unclipped frame's effects apply to its children too, past its box included.
(Some(kids), _) => own.union(n.grow_by_effects(kids)),
@@ -778,15 +789,15 @@ impl Document {
}
/// What `n`'s visible children show, together: each mask's run within the mask's bounds.
fn children_render_bounds(&self, n: &Node, depth: usize) -> Option<Rect> {
fn children_render_bounds(&self, n: &Node, depth: usize, left: &std::cell::Cell<usize>) -> Option<Rect> {
let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask);
let mut out: Option<Rect> = None;
for run in self.paint_runs(n) {
let ids = n.children.get(run).unwrap_or(&[]);
let mask = ids.first().copied().filter(|m| self.node(*m).is_some_and(|c| c.is_mask && c.visible));
let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth)).reduce(|a, b| a.union(b));
let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, left)).reduce(|a, b| a.union(b));
let r = match mask {
Some(m) => r.zip(self.render_bounds_at(m, depth)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0),
Some(m) => r.zip(self.render_bounds_at(m, depth, left)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0),
None => r,
};
out = match (out, r) {
@@ -1223,7 +1234,7 @@ impl Document {
.styles
.iter()
.filter_map(|s| match &s.kind {
StyleKind::Text { style } => Some((s.id.clone(), style.clone())),
StyleKind::Text { style, .. } => Some((s.id.clone(), style.clone())),
_ => None,
})
.collect();
@@ -1303,6 +1314,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap<NodeId, NodeId>) {
#[cfg(test)]
mod blur_tests;
#[cfg(test)]
mod board_route_tests;
#[cfg(test)]
mod board_shape_tests;
#[cfg(test)]
mod boolean_hit_tests;
+28 -8
View File
@@ -416,9 +416,13 @@ impl NodeKind {
self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. })
}
/// Kinds whose rounded corners are drawn with corner smoothing (a vector's rounded points are drawn without it).
/// Kinds whose rounded corners are drawn with corner smoothing: a vector only when its network
/// has a closed region (an open path's rounded points are drawn without it).
pub fn has_corner_smoothing(&self) -> bool {
self.has_corner_radius() && !matches!(self, NodeKind::Vector { .. })
match self {
NodeKind::Vector { network } => !network.regions.is_empty(),
_ => self.has_corner_radius(),
}
}
pub fn text(&self) -> Option<&TextData> {
@@ -944,8 +948,12 @@ impl Node {
if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w };
// Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown
// box; an arc's corners don't.
let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter
let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
// A dash's square end stands out along the path as far as the band does across it:
// its corners reach √2 times as far from the path, past the box round a curve.
let square_dashes = !self.stroke.dashes.is_empty() && self.stroke.band_caps().contains(&StrokeCap::Square);
let corners = if square_dashes { miter.max(std::f64::consts::SQRT_2) } else { miter };
base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * corners
} else {
0.0
};
@@ -960,9 +968,10 @@ impl Node {
!(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke()))
}
/// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc
/// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides.
fn grows_by_exactly_its_spread(&self) -> bool {
/// Whether this node's outline has no sharp corners (right-angled ones aside), so mitres along
/// it end on its box grown by as much: a box or a whole ellipse. An arc (an ellipse that doesn't
/// go all the way round) has corners where its ends meet its sides.
fn outline_mitres_end_on_its_box(&self) -> bool {
match self.kind {
NodeKind::Rectangle | NodeKind::Section { .. } => true,
NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep),
@@ -970,9 +979,20 @@ impl Node {
}
}
/// Whether a spread grows this node by exactly the spread: its outline mitres end on its box
/// (see [`Node::outline_mitres_end_on_its_box`]), and so does its stroke. A dashed stroke is
/// cut into dashes with corners wherever they fall round the outline, and a width profile or a
/// brush can give the stroke corners of its own, which the spread mitres out.
fn grows_by_exactly_its_spread(&self) -> bool {
let s = &self.stroke;
let cornered = self.has_visible_stroke() && (!s.dashes.is_empty() || s.profile().is_some() || s.brush.is_some());
!cornered && self.outline_mitres_end_on_its_box()
}
/// How much further than its spread a drop shadow can reach at the outline's sharp corners:
/// spread moves the edges out in parallel and they meet in a mitre (see
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread.
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread,
/// unless their stroke has corners (see [`Node::grows_by_exactly_its_spread`]).
fn spread_miter_reach(&self) -> f64 {
if self.grows_by_exactly_its_spread() {
return 0.0;
+88 -9
View File
@@ -1,6 +1,6 @@
//! Node property types: strokes, effects, corners, constraints, auto layout, grids, exports.
use figcraft_color::{BlendMode, Color};
use figcraft_color::{BlendMode, Color, ColorProfile};
use serde::{Deserialize, Serialize};
/// Where a stroke sits relative to the shape edge.
@@ -146,10 +146,16 @@ impl Brush {
}
}
/// How much wider than the stroke weight the brush can paint (larger copies, strays).
pub fn reach_factor(&self) -> f64 {
/// The farthest a built-in brush shape reaches from the path, in stroke weights: the ink
/// brush's ragged edges stand a little past half the weight.
pub const SHAPE_REACH: f64 = 0.54;
/// How much wider than the stroke weight the brush can paint where a width profile scales it
/// at most `scale`: its shapes' edges and larger copies, which the profile scales, and strays,
/// which it doesn't.
pub fn reach_factor(&self, scale: f64) -> f64 {
let b = self.sanitized();
1.0 + b.size_jitter + 2.0 * b.scatter
2.0 * Self::SHAPE_REACH * (1.0 + b.size_jitter) * scale + 2.0 * b.scatter
}
}
@@ -188,7 +194,8 @@ impl StrokeProps {
/// The widest the stroke gets anywhere along the path (the weight, scaled by a width profile
/// and widened by a brush's reach).
pub fn max_weight(&self) -> f64 {
self.profile().map_or(self.weight, |p| self.weight * p.max_scale()) * self.brush.as_ref().map_or(1.0, Brush::reach_factor)
let scale = self.profile().map_or(1.0, WidthProfile::max_scale);
self.weight * self.brush.as_ref().map_or(scale, |b| b.reach_factor(scale))
}
/// The miter limit as the angle (degrees) below which joins bevel: limit = 1 / sin(angle / 2),
@@ -663,7 +670,9 @@ pub struct Glass {
/// Blur of the backdrop (a blur radius, document units, 0–[`Self::MAX_FROST`]).
pub frost: f64,
/// Which way the curved edge bends the backdrop: towards the shape's core (0; along the edge's
/// normal for a shape too big to work one out) to away from the layer's centre (1).
/// normal for a shape too big to work one out) to away from the centre of the layer's bounds
/// (1; on a ring or an L, whose centre lies outside the shape, an inner edge bends towards the
/// hole, as the reference tool's does).
pub splay: f64,
}
@@ -673,6 +682,13 @@ impl Default for Glass {
}
}
/// `deg` (finite) as the same direction within -180 (exclusive) to 180 degrees.
fn wrap_degrees(deg: f64) -> f64 {
// `+ 0.0`: -0 reads as 0, so a saved file says 0.
let a = deg.rem_euclid(360.0) + 0.0;
if a > 180.0 { a - 360.0 } else { a }
}
impl Glass {
/// The most frost a glass takes, as the reference tool's Frost field (0–100).
pub const MAX_FROST: f64 = 100.0;
@@ -682,15 +698,16 @@ impl Glass {
/// Sets `field` (one of [`Self::BOUND_FIELDS`]) from a bound number variable, read as the
/// Design panel's field shows it: intensity, refraction, dispersion and splay in percent, the
/// frost as `radius`, each clamped to the field's range. False for a field glass doesn't have
/// or a value that isn't finite (nothing changes).
/// frost as `radius`, each clamped to the field's range, and the light angle turned into
/// -180–180 (270 is -90, the same way). False for a field glass doesn't have or a value that
/// isn't finite (nothing changes).
pub fn set_bound(&mut self, field: &str, x: f64) -> bool {
if !x.is_finite() {
return false;
}
let pct = (x / 100.0).clamp(0.0, 1.0);
match field {
"lightAngle" => self.light_angle = x.clamp(-180.0, 180.0),
"lightAngle" => self.light_angle = wrap_degrees(x),
"lightIntensity" => self.light_intensity = pct,
"refraction" => self.refraction = pct,
"depth" => self.depth = x.clamp(1.0, 1000.0),
@@ -1518,6 +1535,54 @@ pub struct ExportSetting {
/// Android Vector Drawable: what to do with what a drawable can't hold exactly.
#[serde(skip_serializing_if = "VdCompat::is_default")]
pub vd_compat: VdCompat,
/// PNG, JPG and WebP: the color profile the file is written in. SVG, PDF and XML are always
/// sRGB, whatever this says.
#[serde(skip_serializing_if = "ExportColorProfile::is_default")]
pub color_profile: ExportColorProfile,
/// JPG: the encoder's quality, 1 (smallest file) to 100 (see [`ExportSetting::quality`]).
#[serde(skip_serializing_if = "is_default_quality")]
pub quality: u8,
}
/// The color profile an export setting writes PNG, JPG and WebP files in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum ExportColorProfile {
/// The document's own profile at the time of the export.
#[default]
SameAsFile,
Srgb,
DisplayP3,
}
impl ExportColorProfile {
pub const ALL: [ExportColorProfile; 3] = [ExportColorProfile::SameAsFile, ExportColorProfile::Srgb, ExportColorProfile::DisplayP3];
fn is_default(&self) -> bool {
*self == ExportColorProfile::SameAsFile
}
/// The name commands and files use ("sameAsFile", "srgb", "displayP3").
pub fn key(self) -> &'static str {
match self {
ExportColorProfile::SameAsFile => "sameAsFile",
ExportColorProfile::Srgb => "srgb",
ExportColorProfile::DisplayP3 => "displayP3",
}
}
pub fn from_key(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.key() == s)
}
/// The profile the file is written in when the document is in `file`.
pub fn resolve(self, file: ColorProfile) -> ColorProfile {
match self {
ExportColorProfile::SameAsFile => file,
ExportColorProfile::Srgb => ColorProfile::Srgb,
ExportColorProfile::DisplayP3 => ColorProfile::DisplayP3,
}
}
}
/// How an Android Vector Drawable export handles what the format can't draw exactly (layer
@@ -1568,6 +1633,8 @@ impl Default for ExportSetting {
svg_id_attribute: false,
svg_simplify_stroke: true,
vd_compat: VdCompat::BestEffort,
color_profile: ExportColorProfile::SameAsFile,
quality: ExportSetting::DEFAULT_QUALITY,
}
}
}
@@ -1580,7 +1647,19 @@ fn is_false(b: &bool) -> bool {
!*b
}
fn is_default_quality(q: &u8) -> bool {
*q == ExportSetting::DEFAULT_QUALITY
}
impl ExportSetting {
/// The JPG quality a setting has unless it sets one.
pub const DEFAULT_QUALITY: u8 = 90;
/// The JPG quality made safe: within `1..=100`.
pub fn quality(&self) -> u8 {
self.quality.clamp(1, 100)
}
/// The row adding a setting after `last` creates: 1x first, then one scale step up with a
/// matching "@2x"-style suffix.
pub fn next_after(last: Option<&ExportSetting>) -> ExportSetting {
+17 -5
View File
@@ -1,7 +1,7 @@
//! Shared styles and variables.
use crate::props::{Effect, LayoutGrid};
use crate::text::TextStyle;
use crate::text::{ParagraphStyle, TextStyle};
use figcraft_color::{Color, Paint};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
@@ -14,10 +14,22 @@ pub type ModeId = String;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum StyleKind {
Paint { paints: Vec<Paint> },
Text { style: TextStyle },
Effect { effects: Vec<Effect> },
Grid { grids: Vec<LayoutGrid> },
Paint {
paints: Vec<Paint>,
},
Text {
style: TextStyle,
/// What the style sets at the paragraph and layer level (#1829); boxed to keep the enum
/// small.
#[serde(default, skip_serializing_if = "crate::node::is_default")]
paragraph: Box<ParagraphStyle>,
},
Effect {
effects: Vec<Effect>,
},
Grid {
grids: Vec<LayoutGrid>,
},
}
impl StyleKind {
+234
View File
@@ -223,6 +223,7 @@ fn text_case() {
assert_eq!(style_weight("Semi Bold Italic"), 600);
assert_eq!(style_weight("Black"), 900);
assert_eq!(style_weight("Regular"), 400);
assert_eq!(style_weight("Hairline"), 100);
}
#[test]
@@ -596,6 +597,22 @@ fn is_ancestor_holds_for_very_deep_chains() {
assert!(matches!(d.reparent(root, leaf, None), Err(DocError::Cycle(..))));
}
#[test]
fn render_bounds_of_a_doubled_child_list_end_at_once() {
// A file can list a child twice at every level: 2^40 visits if each is walked.
let mut d = Document::new("x");
let mut parent = page(&d);
let mut groups = Vec::new();
for _ in 0..40 {
parent = d.create(parent, NodeKind::Group, "G", 0.0, 0.0, 10.0, 10.0).unwrap();
groups.push(parent);
}
for w in groups.windows(2) {
d.node_mut(w[0]).unwrap().children.push(w[1]);
}
assert!(d.world_render_bounds(groups[0]).is_some());
}
#[test]
fn render_bounds_stop_where_drawing_stops_on_very_deep_chains() {
// A crafted file nests groups far deeper than anything draws (#1062). The leaf counts while
@@ -679,6 +696,210 @@ fn two_segment_closed_loop_rounded_corners() {
assert_eq!(r.regions[0].loops[0].len(), 4, "both arcs are in the loop");
let path = net.fill_path();
assert!(!path.elements().is_empty());
// Both points sit next to the curved segment, so smoothing keeps their plain arcs.
assert_eq!(net.rounded_smoothed(0.6), net.rounded(), "a corner next to a curve keeps the plain arc");
}
/// A closed 100 × 100 square whose corners (top left, top right, bottom right, bottom left) have
/// radii `radii`.
fn rounded_square(radii: [f64; 4]) -> VectorNetwork {
let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
let mut net = VectorNetwork::from_points(&pts, true);
for (v, r) in net.vertices.iter_mut().zip(radii) {
v.radius = r;
}
net
}
/// The area a closed path encloses, whichever way it runs.
fn area_of(p: &figcraft_geom::BezPath) -> f64 {
use figcraft_geom::Shape;
p.area().abs()
}
#[test]
fn closed_vectors_smooth_each_rounded_point_with_its_own_radius() {
use figcraft_geom::Shape;
use figcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
// (point radii, smoothing, derivation): a closed square draws the smoothed rectangle's corners,
// each point keeping its own radius and a point without one staying sharp.
let rows: Vec<([f64; 4], f64, &str)> = vec![
([20.0; 4], 0.6, "one radius on every point"),
([30.0, 0.0, 10.0, 0.0], 0.6, "each point keeps its own radius; points without one stay sharp"),
([12.0; 4], 1.0, "full smoothing"),
([40.0; 4], 0.6, "a corner too large for its edges loses smoothing first"),
];
for (radii, s, why) in rows {
let net = rounded_square(radii);
let smoothed = net.rounded_smoothed(s).unwrap().fill_path();
// The rectangle's corners take [top left, top right, bottom right, bottom left] radii.
let want = area_of(&figcraft_geom::rounded_rect(100.0, 100.0, radii, s));
let got = area_of(&smoothed);
assert!((got - want).abs() < 0.1, "{why}: {got} vs the smoothed rectangle's {want}");
assert!((got - area_of(&net.fill_path())).abs() > 1.0, "{why}: smoothing changes the outline");
let b = smoothed.bounding_box();
assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}");
}
// The sharp points stay on the outline, and the outline has no kinks at the rounded points.
let smoothed = rounded_square([30.0, 0.0, 10.0, 0.0]).rounded_smoothed(0.6).unwrap();
let path = smoothed.fill_path();
for p in [Point::new(100.0, 0.0), Point::new(0.0, 100.0)] {
let d = path.segments().map(|seg| seg.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min);
assert!(d < 1e-12, "the sharp point {p:?} stays a corner");
}
let segs: Vec<_> = path.segments().filter(|seg| seg.arclen(1e-6) > 1e-6).collect();
let mut kinks = 0;
for (i, seg) in segs.iter().enumerate() {
let next = segs[(i + 1) % segs.len()];
let out = (seg.eval(1.0) - seg.eval(1.0 - 1e-6)).normalize();
let into = (next.eval(1e-6) - next.eval(0.0)).normalize();
if out.dot(into) < 0.999 {
kinks += 1;
}
}
assert_eq!(kinks, 2, "only the two sharp points turn without a curve");
assert_eq!(smoothed.regions[0].loops[0].len(), smoothed.segments.len(), "the loop walks every curve once");
}
#[test]
fn corner_smoothing_leaves_open_paths_and_zero_alone() {
let square = rounded_square([20.0; 4]);
assert_eq!(square.rounded_smoothed(0.0), square.rounded(), "no smoothing draws the plain rounded points");
assert_eq!(square.rounded_smoothed(f64::NAN), square.rounded(), "an unusable smoothing draws no smoothing");
// An open path (no closed region) keeps its plain arcs.
let pts = [Point::new(200.0, 0.0), Point::new(250.0, 0.0), Point::new(250.0, 50.0)];
let mut open = VectorNetwork::from_points(&pts, false);
for v in &mut open.vertices {
v.radius = 20.0;
}
assert!(open.regions.is_empty());
assert_eq!(open.rounded_smoothed(0.6), open.rounded(), "an open path takes no smoothing");
// In a network with a closed square and a separate open branch, only the square smooths.
let mut mixed = square.clone();
let base = mixed.vertices.len();
mixed.vertices.extend(open.vertices.iter().copied());
mixed.segments.extend(open.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s }));
let runs = mixed.rounded_smoothed(0.6).unwrap().stroke_runs();
let open_run = runs.iter().find(|r| !r.closed).expect("the open branch");
assert_eq!(open_run.path, open.rounded().unwrap().stroke_runs()[0].path, "the open branch keeps its plain arc");
let closed_run = runs.iter().find(|r| r.closed).expect("the square");
assert_eq!(closed_run.path, square.rounded_smoothed(0.6).unwrap().stroke_runs()[0].path, "the square smooths");
assert_ne!(closed_run.path, square.rounded().unwrap().stroke_runs()[0].path, "the square's smoothed corners differ from its arcs");
}
#[test]
fn smoothed_vector_corners_stay_finite_on_awkward_networks() {
use figcraft_geom::Shape;
// A concave L, a square with a square hole, points with unusable radii and a loop that names a
// missing segment.
let l = [(0.0, 0.0), (100.0, 0.0), (100.0, 40.0), (40.0, 40.0), (40.0, 100.0), (0.0, 100.0)];
let mut concave = VectorNetwork::from_points(&l.map(|(x, y)| Point::new(x, y)), true);
for v in &mut concave.vertices {
v.radius = 1000.0;
}
let mut holed = rounded_square([10.0; 4]);
let hole = rounded_square([5.0; 4]);
let (base, seg_base) = (holed.vertices.len(), holed.segments.len());
holed.vertices.extend(hole.vertices.iter().map(|v| Vertex { x: 25.0 + v.x / 2.0, y: 25.0 + v.y / 2.0, ..*v }));
holed.segments.extend(hole.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s }));
holed.regions[0].loops.push((seg_base..seg_base + hole.segments.len()).collect());
holed.regions[0].winding = WindingRule::EvenOdd;
let mut odd = rounded_square([f64::INFINITY, 10.0, f64::NAN, 10.0]);
odd.regions[0].loops[0].push(99);
for (net, s, why) in [(&concave, 1.0, "concave"), (&holed, 0.6, "holed"), (&odd, 0.6, "odd radii")] {
let drawn = net.rounded_smoothed(s).unwrap();
let b = drawn.fill_path().bounding_box();
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()), "{why}: {b:?}");
assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}");
assert!(!drawn.stroke_path().elements().is_empty(), "{why}");
}
let concave_path = concave.rounded_smoothed(1.0).unwrap().fill_path();
assert_ne!(concave_path, concave.fill_path(), "the concave L smooths");
assert!(concave_path.winding(Point::new(20.0, 60.0)) != 0, "the L stays filled");
let holed_net = holed.rounded_smoothed(0.6).unwrap();
assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole");
}
#[test]
fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() {
// A closed square with rounded points and smoothing: a click between the plain arc and the
// smoothed corner selects the layer only where the smoothed fill is drawn.
let pts = [Point::new(0.0, 0.0), Point::new(1000.0, 0.0), Point::new(1000.0, 1000.0), Point::new(0.0, 1000.0)];
let mut net = VectorNetwork::from_points(&pts, true);
for v in &mut net.vertices {
v.radius = 200.0;
}
let smoothed = net.rounded_smoothed(1.0).unwrap();
let mut d = Document::new("x");
let p = page(&d);
let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap();
let n = d.node_mut(v).unwrap();
n.corners.smoothing = 1.0;
n.strokes.clear();
// Walk the row 20 units below the top edge inward to where each outline starts covering it.
let first_inside = |inside: &dyn Fn(Point) -> bool| (0..5_000).map(|i| f64::from(i) * 0.1).find(|&x| inside(Point::new(x, 20.0)));
let plain = first_inside(&|pt| net.fill_contains(pt)).unwrap();
let drawn = first_inside(&|pt| smoothed.fill_contains(pt)).unwrap();
assert!((plain - drawn).abs() > 5.0, "smoothing moves the corner: plain {plain}, smoothed {drawn}");
let pt = Point::new((plain + drawn) / 2.0, 20.0);
assert_ne!(net.fill_contains(pt), smoothed.fill_contains(pt));
assert_eq!(d.hit_test(p, pt, 0.0, None).is_some(), smoothed.fill_contains(pt), "the click follows the smoothed corner at {pt:?}");
assert_eq!(d.hit_test(p, Point::new(500.0, 500.0), 0.0, None), Some(v));
}
/// A rectangle whose top-right corner was cut off in the vector editor (a diagonal between a point
/// on the top edge and one on the right edge), then rounded: the fill, which the fill and the
/// selection outline draw, is cut by an arc at every point just as the stroke is, however the loop
/// lists its segments and whichever way each one runs (#1951, #1506).
#[test]
fn a_chamfered_rectangles_rounded_fill_is_cut_at_every_point() {
use figcraft_geom::BezPath;
use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
let corners = [Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::new(100.0, 50.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min);
let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::<f64>();
for first in 0..corners.len() {
for backwards in [false, true] {
for flipped in 0..(1u32 << corners.len()) {
let mut net = VectorNetwork::from_points(&corners, true);
for v in &mut net.vertices {
v.radius = 43.0;
}
for (i, s) in net.segments.iter_mut().enumerate() {
if flipped & (1 << i) != 0 {
std::mem::swap(&mut s.a, &mut s.b);
std::mem::swap(&mut s.ta, &mut s.tb);
}
}
let lp = &mut net.regions[0].loops[0];
lp.rotate_left(first);
if backwards {
lp.reverse();
}
let why = format!("loop from segment {first}{}, segments flipped {flipped:05b}", if backwards { " backwards" } else { "" });
let stroke = net.stroke_path();
let fill = net.fill_path();
let region = net.rounded().unwrap().region_path(0).unwrap();
for (i, p) in corners.iter().enumerate() {
assert!(keeps_off(&stroke, *p) > 2.0, "{why}: the stroke is cut at point {i} ({:.2} from it)", keeps_off(&stroke, *p));
assert!(keeps_off(&fill, *p) > 2.0, "{why}: the fill runs into point {i} ({:.2} from it)", keeps_off(&fill, *p));
assert!(keeps_off(&region, *p) > 2.0, "{why}: the region runs into point {i} ({:.2} from it)", keeps_off(&region, *p));
}
assert!(
(length(&fill) - length(&stroke)).abs() < 1e-6,
"{why}: fill {} and stroke {} trace the same outline",
length(&fill),
length(&stroke)
);
assert!(
(length(&region) - length(&stroke)).abs() < 1e-6,
"{why}: region {} and stroke {} trace the same outline",
length(&region),
length(&stroke)
);
}
}
}
}
#[test]
@@ -861,6 +1082,19 @@ fn the_colour_walker_visits_calculation_literals() {
assert_eq!(literal.a, 0.5, "the mix's stored literal was converted like every other colour");
}
#[test]
fn frame_relative_ends_on_a_looping_parent_chain() {
let mut d = Document::new("x");
let p = page(&d);
let f = d.create(p, NodeKind::Group, "F", 0.0, 0.0, 100.0, 100.0).unwrap();
let g = d.create(f, NodeKind::Group, "G", 0.0, 0.0, 10.0, 10.0).unwrap();
let mut v = serde_json::to_value(&d).unwrap();
// F's parent is its own child G (as a restored snapshot can leave things).
v["nodes"][f.to_string()]["parent"] = serde_json::json!(g);
let bad: Document = serde_json::from_value(v).unwrap();
let _ = bad.frame_relative(g);
}
#[test]
fn remove_children_removes_every_subtree_and_keeps_the_parent() {
let mut doc = Document::new("T");
+122 -8
View File
@@ -259,10 +259,24 @@ pub enum ListStyle {
Numbered,
}
/// A paragraph's base direction: by its letters, or forced ("controls are available to override
/// text direction per paragraph", Add right-to-left text).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum TextDirection {
/// The first letter with a direction decides (Unicode rules P2 and P3).
#[default]
Auto,
/// Left to right, whatever the letters.
Ltr,
/// Right to left, whatever the letters.
Rtl,
}
/// Deepest list nesting (levels 0..=MAX_LIST_INDENT).
pub const MAX_LIST_INDENT: u8 = 8;
/// One paragraph's list settings.
/// One paragraph's list settings and base direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ParaList {
@@ -276,6 +290,9 @@ pub struct ParaList {
/// (items that go on counting ignore it; other paragraphs are always 0).
#[serde(skip_serializing_if = "crate::node::is_default")]
pub start_offset: u32,
/// The paragraph's base direction (Text ▸ Text direction); `Auto` follows its letters.
#[serde(skip_serializing_if = "crate::node::is_default")]
pub direction: TextDirection,
}
/// Character style. In runs, every field is an override; `None` means "inherit the base".
@@ -307,6 +324,23 @@ pub struct TextStyle {
pub style_id: Option<String>,
}
/// What a text style sets at the paragraph and layer level, beside its character style
/// ([`TextStyle`]): paragraph spacing and indent, the list style and the OpenType features
/// ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType
/// features", Create and apply text styles).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ParagraphStyle {
#[serde(skip_serializing_if = "crate::node::is_default")]
pub paragraph_spacing: f64,
#[serde(skip_serializing_if = "crate::node::is_default")]
pub paragraph_indent: f64,
#[serde(skip_serializing_if = "crate::node::is_default")]
pub list: ListStyle,
#[serde(skip_serializing_if = "crate::node::is_default")]
pub features: std::collections::BTreeMap<String, bool>,
}
/// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`,
/// for a distribution whose users mostly write a script Inter lacks); empty means Inter.
pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") {
@@ -405,8 +439,9 @@ pub fn style_weight(style: &str) -> u16 {
{
return n;
}
let table: [(&str, u16); 10] = [
let table: [(&str, u16); 11] = [
("thin", 100),
("hairline", 100),
("extralight", 200),
("ultralight", 200),
("light", 300),
@@ -533,7 +568,7 @@ impl TextPath {
/// The path (empty when `d` doesn't parse).
pub fn path(&self) -> figcraft_geom::BezPath {
figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default()
figcraft_geom::svg_path(&self.d).unwrap_or_default()
}
/// The start offset clamped into 0..1 (NaN: 0).
@@ -835,6 +870,11 @@ impl TextData {
fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) {
let (a, b) = self.para_span(start, end);
self.set_para_lists_between(a, b, keep_levels, f);
}
/// As [`set_para_lists`](Self::set_para_lists), for paragraphs `a..=b` addressed directly.
fn set_para_lists_between(&mut self, a: usize, b: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) {
self.fill_paragraphs();
for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) {
f(pl);
@@ -863,6 +903,61 @@ impl TextData {
(a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first)
}
/// What a text style made from this text sets at the paragraph and layer level: the paragraph
/// spacing and indent, the list style (the one every paragraph shares; the base one when they
/// differ) and the OpenType features.
pub fn paragraph_style(&self) -> ParagraphStyle {
let list = match self.paragraphs.first() {
Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list,
_ => self.list,
};
ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() }
}
/// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and
/// features on the layer, the list style on every paragraph.
pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) {
self.paragraph_spacing = ps.paragraph_spacing;
self.paragraph_indent = ps.paragraph_indent;
self.features.clone_from(&ps.features);
// Every paragraph by index: `para_span` leaves out an empty one after a final newline.
let last = self.paragraph_count() - 1;
self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list);
}
/// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the
/// paragraphs chars `start..end` touch only; the spacing, indent and features are the
/// layer's, as in Figma.
pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) {
self.paragraph_spacing = ps.paragraph_spacing;
self.paragraph_indent = ps.paragraph_indent;
self.features.clone_from(&ps.features);
self.set_para_lists(start, end, |pl| pl.list = ps.list);
}
/// Follow text style `id`'s paragraph-level definition wherever chars link to it.
pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) {
let linked: Vec<(usize, usize)> =
self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect();
for (a, b) in linked {
self.take_paragraph_style_in(a, b, ps);
}
}
/// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer
/// level: the layer's spacing, indent and features, and their paragraphs' list style.
pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool {
self.paragraph_spacing == ps.paragraph_spacing
&& self.paragraph_indent == ps.paragraph_indent
&& self.features == ps.features
&& self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list)
}
/// Whether the whole text shows what text style `ps` sets at the paragraph and layer level.
pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool {
self.shows_paragraph_style_in(0, self.char_count(), ps)
}
/// Link chars `start..end` (all of them when the range is empty or the whole text) to text
/// style `id`, defined as `def`.
pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) {
@@ -991,20 +1086,20 @@ mod case_tests {
// Files written before start numbers load with none, and write the same bytes.
let old = r#"{"list":"numbered","indent":1}"#;
let pl: ParaList = serde_json::from_str(old).unwrap();
assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 });
assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0, ..ParaList::default() });
assert_eq!(serde_json::to_string(&pl).unwrap(), old);
// One numbered paragraph with a start keeps it (it doesn't fold into `list`).
let mut t = TextData { characters: "Next".into(), ..Default::default() };
t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 });
assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 });
t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() });
assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1, ..ParaList::default() });
// Enter copies it to the new item; different starts don't make the list mixed.
t.replace_range(4, 4, "\nMore");
assert_eq!(t.para_list(1).start_offset, 1);
t.set_para_lists(5, 5, |p| p.start_offset = 0);
assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N));
// Bullets have no number, so no start.
t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 });
assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 });
t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4, ..ParaList::default() });
assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0, ..ParaList::default() });
// A plain paragraph has none.
t.set_para_lists(0, 0, |p| p.list = P);
assert_eq!(t.para_list(0), ParaList::default());
@@ -1039,3 +1134,22 @@ mod title_case_tests {
assert_eq!(TextCase::Title.apply("cafe\u{301}'s"), "Cafe\u{301}'s");
}
}
#[cfg(test)]
mod whole_text_paragraph_style_tests {
use super::*;
#[test]
fn a_text_style_on_the_whole_layer_reaches_a_trailing_empty_paragraph() {
let ps = ParagraphStyle { list: ListStyle::Bulleted, ..Default::default() };
let mut t = TextData::new("a\nb\n");
t.take_paragraph_style(&ps);
assert_eq!(t.paragraph_count(), 3);
assert_eq!(t.para_list(2).list, ListStyle::Bulleted);
assert_eq!(t.list, ListStyle::Bulleted);
assert!(t.paragraphs.is_empty());
let mut plain = TextData::new("a\nb");
plain.take_paragraph_style(&ps);
assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len()));
}
}
+76 -25
View File
@@ -129,9 +129,10 @@ impl Region {
}
}
/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), segment `s2` starts again
/// at `b`, and an arc with handles `ta`/`tb` joins them. `cut1`/`cut2`: where each segment is cut,
/// in its own parameter (curved segments keep the rest of their curve).
/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), and the curves of `chain`
/// lead from there to where segment `s2` starts again (one arc, or a smoothed corner's easing
/// curves and arc). `cut1`/`cut2`: where each segment is cut, in its own parameter (curved
/// segments keep the rest of their curve).
struct Corner {
v: usize,
s1: usize,
@@ -139,13 +140,19 @@ struct Corner {
s2: usize,
s2_at_a: bool,
a: Point,
b: Point,
ta: (f64, f64),
tb: (f64, f64),
chain: Vec<CornerCurve>,
cut1: f64,
cut2: f64,
}
/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to
/// those ends, and the point it ends at.
struct CornerCurve {
ta: (f64, f64),
tb: (f64, f64),
end: Point,
}
/// Accuracy of arc lengths along curved segments (local units).
const ARCLEN_ACC: f64 = 1e-6;
@@ -382,9 +389,19 @@ impl VectorNetwork {
/// the rest of its curve, the arc leaving along its direction there. `None` when no point is
/// rounded.
pub fn rounded(&self) -> Option<VectorNetwork> {
self.rounded_smoothed(0.0)
}
/// [`Self::rounded`] with the layer's corner smoothing (0..=1): a rounded point between two
/// straight segments that both belong to a region's loops gets a smoothed corner, drawn with
/// the profile of a smoothed polygon's corners (`figcraft_geom::smoothed_corner`). Other
/// rounded points (on open branches, or next to a curved segment) keep the plain arc, and a
/// point without a radius stays sharp. Without smoothing this is [`Self::rounded`].
pub fn rounded_smoothed(&self, smoothing: f64) -> Option<VectorNetwork> {
if !self.vertices.iter().any(|v| v.radius > 0.0) {
return None;
}
let smoothing = if smoothing.is_finite() { smoothing.clamp(0.0, 1.0) } else { 0.0 };
let mut incident: Vec<Vec<(usize, bool)>> = vec![Vec::new(); self.vertices.len()];
for (i, s) in self.segments.iter().enumerate() {
for (v, at_a) in [(s.a, true), (s.b, false)] {
@@ -393,7 +410,14 @@ impl VectorNetwork {
}
}
}
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?)).collect();
// The segments that bound a closed region, where corners take smoothing.
let mut on_loop = vec![false; if smoothing > 0.0 { self.segments.len() } else { 0 }];
for &i in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) {
if let Some(x) = on_loop.get_mut(i) {
*x = true;
}
}
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
let mut out = self.clone();
for v in &mut out.vertices {
v.radius = 0.0;
@@ -420,26 +444,33 @@ impl VectorNetwork {
s.ta = (q.p1.x - q.p0.x, q.p1.y - q.p0.y);
s.tb = (q.p2.x - q.p3.x, q.p2.y - q.p3.y);
}
let mut by_vertex: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new();
// Each rounded point's curves in order from `s1`'s side, by point.
let mut by_vertex: std::collections::BTreeMap<usize, (usize, Vec<usize>)> = std::collections::BTreeMap::new();
for c in corners {
if let Some(v) = out.vertices.get_mut(c.v) {
(v.x, v.y) = (c.a.x, c.a.y);
}
out.vertices.push(Vertex::new(c.b.x, c.b.y));
let nb = out.vertices.len() - 1;
let mut from = c.v;
let mut arcs = Vec::with_capacity(c.chain.len());
for CornerCurve { ta, tb, end } in c.chain {
out.vertices.push(Vertex::new(end.x, end.y));
let to = out.vertices.len() - 1;
out.segments.push(Segment { a: from, b: to, ta, tb });
arcs.push(out.segments.len() - 1);
from = to;
}
if let Some(s) = out.segments.get_mut(c.s2) {
if c.s2_at_a {
s.a = nb;
s.a = from;
} else {
s.b = nb;
s.b = from;
}
}
out.segments.push(Segment { a: c.v, b: nb, ta: c.ta, tb: c.tb });
let arc = out.segments.len() - 1;
by_vertex.insert(c.v, arc);
by_vertex.insert(c.v, (c.s1, arcs));
}
// The arc goes between the two segments wherever a loop walks through the point. Each loop
// is rebuilt in one pass, so a polygon with many rounded corners isn't quadratic.
// The curves go between the two segments wherever a loop walks through the point, in the
// order the loop meets them. Each loop is rebuilt in one pass, so a polygon with many
// rounded corners isn't quadratic.
for lp in out.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) {
let Some(&first_idx) = lp.first() else { continue };
let start_v = match (self.segments.get(first_idx), lp.get(1).and_then(|&i| self.segments.get(i))) {
@@ -453,8 +484,12 @@ impl VectorNetwork {
rebuilt.push(x);
let Some(s) = self.segments.get(x) else { continue };
cur = if s.a == cur { s.b } else { s.a };
if let Some(&arc) = by_vertex.get(&cur) {
rebuilt.push(arc);
if let Some((s1, arcs)) = by_vertex.get(&cur) {
if x == *s1 {
rebuilt.extend(arcs.iter().copied());
} else {
rebuilt.extend(arcs.iter().rev().copied());
}
}
}
*lp = rebuilt;
@@ -463,8 +498,9 @@ impl VectorNetwork {
}
/// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments
/// run on smoothly or fold back.
fn corner(&self, v: usize, incident: &[(usize, bool)]) -> Option<Corner> {
/// run on smoothly or fold back. With `smoothing`, a point between two straight segments that
/// are both `on_loop` gets a smoothed corner.
fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option<Corner> {
let r = self.vertices.get(v)?.radius;
let [(s1, a1), (s2, a2)] = *incident else { return None };
if !(r > 0.0 && r.is_finite()) || s1 == s2 {
@@ -480,6 +516,24 @@ impl VectorNetwork {
if !(l1 > 1e-9 && l2 > 1e-9) {
return None;
}
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false);
if smoothing > 0.0
&& is_line(&c1)
&& is_line(&c2)
&& closed(s1)
&& closed(s2)
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing)
&& let (Some(first), Some(last)) = (curves.first(), curves.last())
{
let (a, b) = (first.p0, last.p3);
let chain = curves
.iter()
.map(|q| CornerCurve { ta: (q.p1.x - q.p0.x, q.p1.y - q.p0.y), tb: (q.p2.x - q.p3.x, q.p2.y - q.p3.y), end: q.p3 })
.collect();
let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2);
return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) });
}
let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0);
let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2));
// A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between
@@ -490,7 +544,6 @@ impl VectorNetwork {
if !(k.is_finite() && a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) {
return None;
}
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
Some(Corner {
v,
s1,
@@ -498,9 +551,7 @@ impl VectorNetwork {
s2,
s2_at_a: a2,
a,
b,
ta: (d1.x * k, d1.y * k),
tb: (d2.x * k, d2.y * k),
chain: vec![CornerCurve { ta: (d1.x * k, d1.y * k), tb: (d2.x * k, d2.y * k), end: b }],
cut1: own(a1, k1),
cut2: own(a2, k2),
})
+13
View File
@@ -345,3 +345,16 @@ fn remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(laid_out(&s), [true, true, true]);
}
#[test]
fn reorder_rejects_negative_and_fractional_indexes() {
let mut s = Session::new();
let f = frame(&mut s, None, 0.0, 0.0, 200.0, 200.0);
let a = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
for bad in [json!(-1), json!(0.5), json!("x")] {
assert!(s.execute("node.reorder", &json!({"id": c, "index": bad})).is_err(), "{bad} accepted");
assert_eq!(kids(&s, f), vec![a, b, c]);
}
}
+9
View File
@@ -1352,6 +1352,15 @@ pub fn library_of(doc: &Document, id: NodeId) -> Option<&str> {
doc.libraries.import_of(root).map(|r| r.library.as_str())
}
pub fn library_source(doc: &Document, id: NodeId) -> Option<(&str, NodeId)> {
if !doc.is_remote(id) {
return None;
}
let record = doc.libraries.import_of(asset_root(doc, id)?)?;
let key = record.ids.iter().find(|(_, local)| **local == id).map_or(record.key, |(key, _)| *key);
Some((record.library.as_str(), key))
}
/// The display name of library `id` in `doc` (its link's name, else the id).
pub fn library_name<'a>(doc: &'a Document, id: &'a str) -> &'a str {
doc.libraries.link(id).map_or(id, |l| l.name.as_str())
+69 -2
View File
@@ -189,8 +189,6 @@ fn assert_remote_read_only(s: &mut Session, b: NodeId, remote_button: NodeId) {
let style = s.doc().unwrap().styles[0].id.clone();
assert!(s.execute("style.update", &json!({"style": style, "name": "Mine"})).is_err());
assert!(s.execute("style.delete", &json!({"style": style})).is_err());
let e = s.execute("component.goToMain", &json!({"id": b})).unwrap_err();
assert!(e.to_string().contains("library"), "{e}");
assert!(s.execute("select.set", &json!({"ids": [remote_button]})).is_err(), "library copies can't be selected");
assert!(s.doc().unwrap().pages.contains(&s.page().unwrap()));
assert!(s.execute("component.pushChanges", &json!({"id": b})).is_err());
@@ -399,6 +397,75 @@ fn add_place_and_update_keep_overrides() {
let _ = std::fs::remove_dir_all(&d);
}
fn go_to_main(s: &mut Session, id: NodeId) -> Value {
s.active = 0;
ex(s, "component.goToMain", json!({"id": id}))
}
#[test]
fn going_to_a_library_main_opens_the_library_file() {
let d = dir("go-to-main");
let lib_path = path_str(&d.join("kit.figcraft"));
let mut lib = Session::new();
let k = kit(&mut lib);
let mut chips = Vec::new();
for (i, color) in ["#ff0000", "#00ff00"].iter().enumerate() {
let f = idv(&ex(&mut lib, "frame.create", json!({"x": 400.0 + i as f64 * 100.0, "y": 0, "width": 60, "height": 20, "name": "Chip"})));
ex(&mut lib, "node.set", json!({"id": f, "props": {"fill": color}}));
chips.push(idv(&ex(&mut lib, "component.create", json!({"ids": [f]}))));
}
ex(&mut lib, "component.combineVariants", json!({"ids": chips}));
let kit_page = lib.doc().unwrap().page_of(k.card).unwrap();
ex(&mut lib, "page.add", json!({"name": "Notes"}));
let lid = publish_to(&mut lib, &lib_path);
let mut s = Session::new();
ex(&mut s, "library.add", json!({"path": lib_path}));
let card = idv(&ex(&mut s, "library.place", json!({"library": lid, "component": "Card", "x": 0, "y": 0})));
let nested_button = node(&s, card).children[0];
let chip = idv(&ex(&mut s, "library.place", json!({"library": lid, "component": "Chip", "x": 0, "y": 200})));
ex(&mut s, "instance.setProperties", json!({"ids": [chip], "properties": {"Property 1": "Variant2"}}));
s.ds_mut().unwrap().view.vw = 900.0;
s.ds_mut().unwrap().view.vh = 500.0;
let using = s.doc().unwrap().clone();
let r = go_to_main(&mut s, card);
assert_eq!((id_of(&r["id"]), r["index"].as_u64()), (Some(k.card), Some(1)), "{r}");
let ds = s.ds().unwrap();
assert_eq!(ds.path.as_deref(), Some(lib_path.as_str()));
assert_eq!((ds.selection.clone(), ds.page), (vec![k.card], kit_page));
assert_eq!((ds.view.vw, ds.view.vh), (900.0, 500.0), "the canvas it opens on is the one shown, so the fit stands");
let shown = ds.doc.world_bounds(k.card).unwrap().center();
assert_eq!((ds.view.cx, ds.view.cy), (shown.x, shown.y));
for (layer, main) in [(nested_button, k.button), (chip, chips[1])] {
let r = go_to_main(&mut s, layer);
assert_eq!((id_of(&r["id"]), r["index"].as_u64()), (Some(main), Some(1)), "{r}");
assert_eq!(s.ds().unwrap().selection, vec![main]);
}
assert_eq!(s.docs.len(), 2, "the open library file comes to the front");
assert_eq!(s.docs[0].doc.as_ref(), &using, "the file going there is unchanged");
s.active = 1;
ex(&mut s, "edit.delete", json!({"ids": [k.card]}));
let r = go_to_main(&mut s, card);
assert!(r["id"].is_null() && r["index"] == 1, "{r}");
assert!(s.message.take().is_some_and(|m| m.contains("isn't in this file any more")));
ex(&mut s, "file.close", json!({"index": 1, "force": true}));
std::fs::rename(&lib_path, d.join("moved.figcraft")).unwrap();
s.active = 0;
let e = s.execute("component.goToMain", &json!({"id": card})).unwrap_err();
assert!(e.to_string().contains("isn't at"), "{e}");
assert_eq!(s.docs.len(), 1);
let NodeKind::Instance { component: copy, .. } = node(&s, card).kind else { panic!("not an instance") };
s.doc_mut().unwrap().libraries_mut().components.retain(|r| r.root != copy);
let e = s.execute("component.goToMain", &json!({"id": card})).unwrap_err();
assert!(e.to_string().contains("no link to its library"), "an imported copy without its record: {e}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn library_styles_apply_and_import_with_pages() {
let d = dir("styles");
+16 -9
View File
@@ -29,13 +29,7 @@ pub fn field_type(kind: &StyleKind, key: &str) -> Option<VariableType> {
};
ok.then_some(Color)
}
(StyleKind::Effect { effects }, Some((BoundList::Effects, i, field))) => match (&effects.get(i)?.kind, field) {
(EffectKind::DropShadow(_) | EffectKind::InnerShadow(_), "color") => Some(Color),
(EffectKind::DropShadow(_) | EffectKind::InnerShadow(_), "radius" | "spread" | "offsetX" | "offsetY") => Some(Number),
(EffectKind::LayerBlur(_) | EffectKind::BackgroundBlur(_), "radius" | "startRadius") => Some(Number),
(EffectKind::Glass(_), f) if figcraft_doc::Glass::BOUND_FIELDS.contains(&f) => Some(Number),
_ => None,
},
(StyleKind::Effect { effects }, Some((BoundList::Effects, i, field))) => effect_field_type(&effects.get(i)?.kind, field),
(StyleKind::Grid { grids }, Some((BoundList::Grids, i, "size" | "count" | "gutter" | "offset"))) => grids.get(i).map(|_| Number),
(StyleKind::Text { .. }, None) => match key {
"fontSize" | "lineHeight" | "letterSpacing" => Some(Number),
@@ -46,6 +40,19 @@ pub fn field_type(kind: &StyleKind, key: &str) -> Option<VariableType> {
}
}
/// The type of variable an effect of `kind` takes on `field` (the last part of an
/// `effects/<i>/<field>` key), on a layer or in an effect style; None when it has no such field.
pub fn effect_field_type(kind: &EffectKind, field: &str) -> Option<VariableType> {
use VariableType::{Color, Number};
match (kind, field) {
(EffectKind::DropShadow(_) | EffectKind::InnerShadow(_), "color") => Some(Color),
(EffectKind::DropShadow(_) | EffectKind::InnerShadow(_), "radius" | "spread" | "offsetX" | "offsetY") => Some(Number),
(EffectKind::LayerBlur(_) | EffectKind::BackgroundBlur(_), "radius" | "startRadius") => Some(Number),
(EffectKind::Glass(_), f) if figcraft_doc::Glass::BOUND_FIELDS.contains(&f) => Some(Number),
_ => None,
}
}
/// The variable scopes a picker offers for `key` of a style of `kind`: a variable scoped to any one
/// of them fits. A paint style's colors take fill and stroke variables, an effect style's fields
/// take effect variables, and a text style's fields take the variables of their font property.
@@ -114,7 +121,7 @@ fn resolved(vars: &Variables, st: &Style, modes: &Modes) -> StyleKind {
(StyleKind::Grid { grids }, Some((BoundList::Grids, i, field)), VariableValue::Number(x)) => {
crate::cmd::lists::set_grid_field(grids, i, field, *x);
}
(StyleKind::Text { style }, None, _) => set_text_field(style, key, &val),
(StyleKind::Text { style, .. }, None, _) => set_text_field(style, key, &val),
_ => {}
}
}
@@ -207,7 +214,7 @@ pub fn refresh(doc: &mut Document, before: Option<&Document>, only: Option<&BTre
&& was.is_none_or(|w| w.kind == n.kind)
{
for st in doc.styles.iter().filter(|s| !s.bound.is_empty()) {
if let StyleKind::Text { style } = kind_for(doc, st, id).as_ref() {
if let StyleKind::Text { style, .. } = kind_for(doc, st, id).as_ref() {
t.update_text_style(&st.id, style);
}
}
+12 -1
View File
@@ -28,6 +28,11 @@ pub fn openable(url: &str) -> bool {
if url.is_empty() || url.chars().any(char::is_control) {
return false;
}
// Never valid in a URL unencoded, and read as syntax by the shells some openers go through
// (webbrowser on WSL hands the address to `cmd.exe /c start`, escaping only `&` and `^`).
if url.chars().any(|c| c.is_whitespace() || matches!(c, '|' | '<' | '>' | '"' | '`' | '\\' | '^')) {
return false;
}
let Some((scheme, rest)) = url.split_once(':') else { return false };
// An RFC 3986 scheme, so a stray colon in text cannot look like one.
let mut chars = scheme.chars();
@@ -44,5 +49,11 @@ pub fn openable(url: &str) -> bool {
// `http` and `https` name a host, so the authority is required: `http:x` is not a web link,
// and `http:///p` has no host.
let Some(after) = rest.strip_prefix("//") else { return false };
!after.is_empty() && !after.starts_with('/')
if after.is_empty() || after.starts_with('/') {
return false;
}
// The authority is made of host characters only (an opener that can't parse the address may
// fall back to treating it as a file path).
let authority = after.split(['/', '?', '#']).next().unwrap_or_default();
authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
}
@@ -277,6 +277,14 @@ pub fn read_capped(path: impl AsRef<Path>, max: u64) -> Result<Vec<u8>> {
return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max))));
}
let f = std::fs::File::open(p).map_err(io(path))?;
// What was opened, not what was looked at: the path could have been swapped in between.
let meta = f.metadata().map_err(io(path))?;
if !meta.is_file() {
return Err(refuse("isn't a regular file (a device or a pipe?), so it isn't read".into()));
}
if meta.len() > max {
return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max))));
}
let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
f.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(io(path))?;
// It grew after it was looked at.
@@ -292,6 +300,12 @@ pub fn open(path: impl AsRef<Path>) -> Result<std::fs::File> {
std::fs::File::open(allow(path, Access::Read)?).map_err(io(path))
}
/// What the file system says about `path` itself (a link is not followed).
pub fn link_metadata(path: impl AsRef<Path>) -> Result<std::fs::Metadata> {
let path = path.as_ref();
std::fs::symlink_metadata(allow(path, Access::Read)?).map_err(io(path))
}
/// What the file system says about `path` (links followed).
pub fn metadata(path: impl AsRef<Path>) -> Result<std::fs::Metadata> {
let path = path.as_ref();
+12
View File
@@ -53,6 +53,7 @@ pub const NODE_KEYS: &[&str] = &[
"layout",
"leadingTrim",
"letterSpacing",
"lineDirections",
"lineHeight",
"lineIndentations",
"lineTypes",
@@ -96,6 +97,7 @@ pub const NODE_KEYS: &[&str] = &[
"textDecorationSkipInk",
"textDecorationStyle",
"textDecorationThickness",
"textDirection",
"textPath",
"textStyleRanges",
"type",
@@ -432,6 +434,16 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
insert_prop(o, options, "listStartOffsets", || t.paragraphs.iter().map(|p| json!(p.start_offset)).collect());
}
}
// The paragraphs' base direction: one for the layer when they agree, else each one's (Auto
// throughout says nothing).
let dirs: Vec<figcraft_doc::TextDirection> = t.paragraphs.iter().map(|p| p.direction).collect();
if let Some(first) = dirs.first().copied().filter(|d| *d != figcraft_doc::TextDirection::Auto)
&& dirs.iter().all(|d| *d == first)
{
insert_prop(o, options, "textDirection", || json!(first));
} else if dirs.iter().any(|d| *d != figcraft_doc::TextDirection::Auto) {
insert_prop(o, options, "lineDirections", || dirs.iter().map(|d| json!(d)).collect());
}
if t.list_spacing != 0.0 {
insert_prop(o, options, "listSpacing", || json!(t.list_spacing));
}
+34
View File
@@ -129,6 +129,40 @@ fn glass_fields_take_number_variables() {
assert!(s.execute("style.bind", &json!({"style": fx, "field": "effects/0/spread", "variable": "large"})).is_err(), "glass has no spread");
}
#[test]
fn a_layer_binds_only_fields_its_effects_have() {
let (mut s, r) = setup();
ex(&mut s, "effect.add", json!({"ids": [r], "type": "dropShadow"}));
ex(&mut s, "effect.add", json!({"ids": [r], "type": "glass"}));
// As an effect style does: a drop shadow has no refraction, glass no spread, there is no
// effect 5, and a key that names no effect's field names nothing. Nothing is bound.
for (field, var, says) in [
("effects/0/refraction", "large", "no field"),
("effects/1/spread", "large", "no field"),
("effects/5/radius", "large", "no field"),
("effects/x/radius", "large", "no field"),
("effects/0", "large", "no field"),
("effects", "large", "no field"),
("effects/1/lightAngle", "brand", "doesn't take a color variable"),
("effects/0/color", "large", "doesn't take a number variable"),
] {
let e = s.execute("variable.bind", &json!({"ids": [r], "field": field, "variable": var})).unwrap_err().to_string();
assert!(e.contains(says), "{field} ← {var}: {e}");
}
assert!(s.doc().unwrap().node(r).unwrap().bound.is_empty());
// The fields each effect has still bind.
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "effects/0/spread", "variable": "small"}));
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "effects/1/refraction", "variable": "large"}));
assert_eq!(s.doc().unwrap().node(r).unwrap().bound.len(), 2);
// A binding an older file already has on a field its effect lacks does nothing, and unbinds.
let large = s.doc().unwrap().variables.get("large").unwrap().id.clone();
s.doc_mut().unwrap().get_mut(r).unwrap().bound.insert("effects/0/refraction".into(), large);
ex(&mut s, "variable.set", json!({"variable": "large", "value": 40}));
assert!(matches!(&s.doc().unwrap().node(r).unwrap().effects[0].kind, EffectKind::DropShadow(_)));
ex(&mut s, "variable.bind", json!({"ids": [r], "field": "effects/0/refraction"}));
assert!(!s.doc().unwrap().node(r).unwrap().bound.contains_key("effects/0/refraction"));
}
fn ex_value(s: &mut Session, cmd: &str, p: serde_json::Value) -> serde_json::Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
@@ -104,3 +104,31 @@ fn the_next_sticky_shortcut_joins_the_next_shape_and_leaves_stickies_as_they_wer
assert!(r.get("connector").is_none(), "{r}");
assert!(matches!(node(&s, id(&r, "id")).board, Some(BoardItem::Sticky { .. })));
}
/// `at` (#1919; "drag the preview to any location on your board", Build faster with quick create):
/// the next one is centred on that point, wherever it is, and the connector takes the sides facing
/// each other; `at` must be two finite numbers.
#[test]
fn the_next_one_goes_where_it_is_dropped() {
let mut s = board();
let a = id(&s.execute("board.shape", &json!({"shape": "diamond", "x": 0, "y": 0, "width": 200, "height": 120})).unwrap(), "id");
let r = s.execute("board.addConnected", &json!({"id": a, "side": "below", "at": [700, 60]})).unwrap();
let (b, c) = (id(&r, "id"), id(&r, "connector"));
assert_eq!(at(&s, b), (600.0, 0.0), "centred on the point");
let k = connector(&s, c);
assert_eq!(
(k.from, k.to),
(End::Node { node: a, side: Side::Bottom, at: None }, End::Node { node: b, side: Side::Auto, at: None }),
"leaves by the handle's side"
);
// Inside a frame at (1000, 500): the page point lands in the frame's coordinates.
let f = id(&s.execute("frame.create", &json!({"x": 1000, "y": 500, "width": 800, "height": 600})).unwrap(), "id");
let inner = id(&s.execute("board.shape", &json!({"shape": "ellipse", "x": 0, "y": 0, "width": 200, "height": 120, "parent": f})).unwrap(), "id");
let r = s.execute("board.addConnected", &json!({"id": inner, "at": [1300, 700]})).unwrap();
let placed = id(&r, "id");
assert_eq!(node(&s, placed).parent, Some(f), "beside it, in the frame");
assert_eq!(at(&s, placed), (200.0, 140.0), "centred on the page point, in the frame's coordinates");
for wrong in [json!([1]), json!("x"), json!([0, "y"]), json!({"x": 1, "y": 2})] {
assert!(s.execute("board.addConnected", &json!({"id": a, "at": wrong})).is_err(), "{wrong}");
}
}
+15 -11
View File
@@ -2,7 +2,7 @@
//! command and a drag of the selected connector's end), curved connectors, and elbows that go
//! around the objects they join.
use figcraft_doc::{BoardItem, End, NodeKind, Routing, Side};
use figcraft_doc::{BoardItem, END_GAP, End, NodeKind, Routing, Side};
use figcraft_geom::{Point, Rect};
use serde_json::json;
@@ -27,7 +27,7 @@ fn reattach_moves_one_end_and_undoes() {
s.execute("board.reattach", &json!({"id": k, "end": "to", "target": c, "side": "top"})).unwrap();
assert_eq!(connector(&s, k).to, End::Node { node: c, side: Side::Top, at: None });
assert_eq!(connector(&s, k).from.node(), Some(a));
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, 0.0)), "arrives on c's top: {:?}", drawn(&s, k));
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, -END_GAP)), "arrives END_GAP above c's top: {:?}", drawn(&s, k));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(connector(&s, k).to.node(), Some(b), "one undo step");
// Off into the canvas: the end stays there, free. The selection is the default connector.
@@ -107,9 +107,9 @@ fn curved_connectors_leave_and_arrive_along_the_sides() {
let NodeKind::Vector { network } = &n.kind else { panic!("a vector") };
assert_eq!((network.vertices.len(), network.segments.len()), (2, 1));
assert!(!network.segments[0].is_straight(), "one curve");
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]);
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]);
// Side to side in a line: the curve's control points lie on that line, so its box is flat.
assert!(n.height.abs() < 1e-9 && (n.width - 200.0).abs() < 1e-9, "{} × {}", n.width, n.height);
assert!(n.height.abs() < 1e-9 && (n.width - 192.0).abs() < 1e-9, "{} × {}", n.width, n.height);
// From a's bottom to c's top: out downwards and in from above; the box holds the whole curve.
let k2 = id(
&s.execute("board.connector", &json!({"from": a, "to": c, "fromSide": "bottom", "toSide": "top", "style": "curved", "label": "x"})).unwrap(),
@@ -146,18 +146,18 @@ fn elbows_go_around_the_objects_they_join() {
let pts = drawn(&s, k2);
let (ra, rb) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0));
assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}");
assert_eq!(pts.first().copied(), Some(Point::new(0.0, 50.0)));
assert_eq!(pts.last().copied(), Some(Point::new(400.0, 50.0)));
assert_eq!(pts.first().copied(), Some(Point::new(-END_GAP, 50.0)));
assert_eq!(pts.last().copied(), Some(Point::new(400.0 + END_GAP, 50.0)));
assert_eq!(pts.len(), 6, "out, over, down and in: {pts:?}");
assert!(pts.iter().all(|p| p.y <= 50.0), "over the top, the nearer way round: {pts:?}");
assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles only");
// Facing each other, the short way stays.
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]);
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]);
// An end at the bottom of b leaving towards a above it: around b's side and up.
s.execute("board.reattach", &json!({"id": k2, "end": "to", "target": b, "side": "bottom"})).unwrap();
let pts = drawn(&s, k2);
assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}");
assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0)));
assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0 + END_GAP)));
}
#[test]
@@ -202,8 +202,12 @@ fn the_connector_being_drawn_is_the_one_made() {
// Over b: its four attach points, the one the end is at lit, and b outlined.
assert_eq!(ov.drop_target, Some(b));
let lit: Vec<[f64; 2]> = ov.attach.iter().filter(|a| a.1).map(|a| a.0).collect();
// The lit attach point is the side's middle, on the border; the route's end sits
// END_GAP outside it along the side's normal (#1916).
let end = *drawn(&s, drawing.id).last().unwrap();
assert_eq!((ov.attach.len(), lit), (4, vec![[end.x, end.y]]), "{style}");
assert_eq!(ov.attach.len(), 4, "{style}");
let [lit] = lit.as_slice() else { panic!("{style}: one lit attach point, got {lit:?}") };
assert!(((lit[0] - end.x).abs() + (lit[1] - end.y).abs() - END_GAP).abs() < 1e-9, "{style}: {lit:?} is END_GAP inside {end:?}");
} else {
assert!(ov.attach.is_empty() && ov.drop_target.is_none(), "a free end");
}
@@ -259,7 +263,7 @@ fn an_end_dropped_along_a_side_attaches_to_that_side() {
s.pointer(&ev(PointerKind::Up, drop)).unwrap();
assert_eq!(connector(&s, k).from, End::Node { node: a, side, at: None }, "{drop:?}");
if side != Side::Auto {
assert_eq!(drawn(&s, k)[0], side.point(bounds), "the route leaves from that side");
assert_eq!(drawn(&s, k)[0], side.point(bounds) + side.normal() * END_GAP, "the route leaves from that side, END_GAP out");
}
}
}
@@ -307,5 +311,5 @@ fn a_connector_end_snaps_to_the_attach_point_under_the_pointer() {
(connector(&s, k).from, connector(&s, k).to),
(End::Node { node: a, side: Side::Right, at: None }, End::Node { node: b, side: Side::Top, at: None })
);
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(350.0, 200.0)]);
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(350.0, 196.0)]);
}
+6 -6
View File
@@ -11,8 +11,8 @@ use crate::board::{route, selected_connector_handles};
use crate::board_tests::{board, connector, drawn, id, near};
use crate::tools::{PointerEvent, PointerKind};
const A: Point = Point::new(100.0, 50.0);
const B: Point = Point::new(300.0, 250.0);
const A: Point = Point::new(104.0, 50.0);
const B: Point = Point::new(296.0, 250.0);
/// Shapes a (at the origin) and b (down and to the right), 100 × 100, joined side to side.
fn joined(style: &str) -> (Session, NodeId, NodeId, NodeId) {
@@ -80,11 +80,11 @@ fn a_reshaped_connector_keeps_the_sides_it_left_by() {
fn the_first_and_last_runs_gain_a_run_and_stay_on_their_ends() {
let (mut s, _, _, k) = joined("elbow");
reshape(&mut s, k, 0.0, 150.0, 120.0).unwrap();
assert_eq!(drawn(&s, k), [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]);
assert_eq!(drawn(&s, k), [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]);
let last = drawn(&s, k).len() - 2;
reshape(&mut s, k, last as f64, 250.0, 200.0).unwrap();
let pts = drawn(&s, k);
assert_eq!(pts, [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(276.0, 200.0), pt(276.0, 250.0), B]);
assert_eq!(pts, [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(272.0, 200.0), pt(272.0, 250.0), B]);
assert!(right_angled(&pts));
}
@@ -97,8 +97,8 @@ fn a_lone_run_gains_a_run_at_each_end() {
let k = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "elbow"})).unwrap(), "id");
assert_eq!(drawn(&s, k).len(), 2);
reshape(&mut s, k, 0.0, 200.0, -40.0).unwrap();
let (l, r) = (pt(100.0, 50.0), pt(300.0, 50.0));
assert_eq!(drawn(&s, k), [l, pt(124.0, 50.0), pt(124.0, -40.0), pt(276.0, -40.0), pt(276.0, 50.0), r]);
let (l, r) = (pt(104.0, 50.0), pt(296.0, 50.0));
assert_eq!(drawn(&s, k), [l, pt(128.0, 50.0), pt(128.0, -40.0), pt(272.0, -40.0), pt(272.0, 50.0), r]);
}
#[test]
+12 -10
View File
@@ -168,7 +168,7 @@ fn connectors_follow_what_they_join_and_undo_with_it() {
let b = id(&s.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id");
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "then"})).unwrap(), "id");
let pts = drawn(&s, c);
assert!(near(pts[0], Point::new(200.0, 100.0)) && near(pts[1], Point::new(400.0, 100.0)), "{pts:?}");
assert!(near(pts[0], Point::new(204.0, 100.0)) && near(pts[1], Point::new(396.0, 100.0)), "{pts:?}");
assert_eq!(node(&s, c).stroke.cap_end, StrokeCap::TriangleArrow);
// Its label sits at the middle.
let label = crate::board::label_of(s.doc().unwrap(), c).unwrap();
@@ -178,19 +178,19 @@ fn connectors_follow_what_they_join_and_undo_with_it() {
s.execute("board.setStyle", &json!({"ids": [c], "style": "elbow"})).unwrap();
s.execute("transform.move", &json!({"ids": [b], "dx": 0, "dy": 300})).unwrap();
let pts = drawn(&s, c);
assert!(near(pts[0], Point::new(200.0, 100.0)) && near(*pts.last().unwrap(), Point::new(400.0, 400.0)), "{pts:?}");
assert!(near(pts[0], Point::new(204.0, 100.0)) && near(*pts.last().unwrap(), Point::new(396.0, 400.0)), "{pts:?}");
assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles: {pts:?}");
// Undo takes the move back and the route with it.
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0)));
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0)));
// A deleted end stays where it was, as a point.
s.execute("edit.delete", &json!({"ids": [b]})).unwrap();
assert!(matches!(connector(&s, c).to, End::Point { .. }));
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0)));
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0)));
// A connector moved on its own takes its free end along; the attached one stays.
s.execute("transform.move", &json!({"ids": [c], "dx": 0, "dy": 50})).unwrap();
assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 400.0 && y == 150.0), "{:?}", connector(&s, c));
assert!(near(drawn(&s, c)[0], Point::new(200.0, 100.0)));
assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 396.0 && y == 150.0), "{:?}", connector(&s, c));
assert!(near(drawn(&s, c)[0], Point::new(204.0, 100.0)));
// Deleting the connector takes its label.
s.execute("edit.delete", &json!({"ids": [c]})).unwrap();
assert!(!s.doc().unwrap().contains(label));
@@ -210,8 +210,8 @@ fn routes_are_the_same_for_the_same_document() {
let doc = s.doc().unwrap();
let r = route(doc, &c).unwrap();
assert_eq!(r, route(&doc.clone(), &c).unwrap());
// Down out of the bottom, across halfway, down into the point.
assert_eq!(r, vec![Point::new(80.0, 160.0), Point::new(80.0, 330.0), Point::new(300.0, 330.0), Point::new(300.0, 500.0)]);
// Down out of the bottom (END_GAP below it), across halfway, down into the point.
assert_eq!(r, vec![Point::new(80.0, 164.0), Point::new(80.0, 332.0), Point::new(300.0, 332.0), Point::new(300.0, 500.0)]);
}
#[test]
@@ -338,7 +338,7 @@ fn boards_sync_in_live_sessions() {
let doc = room.server.document();
let NodeKind::Vector { network } = &doc.node(c).unwrap().kind else { panic!("not a vector") };
let end = doc.world_transform(c) * network.vertices.last().unwrap().point();
assert_eq!(end, Point::new(400.0, 350.0), "to the moved sticky's facing side");
assert_eq!(end, Point::new(396.0, 350.0), "to END_GAP before the moved sticky's facing side");
assert_eq!(doc.node(a).unwrap().fills[0].solid_color(), board_color("violet"));
}
@@ -410,7 +410,9 @@ fn a_press_on_a_stickys_background_picks_and_drags_it() {
s.pointer(&PointerEvent::at(PointerKind::Up, 100.0, 450.0, 1.0)).unwrap();
assert_eq!(s.selection(), vec![a]);
assert_eq!(node(&s, a).transform.translation().y, 300.0);
assert!(near(drawn(&s, c)[0], Point::new(200.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c));
// Its own connector's start, END_GAP outside its edge, is no snap target for it (#1916).
assert_eq!(node(&s, a).transform.translation().x, 0.0, "not nudged sideways by its own connector");
assert!(near(drawn(&s, c)[0], Point::new(204.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c));
}
#[test]
+33 -7
View File
@@ -100,18 +100,18 @@ fn routes_take_named_sides_and_free_points() {
let side = |n, side| End::Node { node: n, side, at: None };
let p = |x, y| End::Point { x, y };
let pt = Point::new;
// Side to side: out, across halfway, in.
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(100.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(300.0, 350.0)]);
// Side to side: out (from END_GAP outside each side), across halfway, in.
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(104.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(296.0, 350.0)]);
// A side and a top or bottom: one turn.
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(100.0, 50.0), pt(350.0, 50.0), pt(350.0, 300.0)]);
assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 100.0), pt(50.0, 350.0), pt(300.0, 350.0)]);
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(104.0, 50.0), pt(350.0, 50.0), pt(350.0, 296.0)]);
assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 104.0), pt(50.0, 350.0), pt(296.0, 350.0)]);
// Two free points: the longer way first; in a line, no turns.
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 40.0)), vec![pt(0.0, 0.0), pt(50.0, 0.0), pt(50.0, 40.0), pt(100.0, 40.0)]);
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 0.0)), vec![pt(0.0, 0.0), pt(100.0, 0.0)]);
// An automatic side faces the other end.
let straight =
route(doc, &figcraft_doc::Connector { from: side(a, Side::Auto), to: p(50.0, 500.0), routing: figcraft_doc::Routing::Straight, path: None });
assert_eq!(straight.unwrap(), vec![pt(50.0, 100.0), pt(50.0, 500.0)]);
assert_eq!(straight.unwrap(), vec![pt(50.0, 104.0), pt(50.0, 500.0)]);
assert_eq!(Side::from_id("TOP"), Some(Side::Top));
assert_eq!(Side::from_id("inside"), None);
// The same place twice is refused, as are a side that doesn't exist and a point without numbers.
@@ -128,10 +128,10 @@ fn a_connector_follows_a_layer_whose_section_moves_and_ignores_unrelated_edits()
let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id");
let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id");
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight"})).unwrap(), "id");
assert!(near(drawn(&s, c)[0], Point::new(250.0, 150.0)));
assert!(near(drawn(&s, c)[0], Point::new(254.0, 150.0)));
// Only the section is edited; the sticky inside it moves with it, and so does the connector.
s.execute("transform.move", &json!({"ids": [sec], "dx": 0, "dy": 100})).unwrap();
assert!(near(drawn(&s, c)[0], Point::new(250.0, 250.0)), "{:?}", drawn(&s, c));
assert!(near(drawn(&s, c)[0], Point::new(254.0, 250.0)), "{:?}", drawn(&s, c));
// An edit that touches neither end leaves the connector as it was.
let before = s.doc().unwrap().node_arc(c).cloned().unwrap();
s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap();
@@ -276,3 +276,29 @@ fn a_board_tool_left_on_presses_as_move_in_a_design_file() {
assert_eq!(s.tool.tool, ToolId::Move);
assert_eq!(s.selection(), vec![r], "the press selected as Move does");
}
/// #1916: a connector's start, END_GAP outside the layer it leaves, is a snap line for other layers
/// but not for that layer, nor for a section holding it (both carry the connector along), and nor
/// is the connector's label.
#[test]
fn a_connector_joined_to_a_moving_layer_or_its_section_is_no_snap_target() {
let mut s = board();
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 300, "height": 300})).unwrap(), "id");
let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id");
let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id");
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "to"})).unwrap(), "id");
// A layer the connector has nothing to do with.
let d = id(&s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap(), "id");
let page = s.page().unwrap();
let start = drawn(&s, c)[0].x;
let label = crate::board::label_of(s.doc().unwrap(), c).unwrap();
let lx = s.doc().unwrap().world_bounds(label).unwrap().x0;
// A box whose left edge is 1 past a line snaps back by 1 when the line is a target.
let pull = |s: &Session, moving: &[NodeId], x: f64| {
let t = crate::snap::Targets::gather(s.doc().unwrap(), page, moving);
t.snap_rect(figcraft_geom::Rect::new(x + 1.0, 600.0, x + 9.0, 610.0), 4.0).0
};
assert_eq!((pull(&s, &[d], start), pull(&s, &[d], lx)), (-1.0, -1.0), "for an unrelated layer, the connector and its label snap");
assert_eq!(pull(&s, &[b], start), 0.0, "not for the layer it arrives at");
assert_eq!((pull(&s, &[sec], start), pull(&s, &[sec], lx)), (0.0, 0.0), "not for the section the connector leaves from");
}
+31 -1
View File
@@ -33,6 +33,36 @@ pub use connectors::{END_HANDLE_PX, selected_connector_ends};
use connectors::{connector_cmd, reattach};
pub use derived::route;
pub(crate) use derived::{settle_routes, settle_stamps, settle_text, stamp_target};
/// The topmost sticky or shape at `p` on `page`, other than `except`, sections and frames looked
/// into: what a "+" handle dragged onto it joins (#1919).
pub fn sticky_or_shape_at(doc: &Document, page: NodeId, p: Point, except: Option<NodeId>) -> Option<NodeId> {
fn find(doc: &Document, id: NodeId, p: Point, except: Option<NodeId>, depth: usize) -> Option<NodeId> {
let n = doc.node(id)?;
for c in n.children.iter().rev() {
let Some(k) = doc.node(*c) else { continue };
if !k.visible {
continue;
}
match k.board {
Some(BoardItem::Sticky { .. } | BoardItem::Shape { .. }) => {
if Some(*c) != except && doc.world_bounds(*c).is_some_and(|b| b.contains(p)) {
return Some(*c);
}
}
// Not a board object of its own (a section, a frame): what is inside it may be.
None if depth < 32 => {
if let Some(hit) = find(doc, *c, p, except, depth + 1) {
return Some(hit);
}
}
_ => {}
}
}
None
}
find(doc, page, p, except, 0)
}
pub use edit::label_of;
pub(crate) use edit::{copied_items, copy_map, rejoin};
use edit::{label_cmd, set_color, set_style};
@@ -114,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"board.addConnected",
"Add connected shape",
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector",
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), at? ([x, y] on the page: the next one's centre, anywhere, instead of its place on that side; the connector then leaves by `side` and arrives by the side facing it), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector",
true,
add_connected
),
+23
View File
@@ -223,6 +223,19 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
let color = color.unwrap_or(s.tool.board.sticky);
let (to_at, from_side, to_side) = connected_place((at.x, at.y), (n.width, n.height), next, &side)
.ok_or_else(|| bad(cmd, format!("`side` is right, below, left or above, not `{side}`")))?;
// Dropped somewhere by hand ("drag the preview to any location on your board", #1919): the
// next one is centred on that point of the page (placed in the parent's coordinates), and the
// connector leaves by the handle's side and arrives by the side facing it.
let (to_at, from_side, to_side) = match drop_point(cmd, p)? {
Some((x, y)) => {
let local = doc.world_transform(parent).inverse() * figcraft_geom::Point::new(x, y);
if !(local.x.is_finite() && local.y.is_finite()) {
return Err(bad(cmd, "`at` can't be placed in that parent"));
}
((local.x - next.0 / 2.0, local.y - next.1 / 2.0), from_side, Side::Auto)
}
None => (to_at, from_side, to_side),
};
let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?);
if editing.is_some() {
textedit::end(s)?;
@@ -246,6 +259,16 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"id": id, "text": text, "connector": line}))
}
/// `at?` of `board.addConnected`: a point on the page, `[x, y]`, or none.
fn drop_point(cmd: &str, p: &Value) -> Result<Option<(f64, f64)>> {
let Some(v) = get(p, "at") else { return Ok(None) };
let pair = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)));
match pair {
Some((x, y)) if x.is_finite() && y.is_finite() => Ok(Some((x, y))),
_ => Err(bad(cmd, "`at` is [x, y] on the page, two finite numbers")),
}
}
/// A shape with text's layers: the frame, its outline and its text.
fn make_shape(
doc: &mut Document,
+9 -3
View File
@@ -133,13 +133,19 @@ impl Session {
(to.node().is_none() || to.node() != from.node()).then_some(to)
}
/// The object `end` is on (if any) outlined, with its attach points; the one the end is at
/// (`at`, else its named side's) lit.
/// The object `end` is on (if any) outlined, with its attach points (the side middles, on the
/// border); the one the end is at lit: the nearest to `at` (a route's end sits `END_GAP` outside
/// its side's middle, #1916), else its named side's.
fn show_attach(&mut self, end: Option<End>, at: Option<Point>) {
let attach = match end {
Some(End::Node { node, side, .. }) => self.doc().ok().and_then(|d| d.world_bounds(node)).map(|b| {
let on = at.or_else(|| (side != Side::Auto).then(|| side.point(b)));
SIDES.map(|s| s.point(b)).map(|p| ([p.x, p.y], on.is_some_and(|o| (o - p).hypot() < 1e-6))).to_vec()
let pts = SIDES.map(|s| s.point(b));
let lit = on.and_then(|o| {
let near = pts.iter().enumerate().map(|(i, p)| (i, (o - *p).hypot())).filter(|(_, d)| *d <= figcraft_doc::END_GAP + 1e-6);
near.min_by(|x, y| x.1.total_cmp(&y.1)).map(|(i, _)| i)
});
pts.iter().enumerate().map(|(i, p)| ([p.x, p.y], lit == Some(i))).collect()
}),
_ => None,
};
+114 -2
View File
@@ -193,6 +193,109 @@ fn branch_commands_refuse_what_makes_no_sense() {
assert!(s.execute("branch.merge", &json!({"id": "nope"})).is_err());
}
/// Node id `v` of a command's answer (`{"id": …}` or a bare id).
fn idv(v: &Value) -> NodeId {
NodeId(v.get("id").unwrap_or(v).as_u64().unwrap())
}
/// The issue #2026 file, with a branch of it made and shown: a component `Card` (horizontal auto
/// layout hugging its contents, padding 12, one 40×20 rectangle) and an instance of it in a
/// vertical auto layout frame hugging its contents. Returns (session, branch id, card, instance,
/// frame, rectangle).
fn card_file() -> (Session, String, NodeId, NodeId, NodeId, NodeId) {
let mut s = Session::with_document(Document::new("Cards"));
let props = json!({"layout": "horizontal", "padding": 12, "sizingH": "hug", "sizingV": "hug"});
let frame = idv(&ok(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Card", "props": props})));
let rect = idv(&ok(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20, "parent": frame})));
let card = idv(&ok(&mut s, "component.create", json!({"ids": [frame]})));
let props = json!({"layout": "vertical", "padding": 0, "sizingH": "hug", "sizingV": "hug"});
let stack = idv(&ok(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 100, "name": "Stack", "props": props})));
let inst = idv(&ok(&mut s, "instance.create", json!({"component": card, "parent": stack})));
let b = ok(&mut s, "branch.create", json!({"name": "padding 8"}));
(s, b["id"].as_str().unwrap().to_string(), card, inst, stack, rect)
}
/// Size and place of every layer of `doc` (what auto layout works out).
fn geometry(doc: &Document) -> Vec<(NodeId, [f64; 8])> {
doc.nodes()
.map(|n| {
let c = n.transform.as_coeffs();
(n.id, [n.width, n.height, c[0], c[1], c[2], c[3], c[4], c[5]])
})
.collect()
}
/// Issue #2026: one auto layout edit on each side is one conflict (the field changed both ways),
/// not one for every size and place auto layout works out from it; the merged file lays out
/// from the padding picked.
#[test]
fn one_conflicting_auto_layout_edit_is_one_conflict() {
for (pick, padding) in [("branch", 8.0), ("main", 16.0)] {
let (mut s, id, card, inst, _, _) = card_file();
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 8}}));
ok(&mut s, "doc.switch", json!({"index": 0}));
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 16}}));
// What main looks like with the picked padding set directly.
let mut direct = Session::with_document(s.doc().unwrap().clone());
ok(&mut direct, "node.set", json!({"id": card, "props": {"padding": padding}}));
let review = ok(&mut s, "branch.review", json!({"id": id}));
let conflicts = review["conflicts"].as_array().unwrap();
assert_eq!(conflicts.len(), 1, "{review}");
let key = format!("{card}/layout.padding");
assert_eq!(conflicts[0]["key"], key.as_str());
assert_eq!(
(&conflicts[0]["property"], &conflicts[0]["branch"], &conflicts[0]["main"]),
(&json!("auto layout padding"), &json!("8, 8, 8, 8"), &json!("16, 16, 16, 16"))
);
let err = s.execute("branch.merge", &json!({"id": id})).unwrap_err().to_string();
assert!(err.contains(&key) && !err.contains("width"), "{err}");
ok(&mut s, "branch.merge", json!({"id": id, "resolutions": {&key: pick}}));
let doc = s.doc().unwrap();
for n in [card, inst] {
assert_eq!(doc.node(n).unwrap().layout.as_ref().unwrap().padding, [padding; 4], "{pick} wins");
}
assert_eq!(geometry(doc), geometry(direct.doc().unwrap()), "{pick} wins: laid out from the padding picked");
}
}
/// Auto layout merges field by field: a gap changed only on the branch is kept whichever side's
/// padding wins, both when merging and when updating the branch from main.
#[test]
fn auto_layout_fields_changed_one_way_survive_a_conflict() {
for (cmd, pick, padding) in [("branch.merge", "main", 16.0), ("branch.merge", "branch", 8.0), ("branch.updateFromMain", "main", 16.0)] {
let (mut s, id, card, _, _, _) = card_file();
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 8, "gap": 30}}));
ok(&mut s, "doc.switch", json!({"index": 0}));
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 16, "mainAlign": "center"}}));
let key = format!("{card}/layout.padding");
let review = ok(&mut s, "branch.review", json!({"id": id}));
assert_eq!(review["conflicts"].as_array().unwrap().iter().map(|c| c["key"].clone()).collect::<Vec<_>>(), vec![json!(key)], "{review}");
ok(&mut s, cmd, json!({"id": id, "resolutions": {&key: pick}}));
if cmd == "branch.updateFromMain" {
ok(&mut s, "doc.switch", json!({"index": 1}));
}
let layout = s.doc().unwrap().node(card).unwrap().layout.clone().unwrap();
assert_eq!((layout.padding, layout.gap, layout.main_align), ([padding; 4], 30.0, figcraft_doc::MainAlign::Center), "{cmd}, {pick} wins");
}
}
/// Auto layout on one side and a hugging frame's size on both: the sizes auto layout works out
/// on each side are no conflict, and merging leaves no stale size behind.
#[test]
fn sizes_auto_layout_works_out_never_conflict() {
let (mut s, id, card, _, stack, rect) = card_file();
ok(&mut s, "node.set", json!({"id": rect, "props": {"width": 60}}));
ok(&mut s, "doc.switch", json!({"index": 0}));
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 4}}));
let review = ok(&mut s, "branch.review", json!({"id": id}));
assert_eq!(review["conflicts"], json!([]), "{review}");
let mut direct = Session::with_document(s.doc().unwrap().clone());
ok(&mut direct, "node.set", json!({"id": rect, "props": {"width": 60}}));
ok(&mut s, "branch.merge", json!({"id": id}));
assert_eq!(s.doc().unwrap().node(stack).unwrap().width, 60.0 + 8.0);
assert_eq!(geometry(s.doc().unwrap()), geometry(direct.doc().unwrap()));
}
/// Every change a side made (that the other side didn't overwrite) shows in `doc`.
fn shows(changes: &[Change], doc: &Document) -> Result<(), String> {
let r = Replica::new(doc.clone());
@@ -282,16 +385,25 @@ fn random_edits_on_both_sides_merge() {
let none = |_: &figcraft_collab::merge::Key| None;
let (into_main, _) = p.merge(&m, Side::Branch, &none).unwrap_or_else(|e| panic!("seed {seed}: {e}"));
let (into_branch, _) = p.merge(&b, Side::Main, &none).unwrap_or_else(|e| panic!("seed {seed}: {e}"));
// Values both sides work out for themselves (sizes and places auto layout gives) stay
// as the file merged into has them.
let chosen = |changes: &[Change]| -> Vec<Change> {
changes
.iter()
.filter(|c| !matches!(c, Change::Set { id, prop, .. } if p.derived().contains(&Key::Node(*id, *prop))))
.cloned()
.collect()
};
let mut both = Replica::new(start.clone());
both.apply(&p.main, Mode::Strict).unwrap();
both.apply(&p.branch, Mode::Strict).unwrap();
both.apply(&chosen(&p.branch), Mode::Strict).unwrap();
let mut want = both.document().clone();
(want.name, want.current_page) = (m.name.clone(), m.current_page);
assert_eq!(into_main, want, "seed {seed}");
for doc in [&into_main, &into_branch] {
assert!(doc.validate().is_empty(), "seed {seed}: {:?}", doc.validate());
for side in [&p.branch, &p.main] {
shows(side, doc).unwrap_or_else(|c| panic!("seed {seed}: lost {c}"));
shows(&chosen(side), doc).unwrap_or_else(|c| panic!("seed {seed}: lost {c}"));
}
}
} else {
+42
View File
@@ -107,3 +107,45 @@ fn the_pencil_records_pressure_and_its_brush() {
let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap();
assert!(last.stroke.profile().is_none() && last.stroke.brush.is_none());
}
/// The Pencil draws black on a light page and white on a dark page or inside a dark frame, the
/// rule new text follows (#1741; Figma: "in black, unless you're sketching on a dark canvas or
/// frame"), and the stroke in progress previews in that colour.
#[test]
fn the_pencil_draws_white_on_a_dark_background() {
use figcraft_color::Color;
let mut s = Session::new();
s.execute("tool.set", &json!({"tool": "pencil"})).unwrap();
// A stroke from (x, y); its colour, and the preview colour the overlay carried while drawing.
let stroke = |s: &mut Session, x: f64, y: f64| {
s.pointer(&PointerEvent::at(PointerKind::Down, x, y, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Move, x + 40.0, y + 10.0, 1.0)).unwrap();
let preview = s.tool.overlay.pen_color;
s.pointer(&PointerEvent::at(PointerKind::Move, x + 80.0, y, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Up, x + 80.0, y, 1.0)).unwrap();
assert!(s.tool.overlay.pen_color.is_none(), "no preview colour after the stroke");
let doc = s.doc().unwrap();
let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap();
(last.strokes.first().and_then(|p| p.solid_color()).unwrap(), preview)
};
assert_eq!(stroke(&mut s, 0.0, 0.0), (Color::BLACK, Some(Color::BLACK)), "a light page");
s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap();
assert_eq!(stroke(&mut s, 0.0, 100.0), (Color::WHITE, Some(Color::WHITE)), "a dark page");
// A dark frame on a light page, and a light frame on a dark page.
s.execute("page.setBackground", &json!({"color": "#F5F5F5"})).unwrap();
s.execute("node.create", &json!({"type": "frame", "x": 300, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#202020"]}})).unwrap();
assert_eq!(stroke(&mut s, 320.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "inside a dark frame");
s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap();
s.execute("node.create", &json!({"type": "frame", "x": 600, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF"]}})).unwrap();
assert_eq!(stroke(&mut s, 620.0, 320.0), (Color::BLACK, Some(Color::BLACK)), "inside a light frame on a dark page");
// A frame without a fill, or with a see-through one, is looked through to what is behind it.
s.execute("node.create", &json!({"type": "frame", "x": 900, "y": 300, "width": 200, "height": 200, "props": {"fills": []}})).unwrap();
assert_eq!(stroke(&mut s, 920.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a frame without a fill on a dark page");
s.execute("node.create", &json!({"type": "frame", "x": 1200, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF40"]}})).unwrap();
assert_eq!(stroke(&mut s, 1220.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a mostly transparent light frame on a dark page");
// The threshold is Color::is_dark: white reads better than black from #757575 down.
for (bg, want) in [("#767676", Color::BLACK), ("#757575", Color::WHITE)] {
s.execute("page.setBackground", &json!({"color": bg})).unwrap();
assert_eq!(stroke(&mut s, 0.0, 600.0).0, want, "on {bg}");
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
//! Arc handles: the on-canvas handles of a selected ellipse's arc (as public documentation of
//! Figma-class tools describes them).
//! Arc handles: on-canvas controls for a selected ellipse's arc.
//!
//! - **Sweep** starts on the ellipse's right edge, on its centre line. Dragging it around the
//! ellipse opens it into an arc: the sweep is a signed share of a full turn, positive dragging up
+2 -2
View File
@@ -134,8 +134,8 @@ fn world_area(doc: &Document, part: Part) -> Option<(BezPath, bool)> {
}
match (&n.kind, part.region) {
(NodeKind::Vector { network }, Some(i)) => {
let rounded = network.rounded();
let net = rounded.as_ref().unwrap_or(network);
let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing);
let net = drawn.as_ref();
let region = net.regions.get(i)?;
let path = net.region_path(i)?;
(path, if region.winding == WindingRule::EvenOdd { figcraft_render::FillRule::EvenOdd } else { figcraft_render::FillRule::Winding })
+16 -3
View File
@@ -4,7 +4,7 @@
//! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to
//! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide).
use figcraft_doc::{Document, NodeId};
use figcraft_doc::{BoardItem, Document, NodeId};
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
use serde::Serialize;
@@ -94,10 +94,23 @@ impl Targets {
t.ys.push((y, b.x0, b.x1));
}
}
// Siblings and, at the top level, all top-level layers.
// Siblings and, at the top level, all top-level layers. A board connector joined to a
// moving layer, or to one inside it (a section carries its stickies), re-routes with it, as
// does its label: no snapping to where its own route starts (#1916).
let carried = |e: NodeId| moving.contains(&e) || doc.ancestors(e).iter().any(|a| moving.contains(a));
let follows = |id: NodeId| match doc.node(id).and_then(|n| n.board.as_ref()) {
Some(BoardItem::Connector(k)) => [k.from.node(), k.to.node()].into_iter().flatten().any(carried),
_ => false,
};
if let Some(p) = doc.node(parent) {
for c in &p.children {
if moving.contains(c) || !doc.node(*c).is_some_and(|n| n.visible) {
let Some(n) = doc.node(*c).filter(|n| n.visible) else { continue };
let joined = match n.board.as_ref() {
Some(BoardItem::Connector(_)) => follows(*c),
Some(BoardItem::Label { connector }) => follows(*connector),
_ => false,
};
if moving.contains(c) || joined {
continue;
}
if let Some(b) = bbox(*c) {
+7
View File
@@ -184,14 +184,21 @@ fn edit_if(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit) -> bool
let doc = ds.doc_mut();
let n = doc.get_mut(te.id)?;
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("not a text layer".into())) };
let derived_before = crate::cmd::props::text_layer_name(&t.characters);
if !f(t, &mut te) {
return Ok(false);
}
// Any edit ends a composition (a commit replaces it with the final text).
te.preedit = None;
let len = t.char_count();
let derived_after = crate::cmd::props::text_layer_name(&t.characters);
te.caret = te.caret.min(len);
te.anchor = te.anchor.min(len);
// The layer's name follows the characters while it is the name they derive, so the Layers
// panel keeps up with what the canvas shows; a name the author typed is left alone.
if crate::cmd::props::text_name_is_derived(&n.name, derived_before.as_ref()) {
n.name = derived_after.unwrap_or_default();
}
if n.source.is_some() {
n.overrides.insert("characters".into());
}
+13
View File
@@ -201,6 +201,7 @@ impl ToolId {
| ToolId::Star
| ToolId::Line
| ToolId::Arrow
| ToolId::BoardShape
)
}
}
@@ -327,6 +328,9 @@ pub struct Overlay {
pub cursor: Cursor,
/// Pen tool: the in-progress path's anchor points and the rubber band to the pointer.
pub pen: Vec<[f64; 2]>,
/// Pencil: the colour of the stroke in progress, for its preview (white over a dark page or
/// frame); None outside a Pencil stroke.
pub pen_color: Option<figcraft_color::Color>,
pub rubber: Option<[f64; 4]>,
/// Pen tool: the handles shaping the segments at the pen (anchor x, y, handle x, y): the last
/// anchor's in and out handles and the one before's out handle.
@@ -544,6 +548,8 @@ pub struct PenPath {
pub closed: bool,
/// The path ends connected to this anchor of its own (a vector network).
pub join: Option<usize>,
/// Anchors taken back by undo, the last one first to come back on redo.
pub undone: Vec<(Point, Vec2, Vec2)>,
}
#[derive(Clone, Debug, Default)]
@@ -589,6 +595,13 @@ pub struct ToolState {
pub picked: Option<figcraft_color::Color>,
/// The widget layers whose hover styles show while the pointer is over them (a live preview).
pub(crate) widget_hover: Vec<NodeId>,
/// The placement crosshair: where Enter puts the next shape or frame once the arrows have
/// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates
/// of the document and page in `place_on` (elsewhere it isn't shown: `Session::crosshair`).
/// Placing, Escape and a change of tool take it away.
pub place_at: Option<Point>,
/// The document (uid) and page the crosshair was shown on.
pub(crate) place_on: Option<(u64, NodeId)>,
}
impl ToolState {
+12 -5
View File
@@ -193,6 +193,7 @@ impl Session {
}
// New text at the click (Figma puts the baseline-ish top-left there).
let parent = frame_at(&doc, page, ev.p(), &[]).unwrap_or(page);
let defaults = self.default_props.text.clone();
let ds = self.ds_mut()?;
let d = ds.doc_mut();
let id = d.alloc_id();
@@ -204,12 +205,18 @@ impl Session {
if let Some(fills) = readable_text_fills(d, parent) {
n.fills = fills;
}
if let Some((w, h)) = figcraft_text::auto_size(&n) {
n.width = w.max(1.0);
n.height = h;
}
let line = n.height;
d.insert(n, parent, None)?;
// Edit ▸ Set default properties from a text layer: its fills and font (best effort).
if let Some(defaults) = &defaults {
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", d, id, defaults);
}
let line = d.node_mut(id).map_or(14.0, |n| {
if let Some((w, h)) = figcraft_text::auto_size(n) {
n.width = w.max(1.0);
n.height = h;
}
n.height
});
ds.selection = vec![id];
textedit::begin(self, id, Some(0), true)?;
self.tool.gesture = Gesture::TextBox { id, start: ev.p(), line };
+14 -12
View File
@@ -218,15 +218,16 @@ impl Session {
// Cmd/Ctrl (and Control on macOS) held while dragging suspends snapping.
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
let mut guides = Vec::new();
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one);
// snapping to layers comes after, so it wins on the axes it snaps.
d = targets.round_move(d);
}
if snap_on {
let (c, g2) = targets.snap_move(d, SNAP_PX / ev.zoom.max(1e-6));
d += c;
guides = g2;
}
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one).
d = targets.round_move(d);
}
let ids = ids.clone();
let dup = *duplicate;
let page = self.page()?;
@@ -475,20 +476,21 @@ impl Session {
let targets = if snap { Some(Targets::gather(self.doc()?, page, &ids)) } else { None };
let mut p = ev.p();
let mut guides = Vec::new();
let _ = start;
// In the handle box's own axes (one layer: its local space).
let (frame, w0, h0) = r.frame;
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
// scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes
// it snaps.
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
p = Point::new(p.x.round(), p.y.round());
}
if let Some(t) = &targets {
let (dx, dy, g) = t.snap_point(p.x, p.y, SNAP_PX / ev.zoom.max(1e-6));
p.x += dx;
p.y += dy;
guides = g;
}
let _ = start;
// In the handle box's own axes (one layer: its local space).
let (frame, w0, h0) = r.frame;
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
// scales by the factor as dragged).
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
p = Point::new(p.x.round(), p.y.round());
}
let q = frame.inverse() * p;
let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false);
if scale_tool {
+20 -3
View File
@@ -29,20 +29,30 @@ impl Session {
let tool = self.tool.tool;
let mut p = ev.p();
let mut guides = Vec::new();
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
// The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps.
if pixel {
p = Point::new(p.x.round(), p.y.round());
}
if self.ds().map(|d| d.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl {
let (dx, dy, g) = targets.snap_point(p.x, p.y, SNAP_PX / ev.zoom.max(1e-6));
p.x += dx;
p.y += dy;
guides = g;
}
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
let mut created = id;
let page = self.page()?;
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
// or arrows, which keep their own look).
let defaults = if matches!(tool, ToolId::Rectangle | ToolId::Ellipse | ToolId::Polygon | ToolId::Star) {
self.default_props.shape.clone()
} else {
None
};
self.preview(|doc, sel| {
let (mut a, mut b) = (start, p);
let (mut a, b) = (start, p);
if pixel {
a = Point::new(a.x.round(), a.y.round());
b = Point::new(b.x.round(), b.y.round());
}
let pw = doc.world_transform(parent);
let (kind, base) = match tool {
@@ -89,6 +99,10 @@ impl Session {
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
}
doc.insert(n, parent, None)?;
if let Some(d) = &defaults {
// Best effort: a default the shape can't take leaves it as drawn.
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
}
*sel = vec![nid];
created = Some(nid);
let _ = page;
@@ -209,6 +223,8 @@ impl Session {
crate::normalize(ds.doc_mut(), &before);
}
self.commit_interaction()?;
// A placement by the pointer takes the placement crosshair with it, as Enter does.
self.tool.place_at = None;
if !self.prefs.keep_tool {
self.set_tool(ToolId::Move);
}
@@ -221,6 +237,7 @@ impl Session {
}
Gesture::Pencil { mut points, mut pressure } => {
self.tool.overlay.pen.clear();
self.tool.overlay.pen_color = None;
// The stroke ends where the button came up, even without a move to get there.
if points.last().is_none_or(|l| (*l - ev.p()).hypot() > 0.5 / ev.zoom.max(1e-6)) {
points.push(ev.p());
+25 -8
View File
@@ -36,16 +36,33 @@ pub fn anchor_name(a: (u8, u8)) -> &'static str {
ANCHORS.get(usize::from(a.1.min(2)) * 3 + usize::from(a.0.min(2))).copied().unwrap_or("tl")
}
/// Whether what is drawn in `parent` sits on a dark background: the nearest layer from `parent`
/// out whose top visible fill is a mostly opaque (alpha 0.5 or more) solid colour, else the page
/// (#362); a frame without such a fill is looked through to what is behind it. Dark means white
/// reads better on it than black (`Color::is_dark`: `#757575` is dark, `#767676` is light).
pub(crate) fn on_dark_background(doc: &Document, parent: NodeId) -> bool {
std::iter::once(parent)
.chain(doc.ancestors(parent))
.filter_map(|id| doc.node(id))
.find_map(|n| match &n.kind {
NodeKind::Page { background, .. } => Some(background.is_dark()),
_ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()),
})
.unwrap_or(false)
}
/// The fill new text takes to be readable where it is drawn, in `parent`: white on a dark
/// background (None: the model's default, black). The background is the nearest layer from `parent`
/// out whose top visible fill is a mostly opaque solid colour, else the page (#362). For text made
/// in the app: by the Text tool, or by a command that names no fill while the interface is up.
/// background (None: the model's default, black). For text made in the app: by the Text tool, or
/// by a command that names no fill while the interface is up.
pub(crate) fn readable_text_fills(doc: &Document, parent: NodeId) -> Option<Vec<figcraft_color::Paint>> {
let dark = std::iter::once(parent).chain(doc.ancestors(parent)).filter_map(|id| doc.node(id)).find_map(|n| match &n.kind {
NodeKind::Page { background, .. } => Some(background.is_dark()),
_ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()),
});
dark.unwrap_or(false).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)])
on_dark_background(doc, parent).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)])
}
/// The colour the Pencil draws with in `parent`: [`PENCIL_STROKE`]'s black, or white on a dark
/// background by the rule text follows (#1741; "in black, unless you're sketching on a dark canvas
/// or frame").
pub(crate) fn pencil_color(doc: &Document, parent: NodeId) -> figcraft_color::Color {
if on_dark_background(doc, parent) { figcraft_color::Color::WHITE } else { PENCIL_STROKE.0 }
}
const ANCHORS: [&str; 9] = ["tl", "t", "tr", "l", "c", "r", "bl", "b", "br"];
+26 -3
View File
@@ -84,9 +84,14 @@ impl Session {
if self.tool.busy() {
return refuse("finish the drag first");
}
// The crosshair the arrows moved goes with the placement, which lands on it when no point
// is given.
let crosshair = self.crosshair();
self.tool.place_at = None;
let v = &self.ds()?.view;
let (c, zoom) = (at.unwrap_or(Point::new(v.cx, v.cy)), v.zoom);
let (w, h) = tool.click_size();
let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom);
// The board Shapes tool centres its own shape on the press; the others get half a click's size.
let (w, h) = if matches!(tool, ToolId::BoardShape) { (0.0, 0.0) } else { tool.click_size() };
let ev = |kind| PointerEvent::at(kind, c.x - w / 2.0, c.y - h / 2.0, zoom);
let r = self.pointer(&ev(PointerKind::Down)).and_then(|()| self.pointer(&ev(PointerKind::Up)));
if r.is_err() {
@@ -111,6 +116,16 @@ impl Session {
self.tool.overlay = Overlay::default();
return self.cancel_interaction();
}
// The placement crosshair goes first; the tool stays. One left on another page or
// document goes quietly.
let shown = self.crosshair().is_some();
self.tool.place_at = None;
if shown {
if let Ok(ds) = self.ds_mut() {
ds.revision += 1;
}
return Ok(());
}
if self.end_origin_edit() {
return Ok(());
}
@@ -174,6 +189,14 @@ impl Session {
/// Snapshot of tool state for the UI / inspect.
pub fn tool_info(&self) -> serde_json::Value {
let shapes: Vec<serde_json::Value> = self.shape_handles().into_iter().map(|(h, at)| json!({"handle": h, "at": at})).collect();
json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes})
let crosshair = self.crosshair().map(|p| [p.x, p.y]);
json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes, "crosshair": crosshair})
}
/// The placement crosshair, while the document and page it was shown on are the ones in
/// front (`ToolState::place_at`).
pub fn crosshair(&self) -> Option<Point> {
let here = self.ds().ok().map(|d| (d.uid, d.page));
self.tool.place_at.filter(|_| here.is_some() && here == self.tool.place_on)
}
}
+49 -1
View File
@@ -118,10 +118,47 @@ impl Session {
p = at_45_degrees(*last, p);
}
pen.points.push((p, Vec2::ZERO, Vec2::ZERO));
pen.undone.clear();
self.tool.gesture = Gesture::PenDrag { anchor: p };
self.pen_update()
}
/// Undo while the pen draws (#1745): its last anchor goes (before two anchors, with the layer
/// they made; with the only one, the whole path). Returns whether there was a path.
pub(crate) fn pen_undo(&mut self) -> Result<bool> {
let Some(pen) = self.tool.pen.as_mut() else { return Ok(false) };
let Some(last) = pen.points.pop() else {
self.tool.pen = None;
return Ok(false);
};
pen.undone.push(last);
let drop_layer = pen.points.len() < 2 && pen.id.take().is_some();
let empty = pen.points.is_empty();
self.tool.gesture = Gesture::None;
self.tool.overlay.rubber = None;
self.tool.overlay.rubber_handle = None;
if drop_layer {
self.cancel_interaction()?;
}
if empty {
self.pen_finish()?;
return Ok(true);
}
self.pen_update()?;
Ok(true)
}
/// Redo while the pen draws: the last anchor undo took back returns. Returns whether there was
/// one.
pub(crate) fn pen_redo(&mut self) -> Result<bool> {
let Some(pen) = self.tool.pen.as_mut() else { return Ok(false) };
let Some(point) = pen.undone.pop() else { return Ok(false) };
pen.points.push(point);
self.tool.gesture = Gesture::None;
self.pen_update()?;
Ok(true)
}
/// Rebuild the pen's vector node from its anchors.
pub(super) fn pen_update(&mut self) -> Result<()> {
let Some(pen) = self.tool.pen.clone() else { return Ok(()) };
@@ -296,7 +333,9 @@ impl Session {
let mut local = fitted.clone();
local.apply_affine(pw.inverse());
let _ = d;
let (color, weight) = PENCIL_STROKE;
// Black, or white on a dark page or frame (#1741).
let (_, weight) = PENCIL_STROKE;
let color = super::handles::pencil_color(self.doc()?, parent);
let mut props = json!({"fills": [], "strokes": [color.to_css_hex()], "strokeWeight": weight, "strokeCap": "round", "strokeJoin": "round", "strokeAlign": "center"});
// Pen pressure becomes the stroke's width profile (brushes follow it too).
if let Some(points) = pressure_profile(points, pressure) {
@@ -311,4 +350,13 @@ impl Session {
)?;
Ok(())
}
/// The colour a Pencil stroke starting at `p` will have: it goes into the frame under `p`
/// (else the page), and is white when that is dark (`pencil_color`).
pub(super) fn pencil_color_at(&self, p: figcraft_geom::Point) -> Result<figcraft_color::Color> {
let page = self.page()?;
let doc = self.doc()?;
let parent = frame_at(doc, page, p, &[]).unwrap_or(page);
Ok(super::handles::pencil_color(doc, parent))
}
}
@@ -76,6 +76,10 @@ impl Session {
if !matches!(t, ToolId::Move | ToolId::Scale | ToolId::Hand) && self.ds().is_ok_and(|d| d.vector_edit.is_some()) {
let _ = crate::vectoredit::end(self);
}
// The placement crosshair goes with a change of tool, not with the same tool chosen again.
if self.tool.tool != t {
self.tool.place_at = None;
}
self.tool.tool = t;
self.tool.gesture = Gesture::None;
self.tool.pick_only = false;
@@ -156,6 +160,8 @@ impl Session {
ToolId::TextOnPath => self.text_on_path_down(ev),
ToolId::Pen => self.pen_down(ev),
ToolId::Pencil => {
// The preview draws in the colour the stroke will have (#1741).
self.tool.overlay.pen_color = self.pencil_color_at(ev.p()).ok();
self.tool.gesture = Gesture::Pencil { points: vec![ev.p()], pressure: vec![ev.pressure] };
Ok(())
}
+14
View File
@@ -1261,6 +1261,20 @@ pub fn paint_all(doc: &mut Document, id: NodeId, pts: &[Point]) -> Result<bool>
Ok(filled)
}
/// The fills the Fill section shows for layer `id` while regions of it are selected in edit
/// mode: the stack those regions share (their own, else the layer's), `Some(None)` when they
/// differ (mixed), `None` when no region of that layer is selected (the layer's fills show). The
/// fill commands edit the same regions then (#1875).
pub fn selected_region_fills(s: &Session, id: NodeId) -> Option<Option<Vec<figcraft_color::Paint>>> {
let ve = s.ds().ok()?.vector_edit.as_ref().filter(|ve| ve.id == id && !ve.regions.is_empty())?;
let doc = s.doc().ok()?;
let node = doc.node(id)?;
let net = network(doc, id)?;
let mut stacks = ve.regions.iter().filter_map(|r| net.regions.get(*r)).map(|r| r.fills.clone().unwrap_or_else(|| node.fills.clone()));
let first = stacks.next()?;
Some(stacks.all(|st| st == first).then_some(first))
}
/// Add points `vs` of edited layer `id` to its selection.
pub(crate) fn add_points(ve: &mut VectorEdit, id: NodeId, vs: &[usize]) {
let list = if id == ve.id { Some(&mut ve.vertices) } else { ve.others.iter_mut().find(|o| o.id == id).map(|o| &mut o.vertices) };
+65 -2
View File
@@ -658,8 +658,28 @@ pub fn connect(net: &mut VectorNetwork, a: usize, b: usize, ta: (f64, f64), tb:
net.segments.push(Segment { a, b, ta: finite_t(ta), tb: finite_t(tb) });
let si = net.segments.len() - 1;
if ends && let Some(mut lp) = path_between(net, b, a, si) {
let unfilled = !net.regions.iter().any(|r| r.loops.iter().flatten().any(|s| lp.contains(s)));
if unfilled {
let filled = net.regions.iter().any(|r| r.loops.iter().flatten().any(|s| lp.contains(s)));
if filled {
// A loop broken open at these ends (a point of it deleted, say) closes through the new
// segment, so the fill follows it instead of a straight line across the gap (#1951). The
// segment goes in at the gap, in the loop's own order, so the loop keeps its direction: a
// hole wound against its outline stays a hole whichever end was clicked first. Only a
// loop the segment makes one continuous chain is closed; one listed out of walking order
// is left as it was.
let segs = &net.segments;
let shares = |x: usize, y: usize| segs.get(x).zip(segs.get(y)).is_some_and(|(p, q)| p.a == q.a || p.a == q.b || p.b == q.a || p.b == q.b);
for l in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) {
if l.len() == lp.len() && l.iter().all(|s| lp.contains(s)) {
let gap = (1..l.len()).find(|&k| l.get(k - 1).zip(l.get(k)).is_some_and(|(&x, &y)| !shares(x, y))).unwrap_or(l.len());
let mut closed = l.clone();
closed.insert(gap, si);
let n = closed.len();
if (0..n).all(|k| closed.get(k).zip(closed.get((k + 1) % n)).is_some_and(|(&x, &y)| shares(x, y))) {
*l = closed;
}
}
}
} else {
lp.insert(0, si);
net.regions.push(Region { loops: vec![lp], winding: WindingRule::NonZero, fills: None, ..Default::default() });
}
@@ -997,6 +1017,49 @@ mod tests {
assert!(connect(&mut n, 1, 99, (0.0, 0.0), (0.0, 0.0)).is_none());
}
#[test]
fn connecting_the_ends_of_a_hole_keeps_its_winding() {
// A ring: the hole's loop walks the other way round from the outline's, so the non-zero
// rule leaves it empty.
let mut n = square();
for (x, y) in [(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)] {
n.vertices.push(Vertex::new(x, y));
}
for (a, b) in [(4, 5), (5, 6), (6, 7), (7, 4)] {
n.segments.push(Segment::line(a, b));
}
n.regions[0].loops.push(vec![7, 6, 5, 4]);
let (hole, ring, cut) = (Point::new(40.0, 60.0), Point::new(10.0, 50.0), Point::new(70.0, 30.0));
assert!(!n.fill_contains(hole) && n.fill_contains(ring) && !n.fill_contains(cut), "a ring to start with");
// Delete a corner of the hole (the path opens; its fill closes across the gap, so the cut-off
// corner is filled), then connect the two open ends again, either end first: the hole is a
// triangle, still empty.
let at = |m: &VectorNetwork, (x, y): (f64, f64)| m.vertices.iter().position(|v| v.x == x && v.y == y).unwrap();
for (first, second) in [((25.0, 25.0), (75.0, 75.0)), ((75.0, 75.0), (25.0, 25.0))] {
let mut m = n.clone();
delete_vertices(&mut m, &[5], false);
assert!(!m.fill_contains(hole) && m.fill_contains(cut), "opened: {:?}", m.regions);
let (a, b) = (at(&m, first), at(&m, second));
connect(&mut m, a, b, (0.0, 0.0), (0.0, 0.0)).unwrap();
let loops = &m.regions[0].loops;
assert_eq!((m.regions.len(), loops.len(), loops[1].len()), (1, 2, 3), "{first:?} first: {:?}", m.regions);
assert!(!m.fill_contains(hole), "{first:?} first: the hole is filled, {loops:?}");
assert!(m.fill_contains(ring) && m.fill_contains(cut), "{first:?} first: the ring is filled");
}
}
#[test]
fn connecting_leaves_a_loop_out_of_walking_order_alone() {
// The open chain A-B-C-D-E with its loop listed out of walking order: no place for the new
// segment makes it one continuous chain, so the loop is left as it was, and no region is added.
let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0), Point::new(-50.0, 50.0)];
let mut n = VectorNetwork::from_points(&pts, false);
n.regions.push(Region { loops: vec![vec![0, 2, 1, 3]], winding: WindingRule::NonZero, fills: None, ..Default::default() });
let s = connect(&mut n, 0, 4, (0.0, 0.0), (0.0, 0.0)).unwrap();
assert_eq!(n.regions.len(), 1);
assert_eq!(n.regions[0].loops, vec![vec![0, 2, 1, 3]], "left as it was, without segment {s}");
}
#[test]
fn join_merges_overlapping_points_and_connects_ends() {
let mut n = open_line();
@@ -56,12 +56,10 @@ fn region_filled(n: &figcraft_doc::Node, net: &VectorNetwork, i: usize) -> bool
net.regions.get(i).is_some_and(|r| r.fills.as_deref().unwrap_or(&n.fills).iter().any(|f| f.visible))
}
/// The network as its fill draws it: rounded points drawn in (region indexes are kept).
fn drawn(net: &VectorNetwork) -> std::borrow::Cow<'_, VectorNetwork> {
match net.rounded() {
Some(r) => std::borrow::Cow::Owned(r),
None => std::borrow::Cow::Borrowed(net),
}
/// The network as its fill draws it: rounded points drawn in with the layer's corner `smoothing`
/// (region indexes are kept).
fn drawn(net: &VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, VectorNetwork> {
figcraft_doc::geometry::drawn_network(net, smoothing)
}
/// The region of the active layer under page point `p` at `zoom`: none when a point is within
@@ -90,7 +88,7 @@ pub fn region_hit(doc: &Document, ve: &VectorEdit, p: Point, zoom: f64) -> Optio
if (0..net.segments.len()).filter_map(|i| net.cubic(i)).any(|c| c.nearest(lp, 0.01).distance_sq.sqrt() <= sc) {
return None;
}
let drawn = drawn(net);
let drawn = drawn(net, node.corners.smoothing);
(0..drawn.regions.len()).rev().find(|i| region_filled(node, &drawn, *i) && drawn.region_contains(*i, lp))
}
@@ -221,7 +219,7 @@ pub fn region_hatch(doc: &Document, ve: &VectorEdit, regions: &[usize], view: Af
let zoom = view.determinant().abs().sqrt();
let Some(spacing) = hatch_spacing(zoom).filter(|_| !regions.is_empty()) else { return Vec::new() };
let Some(net) = network(doc, ve.id) else { return Vec::new() };
let net = drawn(net);
let net = drawn(net, doc.node(ve.id).map_or(0.0, |n| n.corners.smoothing));
let m = view * doc.world_transform(ve.id);
let anchor = m * Point::ZERO;
let mut out = Vec::new();
@@ -6,6 +6,7 @@ use figcraft_geom::{Affine, Point, Rect, Vec2};
use serde_json::json;
use super::regions::*;
use super::selected_region_fills;
use super::tests::{ex, net, ve};
use crate::Session;
use crate::tools::{PointerEvent, PointerKind};
@@ -540,3 +541,85 @@ fn hovered_and_selected_is_hatched_once_and_regions_share_one_pattern() {
assert!(!part.is_empty() && part.len() < all.len());
assert!(part.iter().all(|x| all.iter().any(|y| (x - y).abs() < 1e-6)));
}
/// Each closed region of a vector network has its own fill (#1875): with regions selected in edit mode, the fill
/// commands edit those regions' own fills and leave the layer's; `regions` names them outright.
#[test]
fn the_fill_commands_edit_the_selected_regions() {
let mut s = Session::new();
let id = editing_vector(&mut s, overlapping());
let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone();
let layer = |s: &Session| s.doc().unwrap().node(id).unwrap().fills.clone();
let colour = |s: &Session, r: usize, i: usize| fills_of(s, r).unwrap()[i].solid_color().unwrap().to_css_hex().to_ascii_uppercase();
let before = layer(&s);
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"}));
assert_eq!(fills_of(&s, 1).map(|f| f.len()), Some(1));
assert_eq!(colour(&s, 1, 0), "#FF0000");
assert_eq!(fills_of(&s, 0), None, "the other region still inherits");
assert_eq!(layer(&s), before, "the layer's fills are untouched");
// The section's list for the layer is the region's own stack.
assert_eq!(selected_region_fills(&s, id).and_then(|l| l).map(|l| l.len()), Some(1));
ex(&mut s, "fill.add", json!({"ids": [id], "color": "#00FF00"}));
assert_eq!(fills_of(&s, 1).unwrap().len(), 2);
ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 1}));
assert_eq!((colour(&s, 1, 0), colour(&s, 1, 1)), ("#00FF00".to_string(), "#FF0000".to_string()));
ex(&mut s, "fill.remove", json!({"ids": [id], "index": 0}));
assert_eq!(fills_of(&s, 1).unwrap().len(), 1);
assert_eq!(colour(&s, 1, 0), "#FF0000");
assert_eq!(layer(&s), before);
// Both regions selected with different fills: the section shows mixed content.
ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]}));
assert_eq!(selected_region_fills(&s, id), Some(None));
// Named outright, with no selection; junk is refused.
ex(&mut s, "vector.edit.select", json!({}));
ex(&mut s, "fill.set", json!({"ids": [id], "regions": [0], "color": "#0000FF"}));
assert_eq!(colour(&s, 0, 0), "#0000FF");
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [9], "color": "#0000FF"})).is_err());
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": "all", "color": "#0000FF"})).is_err());
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [], "color": "#0000FF"})).is_err());
// Nothing selected: the layer's fills, as before; the regions keep their own.
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#123456"}));
assert_ne!(layer(&s), before);
assert_eq!(colour(&s, 1, 0), "#FF0000");
assert_eq!(selected_region_fills(&s, id), None);
s.undo().unwrap();
assert_eq!(layer(&s), before, "one undo step per command");
}
/// Region fill edits from review: a region named twice is edited once; an edit that changes
/// nothing leaves an inheriting region inheriting; Copy fill reads the selected region's fill.
#[test]
fn region_fill_edits_apply_once_skip_no_ops_and_copy_the_region() {
let mut s = Session::new();
let id = editing_vector(&mut s, overlapping());
let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone();
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 0}));
assert_eq!(fills_of(&s, 1), None, "moving a paint onto itself leaves the region inheriting");
ex(&mut s, "fill.remove", json!({"ids": [id], "index": 5}));
assert_eq!(fills_of(&s, 1), None, "removing a paint that isn't there leaves it inheriting");
ex(&mut s, "fill.add", json!({"ids": [id], "regions": [0, 0], "color": "#00FF00"}));
assert_eq!(fills_of(&s, 0).map(|f| f.len()), Some(2), "the layer's fill and one added, once");
// Copy fill takes the selected region's own paint, not the layer's.
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"}));
ex(&mut s, "fill.copy", json!({"ids": [id], "index": 0}));
let copied = s.clipboard.paint.clone().map(|(_, p)| p.solid_color().unwrap().to_css_hex().to_ascii_uppercase());
assert_eq!(copied.as_deref(), Some("#FF0000"));
// Regions whose fills differ have no one paint to copy.
ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]}));
assert!(s.execute("fill.copy", &json!({"ids": [id], "index": 0})).is_err());
}
/// `fill.pattern` sets the layer's fill, as its spec says, also while regions are selected.
#[test]
fn fill_pattern_sets_the_layers_fill_with_regions_selected() {
let mut s = Session::new();
let src = crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": 400, "y": 0, "width": 20, "height": 20}))["id"]).unwrap();
let id = editing_vector(&mut s, overlapping());
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
ex(&mut s, "fill.pattern", json!({"ids": [id], "source": src}));
assert_eq!(net(&s, id).regions[1].fills, None, "the region still inherits");
let top = s.doc().unwrap().node(id).unwrap().fills.last().cloned().unwrap();
assert!(matches!(top.kind, figcraft_color::PaintKind::Pattern(_)), "{top:?}");
}
@@ -597,3 +597,85 @@ fn the_pen_shows_its_ghost_anchor_on_the_segment_under_it() {
assert_eq!(net(&s, id).vertices.len(), 5, "the press added the point");
assert_eq!(ve(&s).anchor, None, "the click ended the pen's path");
}
/// A rectangle's corner cut off in the editor (a point added on each edge next to it, the corner
/// deleted with Shift+Delete so the two join) and the shape rounded: the fill, which the fill and
/// the selection outline draw, traces the stroke's outline, cut at both ends of the diagonal (#1951).
#[test]
fn a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs() {
for top_first in [true, false] {
let mut s = Session::new();
let id = rect(&mut s);
// Splitting keeps the split edge's index, so the other edge's stays: top 0, right 1.
let (first, second) = if top_first { (0, 1) } else { (1, 0) };
ex(&mut s, "vector.edit.addVertex", json!({"segment": first, "t": 0.5}));
ex(&mut s, "vector.edit.addVertex", json!({"segment": second, "t": 0.5}));
let corner = vertex_at(&net(&s, id), 100.0, 0.0);
ex(&mut s, "vector.edit.select", json!({"vertices": [corner]}));
ex(&mut s, "vector.deleteHeal", json!({}));
let n = net(&s, id);
assert_eq!((n.vertices.len(), n.segments.len(), n.regions.len()), (5, 5, 1), "top first {top_first}: a pentagon");
ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]}));
fill_traces_stroke(&s, id, &format!("top first {top_first}"));
// A region with a fill of its own is drawn through the region path and the planar normaliser.
if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(id).unwrap().kind {
network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]);
}
fill_traces_stroke(&s, id, &format!("top first {top_first}, region fill"));
}
}
/// The chamfer made other ways: the corner deleted plainly, which opens the path between the two
/// new points, and the two connected again; or the pentagon drawn with the pen (#1951).
#[test]
fn a_rounded_chamfer_made_other_ways_fills_along_its_arcs() {
let mut s = Session::new();
let id = rect(&mut s);
ex(&mut s, "vector.edit.addVertex", json!({"segment": 0, "t": 0.5}));
ex(&mut s, "vector.edit.addVertex", json!({"segment": 1, "t": 0.5}));
let corner = vertex_at(&net(&s, id), 100.0, 0.0);
ex(&mut s, "vector.edit.select", json!({"vertices": [corner]}));
ex(&mut s, "vector.edit.delete", json!({}));
let n = net(&s, id);
assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (4, 4), "the path opened: {:?}", n.regions);
let (top, right) = (vertex_at(&n, 50.0, 0.0), vertex_at(&n, 100.0, 50.0));
ex(&mut s, "vector.edit.connect", json!({"a": top, "b": right}));
assert_eq!(net(&s, id).segments.len(), 5, "connected again");
ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]}));
fill_traces_stroke(&s, id, "deleted and connected");
// Drawn with the pen: continue from the end of an open two-point path and close on its start.
let mut s = Session::new();
let r = ex(&mut s, "vector.create", json!({"points": [[0, 0], [50, 0]], "closed": false}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
ex(&mut s, "vector.edit.tool", json!({"tool": "pen"}));
click(&mut s, 50.0, 0.0);
for (x, y) in [(100.0, 50.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)] {
click(&mut s, x, y);
}
let n = net(&s, id);
assert_eq!((n.vertices.len(), n.segments.len(), n.regions.len()), (5, 5, 1), "closed by the pen");
ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]}));
fill_traces_stroke(&s, id, "drawn with the pen");
}
/// The rounded chamfered rectangle `id` (five points on the origin's 100×100 box, the top-right
/// corner cut off between (50, 0) and (100, 50)): one region with every segment in its loop, and a
/// fill that keeps off every sharp point and traces the same outline as the stroke.
fn fill_traces_stroke(s: &Session, id: NodeId, why: &str) {
use figcraft_geom::BezPath;
use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
let n = net(s, id);
assert_eq!(n.regions.len(), 1, "{why}: one region, {:?}", n.regions);
assert_eq!(n.regions[0].loops[0].len(), n.segments.len(), "{why}: every segment in the loop, {:?}", n.regions[0].loops);
let doc = s.doc().unwrap();
let (fill, _) = figcraft_render::node_outline(doc, doc.node(id).unwrap()).unwrap();
let stroke = n.stroke_path();
let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min);
let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::<f64>();
for p in [pt(50.0, 0.0), pt(100.0, 50.0), pt(0.0, 0.0), pt(100.0, 100.0), pt(0.0, 100.0)] {
assert!(keeps_off(&stroke, p) > 2.0, "{why}: the stroke is cut at {p:?} ({:.2} from it)", keeps_off(&stroke, p));
assert!(keeps_off(&fill, p) > 2.0, "{why}: the fill runs into {p:?} ({:.2} from it)", keeps_off(&fill, p));
}
assert!((length(&fill) - length(&stroke)).abs() < 1e-3, "{why}: fill {} and stroke {} trace the same outline", length(&fill), length(&stroke));
}
+6 -1
View File
@@ -216,6 +216,11 @@ pub static MENU: &[MenuItem] = &[
m!("Text/Case", "Uppercase", "text.caseUpper"),
m!("Text/Case", "Lowercase", "text.caseLower"),
m!("Text/Case", "Title case", "text.caseTitle"),
// "Go to Text > Text direction. Select Left to right or Right to left." (Add right-to-left
// text); Auto, the way back to detection, is FigCraft's own (in `OWN`).
m!("Text/Text direction", "Auto", "text.directionAuto"),
m!("Text/Text direction", "Left to right", "text.directionLtr"),
m!("Text/Text direction", "Right to left", "text.directionRtl"),
m!("Text", SEP, ""),
m!("Text", "Missing fonts…", "text.missingFonts"),
// Arrange
@@ -292,7 +297,7 @@ pub fn items() -> impl Iterator<Item = &'static MenuItem> {
}
/// Items of FigCraft's own that the parity count leaves out (as it does the `collab.` ones).
const OWN: [&str; 5] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop"];
const OWN: [&str; 6] = ["file.newFromTemplate", "file.newBoard", "help.gettingStarted", "text.missingFonts", "image.crop", "text.directionAuto"];
/// Coverage: (implemented, total, missing ids). `extra` lists ids implemented by the UI layer.
pub fn parity(extra: &[&str]) -> (usize, usize, Vec<&'static str>) {
+72 -21
View File
@@ -186,28 +186,42 @@ pub fn specs() -> Vec<CommandSpec> {
true,
reset_override
),
spec!("component.goToMain", "Go to main component", "{id?}", false, |s, p| {
let cmd = "component.goToMain";
let i = targets(s, p).first().copied().ok_or_else(|| bad(cmd, "select an instance"))?;
let doc = s.doc()?;
let inst = owning_instance(doc, i).ok_or_else(|| bad(cmd, "not an instance"))?;
let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|n| n.kind.clone()) else {
return Err(bad(cmd, "not an instance"));
};
if !doc.contains(component) {
return Err(EngineError::Disabled(cmd.into(), "the main component was deleted (use component.restoreMain)".into()));
spec!(
"component.goToMain",
"Go to main component",
"{id?} selects the instance's main component; a library component's main is in its library file, which opens in a tab (or comes to the front) with the main selected. Returns {id} (the main in the file now shown), and `index` (the tab) when it went to a library file",
false,
|s, p| {
let cmd = "component.goToMain";
let i = targets(s, p).first().copied().ok_or_else(|| bad(cmd, "select an instance"))?;
let doc = s.doc()?;
let inst = owning_instance(doc, i).ok_or_else(|| bad(cmd, "not an instance"))?;
let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|n| n.kind.clone()) else {
return Err(bad(cmd, "not an instance"));
};
if !doc.contains(component) {
return Err(EngineError::Disabled(cmd.into(), "the main component was deleted (use component.restoreMain)".into()));
}
if let Some((library, key)) = crate::library::library_source(doc, component) {
let name = crate::library::library_name(doc, library).to_string();
let library = library.to_string();
return go_to_library_main(s, &library, &name, key);
}
if doc.is_remote(component) {
return Err(EngineError::Disabled(
cmd.into(),
"the main component is a library copy with no link to its library (it came with an imported file): enable that library to reach it"
.into(),
));
}
super::edit::select_and_page(s, vec![component])?;
let ds = s.ds_mut()?;
if let Some(b) = ds.doc.world_bounds(component) {
ds.view.fit(b, 2.0);
}
Ok(json!({"id": component}))
}
if let Some(lib) = crate::library::library_of(doc, component) {
let name = crate::library::library_name(doc, lib);
return Err(EngineError::Disabled(cmd.into(), format!("the main component is in the library \"{name}\": open that file to edit it")));
}
super::edit::select_and_page(s, vec![component])?;
let ds = s.ds_mut()?;
if let Some(b) = ds.doc.world_bounds(component) {
ds.view.fit(b, 2.0);
}
Ok(json!({"id": component}))
}),
),
spec!("component.pushChanges", "Push changes to main component", "{id?}", true, push_changes),
spec!(
"component.restoreMain",
@@ -283,6 +297,43 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn go_to_library_main(s: &mut Session, library: &str, name: &str, key: NodeId) -> Result<Value> {
let cmd = "component.goToMain";
let refuse = |why: String| EngineError::Disabled(cmd.into(), why);
let path = s
.doc()?
.libraries
.link(library)
.map(|l| l.path.clone())
.ok_or_else(|| refuse(format!("the library \"{name}\" was removed from this file")))?;
if crate::library_server::is_server_link(&path) {
return Err(refuse(format!("the main component is in the team library \"{name}\": open its file from the server to edit it")));
}
if !craft_docpath::is_local(&path) {
return Err(refuse(format!("{path}: a library is opened only from this computer")));
}
if !crate::file_access::exists(&path) {
return Err(refuse(format!("the library file of \"{name}\" isn't at {path} any more")));
}
let viewport = s.ds().map(|d| (d.view.vw, d.view.vh))?;
let opened = super::file::open(s, &json!({"path": path}))?;
let ds = s.ds_mut()?;
(ds.view.vw, ds.view.vh) = viewport;
let doc = &ds.doc;
let same_library = doc.published.as_ref().is_some_and(|p| p.manifest.id == library);
let main = doc.node(key).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }));
if !same_library || !main || doc.is_remote(key) {
s.message = Some(format!("{name}: the main component isn't in this file any more"));
return Ok(json!({"id": null, "index": opened["index"]}));
}
super::edit::select_and_page(s, vec![key])?;
let ds = s.ds_mut()?;
if let Some(b) = ds.doc.world_bounds(key) {
ds.view.fit(b, 2.0);
}
Ok(json!({"id": key, "index": opened["index"]}))
}
/// Place an instance of `component` centred on page point (`x`, `y`), in the frame or auto layout
/// slot under it (`instance.place`).
pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
+12 -3
View File
@@ -194,7 +194,7 @@ fn create_kind(s: &mut Session, p: &Value, t: &str) -> Result<Value> {
/// Parse SVG path data (`M L H V C S Q T A Z`, absolute and relative) into a bezier path.
pub fn parse_path_data(d: &str) -> Option<figcraft_geom::BezPath> {
figcraft_geom::BezPath::from_svg(d).ok()
figcraft_geom::svg_path(d).ok()
}
/// A vector's geometry made from SVG path data (see [`path_network`]).
@@ -213,7 +213,9 @@ pub(crate) struct PathShape {
pub(crate) fn path_network(cmd: &str, d: &str, width: Option<f64>, height: Option<f64>) -> Result<PathShape> {
use figcraft_geom::Shape;
let empty = || bad(cmd, "`path` draws nothing: a vector needs a visible line or area");
let mut path = parse_path_data(d).ok_or_else(|| bad(cmd, "`path` is not valid SVG path data"))?;
let mut path = figcraft_geom::svg_path(d).map_err(|e| {
if e.contains("too large") { bad(cmd, "`path` has coordinates too large to draw") } else { bad(cmd, "`path` is not valid SVG path data") }
})?;
let bb = path.bounding_box();
if !(bb.x0.is_finite() && bb.y0.is_finite() && bb.width().is_finite() && bb.height().is_finite()) {
return Err(bad(cmd, "`path` has coordinates too large to draw"));
@@ -302,7 +304,14 @@ pub fn create(s: &mut Session, p: &Value) -> Result<Value> {
}
(w, h, offset) = (shape.width, shape.height, shape.offset);
} else if let Some(Value::Array(pts)) = get(p, "points") {
let pts: Vec<Point> = pts.iter().filter_map(|v| Some(Point::new(f64_of(v.get(0)?)?, f64_of(v.get(1)?)?))).collect();
let pts: Vec<Point> = pts
.iter()
.map(|v| {
let xy = v.as_array().filter(|a| a.len() == 2)?;
Some(Point::new(f64_of(&xy[0])?, f64_of(&xy[1])?))
})
.collect::<Option<_>>()
.ok_or_else(|| bad(cmd, "`points` entries must be numeric [x, y] pairs"))?;
if pts.len() < 2 {
return Err(bad(cmd, "`points` needs at least two [x, y] pairs"));
}
+43 -13
View File
@@ -15,8 +15,10 @@ use crate::{BatchStep, EngineError, Result, Session, bad, spec};
mod clipboard;
mod props;
pub(crate) use props::{edit_region_fills, fill_regions};
mod select;
pub(crate) use clipboard::apply_copied_props;
pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into};
use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace};
use props::{
@@ -142,12 +144,26 @@ pub fn specs() -> Vec<CommandSpec> {
true,
find_replace
),
spec!("edit.setDefaultProperties", "Set default properties", "{id?}", false, |s, p| {
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?;
let v = copy_props_of(s.doc()?, id);
s.clipboard.props = Some(v);
ok()
}),
spec!(
"edit.setDefaultProperties",
"Set default properties",
"{id?} the layer's fills, strokes, effects, opacity and corners (a text layer's: also its font) become what new rectangles, ellipses, polygons and stars (or, from a text layer, new text) drawn with the tools take → {for: shapes|text, properties}",
false,
|s, p| {
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?;
let doc = s.doc()?;
let text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
let v = copy_props_of(doc, id);
let kind = if text {
s.default_props.text = Some(v.clone());
"text"
} else {
s.default_props.shape = Some(v.clone());
"shapes"
};
Ok(json!({"for": kind, "properties": v}))
}
),
spec!("select.set", "Select", "{ids: [..]} (replace the selection)", false, |s, p| {
let ids = match get(p, "ids") {
Some(Value::Array(a)) => a.iter().filter_map(id_of).collect(),
@@ -326,18 +342,32 @@ pub fn specs() -> Vec<CommandSpec> {
),
spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| {
let i = req_id("node.reorder", p, "id")?;
let idx = req_num("node.reorder", p, "index")?.max(0.0) as usize;
let idx = req_index("node.reorder", p, "index")?;
s.doc_mut()?.reorder(i, idx)?;
ok()
}),
spec!("fill.add", "Add fill", "{ids?, paint? | color? (default #D9D9D9 or white for frames)}", true, |s, p| paint_list(s, p, true, true)),
spec!(
"fill.add",
"Add fill",
"{ids?, paint? | color? (default #D9D9D9 or white for frames), regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
true,
|s, p| paint_list(s, p, true, true)
),
spec!("stroke.add", "Add stroke", "{ids?, paint? | color? (default black)}", true, |s, p| paint_list(s, p, false, true)),
spec!("fill.remove", "Remove fill", "{ids?, index}", true, |s, p| paint_list(s, p, true, false)),
spec!("fill.remove", "Remove fill", "{ids?, index, regions?}", true, |s, p| paint_list(s, p, true, false)),
spec!("stroke.remove", "Remove stroke", "{ids?, index}", true, |s, p| paint_list(s, p, false, false)),
spec!("fill.set", "Set fill", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, true)),
spec!(
"fill.set",
"Set fill",
"{ids?, index?, paint | color, opacity?, visible?, blend?, regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
true,
|s, p| paint_set(s, p, true)
),
spec!("stroke.set", "Set stroke", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, false)),
spec!("fill.copy", "Copy fill", "{id?, index? (default the top fill)}", false, |s, p| paint_copy(s, p, true)),
spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one)}", true, |s, p| paint_paste(s, p, true)),
spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one), regions?}", true, |s, p| paint_paste(
s, p, true
)),
spec!(
"stroke.copy",
"Copy stroke",
@@ -418,7 +448,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"export.add",
"Add export setting",
"{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)",
"{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), colorProfile? (PNG, JPG and WebP: sameAsFile|srgb|displayP3), quality? (JPG: 1-100, default 90)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)",
true,
|s, p| {
let cmd = "export.add";
@@ -436,7 +466,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"export.update",
"Edit export setting",
"{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}",
"{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), colorProfile? (PNG, JPG and WebP: sameAsFile (the document's profile when it exports)|srgb|displayP3; kept when the format changes), quality? (JPG: 1-100), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}",
true,
|s, p| {
let cmd = "export.update";
+16 -10
View File
@@ -357,21 +357,27 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
Ok(v)
}
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
/// properties only to text, the corners only to a layer with corners.
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
let mut m = props.as_object().cloned().unwrap_or_default();
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
if !is_text {
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
}
if !doc.get(id)?.kind.has_corner_radius() {
m.remove("cornerRadius");
m.remove("cornerSmoothing");
}
crate::cmd::props::apply(cmd, doc, id, &m)
}
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
let ids = req_targets("edit.pasteProperties", s, p)?;
let doc = s.doc_mut()?;
for i in ids {
let mut m = props.as_object().cloned().unwrap_or_default();
let is_text = matches!(doc.get(i)?.kind, NodeKind::Text(_));
if !is_text {
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
}
if !doc.get(i)?.kind.has_corner_radius() {
m.remove("cornerRadius");
m.remove("cornerSmoothing");
}
crate::cmd::props::apply("edit.pasteProperties", doc, i, &m)?;
apply_copied_props("edit.pasteProperties", doc, i, &props)?;
}
ok()
}
+142 -12
View File
@@ -260,13 +260,107 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// The regions of a vector whose own fill stacks a fill command edits instead of the layer's: the
/// `regions` named (with one target, a vector; indices into its network's regions), else the
/// regions selected in vector edit mode when the one target is the layer being edited (#1875).
/// None: the layer's.
pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> Result<Option<(NodeId, Vec<usize>)>> {
let doc = s.doc()?;
let region_count = |id: NodeId| match doc.node(id).map(|n| &n.kind) {
Some(NodeKind::Vector { network }) => Some(network.regions.len()),
_ => None,
};
if let Some(list) = get(p, "regions") {
let [id] = ids else { return Err(bad(cmd, "`regions` goes with one vector layer")) };
let Some(count) = region_count(*id) else { return Err(bad(cmd, "`regions` goes with a vector layer")) };
let mut regions = list
.as_array()
.ok_or_else(|| bad(cmd, "regions: [index, ...]"))?
.iter()
.map(|v| {
v.as_u64()
.and_then(|i| usize::try_from(i).ok())
.filter(|i| *i < count)
.ok_or_else(|| bad(cmd, format!("regions: indices below {count}")))
})
.collect::<Result<Vec<usize>>>()?;
// A region named twice is edited once.
regions.sort_unstable();
regions.dedup();
if regions.is_empty() {
return Err(bad(cmd, "regions: at least one"));
}
return Ok(Some((*id, regions)));
}
let [id] = ids else { return Ok(None) };
let Some(ve) = s.ds()?.vector_edit.as_ref().filter(|ve| ve.id == *id && !ve.regions.is_empty()) else { return Ok(None) };
let count = region_count(*id).unwrap_or(0);
let mut regions: Vec<usize> = ve.regions.iter().copied().filter(|r| *r < count).collect();
regions.sort_unstable();
regions.dedup();
Ok((!regions.is_empty()).then_some((*id, regions)))
}
/// Runs `f` on the own fill stack of each of `regions` of vector `id` (a region without one
/// starts from the layer's fills, which stay as they are). A region that inherits the layer's
/// fills keeps inheriting when `f` leaves the stack as it was, so later edits of the layer's
/// fills still reach it; a region's own stack is only replaced once `f` succeeds.
pub(crate) fn edit_region_fills(
doc: &mut figcraft_doc::Document,
id: NodeId,
regions: &[usize],
mut f: impl FnMut(&mut Vec<figcraft_color::Paint>) -> Result<()>,
) -> Result<()> {
let inherited = doc.get(id)?.fills.clone();
let NodeKind::Vector { network } = &mut doc.get_mut(id)?.kind else { return Err(bad("fill", "not a vector layer")) };
for &r in regions {
let Some(region) = network.regions.get_mut(r) else { continue };
let mut list = region.fills.clone().unwrap_or_else(|| inherited.clone());
f(&mut list)?;
if region.fills.is_some() || list != inherited {
region.fills = Some(list);
}
}
Ok(())
}
pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> Result<Value> {
let cmd = if fills { "fill" } else { "stroke" };
let ids = req_targets(cmd, s, p)?;
let index = if add || get(p, "index").is_none() { None } else { Some(req_index(cmd, p, "index")?) };
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills) {
let paint = match get(p, "paint").or_else(|| get(p, "color")) {
Some(v) => Some(paint_of(v).ok_or_else(|| bad(cmd, "invalid paint"))?),
None => None,
};
edit_region_fills(s.doc_mut()?, id, &regions, |list| {
if add {
list.push(paint.clone().unwrap_or_else(|| figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)));
} else {
let idx = index.unwrap_or(list.len().saturating_sub(1));
if idx < list.len() {
let _ = list.remove(idx);
}
}
Ok(())
})?;
return ok();
}
let doc = s.doc_mut()?;
for i in ids {
let n = doc.get_mut(i)?;
// A removal that names no paint among the rows shown changes nothing, the characters' own
// fills included; characters coloured differently show no rows at all ("Click + to
// replace mixed content").
if !add {
let shown = if fills { crate::cmd::lists::character_fills(n).map_or(0, |f| f.len()) } else { n.strokes.len() };
if index.unwrap_or(shown.saturating_sub(1)) >= shown {
continue;
}
}
if fills {
crate::cmd::lists::take_character_fills(n);
}
let frameish = n.kind.is_frame_like();
let list = if fills { &mut n.fills } else { &mut n.strokes };
if add {
@@ -287,6 +381,12 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
}
pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value> {
paint_set_in(s, p, fills, true)
}
/// [`paint_set`]; `to_regions`: whether the regions selected (or named) on a vector take the
/// edit in their own fills (#1875), as for `fill.set`; `fill.pattern` always sets the layer's.
fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Result<Value> {
let cmd = if fills { "fill.set" } else { "stroke.set" };
let ids = req_targets(cmd, s, p)?;
let idx = opt_index(cmd, p, "index")?;
@@ -295,16 +395,8 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
None => None,
};
let col = color(p, "color");
let doc = s.doc_mut()?;
for i in ids {
let n = doc.get_mut(i)?;
let list = if fills { &mut n.fills } else { &mut n.strokes };
let at = idx.unwrap_or(list.len().saturating_sub(1));
if list.is_empty() {
list.push(figcraft_color::Paint::solid(if fills { figcraft_color::Color::DEFAULT_SHAPE } else { figcraft_color::Color::BLACK }));
}
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
let old = slot.clone();
// The edit of one paint slot, the same for a layer's list and a region's.
let edit_slot = |slot: &mut figcraft_color::Paint| {
if let Some(np) = &new_paint {
*slot = np.clone();
}
@@ -325,6 +417,33 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
if let Some(b) = blend(p, "blend") {
slot.blend = b;
}
};
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills && to_regions) {
edit_region_fills(s.doc_mut()?, id, &regions, |list| {
if list.is_empty() {
list.push(figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE));
}
let at = idx.unwrap_or(list.len().saturating_sub(1));
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
edit_slot(slot);
Ok(())
})?;
return ok();
}
let doc = s.doc_mut()?;
for i in ids {
let n = doc.get_mut(i)?;
if fills {
crate::cmd::lists::take_character_fills(n);
}
let list = if fills { &mut n.fills } else { &mut n.strokes };
let at = idx.unwrap_or(list.len().saturating_sub(1));
if list.is_empty() {
list.push(figcraft_color::Paint::solid(if fills { figcraft_color::Color::DEFAULT_SHAPE } else { figcraft_color::Color::BLACK }));
}
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
let old = slot.clone();
edit_slot(slot);
crate::cmd::lists::rebind_edited_paint(n, fills, at, &old);
if fills {
n.styles.fill = None;
@@ -344,7 +463,15 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result<Valu
let (paint, stroke) = {
let doc = s.doc()?;
let n = doc.get(id)?;
let list = if fills { &n.fills } else { &n.strokes };
// Regions selected in vector edit mode: their own fills, as the Fill section lists them
// (#1875); a text's fills are what its characters show (#1856).
let regions = if fills { crate::vectoredit::selected_region_fills(s, id) } else { None };
let list: Vec<figcraft_color::Paint> = match regions {
Some(Some(list)) => list,
Some(None) => return Err(bad(cmd, "the selected regions' fills differ")),
None if fills => crate::cmd::lists::character_fills(n).unwrap_or_default(),
None => n.strokes.clone(),
};
let at = at.unwrap_or(list.len().saturating_sub(1));
let paint = list.get(at).cloned().ok_or_else(|| bad(cmd, format!("no {} at index {at}", if fills { "fill" } else { "stroke" })))?;
(paint, (!fills).then(|| n.stroke.clone()))
@@ -413,6 +540,9 @@ pub(super) fn paint_paste(s: &mut Session, p: &Value, fills: bool) -> Result<Val
}
}
let mut q = json!({"ids": ids, "paint": serde_json::to_value(paint).map_err(|e| bad(cmd, e.to_string()))?});
if let Some(regions) = get(p, "regions") {
q["regions"] = regions.clone();
}
let out = match opt_index(cmd, p, "index")? {
Some(at) => {
q["index"] = json!(at);
@@ -448,7 +578,7 @@ pub(super) fn pattern_fill(s: &mut Session, p: &Value) -> Result<Value> {
q["paint"] =
serde_json::to_value(figcraft_color::Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..figcraft_color::Paint::pattern(src.0) })
.map_err(|e| bad(CMD, e.to_string()))?;
paint_set(s, &q, true)
paint_set_in(s, &q, true, false)
}
pub(super) fn effect_add(s: &mut Session, p: &Value) -> Result<Value> {
+34 -7
View File
@@ -4,8 +4,8 @@ use std::sync::Arc;
use base64::Engine as _;
use figcraft_doc::{
BOARD_PAGE, Document, ExportFormat, ExportSetting, ExportSize, FileKind, LineHeight, Node, NodeId, NodeKind, PrintSettings, StyleKind, TextStyle,
VdCompat,
BOARD_PAGE, Document, ExportColorProfile, ExportFormat, ExportSetting, ExportSize, FileKind, LineHeight, Node, NodeId, NodeKind, PrintSettings,
StyleKind, TextStyle, VdCompat,
};
use figcraft_format::Version;
use serde_json::{Value, json};
@@ -15,6 +15,7 @@ use crate::params::{bool_of, boolean, get, id, num, num_or, req_index, req_strin
use crate::{DocState, EngineError, Result, Session, bad, spec};
mod export;
mod import_ids;
mod load;
mod open;
mod save;
@@ -37,7 +38,8 @@ pub(crate) use load::{load_fig, read_capped, recovered, recovered_from, variable
pub use open::MAX_RECENT;
#[cfg(test)]
use open::append_pages;
use open::{import, open, open_recent, revert};
pub(crate) use open::open;
use open::{import, open_recent, revert};
pub(crate) use save::save_ends_preview;
pub use save::{FileSnapshot, file_bytes, thumbnail};
use save::{color_profile, mark_saved, save, save_as};
@@ -118,14 +120,14 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"file.export",
"Export",
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings))}",
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, PDF and XML are always sRGB), quality? (JPG: 1-100, default 90)}",
false,
export
),
spec!(
"file.exportLayers",
"Export layers",
"{ids? (default the selection, else every layer on the page with export settings), assets? (true: the Inspect tab's assets in and under them instead: layers with export settings, icons as SVG, images as PNG), dir? (folder to write into; else each file comes back as base64 `data`), zip? (no dir: the files come back together as one base64 zip `data` instead), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options): for every PDF instead of each setting's own, vdCompat? (bestEffort|exact|ignore: for every XML instead of each setting's own)} every layer once per export setting, named `<layer><suffix>.<format>` (\"@2x\" when a scaled export has no suffix; repeats get \" 2\"; slashes in a layer name make folders). Returns {files: [{name, id, bytes, path | data, warnings (XML only)}], skipped (layers without settings), data? (zip)}",
"{ids? (default the selection, else every layer on the page with export settings), assets? (true: the Inspect tab's assets in and under them instead: layers with export settings, icons as SVG, images as PNG), dir? (folder to write into; else each file comes back as base64 `data`), zip? (no dir: the files come back together as one base64 zip `data` instead), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options): for every PDF instead of each setting's own, vdCompat? (bestEffort|exact|ignore: for every XML instead of each setting's own), colorProfile? (sameAsFile|srgb|displayP3: for every PNG, JPG and WebP instead of each setting's own)} every layer once per export setting, named `<layer><suffix>.<format>` (\"@2x\" when a scaled export has no suffix; repeats get \" 2\"; slashes in a layer name make folders). Returns {files: [{name, id, bytes, path | data, warnings (XML only)}], skipped (layers without settings), data? (zip)}",
false,
export_layers
),
@@ -406,13 +408,38 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal
Ok((pdf_bytes(doc, &groups, &setting.print, (!own_area).then_some(area))?, Vec::new()))
}
_ => {
let pix = figcraft_render::render_area(doc, &drawn, area, scale)
let mut pix = figcraft_render::render_area(doc, &drawn, area, scale)
.ok_or_else(|| EngineError::Other("render failed (empty or too large)".into()))?;
Ok((figcraft_render::encode_export(&pix, setting.format, doc.color_profile).map_err(EngineError::Other)?, Vec::new()))
// The render is in the document's profile; the setting's profile converts the pixels
// (out-of-gamut colors clip) and tags the file.
let profile = setting.color_profile.resolve(doc.color_profile);
let conversion = doc.color_profile.conversion_to(profile);
// JPG has no alpha: the render is flattened over white in the document's profile
// before the conversion, so translucent pixels match what the document shows.
if setting.format == ExportFormat::Jpg && !conversion.is_identity() {
for [r, g, b, a] in pix.data_mut().as_chunks_mut::<4>().0.iter_mut() {
let under = 255 - *a;
*r = r.saturating_add(under);
*g = g.saturating_add(under);
*b = b.saturating_add(under);
*a = 255;
}
}
conversion.apply_pixels(pix.data_mut());
let bytes = figcraft_render::encode_export_with(&pix, setting.format, profile, setting.quality());
Ok((bytes.map_err(EngineError::Other)?, Vec::new()))
}
}
}
/// The `colorProfile` `p` passes: sameAsFile, srgb or displayP3 (anything else is an error).
fn color_profile_param(cmd: &str, p: &Value) -> Result<Option<ExportColorProfile>> {
match get(p, "colorProfile") {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_str().and_then(ExportColorProfile::from_key).map(Some).ok_or_else(|| bad(cmd, "colorProfile: sameAsFile|srgb|displayP3")),
}
}
/// The `vdCompat` `p` passes: bestEffort, exact or ignore (anything else is an error).
fn vd_compat_param(cmd: &str, p: &Value) -> Result<Option<VdCompat>> {
match get(p, "vdCompat") {
+27 -3
View File
@@ -1,6 +1,7 @@
use super::load::{ext, write};
use super::save::thumbnail;
use super::*;
use crate::params::f64_of;
/// Encode `ids` (or the page) in `format` at `scale`.
pub fn export_bytes(doc: &Document, ids: &[NodeId], format: ExportFormat, scale: f64) -> Result<Vec<u8>> {
@@ -159,7 +160,8 @@ pub fn export_scale(doc: &Document, ids: &[NodeId], setting: &ExportSetting) ->
export_area(doc, ids, setting).map_or(1.0, |b| setting.size.scale_for(b.width(), b.height()))
}
/// `e` with the `size` ("2x", "512w", "512h" or `{by, value}`), `suffix` and `format` that `p` sets.
/// `e` with the `size` ("2x", "512w", "512h" or `{by, value}`), `suffix`, `format` and the
/// format options (`quality`, `vdCompat`, PDF print options, the SVG flags) that `p` sets.
pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value) -> Result<ExportSetting> {
if let Some(size) = size_param(cmd, p)? {
e.size = size;
@@ -173,6 +175,12 @@ pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value)
if let Some(c) = vd_compat_param(cmd, p)? {
e.vd_compat = c;
}
if let Some(c) = color_profile_param(cmd, p)? {
e.color_profile = c;
}
if let Some(q) = quality_param(cmd, p)? {
e.quality = q;
}
e.print = print_param(cmd, p, e.print)?;
for (key, slot) in [
("contentsOnly", &mut e.contents_only),
@@ -189,6 +197,16 @@ pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value)
Ok(e)
}
/// The JPG `quality` `p` passes: a whole number from 1 to 100 (anything else is an error).
fn quality_param(cmd: &str, p: &Value) -> Result<Option<u8>> {
let Some(v) = get(p, "quality") else { return Ok(None) };
let q = if v.is_boolean() { None } else { f64_of(v) };
match q.filter(|q| q.fract() == 0.0 && (1.0..=100.0).contains(q)) {
Some(q) => Ok(Some(q as u8)),
None => Err(bad(cmd, "quality: a whole number from 1 to 100 (JPG)")),
}
}
/// Whether `p` sets any PDF print option.
fn has_print_param(p: &Value) -> bool {
["bleed", "cropMarks", "bleedMarks", "cmyk"].iter().any(|k| get(p, k).is_some_and(|v| !v.is_null()))
@@ -327,10 +345,16 @@ pub(super) fn export_layers(s: &mut Session, p: &Value) -> Result<Value> {
let print = has_print_param(p).then(|| print_param(cmd, p, PrintSettings::default())).transpose()?;
// And a compatibility mode for every Android Vector Drawable.
let compat = vd_compat_param(cmd, p)?;
// And a color profile for every PNG, JPG and WebP.
let profile = color_profile_param(cmd, p)?;
let mut files = Vec::with_capacity(jobs.len());
for job in &jobs {
let setting =
ExportSetting { print: print.unwrap_or(job.setting.print), vd_compat: compat.unwrap_or(job.setting.vd_compat), ..job.setting.clone() };
let setting = ExportSetting {
print: print.unwrap_or(job.setting.print),
vd_compat: compat.unwrap_or(job.setting.vd_compat),
color_profile: profile.unwrap_or(job.setting.color_profile),
..job.setting.clone()
};
let scale = export_scale(doc, &[job.id], &setting);
let (bytes, warnings) = export_file(doc, &[job.id], &setting, scale)?;
let mut f = json!({"name": job.file, "id": job.id, "bytes": bytes.len()});
+254
View File
@@ -0,0 +1,254 @@
//! Ids a file being imported brings that the document already uses for something else.
//!
//! Style, variable and collection ids are numbered per file (`S:1`, `VariableID:1`,
//! `VariableCollectionId:1`; see [`figcraft_doc::ids`]), so two files made apart use the same ones
//! for unrelated things. Kept as they were, the imported layers would show the document's
//! variables and styles instead of their own.
use std::collections::{BTreeMap, BTreeSet};
use figcraft_doc::ids::MODE_ID_INFIX;
use figcraft_doc::proto::{Action, Expr, MAX_EXPR_DEPTH, walk_mut};
use figcraft_doc::{Document, ModeId, NodeId, NodeKind, VariableValue, Variables};
/// A style, variable or collection of the file being imported.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Asset<'a> {
Style(&'a str),
Variable(&'a str),
Collection(&'a str),
}
/// New ids for styles, variables and collections of a file being imported (its id → the new one).
#[derive(Debug, Default)]
pub(super) struct Renames {
styles: BTreeMap<String, String>,
variables: BTreeMap<String, String>,
collections: BTreeMap<String, String>,
}
impl Renames {
/// The new ids `other`'s styles, variables and collections take when appended to `doc`.
///
/// One whose id `doc` doesn't use keeps it. One `doc` already has is shared and keeps its id:
/// the same content under the same id, naming only things that are shared too (the same file
/// imported again). A collection and its variables are shared only all together, so variables
/// of one file never join a collection of another. Library copies keep their ids and are shared
/// with the document's copies, as before (`merge_store` records them). Every other id `doc`
/// already uses is replaced by a new one from `doc`'s allocators, clear of `other`'s ids too.
pub(super) fn new(doc: &mut Document, other: &Document) -> Renames {
let (theirs, libs) = (&other.variables, &other.libraries);
// Each with whether `doc` has the same under its id (None: nothing there), and whether
// it's a library copy.
let styles = other.styles.iter().map(|s| {
let here = doc.styles.iter().find(|m| m.id == s.id);
(Asset::Style(&s.id), here.map(|m| m == s), libs.style_import(&s.id).is_some())
});
let colls = theirs.collections.iter().map(|c| {
let here = doc.variables.collection_by_id(&c.id);
(Asset::Collection(&c.id), here.map(|m| m == c), libs.collection_import(&c.id).is_some())
});
let vars = theirs.variables.iter().map(|v| {
let here = doc.variables.get_by_id(&v.id);
(Asset::Variable(&v.id), here.map(|m| m == v), libs.variable_import(&v.id).is_some())
});
// `taken`: ids `doc` uses; `differs`: what `doc` doesn't have the same of.
let (mut taken, mut copies, mut differs) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
for (a, same, copy) in styles.chain(colls).chain(vars) {
match same {
None => {
differs.insert(a);
}
Some(same) => {
taken.insert(a);
if copy {
copies.insert(a);
} else if !same {
differs.insert(a);
}
}
}
}
// What differs makes what names it differ (library copies aside), and a collection and its
// variables differ together.
let mut named_by: BTreeMap<Asset, Vec<Asset>> = BTreeMap::new();
for v in &theirs.variables {
let (var, coll) = (Asset::Variable(&v.id), Asset::Collection(&v.collection));
named_by.entry(coll).or_default().push(var);
named_by.entry(var).or_default().push(coll);
for r in v.values.values().flat_map(VariableValue::references).chain(&v.extends) {
named_by.entry(Asset::Variable(r)).or_default().push(var);
}
}
for c in &theirs.collections {
if let Some(e) = &c.extends {
named_by.entry(Asset::Collection(e)).or_default().push(Asset::Collection(&c.id));
}
}
for s in &other.styles {
for v in s.bound.values() {
named_by.entry(Asset::Variable(v)).or_default().push(Asset::Style(&s.id));
}
}
let mut todo: Vec<Asset> = differs.iter().copied().collect();
while let Some(a) = todo.pop() {
for &n in named_by.get(&a).into_iter().flatten() {
if !copies.contains(&n) && differs.insert(n) {
todo.push(n);
}
}
}
let renamed = |a: Asset| taken.contains(&a) && differs.contains(&a);
Renames {
collections: fresh(
theirs.collections.iter().map(|c| &c.id),
|id| renamed(Asset::Collection(id)),
|avoid| doc.new_collection_id_avoiding(avoid),
),
variables: fresh(theirs.variables.iter().map(|v| &v.id), |id| renamed(Asset::Variable(id)), |avoid| doc.new_variable_id_avoiding(avoid)),
styles: fresh(other.styles.iter().map(|s| &s.id), |id| renamed(Asset::Style(id)), |avoid| doc.new_style_id_avoiding(avoid)),
}
}
pub(super) fn is_empty(&self) -> bool {
self.styles.is_empty() && self.variables.is_empty() && self.collections.is_empty()
}
/// `other` with the renamed styles, variables and collections under their new ids, and what
/// names them following: layers' style links (text ranges too), bindings, explicit modes and
/// prototype actions; styles' bindings; variables' collections, aliases and calculations; what
/// extended collections and their variables extend; and the ids of the renamed collections'
/// modes, which name their collection (`<collection>/mode<k>`).
pub(super) fn applied(&self, other: &Document) -> Document {
let theirs = &other.variables;
let mut doc = other.clone();
let (styles, vars, colls) = (&self.styles, &self.variables, &self.collections);
for s in &mut doc.styles {
rename(styles, &mut s.id);
s.bound.values_mut().for_each(|v| rename(vars, v));
}
for c in &mut doc.variables.collections {
for m in &mut c.modes {
self.mode(theirs, &c.id, &mut m.id);
}
for id in std::iter::once(&mut c.id).chain(&mut c.extends) {
rename(colls, id);
}
}
for v in &mut doc.variables.variables {
let values = std::mem::take(&mut v.values).into_iter().map(|(mut mode, mut val)| {
self.mode(theirs, &v.collection, &mut mode);
val.references_mut().into_iter().for_each(|r| rename(vars, r));
(mode, val)
});
v.values = values.collect();
let overrides = std::mem::take(&mut v.overrides).into_iter().map(|mut mode| {
self.mode(theirs, &v.collection, &mut mode);
mode
});
v.overrides = overrides.collect();
rename(colls, &mut v.collection);
for id in std::iter::once(&mut v.id).chain(&mut v.extends) {
rename(vars, id);
}
}
let ids: Vec<NodeId> = doc.ids().collect();
for id in ids {
let Some(n) = doc.node_mut(id) else { continue };
let links = [&mut n.styles.fill, &mut n.styles.stroke, &mut n.styles.effect, &mut n.styles.grid, &mut n.styles.text];
for s in links.into_iter().flatten() {
rename(styles, s);
}
if let NodeKind::Text(t) = &mut n.kind {
t.map_text_styles(|s| Some(styles.get(s).cloned().unwrap_or_else(|| s.to_string())));
}
n.bound.values_mut().for_each(|v| rename(vars, v));
n.var_modes = std::mem::take(&mut n.var_modes)
.into_iter()
.map(|(mut c, mut mode)| {
self.mode(theirs, &c, &mut mode);
rename(colls, &mut c);
(c, mode)
})
.collect();
for it in &mut n.interactions {
walk_mut(&mut it.actions, &mut |a| self.action(theirs, a));
}
}
doc
}
/// Rename mode `mode` of collection `of` (`theirs`: the imported file's variables as they were).
/// A mode id names the collection it was made in: `of`, or one `of` extends (an extended
/// collection has the modes of the one it extends). Library copies keep their library's mode
/// ids, which may name one of the file's own collections.
fn mode(&self, theirs: &Variables, of: &str, mode: &mut ModeId) {
let mut at = Some(of);
for _ in 0..=theirs.collections.len() {
let Some(c) = at else { return };
if let Some(k) = mode.strip_prefix(c).and_then(|rest| rest.strip_prefix(MODE_ID_INFIX)) {
if let Some(new) = self.collections.get(c) {
*mode = format!("{new}{MODE_ID_INFIX}{k}");
}
return;
}
at = theirs.collection_by_id(c).and_then(|c| c.extends.as_deref());
}
}
/// Rename what one prototype action names (not the actions nested in it).
fn action(&self, theirs: &Variables, a: &mut Action) {
match a {
Action::SetVariable { variable, expr, .. } => {
rename(&self.variables, variable);
if let Some(e) = expr {
self.expr(theirs, e, 0);
}
}
Action::SetVariableMode { collection, mode } => {
self.mode(theirs, collection, mode);
rename(&self.collections, collection);
}
Action::Conditional { blocks } => blocks.iter_mut().filter_map(|b| b.condition.as_mut()).for_each(|c| self.expr(theirs, c, 0)),
_ => {}
}
}
fn expr(&self, theirs: &Variables, e: &mut Expr, depth: usize) {
match e {
Expr::Value(v) => v.references_mut().into_iter().for_each(|r| rename(&self.variables, r)),
Expr::Op { args, .. } if depth < MAX_EXPR_DEPTH => args.iter_mut().for_each(|a| self.expr(theirs, a, depth + 1)),
Expr::Op { .. } => {}
Expr::Mode { collection } => rename(&self.collections, collection),
Expr::InMode { variable, mode } => {
if let Some(v) = theirs.get_by_id(variable) {
self.mode(theirs, &v.collection, mode);
}
rename(&self.variables, variable);
}
}
}
}
/// New ids, from `new_id`, for those of `ids` that `pick` picks; each clear of all of `ids`.
fn fresh<'a>(
ids: impl Iterator<Item = &'a String> + Clone,
pick: impl Fn(&str) -> bool,
mut new_id: impl FnMut(&BTreeSet<String>) -> String,
) -> BTreeMap<String, String> {
let mut avoid: BTreeSet<String> = ids.clone().cloned().collect();
let mut out = BTreeMap::new();
for id in ids.filter(|id| pick(id)) {
let new = new_id(&avoid);
avoid.insert(new.clone());
out.insert(id.clone(), new);
}
out
}
/// `id` as `map` renames it.
fn rename(map: &BTreeMap<String, String>, id: &mut String) {
if let Some(new) = map.get(id.as_str()) {
*id = new.clone();
}
}
+3 -3
View File
@@ -250,7 +250,7 @@ fn match_font_families(doc: &mut Document) {
}
// Shared text styles too, so they stay like the layers linked to them.
for st in &mut doc.styles {
if let StyleKind::Text { style } = &mut st.kind {
if let StyleKind::Text { style, .. } = &mut st.kind {
fix(style);
}
}
@@ -294,7 +294,7 @@ fn platform_tracking(doc: &mut Document) {
}
}
for st in &mut doc.styles {
if let StyleKind::Text { style } = &mut st.kind {
if let StyleKind::Text { style, .. } = &mut st.kind {
track(style);
}
}
@@ -365,7 +365,7 @@ fn sketch_line_heights(doc: &mut Document) {
}
}
for st in &mut doc.styles {
if let StyleKind::Text { style } = &mut st.kind {
if let StyleKind::Text { style, .. } = &mut st.kind {
set(style);
}
}
+13 -2
View File
@@ -1,3 +1,4 @@
use super::import_ids::Renames;
use super::load::{ext, file_stem, import_summary, load_path, load_with, read, rest_images, sibling_variables, variables_param};
use super::*;
@@ -54,7 +55,7 @@ pub(super) fn open_recent(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"files": files}))
}
pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
let variables = variables_param("file.open", p)?;
if string(p, "path").is_none()
&& let Some(d) = string(p, "data")
@@ -218,8 +219,18 @@ pub(super) fn import(s: &mut Session, p: &Value) -> Result<Value> {
/// Append `other`'s pages (with their settings and flows, its images, styles and variables) to
/// `doc`. Ids are remapped across all pages at once, so instances keep their main, instance layers
/// their source and interactions and flows their targets wherever those are. Styles, variables and
/// collections whose id the document already has are kept as they are.
/// collections the document already has (the same under the same id, as when a file comes in
/// again) and library copies are shared; others whose id the document uses for something else get
/// new ids, and what comes in names them by those ([`Renames`]).
pub(super) fn append_pages(doc: &mut Document, other: &Document) -> Result<Vec<NodeId>> {
let renames = Renames::new(doc, other);
let renamed;
let other = if renames.is_empty() {
other
} else {
renamed = renames.applied(other);
&renamed
};
for (k, v) in &other.images {
doc.images.entry(k.clone()).or_insert_with(|| v.clone());
}
+10 -3
View File
@@ -184,9 +184,10 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"image": image, "width": width, "height": height, "changed": changed}))
}
/// The index of a layer's top visible image fill (fills paint bottom to top).
/// The index of a layer's top visible image fill among the fills it shows (fills paint bottom to
/// top): a text's characters' shared list, so none while they are coloured differently.
pub fn top_image_fill(n: &Node) -> Option<usize> {
n.fills.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_)))
crate::cmd::lists::character_fills(n)?.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_)))
}
fn crop(s: &mut Session, p: &Value) -> Result<Value> {
@@ -197,11 +198,15 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) };
let doc = s.doc()?;
let n = doc.get(id)?;
// A text's fills are its characters' (the Design panel's rows): the crop edits that list, and
// characters coloured differently have no row to crop ("Click + to replace mixed content").
let shown =
crate::cmd::lists::character_fills(n).ok_or_else(|| refuse("the characters have different fills, so there is no one fill to crop"))?;
let index = match get(p, "index") {
None | Some(Value::Null) => top_image_fill(n).ok_or_else(|| refuse("the layer has no image fill to crop"))?,
Some(_) => req_index(cmd, p, "index")?,
};
let mut paint = n.fills.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?;
let mut paint = shown.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?;
let PaintKind::Image(img) = &mut paint.kind else { return Err(bad(cmd, "that fill is not an image")) };
// An image already in Crop mode only enters crop mode: no edit, no undo step.
if img.scale_mode != ImageScaleMode::Crop {
@@ -209,6 +214,8 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
img.crop = Some(img.placement_crop(f64::from(data.width), f64::from(data.height), n.width, n.height));
img.scale_mode = ImageScaleMode::Crop;
let n = s.doc_mut()?.get_mut(id)?;
// The characters' shared list becomes the layer's, so the crop shows on every one of them.
crate::cmd::lists::take_character_fills(n);
if let Some(f) = n.fills.get_mut(index) {
*f = paint;
}
+24
View File
@@ -215,6 +215,30 @@ mod tests {
assert_eq!(x(&s, small).0, x(&s, big).0);
}
/// "for baseline alignment, the bottoms of the icon and the word home are aligned on the red
/// line" (Use the horizontal and vertical flows in auto layout, the figure's caption; #1825): a
/// layer without text sits on the text's baseline with its bottom edge, not at the top.
#[test]
fn baseline_alignment_puts_an_icons_bottom_on_the_text_baseline() {
let mut s = Session::new();
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 100, "props": {"layout": "horizontal", "gap": 8}})));
let icon = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 16, "height": 16, "parent": f})));
let home = id(&ex(&mut s, "text.create", json!({"text": "Home", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 48}})));
ex(&mut s, "node.set", json!({"id": f, "props": {"crossAlign": "baseline"}}));
let base = figcraft_text::layout_node(&node(&s, home)).and_then(|(l, dy)| l.lines.first().map(|line| line.baseline + dy));
// Only meaningful when the text was measured (fonts available) and its baseline is below
// the icon's height.
if let Some(b) = base
&& b > 16.0
{
let bottom = x(&s, icon).1 + 16.0;
assert!((bottom - (x(&s, home).1 + b)).abs() < 1e-6, "icon bottom {bottom}, text baseline {}", x(&s, home).1 + b);
}
// Top alignment puts it back at the top.
ex(&mut s, "node.set", json!({"id": f, "props": {"crossAlign": "min"}}));
assert_eq!(x(&s, icon).1, x(&s, home).1);
}
#[test]
fn grid_tracks_cells_and_undo() {
let mut s = Session::new();

Some files were not shown because too many files have changed in this diff Show More