Merge main into #2094

This commit is contained in:
bflatastic committed 2026-11-12 10:50:07 +07:00
commit 3c0505def6
118 files changed
+4957 -318

No files matched your search

Generated
+1
View File
@@ -1812,6 +1812,7 @@ dependencies = [
"windows",
"winit",
"winresource",
"winsafe",
"zbus",
]
+11 -20
View File
@@ -37,7 +37,7 @@ use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate};
use serde_json::{Value, json};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, future_to_promise};
use wasm_bindgen_futures::JsFuture;
use crate::saved_files::SavedFiles;
@@ -150,15 +150,6 @@ async fn sleep(ms: i32) {
let _ = JsFuture::from(promise).await;
}
/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`.
fn outcome(reply: &Value) -> Result<JsValue, JsValue> {
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(to_js(reply.get("result").unwrap_or(&Value::Null)))
} else {
Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into())
}
}
fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> {
js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ())
}
@@ -169,20 +160,20 @@ pub fn install() -> Result<(), JsValue> {
Rc::new(PageApi::new(APP, Methods::default(), request)).install()?;
let window = web_sys::window().ok_or("no window")?;
let obj: js_sys::Object = js_sys::Reflect::get(&window, &APP.into())?.unchecked_into();
set_fn(
&obj,
"inspect",
Closure::<dyn Fn() -> js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("document.inspect", json!({})).await) }))
.into_js_value(),
)?;
// `inspect` is `docInspect` under its earlier name: the crate's function, so it times out too.
let doc_inspect = js_sys::Reflect::get(&obj, &"docInspect".into())?;
js_sys::Reflect::set(&obj, &"inspect".into(), &doc_inspect)?;
// `openFile` runs `file.open` through the crate's `execute`, so a call the app does not answer times out and is cancelled.
let execute: js_sys::Function = js_sys::Reflect::get(&obj, &"execute".into())?.unchecked_into();
let this = obj.clone();
set_fn(
&obj,
"openFile",
Closure::<dyn Fn(String, js_sys::Uint8Array) -> js_sys::Promise>::new(|name: String, bytes: js_sys::Uint8Array| {
Closure::<dyn Fn(String, js_sys::Uint8Array) -> JsValue>::new(move |name: String, bytes: js_sys::Uint8Array| {
let data = base64::engine::general_purpose::STANDARD.encode(bytes.to_vec());
future_to_promise(async move {
outcome(&send("engine.execute", json!({"command": "file.open", "params": {"name": name, "data": data}})).await)
})
execute
.call2(&this, &"file.open".into(), &to_js(&json!({"name": name, "data": data})))
.unwrap_or_else(|e| js_sys::Promise::reject(&e).into())
})
.into_js_value(),
)?;
+3
View File
@@ -39,6 +39,9 @@ env_logger = { version = "0.11", default-features = false, features = ["auto-col
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] }
# The custom title bar's window styles (src/window_frame.rs): safe Win32 wrappers (MIT); the `user`
# feature is User32.dll only. Same version as DesignCraft and PhotoCraft.
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
# The system colour scheme (org.freedesktop.portal.Settings): winit reports no theme on Linux and
# the BSDs, so the interface's "system" mode follows the portal's instead. zbus comes in through
+10
View File
@@ -29,6 +29,7 @@ mod graphics;
mod recovery;
mod services;
mod startup;
mod window_frame;
#[cfg(all(test, target_os = "macos"))]
mod apple_events_tests;
@@ -63,6 +64,8 @@ struct App {
title: String,
/// Shared with the services, which write the copies after a panic.
recovery: recovery::Shared,
/// Keeps the custom title bar's undecorated windows borderless (Windows, #1343).
window_frame: window_frame::WindowFrame,
/// Documents and quit requests from Finder, the Dock and Open With.
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -111,6 +114,9 @@ impl eframe::App for App {
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
// winit gives an undecorated window its caption back when it changes the window's flags
// (maximize, restore, ...): take it off again before the frame is laid out (#1343).
self.window_frame.run();
// Pointer and key events sent over the control channel (`ui.input`), for the window
// about to draw.
if let Some(events) = with_app(|fig| figcraft_ui_egui::windows::take_input(fig, raw_input.viewport_id)) {
@@ -268,6 +274,7 @@ fn main() -> eframe::Result {
// the old bespoke xdg-decoration probe that always drew FigCraft's custom title bar on KDE.
fig.ui.title_bar = desktop_title_bar();
viewport = window_chrome(viewport, fig.ui.title_bar);
let custom_titlebar = fig.ui.title_bar == figcraft_ui_egui::TitleBar::Custom;
if let Some(icon) = icon {
viewport = viewport.with_icon(icon);
}
@@ -304,6 +311,9 @@ fn main() -> eframe::Result {
ctx_slot,
title: String::new(),
recovery,
// The custom title bar's undecorated window must stay borderless, or its caption
// and border offset the content and the pointer on some Windows systems (#1343).
window_frame: window_frame::WindowFrame::new(custom_titlebar),
#[cfg(target_os = "macos")]
apple_events: apple_events.connect(&cc.egui_ctx),
}))
+177
View File
@@ -0,0 +1,177 @@
//! Keeps the custom (undecorated) title bar windows truly borderless on Windows (#1343).
//!
//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the
//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems the
//! desktop compositor still reserves that frame for the window surface: the content is drawn about
//! 30 px low (a black band above it) while the pointer keeps the un-offset client coordinates, so
//! clicks land on something other than what is drawn under them.
//!
//! winit 0.27 omitted those styles for undecorated windows and had no offset. [`WindowFrame`]
//! restores that: it strips `WS_CAPTION` and `WS_BORDER` from every window of this process that
//! draws its own title bar, and has Windows recalculate the frame. winit puts the styles back
//! whenever it changes the window flags (maximize, restore, ...), so the step runs every frame; it
//! reads each style and writes only when it differs, so it costs next to nothing.
//!
//! The same fix is in DesignCraft (#2139) and PhotoCraft (#2401). The long-term fix is in winit
//! (storytold/winit#17); this module goes when the pinned winit has it.
//!
//! The Windows calls go through safe `winsafe` wrappers (the workspace forbids `unsafe`). Which
//! windows are ours is found by enumerating this process's top-level windows of winit's window
//! class, so the main window and every other window opened later are covered alike, and a file
//! dialog or message box of the same process is left alone.
/// `WS_BORDER`.
#[cfg(any(windows, test))]
const WS_BORDER: u32 = 0x0080_0000;
/// `WS_CAPTION`, which already includes `WS_BORDER`.
#[cfg(any(windows, test))]
const WS_CAPTION: u32 = 0x00C0_0000;
/// `style` without the OS title bar and frame (`WS_CAPTION`, `WS_BORDER`). The sizing border
/// (`WS_THICKFRAME`) and the window buttons stay, so edge resizing, Aero snap and the system menu
/// keep working, as they did with winit 0.27's undecorated windows.
#[cfg(any(windows, test))]
pub fn borderless_style(style: u32) -> u32 {
style & !(WS_CAPTION | WS_BORDER)
}
/// The per-frame step that keeps the windows borderless; a no-op where the OS draws the frame
/// (macOS, Linux, the BSDs), where the app uses the system title bar, and in the browser.
pub struct WindowFrame {
step: Option<Box<dyn FnMut()>>,
}
impl WindowFrame {
/// The step for an app whose windows draw their own title bar when `custom_titlebar`.
pub fn new(custom_titlebar: bool) -> Self {
Self { step: platform::step(custom_titlebar) }
}
/// Run the step; call it once per frame, before the frame is laid out.
pub fn run(&mut self) {
if let Some(step) = self.step.as_mut() {
step();
}
}
#[cfg(test)]
fn with_step(step: Box<dyn FnMut()>) -> Self {
Self { step: Some(step) }
}
}
#[cfg(windows)]
mod platform {
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
/// winit's window class (`WindowAttributes`' default `class_name`).
const WINIT_CLASS: &str = "Window Class";
/// A step that strips the frame styles from this process's windows each call, or `None` when
/// the app uses the system title bar (the windows are decorated).
pub fn step(custom_titlebar: bool) -> Option<Box<dyn FnMut()>> {
if !custom_titlebar {
return None;
}
let pid = std::process::id();
Some(Box::new(move || {
// The windows are handed over as real `HWND`s; nothing is wrapped from a raw handle.
let _ = winsafe::EnumWindows(|hwnd| {
strip_if_ours(&hwnd, pid);
true
});
}))
}
/// Strip `hwnd` when it is one of this process's winit windows.
fn strip_if_ours(hwnd: &HWND, pid: u32) {
if hwnd.GetWindowThreadProcessId().1 != pid || !matches!(hwnd.GetClassName().as_deref(), Ok(WINIT_CLASS)) {
return;
}
strip(hwnd);
}
/// Removes `WS_CAPTION`/`WS_BORDER` and has Windows recalculate the frame; a no-op once they
/// are gone.
fn strip(hwnd: &HWND) {
let style = hwnd.style();
// The decision is the tested arithmetic; the write uses the same bits as winsafe's flags.
if super::borderless_style(style.raw()) == style.raw() {
return;
}
hwnd.set_style(style & !(co::WS::CAPTION | co::WS::BORDER));
let _ = hwnd.SetWindowPos(
HwndPlace::None,
POINT::new(),
SIZE::new(),
co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
);
}
}
#[cfg(not(windows))]
mod platform {
pub fn step(_custom_titlebar: bool) -> Option<Box<dyn FnMut()>> {
None
}
}
#[cfg(test)]
mod window_frame_tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::{WS_BORDER, WS_CAPTION, WindowFrame, borderless_style};
#[cfg(windows)]
#[test]
fn the_style_bits_match_winsafes() {
use winsafe::co;
assert_eq!(co::WS::CAPTION.raw(), WS_CAPTION);
assert_eq!(co::WS::BORDER.raw(), WS_BORDER);
}
const WS_SYSMENU: u32 = 0x0008_0000;
const WS_THICKFRAME: u32 = 0x0004_0000;
const WS_MINIMIZEBOX: u32 = 0x0002_0000;
const WS_MAXIMIZEBOX: u32 = 0x0001_0000;
const WS_VISIBLE: u32 = 0x1000_0000;
#[test]
fn the_borderless_style_drops_the_caption_and_border_only() {
let decorated = WS_CAPTION | WS_BORDER | WS_SYSMENU | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_VISIBLE;
let bare = borderless_style(decorated);
assert_eq!(bare & WS_CAPTION, 0, "caption gone");
assert_eq!(bare & WS_BORDER, 0, "border gone");
assert_eq!(bare & WS_THICKFRAME, WS_THICKFRAME, "edge resizing kept");
assert_eq!(bare & (WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU), WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU, "window buttons kept");
assert_eq!(bare & WS_VISIBLE, WS_VISIBLE, "unrelated bits kept");
}
#[test]
fn an_already_borderless_style_is_unchanged_so_no_frame_change_is_made() {
let bare = WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_VISIBLE;
assert_eq!(borderless_style(bare), bare);
assert_eq!(borderless_style(borderless_style(bare | WS_CAPTION)), bare);
}
#[test]
fn the_step_runs_each_time_the_frame_runs_it() {
let calls = Arc::new(AtomicUsize::new(0));
let n = calls.clone();
let mut frame = WindowFrame::with_step(Box::new(move || {
n.fetch_add(1, Ordering::SeqCst);
}));
for _ in 0..3 {
frame.run();
}
assert_eq!(calls.load(Ordering::SeqCst), 3);
}
#[test]
fn no_step_is_fine() {
// Decorated windows and other platforms have no step; running must do nothing.
let mut frame = WindowFrame::new(false);
frame.run();
}
}
+3
View File
@@ -115,3 +115,6 @@ display_name = "Hamza0101"
[people.ashokram-si]
real_name = "Ashok Ram"
[people.GiovanniBot]
sync_github_name = true
+37 -1
View File
@@ -4,7 +4,7 @@
use std::sync::{Arc, Mutex};
use figcraft_collab::message::{Peer, Presence, ServerMsg};
use figcraft_collab::message::{Access, CatchUp, Peer, Presence, Processed, ServerMsg};
use figcraft_engine::live::{Event, MAX_PEERS};
use crate::guest::GuestConfig;
@@ -59,3 +59,39 @@ fn joins_past_the_cap_are_left_out_until_someone_leaves() {
send(joined(over));
assert!(matches!(inbox.drain().as_slice(), [Event::PeerLeft(7), Event::PeerJoined(p)] if p.client_id == over));
}
#[test]
fn a_hosts_long_names_and_colours_are_cut_where_they_are_kept() {
let inbox = inbox();
let cfg = GuestConfig::new(Invite::new("127.0.0.1:47900", "0123456789abcdef", "AbCdEfGhIjKlMnOpQrStUv"), "Ada".into());
let resume = Mutex::new(None);
let mut seen = Seen::default();
let long = "x".repeat(100_000);
take(ServerMsg::PeerJoined(Peer { client_id: 1, name: long.clone(), color: long }), &cfg, &inbox, &mut seen, &resume, &|| {});
match inbox.drain().as_slice() {
[Event::PeerJoined(p)] => assert_eq!((p.name.as_str(), p.color.as_str()), ("x".repeat(256).as_str(), "x".repeat(32).as_str())),
other => panic!("{other:?}"),
}
}
#[test]
fn the_welcome_handed_to_the_sync_client_carries_the_bounded_roster() {
let inbox = inbox();
let cfg = GuestConfig::new(Invite::new("127.0.0.1:47900", "0123456789abcdef", "AbCdEfGhIjKlMnOpQrStUv"), "Ada".into());
let resume = Mutex::new(None);
let long = "y".repeat(100_000);
let welcome = ServerMsg::Welcome {
session: 1,
client_id: 9,
seq: 0,
catch_up: CatchUp::Snapshot(Vec::new()),
processed: Processed::default(),
peers: vec![Peer { client_id: 1, name: long.clone(), color: long }],
access: Access::default(),
secret: 0,
};
take(welcome, &cfg, &inbox, &mut Seen::default(), &resume, &|| {});
let events = inbox.drain();
let Some(Event::Sync(ServerMsg::Welcome { peers, .. })) = events.iter().find(|e| matches!(e, Event::Sync(_))) else { panic!("{events:?}") };
assert_eq!(peers.first().map(|p| (p.name.chars().count(), p.color.chars().count())), Some((256, 32)));
}
+21 -4
View File
@@ -226,6 +226,19 @@ pub(crate) struct Seen {
peers: Vec<Peer>,
}
/// `p` with its name and colour cut to what the UI shows: the host is untrusted, and the roster is
/// copied whenever someone's identity is updated.
fn bounded(mut p: Peer) -> Peer {
p.name = p.name.chars().take(MAX_PEER_NAME).collect();
p.color = p.color.chars().take(MAX_COLOR).collect();
p
}
/// The most characters of a colour (`#rrggbb` and a few spellings more) kept for someone.
const MAX_COLOR: usize = 32;
/// The most characters of a name kept for someone.
const MAX_PEER_NAME: usize = 256;
/// What taking in one message from the host means for the connection.
pub(crate) enum Taken {
Continue,
@@ -251,7 +264,7 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
*r = Some(Resume { session, client_id, seq, secret });
}
// The sync client opens the document (and fills in its name and pages).
let peers: Vec<Peer> = peers.iter().take(MAX_PEERS).cloned().collect();
let peers: Vec<Peer> = peers.iter().take(MAX_PEERS).cloned().map(bounded).collect();
let inv = &cfg.invite;
let info = SessionInfo {
role: Role::Guest,
@@ -268,20 +281,24 @@ pub(crate) fn take(mut m: ServerMsg, cfg: &GuestConfig, inbox: &Inbox, seen: &mu
view: None,
};
seen.peers = peers.clone();
// The sync client keeps the roster of the welcome it is handed: the bounded one.
if let ServerMsg::Welcome { peers: sent, .. } = &mut m {
sent.clone_from(&peers);
}
seen.info = Some(info.clone());
welcomed();
inbox.push(Event::Welcome { info, peers });
inbox.push(Event::Sync(m));
return Taken::Welcomed;
}
ServerMsg::PeerJoined(p) => match seen.info.as_mut() {
ServerMsg::PeerJoined(p) => match (seen.info.as_mut(), bounded(p)) {
// The host tells you how you are shown.
Some(info) if p.client_id == info.me => {
(Some(info), p) if p.client_id == info.me => {
info.name = p.name;
info.color = p.color;
inbox.push(Event::Welcome { info: info.clone(), peers: seen.peers.clone() });
}
_ => {
(_, p) => {
match seen.peers.iter().position(|q| q.client_id == p.client_id) {
Some(i) => {
seen.peers.remove(i);
+2 -2
View File
@@ -37,8 +37,8 @@ impl FileKind {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum BoardItem {
/// A sticky note: a frame whose first text layer is the note (its size shrinks as the note
/// grows) and, below it, who wrote it.
/// A sticky note: a frame whose first text layer is the note (its size stays fixed, the note
/// grows taller) and, below it, who wrote it.
Sticky {
#[serde(default, skip_serializing_if = "String::is_empty")]
author: String,
+127 -18
View File
@@ -355,14 +355,15 @@ pub fn enter_target(doc: &Document, leaf: NodeId, selection: &[NodeId]) -> NodeI
inner.unwrap_or_else(|| select_target(doc, leaf, selection, false))
}
/// Nodes on `page` whose world bounds intersect `rect` (marquee): top-level children, or the
/// children of top-level frames when the marquee starts inside a frame (`within`).
/// Nodes a marquee over `rect` touches, one level only: the children of `within` (a focus view's
/// frame), or the top-level layers of `page`. Frames are not opened or enclosed here; see
/// [`marquee_select`] for a plain marquee.
pub fn marquee(doc: &Document, page: NodeId, rect: Rect, within: Option<NodeId>) -> Vec<NodeId> {
let parent = within.unwrap_or(page);
doc.node(parent).map(|p| marquee_children(doc, p, rect)).unwrap_or_default()
}
/// Nodes on `page` a Cmd/Ctrl marquee selects: the innermost layers whose bounds touch `rect`
/// Nodes on `page` a Cmd/Ctrl marquee selects: the innermost layers the marquee touches
/// (frames, groups and instances are looked into; a container none of whose children are touched
/// counts itself; boolean groups count as one shape).
pub fn marquee_deep(doc: &Document, page: NodeId, rect: Rect) -> Vec<NodeId> {
@@ -384,25 +385,133 @@ pub fn marquee_deep(doc: &Document, page: NodeId, rect: Rect) -> Vec<NodeId> {
out
}
/// The visible, unlocked children of `p` whose world bounds touch `rect` (on both axes: lines and
/// other flat layers too).
/// The visible, unlocked children of `p` the marquee touches (see [`marquee_touches`]).
fn marquee_children(doc: &Document, p: &Node, rect: Rect) -> Vec<NodeId> {
p.children
.iter()
.copied()
.filter(|c| doc.node(*c).is_some_and(|n| n.visible && !n.locked))
.filter(|c| doc.world_bounds(*c).is_some_and(|b| b.x0 <= rect.x1 && b.x1 >= rect.x0 && b.y0 <= rect.y1 && b.y1 >= rect.y0))
.collect()
p.children.iter().copied().filter(|c| doc.node(*c).is_some_and(|n| n.visible && !n.locked && marquee_touches(doc, *c, n, rect))).collect()
}
/// Figma marquee rule: a marquee that fully contains a top-level frame selects the frame; one
/// starting on empty canvas selects top-level objects it touches.
pub fn marquee_select(doc: &Document, page: NodeId, rect: Rect, start_inside: Option<NodeId>) -> Vec<NodeId> {
if let Some(frame) = start_inside {
let inside = marquee(doc, page, rect, Some(frame));
return inside;
/// The outline a rotated shape is touched by. One line: return the turned box instead
/// (`figcraft_geom::rounded_rect(n.width, n.height, [0.0; 4], 0.0)`) if Figma proves to test that.
fn marquee_outline(n: &Node) -> Option<BezPath> {
shape_path(n)
}
/// Whether the marquee touches layer `id`: its world box overlaps `rect` (inclusive, so lines and
/// zero-size marquees count) and, for a rotated shape, its outline in page space does too.
fn marquee_touches(doc: &Document, id: NodeId, n: &Node, rect: Rect) -> bool {
let box_hit = doc.world_bounds(id).is_some_and(|b| b.x0 <= rect.x1 && b.x1 >= rect.x0 && b.y0 <= rect.y1 && b.y1 >= rect.y0);
if !box_hit
|| !matches!(
n.kind,
NodeKind::Rectangle
| NodeKind::Ellipse { .. }
| NodeKind::Polygon { .. }
| NodeKind::Star { .. }
| NodeKind::Line
| NodeKind::Vector { .. }
)
{
return box_hit;
}
marquee(doc, page, rect, None)
let xf = doc.world_transform(id);
let [a, b, c, d, e, f] = xf.as_coeffs();
const EPS: f64 = 1e-9;
let rotated = !((b.abs() < EPS && c.abs() < EPS) || (a.abs() < EPS && d.abs() < EPS));
if !rotated {
return true;
}
let det = a * d - b * c;
if ![a, b, c, d, e, f, det].iter().all(|v| v.is_finite()) || det.abs() < EPS {
return true;
}
marquee_outline(n).is_none_or(|path| path_touches_rect(n, &path, xf, rect))
}
/// Whether the marquee and the shape drawn as local `path` under `xf` share a point: a path end
/// inside the marquee, a path segment crossing a marquee edge, or the marquee inside the filled shape.
fn path_touches_rect(n: &Node, path: &BezPath, xf: figcraft_geom::Affine, rect: Rect) -> bool {
use figcraft_geom::kurbo::{Line, ParamCurve, PathSeg};
let inside = |p: Point| p.x >= rect.x0 && p.x <= rect.x1 && p.y >= rect.y0 && p.y <= rect.y1;
let mut world = path.clone();
world.apply_affine(xf);
if world.segments().any(|s| inside(s.start()) || inside(s.end())) {
return true;
}
let (tl, tr, br, bl) = (Point::new(rect.x0, rect.y0), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1));
let edges = [(tl, tr), (tr, br), (br, bl), (bl, tl)];
for (p, q) in edges {
if (q - p).hypot() < 1e-9 {
continue;
}
let line = Line::new(p, q);
if world.segments().any(|s: PathSeg| s.intersect_line(line).iter().any(|h| (0.0..=1.0).contains(&h.line_t))) {
return true;
}
}
is_closed(n) && fills_point(n, path, xf.inverse() * tl)
}
/// Whether a marquee takes a touched top-level layer whole, opens it for the layers in it, or skips it.
enum Touch {
Whole,
/// The frame the drag started in: the layers in it the marquee touches, or the frame itself
/// (whole) once the marquee is at the top level.
Open,
/// A partly covered frame or section: the layers in it, or the frame itself once the marquee is at the top level.
Partial,
Skip,
}
/// Figma's marquee rule (measured in the web app, 2026-11-11): each top-level layer the marquee
/// touches is selected whole, except a frame with children or a section with its contents shown:
/// enclosed by the marquee it is selected itself, otherwise the marquee takes the layers in it that
/// it touches. The frame the drag started in (`start_inside`) is selected only when the marquee also
/// takes another top-level frame (then whole); otherwise only the layers in it the marquee touches.
/// Selecting a frame or section whole keeps the marquee at the top level: no frame opens then, and a
/// partly covered one is selected whole. Components, instances, board items and sections with hidden
/// contents are selected only when enclosed.
pub fn marquee_select(doc: &Document, page: NodeId, rect: Rect, start_inside: Option<NodeId>) -> Vec<NodeId> {
let Some(page_node) = doc.node(page) else { return Vec::new() };
let touched = marquee_children(doc, page_node, rect);
let classified: Vec<(NodeId, Touch, bool)> = touched
.iter()
.filter_map(|t| {
let n = doc.node(*t)?;
let enclosed = doc.world_bounds(*t).is_some_and(|b| rect.contains(b.origin()) && rect.contains(Point::new(b.x1, b.y1)));
let container = n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. });
let opens = match &n.kind {
NodeKind::Frame | NodeKind::Section { .. } => !n.is_board_atom() && !n.hides_contents() && !n.children.is_empty(),
_ => false,
};
let plain_empty_frame = matches!(n.kind, NodeKind::Frame) && n.children.is_empty() && !n.is_board_atom();
let act = if start_inside == Some(*t) {
Touch::Open
} else if opens {
if enclosed { Touch::Whole } else { Touch::Partial }
} else if plain_empty_frame || !(container || n.is_board_atom()) || enclosed {
Touch::Whole
} else {
Touch::Skip
};
let whole_container = container && matches!(act, Touch::Whole);
Some((*t, act, whole_container))
})
.collect();
let top_level_mode = classified.iter().any(|(_, _, whole_container)| *whole_container);
let mut out = Vec::new();
for (t, act, _) in &classified {
match act {
Touch::Whole => out.push(*t),
Touch::Open | Touch::Partial if top_level_mode => out.push(*t),
Touch::Open | Touch::Partial => {
if let Some(n) = doc.node(*t) {
out.extend(marquee_children(doc, n, rect));
}
}
Touch::Skip => {}
}
}
out
}
/// Bounds of a node's outline in page coordinates for snapping (the box corners and centre).
+38
View File
@@ -920,6 +920,25 @@ impl TextData {
}
pl.indent = pl.indent.min(MAX_LIST_INDENT);
}
self.fold_paragraph_lists();
}
/// Give paragraphs `a..=b` (by index) no start number of their own, as an item made by Enter
/// has none. Touches nothing else: a plain paragraph keeps its level, a bullet its settings.
/// One pass over the range, and nothing at all when no paragraph carries a start.
pub fn clear_list_starts(&mut self, a: usize, b: usize) {
if self.paragraphs.iter().all(|p| p.start_offset == 0) {
return;
}
self.fill_paragraphs();
for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) {
pl.start_offset = 0;
}
self.fold_paragraph_lists();
}
/// One style for all paragraphs with no nesting or start folds back into `list`.
fn fold_paragraph_lists(&mut self) {
if let Some(first) = self.paragraphs.first().copied()
&& first == (ParaList { list: first.list, ..ParaList::default() })
&& self.paragraphs.iter().all(|p| *p == first)
@@ -1213,6 +1232,25 @@ mod case_tests {
assert!(t.paragraphs.is_empty());
assert_eq!(t.common_wrap_style(0, t.char_count()), Some(Auto));
}
#[test]
fn clear_list_starts_touches_only_starts() {
use ListStyle::{None as P, Numbered as N};
let mut t = TextData { characters: "a\nb\nc".into(), ..Default::default() };
t.paragraphs = vec![
ParaList { list: N, start_offset: 4, ..ParaList::default() },
ParaList { list: P, indent: 1, ..ParaList::default() },
ParaList { list: N, indent: 2, start_offset: 7, ..ParaList::default() },
];
t.clear_list_starts(1, 2);
assert_eq!(t.para_list(0).start_offset, 4, "outside the range");
assert_eq!(t.para_list(1), ParaList { list: P, indent: 1, ..ParaList::default() }, "a plain paragraph keeps its level");
assert_eq!(t.para_list(2), ParaList { list: N, indent: 2, start_offset: 0, ..ParaList::default() });
// Out of range and no-start cases leave it alone.
t.clear_list_starts(5, 9);
t.clear_list_starts(0, 0);
assert_eq!(t.para_list(0).start_offset, 0);
}
}
#[cfg(test)]
+25 -1
View File
@@ -60,7 +60,7 @@ pub use patch::sync_after_edit;
pub(crate) use patch::{FULL_REBUILD, PATCHED};
#[cfg(test)]
use rebase::RebaseSources;
pub use rebase::rebase_instance;
pub use rebase::{MainPaths, rebase_instance, rebase_instance_with};
pub use sync::keep_text_overrides;
pub use variants::{default_variant, exposed_copies, find_variant, mirror_issues, variant_conflicts, variant_name, variant_options, variant_props};
@@ -298,6 +298,30 @@ pub fn prop_list(doc: &Document, c: NodeId) -> Vec<(String, PropDef)> {
}
}
/// The properties an instance of `component` lists: [`prop_list`] without the boolean, text and
/// instance swap properties that no layer of the component reads. A set's variants share its
/// definitions, so one a variant's layers don't bind (another variant's text, a leftover of a
/// deleted variant) stays defined, and shows on the set, but not on this variant's instances
/// (#2022). Slots stay. Walks as [`slots_of`] does: a nested instance counts, its own layers and
/// the content put into slots are not entered.
pub fn instance_prop_list(doc: &Document, component: NodeId) -> Vec<(String, PropDef)> {
let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut stack = vec![component];
let mut seen = 0usize;
while let Some(c) = stack.pop() {
seen += 1;
if seen > 1_000_000 {
break;
}
let Some(n) = doc.node(c) else { continue };
used.extend(n.prop_refs.values().cloned());
if c == component || (!is_instance(doc, c) && !holds_content(n)) {
stack.extend(n.children.iter().rev().copied());
}
}
prop_list(doc, component).into_iter().filter(|(k, d)| !takes_value(d) || used.contains(k)).collect()
}
/// Whether instances store a value for the property (every kind but slots).
pub fn takes_value(d: &PropDef) -> bool {
!matches!(d, PropDef::Slot { .. })
+20 -2
View File
@@ -165,10 +165,28 @@ impl<'a> RebaseSources<'a> {
/// values (after detaching an outer instance, restoring a main, or copying a nested instance out):
/// the look is kept exactly. Values a component property sets aren't overrides.
pub fn rebase_instance(doc: &mut Document, inst: NodeId) {
rebase_instance_with(doc, inst, &mut MainPaths::new());
}
/// The layers of mains by path, kept across several [`rebase_instance_with`] calls. Rebasing only
/// writes instances' `source` and `overrides`, never a main's layers or names, so a main's paths
/// stay right for as long as the caller changes nothing else.
pub type MainPaths = BTreeMap<NodeId, std::rc::Rc<BTreeMap<String, NodeId>>>;
/// [`rebase_instance`], taking each main's path map from `mains` (and adding it there).
pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPaths) {
let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|n| n.kind.clone()) else { return };
let mine = path_map(doc, inst, true);
let theirs: BTreeMap<String, NodeId> =
if doc.contains(component) { path_map(doc, component, false).into_iter().map(|(k, v)| (v, k)).collect() } else { BTreeMap::new() };
let theirs = mains
.entry(component)
.or_insert_with(|| {
std::rc::Rc::new(if doc.contains(component) {
path_map(doc, component, false).into_iter().map(|(k, v)| (v, k)).collect()
} else {
BTreeMap::new()
})
})
.clone();
let value_groups = |a: &Node, b: &Node| -> Vec<String> {
diff_groups(a, b).into_iter().filter(|g| !matches!(*g, "size" | "position")).map(str::to_string).collect()
};
+22 -7
View File
@@ -34,7 +34,7 @@ pub(super) fn sync_instance_depth(doc: &mut Document, inst: NodeId, depth: usize
let nid = doc.alloc_id();
map.insert(s, nid);
}
let Copies { nodes: new_nodes, nested, mut remeasure } = copy_layers(doc, inst, &src, &map, &old, &edited, eff_props);
let Copies { nodes: new_nodes, nested, mut remeasure } = copy_layers(doc, inst, component, &src, &map, &old, &edited, eff_props);
for n in new_nodes {
let (id, parent) = (n.id, n.parent);
if insert_linked(doc, n).is_err()
@@ -132,6 +132,7 @@ struct Copies {
fn copy_layers(
doc: &Document,
inst: NodeId,
component: NodeId,
src: &[NodeId],
map: &BTreeMap<NodeId, NodeId>,
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
@@ -139,7 +140,7 @@ fn copy_layers(
props: BTreeMap<String, Value>,
) -> Copies {
let mut enclosing: BTreeMap<NodeId, Vec<NodeId>> = BTreeMap::from([(inst, vec![inst])]);
let mut inst_props: BTreeMap<NodeId, BTreeMap<String, Value>> = BTreeMap::from([(inst, props)]);
let mut inst_props: BTreeMap<NodeId, (NodeId, BTreeMap<String, Value>)> = BTreeMap::from([(inst, (component, props))]);
let mut out = Copies { nodes: Vec::new(), nested: Vec::new(), remeasure: Vec::new() };
for s in src {
let Some(orig) = doc.node(*s) else { continue };
@@ -164,12 +165,12 @@ fn copy_layers(
// No longer a slot in the main: it mirrors the main again.
n.overrides.remove(SLOT);
}
// Component properties: the main layer's bindings use this instance's values; layers of
// nested instances use the nested instance's values (one level per source hop).
// Bindings use the enclosing instance of their defining component, even when slot
// content has fewer source hops than enclosing instances.
let enc = enclosing.get(&parent).cloned().unwrap_or_default();
apply_enclosing_props(doc, &mut n, orig, &enc, &inst_props);
if let NodeKind::Instance { component: c, props } = &n.kind {
inst_props.insert(nid, props.clone());
inst_props.insert(nid, (*c, props.clone()));
let mut e = enc;
e.push(nid);
enclosing.insert(nid, e);
@@ -253,14 +254,28 @@ fn rebuild_nested(doc: &mut Document, nested: Vec<NodeId>, old: &BTreeMap<NodeId
}
}
fn apply_enclosing_props(doc: &Document, n: &mut Node, orig: &Node, enc: &[NodeId], inst_props: &BTreeMap<NodeId, BTreeMap<String, Value>>) {
/// Apply bindings from their defining components, preserving explicit overrides and letting
/// nearer source layers take precedence. Slot content need not have one source hop per instance.
fn apply_enclosing_props(
doc: &Document,
n: &mut Node,
orig: &Node,
enc: &[NodeId],
inst_props: &BTreeMap<NodeId, (NodeId, BTreeMap<String, Value>)>,
) {
let mut chain: Vec<&Node> = vec![orig];
while chain.len() < enc.len() {
let Some(next) = chain.last().and_then(|c| c.source).and_then(|x| doc.node(x)) else { break };
chain.push(next);
}
for (j, level) in chain.iter().enumerate().rev() {
let Some(props) = enc.get(j).and_then(|e| inst_props.get(e)) else { continue };
if level.prop_refs.is_empty() {
continue;
}
let Some(owner) = owning_component(doc, level.id) else { continue };
// Instance-owned slot content skips a source hop through the slot's component. Match
// the binding's defining component, not the position in the enclosing instance chain.
let Some((_, props)) = enc.iter().rev().filter_map(|e| inst_props.get(e)).find(|(component, _)| *component == owner) else { continue };
for (field, prop) in &level.prop_refs {
let g = field_group(field);
if n.overrides.contains(g) || (j > 0 && orig.overrides.contains(g)) {
+4 -1
View File
@@ -395,8 +395,11 @@ fn unbind_delete_and_vary(s: &mut Session, c: NodeId, i: NodeId, title: NodeId,
ex(s, "component.deleteProperty", json!({"id": c, "name": "Heading"}));
assert!(node(s, title).prop_refs.is_empty());
assert!(matches!(&node(s, i).kind, NodeKind::Instance { props, .. } if !props.contains_key("Heading")));
let desc = ex(s, "component.properties", json!({"id": i}));
// "Show dot" is still defined but no layer reads it any more: the main lists it, the instance doesn't (#2022).
let desc = ex(s, "component.properties", json!({"id": c}));
assert_eq!(desc["properties"].as_array().unwrap().len(), 1);
let desc = ex(s, "component.properties", json!({"id": i}));
assert!(desc["properties"].as_array().unwrap().is_empty());
// A variant property on a lone component makes it a component set.
let set = idv(&ex(s, "component.addProperty", json!({"id": c, "name": "Theme", "type": "variant", "default": "Light"})));
assert!(matches!(node(s, set).kind, NodeKind::ComponentSet { .. }));
+186 -22
View File
@@ -12,6 +12,11 @@
//! existing folder is resolved and the rest must be plain names. The comparison is by whole
//! components (`/work2` is not inside `/work`), and the I/O uses the resolved path, so what was
//! checked is what is opened.
//!
//! On Windows, resolving a path opens it, and opening a path on another computer contacts that
//! computer and may send it the signed-in user's credentials. So on Windows, before anything is
//! resolved, a path on another computer whose share no root is on, a device path, or one reached
//! through a link that leads to them is refused by how it is spelled (#1094).
#![allow(clippy::disallowed_methods)]
use std::cell::RefCell;
@@ -19,6 +24,8 @@ use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use craft_docpath::Refused;
use crate::{EngineError, Result};
/// What a command does with a file.
@@ -58,6 +65,19 @@ impl Roots {
Access::Read => ([self.read.as_slice(), self.write.as_slice()].concat(), "read"),
Access::Write => (self.write.clone(), "written"),
};
if cfg!(windows) {
match refused_unresolved(path, &roots) {
Some(Unresolved::Spelled(Refused::Network)) => {
return Err(format!(
"automation path rejected: {asked} is on another computer, and no folder that may be {what} is on its share"
));
}
Some(Unresolved::Spelled(_)) => return Err(format!("automation path rejected: {asked} names a device, not a file")),
// Where a link leads is only told by the usual message: it would say what is there.
Some(Unresolved::Linked) => return Err(outside(asked, &roots, what)),
None => {}
}
}
match resolve(path) {
Ok(resolved) if roots.iter().any(|r| resolved.starts_with(r)) => return Ok(resolved),
Ok(_) => {}
@@ -65,11 +85,7 @@ impl Roots {
Err(why) if inside_as_far_as_it_exists(path, &roots) => return Err(format!("automation path rejected: {asked}: {why}")),
Err(_) => {}
}
if roots.is_empty() {
return Err(format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}"));
}
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
Err(format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", ")))
Err(outside(asked, &roots, what))
}
/// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`.
@@ -79,23 +95,165 @@ impl Roots {
}
}
/// Why `asked` is refused: it is outside every one of `roots`, the folders that may be `what`
/// ("read" or "written"). The message lists those folders, or says that no folder may be `what`
/// when `roots` is empty.
fn outside(asked: std::path::Display<'_>, roots: &[PathBuf], what: &str) -> String {
if roots.is_empty() {
return format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}");
}
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", "))
}
/// Why a path is refused before it is resolved (#1094).
#[derive(Debug, PartialEq, Eq)]
enum Unresolved {
/// Its spelling leads to another computer ([`Refused::Network`]) or a device ([`Refused::Device`]).
Spelled(Refused),
/// A link on the way leads there, or the way there can't be looked at: a link or folder on it
/// can't be read, it has more than [`MAX_LINKS`] links, or the path can't be made absolute.
Linked,
}
/// How many links are followed on the way to a path before it is given up on, as on Linux.
const MAX_LINKS: u8 = 40;
/// Why `path` is refused before anything on the way to it is opened, if it is: resolving it would
/// open a path on another computer, which on Windows contacts that computer and may send it the
/// signed-in user's credentials, or open a device (#1094). That is the case when the path as
/// given or made absolute is refused by its spelling ([`refused_spelling`]), or when a link on
/// the way, or on the way on from where one leads, leads to such a path ([`link_refused`]). A path
/// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute
/// is refused as well, rather than left to what comes next.
fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option<Unresolved> {
// Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a
// bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes
// `..` by name, so `link\..\x` is `x` and never goes through the link.
let Ok(abs) = std::path::absolute(path) else { return Some(Unresolved::Linked) };
if let Some(why) = [path, abs.as_path()].into_iter().find_map(|p| refused_spelling(&p.to_string_lossy(), roots)) {
return Some(Unresolved::Spelled(why));
}
link_refused(&abs, roots, MAX_LINKS, &on_disk).then_some(Unresolved::Linked)
}
/// What is at a path, looked at without following a link there.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Entry {
/// Nothing ([`nothing_there`]): resolving the path meets the same there and goes no further.
Missing,
/// Something that can't be looked at (no permission, for one). It may be a link that resolving
/// the path would still follow, so the path is refused.
Unreadable,
/// A file or a folder.
Plain,
/// A link, with where it leads (`None` when that can't be read).
Link(Option<PathBuf>),
}
/// What is at `p` on disk (see [`Entry`]), looked at with [`std::fs::symlink_metadata`], which
/// doesn't follow a link there; a link's target is read with [`std::fs::read_link`].
fn on_disk(p: &Path) -> Entry {
match std::fs::symlink_metadata(p) {
Ok(m) if m.is_symlink() => Entry::Link(std::fs::read_link(p).ok()),
Ok(_) => Entry::Plain,
Err(e) if nothing_there(&e) => Entry::Missing,
Err(_) => Entry::Unreadable,
}
}
/// Whether looking at a path failed with `e` because nothing is there: no such name, a file where
/// a folder was expected, or a name no file can have. Any other failure says nothing about what is
/// there.
fn nothing_there(e: &std::io::Error) -> bool {
use std::io::ErrorKind::{InvalidFilename, NotADirectory, NotFound};
matches!(e.kind(), NotFound | NotADirectory | InvalidFilename)
}
/// Why path `p` is refused by its spelling alone, if it is (see [`craft_docpath::resolve`], which
/// reads both `/` and `\` as separators and compares names ignoring case):
/// - on another computer (`\\server\share`, `//server/share`, `\\?\UNC\…`, `\\.\UNC\…`, or a
/// server without a share) and on no root's share;
/// - a device path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`, `\\.\C:\…`), other than a local volume's
/// `\\?\Volume{…}\` or `\\.\Volume{…}\`, which a folder can be mounted as;
/// - or with a device name (`CON`, `NUL`, `COM1.png`, `lpt1 `…) as any of its names: each folder on
/// the way is opened in turn while the path is resolved, and the device behind a name such as
/// `LPT1` can be a printer on another computer.
fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option<Refused> {
match craft_docpath::resolve(p, None) {
// With a root passed as the document path (what a link would be relative to), a path on
// that root's share is allowed.
Err(Refused::Network) if !roots.iter().any(|r| craft_docpath::resolve(p, Some(r)) != Err(Refused::Network)) => {
return Some(Refused::Network);
}
Err(Refused::Device) if !is_volume(p) => return Some(Refused::Device),
_ => {}
}
// `craft_docpath` stops at the first name it refuses, which may not be the device's.
p.split(['\\', '/']).any(device_name).then_some(Refused::Device)
}
/// Whether `p` is in a local volume by its `\\?\Volume{…}` (or `\\.\Volume{…}`) name.
fn is_volume(p: &str) -> bool {
let mut names = p.split(['\\', '/']);
let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else {
return false;
};
volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}')
}
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
/// refuses, following at most `links` links: one that leads to another, or on through further
/// links, is followed too, as resolving the path would. A link that can't be read, a name on the
/// way that can't be looked at ([`Entry::Unreadable`]), or more links than that, are refused as
/// well. Each name on the way is looked at with `look` ([`on_disk`]), which doesn't follow a
/// link: where a link leads is looked at only once its spelling is known not to be refused.
fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -> Entry) -> bool {
let mut at = PathBuf::new();
let mut rest = abs.components();
while let Some(c) = rest.next() {
at.push(c);
if !matches!(c, Component::Normal(_)) {
continue;
}
let target = match look(&at) {
Entry::Plain => continue,
// Nothing is below what isn't there, so no link either.
Entry::Missing => return false,
Entry::Unreadable => return true,
Entry::Link(target) => target,
};
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true };
// A relative target is relative to the link's folder; an absolute one replaces it.
let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path()));
return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look);
}
false
}
/// `p` with its `.` and `..` taken by name, as Windows takes them.
fn lexical(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
c => out.push(c),
}
}
out
}
/// Whether `path` lies in one of `roots` once made absolute with its `.` and `..` taken by name and
/// its longest leading part that exists resolved, so links on the way are followed as the roots'
/// were (`/tmp/work/x` is inside root `/private/tmp/work`, a link out of a root leads out of it).
fn inside_as_far_as_it_exists(path: &Path, roots: &[PathBuf]) -> bool {
let Ok(abs) = std::path::absolute(path) else { return false };
let mut lexical = PathBuf::new();
for c in abs.components() {
match c {
Component::ParentDir => {
lexical.pop();
}
Component::CurDir => {}
c => lexical.push(c),
}
}
let folded = lexical(&abs);
let mut rest: Vec<&OsStr> = Vec::new();
let mut at = lexical.as_path();
let mut at = folded.as_path();
let resolved = loop {
if let Ok(mut base) = std::fs::canonicalize(at) {
base.extend(rest.iter().rev());
@@ -169,18 +327,24 @@ fn resolve(path: &Path) -> std::result::Result<PathBuf, String> {
fn plain_name(name: &OsStr) -> std::result::Result<(), String> {
if cfg!(windows) {
let n = name.to_string_lossy();
let stem = n.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.chars().count() == 4
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')));
if device || n.contains(':') {
if device_name(&n) || n.contains(':') {
return Err(format!("`{n}` is a device or stream name, not a file"));
}
}
Ok(())
}
/// Whether Windows opens a device for file or folder name `n`: `CON`, `PRN`, `AUX`, `NUL`,
/// `CONIN$`, `CONOUT$`, `COM1`…`COM9` and `LPT1`…`LPT9` (also with `¹`, `²` or `³`), in any case,
/// and with anything after a dot or a colon or trailing spaces (`nul.txt`, `COM1 .png`, `con:x`).
fn device_name(n: &str) -> bool {
let stem = n.split(['.', ':']).next().unwrap_or_default().trim_end().to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.chars().count() == 4
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
}
thread_local! {
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
}
@@ -191,6 +191,283 @@ fn windows_case_devices_and_streams() {
assert!(!e.contains(r"\\?\"), "{e}");
}
/// How each spelling of a path on another computer or of a device is told apart from a local path
/// (#1094), on every system: only Windows checks them, but they are spelled the same everywhere.
#[test]
fn spellings_of_other_computers_and_devices_are_refused() {
use super::refused_spelling;
use craft_docpath::Refused::{Device, Network};
let local = [PathBuf::from(r"C:\work")];
// On `\\192.0.2.1\share`.
let on_the_share = [
r"\\192.0.2.1\share\x.png",
"//192.0.2.1/share/x.png",
r"\/192.0.2.1/share\x.png",
r"\\?\UNC\192.0.2.1\share\x.png",
r"\\?\unc\192.0.2.1\share\x.png",
"//?/UNC/192.0.2.1/share/x.png",
r"\\.\UNC\192.0.2.1\share\x.png",
];
let elsewhere = [
// A server without a share is contacted too.
r"\\192.0.2.1",
r"\\192.0.2.1\",
r"\\SERVER.\share \x.png",
];
let network = [&on_the_share[..], &elsewhere[..]].concat();
let device = [
r"\\.\pipe\figcraft",
r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png",
r"\\.\C:\work\x.png",
r"\\.\COM1",
r"\??\UNC\192.0.2.1\share\x.png",
// A device name anywhere: each folder on the way is opened as the path is resolved.
r"C:\work\COM1",
r"C:\work\nul.txt",
r"C:\work\Com1 .png",
r"C:\work\lpt1.\x.png",
r"C:\work\LPT³\x.png",
r"C:\work\conout$",
r"C:\work\aux:stream",
// After a name `craft_docpath` refuses for another reason.
r"C:\work\a:b\prn.png",
];
let fine = [
r"C:\work\x.png",
r"\\?\C:\work\x.png",
r"C:\work\console.png",
r"C:\work\com10.png",
r"C:\work\lpt.png",
r"C:\work\nul-ish.txt",
r"\\?\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
r"\\.\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
"/home/u/work/x.png",
"x.png",
r"..\x.png",
];
for (paths, want) in [(&network[..], Some(Network)), (&device[..], Some(Device)), (&fine[..], None)] {
for p in paths {
assert_eq!(refused_spelling(p, &[]), want, "{p}");
assert_eq!(refused_spelling(p, &local), want, "{p} with a local root");
}
}
// A root on a share lets the paths on that share through, in any case and spelling, and only them:
// every spelling above of a path on `\\192.0.2.1\share`, but not the server without a share
// or another server.
for root in [r"\\?\UNC\192.0.2.1\share", r"\\192.0.2.1\share\work"] {
let on_share = [PathBuf::from(root)];
for p in on_the_share {
assert_eq!(refused_spelling(p, &on_share), None, "{p} with root {root}");
}
for p in elsewhere {
assert_eq!(refused_spelling(p, &on_share), Some(Network), "{p} with root {root}");
}
}
let shared = [PathBuf::from(r"\\?\UNC\Server\Share\work")];
for p in [r"\\server\SHARE\work\x.png", r"\\?\UNC\SERVER\share\elsewhere\x.png", "//Server/Share/work/x.png"] {
assert_eq!(refused_spelling(p, &shared), None, "{p}");
}
for p in [r"\\server\other\x.png", r"\\other\share\x.png", r"\\server", r"\\server.\share\x.png"] {
assert_eq!(refused_spelling(p, &shared), Some(Network), "{p}");
}
assert_eq!(refused_spelling(r"\\server\share\work\COM1", &shared), Some(Device));
}
/// The links on the way to a path are followed by their spelling before anything they lead to is
/// opened (#1094). The links are made up here, so this runs where tests may not make links.
#[test]
fn links_on_the_way_are_followed_by_their_spelling_first() {
use super::{Entry, MAX_LINKS, link_refused};
use std::cell::RefCell;
use std::collections::HashMap;
let base = std::env::temp_dir().join("figcraft-links");
let at = |rel: &str| base.join(rel);
let mut links: HashMap<PathBuf, Option<PathBuf>> = HashMap::from([
// Relative to the link's folder, to a device name.
(at("root/dev"), Some(PathBuf::from("../outside/nul"))),
// To another link.
(at("root/hop"), Some(at("root/dev"))),
// Within the root.
(at("root/alias"), Some(PathBuf::from("sub"))),
(at("root/loop"), Some(at("root/loop"))),
(at("root/unreadable"), None),
// Below a name that isn't there: never looked at.
(at("missing/dev"), Some(PathBuf::from("nul"))),
]);
if cfg!(windows) {
links.insert(at("root/remote"), Some(PathBuf::from(r"\\192.0.2.1\share")));
links.insert(at("root/far"), Some(at("root/remote/work")));
}
// Chains of `n` links, `root/<n>-1` to `root/<n>-2` and so on, the last one to `root/sub`.
for n in [MAX_LINKS - 1, MAX_LINKS, MAX_LINKS + 1] {
for i in 1..=n {
let next = if i == n { at("root/sub") } else { at(&format!("root/{n}-{}", i + 1)) };
links.insert(at(&format!("root/{n}-{i}")), Some(next));
}
}
let plain = [at("root"), at("root/sub"), at("outside")];
// What can't be looked at (no permission, say) may be a link, so it isn't taken for nothing.
let unreadable = at("root/locked");
let looked = RefCell::new(Vec::new());
let look = |p: &Path| {
looked.borrow_mut().push(p.to_path_buf());
match links.get(p) {
Some(target) => Entry::Link(target.clone()),
None if base.starts_with(p) || plain.iter().any(|q| q == p) => Entry::Plain,
None if p == unreadable => Entry::Unreadable,
None => Entry::Missing,
}
};
let refused = |rel: &str, roots: &[PathBuf]| link_refused(&at(rel), roots, MAX_LINKS, &look);
for rel in ["root/dev/x.png", "root/hop/x.png", "root/loop/x.png", "root/unreadable/x.png", "root/locked/x.png", "root/locked"] {
assert!(refused(rel, &[]), "{rel}");
}
for rel in ["root/alias/x.png", "root/sub/x.png", "root/x.png", "missing/dev/x.png"] {
assert!(!refused(rel, &[]), "{rel}");
}
// As many links as are followed lead on; one more is refused.
assert!(!refused(&format!("root/{}-1/x.png", MAX_LINKS - 1), &[]));
assert!(!refused(&format!("root/{MAX_LINKS}-1/x.png"), &[]));
assert!(refused(&format!("root/{}-1/x.png", MAX_LINKS + 1), &[]));
// A refused target isn't looked at, nor is anything below what isn't there.
let looked = looked.take();
assert!(!looked.contains(&at("outside/nul")) && !looked.contains(&at("missing/dev")), "{looked:?}");
if cfg!(windows) {
for rel in ["root/remote/x.png", "root/far/x.png"] {
assert!(refused(rel, &[]), "{rel}");
// Unless a root is on that share.
assert!(!refused(rel, &[PathBuf::from(r"\\?\UNC\192.0.2.1\share")]), "{rel}");
}
}
}
/// A path that can't be looked at is refused rather than taken for one with nothing there (#1094):
/// only a failure that says nothing is there lets the walk stop, and a path that can't even be
/// made absolute isn't left to the checks after it.
#[test]
fn what_cannot_be_looked_at_is_refused() {
use super::{Unresolved, nothing_there, refused_unresolved};
use std::io::{Error, ErrorKind};
for kind in [ErrorKind::NotFound, ErrorKind::NotADirectory, ErrorKind::InvalidFilename] {
assert!(nothing_there(&Error::from(kind)), "{kind:?}");
}
for kind in [ErrorKind::PermissionDenied, ErrorKind::ResourceBusy, ErrorKind::Interrupted, ErrorKind::Other] {
assert!(!nothing_there(&Error::from(kind)), "{kind:?}");
}
assert_eq!(refused_unresolved(Path::new(""), &[]), Some(Unresolved::Linked));
}
/// On Windows a path is classified as Windows opens it (#1094): with `..` taken by name before
/// anything is opened (so a link followed by `..` is never gone through), and with names that
/// aren't Unicode (a lone surrogate) still read for the parts that are spelled in ASCII.
#[cfg(windows)]
#[test]
fn paths_are_classified_as_windows_opens_them() {
use super::{Unresolved, refused_unresolved};
use craft_docpath::Refused::{Device, Network};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
assert_eq!(std::path::absolute(r"C:\work\remote\..\x.png").unwrap(), PathBuf::from(r"C:\work\x.png"));
// `before`, a lone surrogate, then `after`.
let odd = |before: &str, after: &str| {
let wide: Vec<u16> = before.encode_utf16().chain([0xD800]).chain(after.encode_utf16()).collect();
PathBuf::from(OsString::from_wide(&wide))
};
assert_eq!(refused_unresolved(&odd(r"\\192.0.2.1\share\", ".png"), &[]), Some(Unresolved::Spelled(Network)));
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", r"\nul"), &[]), Some(Unresolved::Spelled(Device)));
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", ".png"), &[]), None);
// A NUL can't be passed to Windows at all, so the path can't be made absolute.
assert_eq!(refused_unresolved(Path::new("C:\\work\\a\0b.png"), &[]), Some(Unresolved::Linked));
}
/// `..` after a link is taken by name, by the check and by Windows when it opens the path, so
/// `root\j\..\in.txt` is `root\in.txt` and the link `j` is never gone through (#1094). Shown with
/// a junction, a link any account can make: `j` leads out of the root to `outside`, and beside
/// `outside` is another `in.txt`, which is what `..` would reach through the link.
#[cfg(windows)]
#[test]
fn a_parent_after_a_link_is_taken_by_name() {
use super::{Entry, on_disk};
let f = Fixture::new("parent");
let r = f.rw();
std::fs::write(f.0.join("in.txt"), b"beside").unwrap();
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(f.0.join(r"root\j")).arg(f.0.join("outside")).output();
assert!(made.is_ok_and(|o| o.status.success()), "a junction can be made");
// The junction is a link to the check, and what is through it is outside.
assert!(matches!(on_disk(&f.0.join(r"root\j")), Entry::Link(Some(_))));
assert!(r.check(Path::new(&f.p(r"root\j\secret.txt")), Access::Read).is_err());
let through = f.p(r"root\j\..\in.txt");
assert_eq!(r.check(Path::new(&through), Access::Read), r.check(Path::new(&f.p(r"root\in.txt")), Access::Read));
assert!(r.check(Path::new(&through), Access::Read).is_ok());
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
}
/// A path on another computer and a device path are refused before anything is opened: resolving
/// them made Windows contact the server, which may send it the signed-in user's credentials
/// (#1094). Each is refused with a message that only the check before resolving gives: had the
/// path been resolved, 192.0.2.1 (an address for documentation, where nothing answers) would have
/// been contacted and the message would be the one for a path that can't be resolved.
#[cfg(windows)]
#[test]
fn other_computers_and_devices_are_refused_before_anything_is_opened() {
let f = Fixture::new("network");
let r = f.rw();
let read_only = Roots::new(&[f.p("root")], &[]).unwrap();
let refused = |roots: &Roots, p: &str, access: Access| roots.check(Path::new(p), access).expect_err(p);
for p in
[r"\\192.0.2.1\share\x.png", "//192.0.2.1/share/x.png", r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\UNC\192.0.2.1\share\x.png", r"\\192.0.2.1"]
{
for access in [Access::Read, Access::Write] {
let e = refused(&r, p, access);
assert!(e.contains("is on another computer, and no folder that may be"), "{p}: {e}");
}
let e = refused(&read_only, p, Access::Write);
assert!(e.ends_with("is on another computer, and no folder that may be written is on its share"), "{p}: {e}");
}
for p in [r"\\.\pipe\figcraft-roots", r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png", &f.p(r"root\COM1\x.png"), "nul"] {
for access in [Access::Read, Access::Write] {
let e = refused(&r, p, access);
assert!(e.ends_with("names a device, not a file"), "{p}: {e}");
}
}
// Local paths, in either spelling, are checked as before.
let inside = std::fs::canonicalize(f.p("root")).unwrap().join("in.txt");
assert!(r.check(&inside, Access::Read).is_ok());
assert!(r.check(Path::new(&f.p(r"root\in.txt")), Access::Read).is_ok());
}
/// A link in a root to another computer is refused before it is followed (#1094), also through
/// another link, and with the message any path outside gets: it doesn't tell where the link
/// leads. Had the link been followed, the message would be the one for a path that can't be
/// resolved. This needs real links, which Windows lets only some accounts make: elsewhere it
/// says so and checks nothing (`links_on_the_way_are_followed_by_their_spelling_first` covers the
/// same walk with made-up links on every system).
#[cfg(windows)]
#[test]
fn links_to_other_computers_are_refused_before_they_are_followed() {
let f = Fixture::new("network-links");
let r = f.rw();
if !symlink_dir(Path::new(r"\\192.0.2.1\share"), &f.0.join("root/remote")) || !symlink_dir(&f.0.join("root/remote/work"), &f.0.join("root/hop")) {
eprintln!("skipped: this system doesn't let tests make symbolic links");
return;
}
// Relative to the link's folder.
assert!(symlink_dir(Path::new(r"..\remote"), &f.0.join("root/sub/up")));
assert!(symlink_file(Path::new(r"\\.\pipe\figcraft-roots"), &f.0.join("root/pipe")));
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
for p in [f.p("root/remote/x.png"), f.p("root/hop/x.png"), f.p("root/sub/up/x.png"), f.p("root/pipe")] {
for access in [Access::Read, Access::Write] {
let e = r.check(Path::new(&p), access).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
}
}
// `..` after the link is taken by name, so the link isn't gone through.
assert!(r.check(Path::new(&f.p(r"root\remote\..\in.txt")), Access::Read).is_ok());
// A link to a folder in the root still leads there.
assert!(symlink_dir(&f.0.join("root/sub"), &f.0.join("root/alias")));
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
}
#[test]
fn a_scope_confines_the_thread_and_ends_with_it() {
let f = Fixture::new("scope");
+64 -8
View File
@@ -7,7 +7,7 @@ use figcraft_doc::{
use figcraft_geom::Point;
use serde_json::{Value, json};
use crate::board::{route, sticky_font_size};
use crate::board::{STICKY_TEXT_SIZE, route};
use crate::collab_live_tests::Room;
use crate::tools::{PointerEvent, PointerKind, ToolId};
use crate::{EngineError, Session};
@@ -77,7 +77,7 @@ fn board_commands_refuse_on_design_files_and_prototyping_refuses_on_boards() {
}
#[test]
fn a_sticky_is_a_square_frame_whose_note_shrinks_as_it_grows() {
fn a_sticky_is_a_square_frame_whose_note_grows_taller_as_it_fills() {
let mut s = board();
s.prefs.user_name = "Ada".into();
let r = s.execute("board.sticky", &json!({"x": 10, "y": 20, "text": "Hi", "color": "blue"})).unwrap();
@@ -88,19 +88,75 @@ fn a_sticky_is_a_square_frame_whose_note_shrinks_as_it_grows() {
assert_eq!(n.fills[0].solid_color(), board_color("blue"));
assert!(n.layout.is_some() && !n.effects.is_empty());
assert_eq!(n.children.len(), 2, "the note and its author");
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 24.0);
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0);
// A click on the note picks the sticky whole.
let doc = s.doc().unwrap();
assert_eq!(figcraft_doc::geometry::select_target(doc, note, &[], false), st);
// A long note takes a smaller size; a very long one grows the sticky past its square.
// A long note keeps the size; a very long one grows the sticky past its square.
let long = "word ".repeat(120);
s.execute("node.set", &json!({"id": note, "props": {"characters": long}})).unwrap();
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, sticky_font_size(&long));
assert!(sticky_font_size(&long) < 16.0);
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, STICKY_TEXT_SIZE);
assert!(node(&s, st).width == 200.0 && node(&s, st).height >= 200.0);
// Undo puts the short note and its size back.
// Undo puts the short note back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 24.0);
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0);
}
#[test]
fn a_new_sticky_starts_at_18() {
let mut s = board();
for (cmd, p) in [("board.sticky", json!({"x": 0, "y": 0, "text": "Hi"})), ("board.sticky", json!({"x": 300, "y": 0}))] {
let note = id(&s.execute(cmd, &p).unwrap(), "text");
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0);
}
let next = id(&s.execute("board.nextSticky", &json!({})).unwrap(), "text");
assert_eq!(node(&s, next).kind.text().unwrap().style.font_size, 18.0);
assert_eq!(STICKY_TEXT_SIZE, 18.0);
}
#[test]
fn a_sticky_keeps_its_text_size_as_text_is_added() {
// The note's growth needs text measured: without craft-fonts that is with a system font,
// scanned here rather than by whichever test happens to run first (#333).
figcraft_text::scan_system_fonts();
let mut s = board();
let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "one"})).unwrap();
let (st, note) = (id(&r, "id"), id(&r, "text"));
let (height, text_height) = (node(&s, st).height, node(&s, note).height);
// Typing in the note: each step is a real edit that runs the normalize pass.
crate::board::edit_text(&mut s, st).unwrap();
for _ in 0..9 {
crate::textedit::key(&mut s, "Enter", false, false, false).unwrap();
crate::textedit::insert(&mut s, "another line").unwrap();
}
let ten = node(&s, note).kind.text().unwrap().clone();
assert_eq!(ten.characters.matches('\n').count(), 9, "ten lines");
assert_eq!(ten.style.font_size, 18.0);
assert!(node(&s, note).height > text_height, "ten lines make the text taller");
assert!(node(&s, st).height > height, "and the note");
assert_eq!(node(&s, st).child_layout.sizing_v, figcraft_doc::Sizing::Hug, "the note hugs its text");
let (w, h10) = (node(&s, st).width, node(&s, st).height);
crate::textedit::insert(&mut s, &"a long paragraph ".repeat(15)).unwrap();
crate::textedit::end(&mut s).unwrap();
let t = node(&s, note).kind.text().unwrap().clone();
assert!(t.characters.chars().count() >= 250);
assert_eq!(t.style.font_size, 18.0);
assert!(t.runs.iter().all(|r| r.style.font_size == 18.0));
assert_eq!(node(&s, st).width, w, "the note keeps its width");
assert!(node(&s, st).height > h10, "and grows taller");
}
#[test]
fn a_sticky_saved_with_another_text_size_keeps_it() {
let mut s = board();
let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "old"})).unwrap();
let (st, note) = (id(&r, "id"), id(&r, "text"));
s.execute("node.set", &json!({"id": note, "props": {"fontSize": 11}})).unwrap();
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0);
s.execute("node.set", &json!({"id": note, "props": {"characters": "old and now much longer than it was"}})).unwrap();
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0, "an edit");
s.execute("node.set", &json!({"id": st, "props": {"x": 40}})).unwrap();
assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 11.0, "a move");
}
#[test]
+1 -1
View File
@@ -69,8 +69,8 @@ pub(crate) use edit::{copied_items, copy_map, rejoin};
use edit::{label_cmd, set_color, set_style};
pub(crate) use items::add_text;
pub use items::{CONNECTED_GAP, connected_place};
pub use items::{STICKY_TEXT_SIZE, edit_text, owner_of_text, text_of};
use items::{add_connected, ink_cmd, next_sticky, shape_cmd, stamp_cmd, sticky_cmd};
pub use items::{edit_text, owner_of_text, sticky_font_size, text_of};
pub(crate) use mindmap::settle_mind_maps;
pub(crate) use reshape::path_handle_at;
pub use reshape::selected_connector_handles;
+3 -16
View File
@@ -1,7 +1,6 @@
use figcraft_doc::RouteEnd;
use super::edit::set_font_size;
use super::items::{owner_of_text, shape_padding, sticky_font_size, text_of};
use super::items::shape_padding;
use super::{
Affine, BTreeSet, BezPath, BoardItem, Connector, Document, End, NodeId, NodeKind, PathEl, Point, Rect, Routing, Shape, VectorNetwork, is_board,
};
@@ -9,26 +8,14 @@ use super::{
// ---------------------------------------------------------------------------------------------
// Derived data (the normalize pass).
/// Before text is measured: a sticky's note takes the size its length calls for, and a resized
/// shape keeps its text inside its outline.
/// Before text is measured: a resized shape keeps its text inside its outline. A sticky's text
/// keeps whatever size it has (FigJam's size is the note's own setting).
pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTreeSet<NodeId>) {
if !is_board(doc) {
return;
}
for &id in touched {
let Some(n) = doc.node(id) else { continue };
if let Some(owner) =
owner_of_text(doc, id).or(Some(id)).filter(|o| doc.node(*o).is_some_and(|k| matches!(k.board, Some(BoardItem::Sticky { .. }))))
&& let Some(t) = text_of(doc, owner)
&& let Some(NodeKind::Text(td)) = doc.node(t).map(|k| &k.kind)
{
let size = sticky_font_size(&td.characters);
let off = td.style.font_size != size || td.runs.iter().any(|r| r.style.font_size != size);
if off && let Some(NodeKind::Text(td)) = doc.node_mut(t).map(|k| &mut k.kind) {
set_font_size(td, size);
}
continue;
}
if let Some(BoardItem::Shape { shape }) = n.board
&& before.node(id).is_none_or(|b| (b.width, b.height) != (n.width, n.height))
{
+4 -13
View File
@@ -57,18 +57,9 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64
Ok(id)
}
/// The text size a sticky's note gets: smaller the more it holds (by characters and lines, so
/// every copy of the file picks the same size whatever fonts it has).
pub fn sticky_font_size(text: &str) -> f64 {
let weight = text.chars().count() + 24 * text.matches('\n').count();
match weight {
0..=24 => 24.0,
25..=64 => 20.0,
65..=140 => 16.0,
141..=280 => 13.0,
_ => 11.0,
}
}
/// The text size of a new sticky's note, FigJam's "Small" default (measured in the web app,
/// 2026-11-09): it never changes as the note fills, the note grows taller instead.
pub const STICKY_TEXT_SIZE: f64 = 18.0;
/// A sticky note's layers: the frame, the note and (when known) its author.
fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, color: Color, author: &str) -> Result<(NodeId, NodeId)> {
@@ -89,7 +80,7 @@ fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, c
n.board = Some(BoardItem::Sticky { author: author.to_string() });
})?;
let inner = STICKY - 2.0 * STICKY_PAD;
let note = add_text(doc, id, text, sticky_font_size(text), INK, TextAlignH::Left, inner)?;
let note = add_text(doc, id, text, STICKY_TEXT_SIZE, INK, TextAlignH::Left, inner)?;
if !author.is_empty() {
let a = add_text(doc, id, author, 10.0, AUTHOR_INK, TextAlignH::Left, inner)?;
if let Some(n) = doc.node_mut(a) {
+66
View File
@@ -8,6 +8,7 @@ use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind, pressure_profile};
use figcraft_doc::{NodeId, NodeKind};
use figcraft_geom::Point;
use figcraft_geom::kurbo::PathEl;
fn id(v: Value) -> NodeId {
id_of(&v["id"]).unwrap()
@@ -149,3 +150,68 @@ fn the_pencil_draws_white_on_a_dark_background() {
assert_eq!(stroke(&mut s, 0.0, 600.0).0, want, "on {bg}");
}
}
/// A Pencil stroke stays where it was drawn: the fitted curve shot far off the stroke, a spike
/// (#1741, its second point), where the stroke went out and back to the very point it left and
/// where samples ran on nearly straight. Pointer pixels become fractional page points, so going
/// back to a pixel lands on exactly the same point. Both sample runs are ones kurbo's fit took
/// hundreds of units off.
///
/// Each stroke is drawn in a fresh session, with the Pencil and with the Marker and Highlighter
/// of a board, whose ink comes from the same fit. Every point along the stroke drawn must lie
/// within 1.5 (twice the fit's accuracy) of the polyline through the samples.
#[test]
fn the_pencil_keeps_its_stroke_where_it_was_drawn() {
let (p, q) = ((86.043_565_719_086_97, -173.744_402_349_100_94), (87.851_850_739_335_35, -179.202_846_445_954_52));
let back = [(80.0, -160.0), p, q, p, (95.0, -185.0)];
let straight = [
(204.0, -198.0),
(209.598_690_794_015_5, -204.909_328_119_739_88),
(211.277_914_263_870_97, -207.190_974_020_753_4),
(214.246_506_828_720_84, -211.228_827_590_623_24),
(218.0, -214.0),
];
for tool in ["pencil", "marker", "highlighter"] {
for (what, samples) in [("out and back", &back[..]), ("nearly straight", &straight[..])] {
let what = format!("{tool}, {what}");
let mut s = if tool == "pencil" { Session::new() } else { crate::board_tests::board() };
s.execute("tool.set", &json!({"tool": tool})).unwrap();
let before: Vec<NodeId> = s.doc().unwrap().nodes().map(|n| n.id).collect();
let (first, last) = (samples[0], samples[samples.len() - 1]);
s.pointer(&PointerEvent::at(PointerKind::Down, first.0, first.1, 1.0)).unwrap();
for (x, y) in &samples[1..] {
s.pointer(&PointerEvent::at(PointerKind::Move, *x, *y, 1.0)).unwrap();
}
s.pointer(&PointerEvent::at(PointerKind::Up, last.0, last.1, 1.0)).unwrap();
// The layer the stroke made, and only it.
let doc = s.doc().unwrap();
let made: Vec<&figcraft_doc::Node> =
doc.nodes().filter(|n| !before.contains(&n.id) && matches!(n.kind, NodeKind::Vector { .. })).collect();
let [n] = made[..] else { panic!("{what}: {} vectors made", made.len()) };
let NodeKind::Vector { network } = &n.kind else { panic!("{what}: not a vector") };
let drawn = doc.world_transform(n.id) * network.stroke_path();
let polyline = figcraft_geom::BezPath::from_vec(
samples
.iter()
.enumerate()
.map(|(k, (x, y))| if k == 0 { PathEl::MoveTo(Point::new(*x, *y)) } else { PathEl::LineTo(Point::new(*x, *y)) })
.collect(),
);
let d = crate::vector_behaviour_tests::strays(&drawn, &polyline);
assert!(d <= 1.5, "{what}: the stroke strays {d} from the samples: {}", drawn.to_svg());
let samples_box = figcraft_geom::points_bounds(samples.iter().map(|(x, y)| Point::new(*x, *y))).unwrap();
let node_box = doc.world_bounds(n.id).unwrap();
if tool == "pencil" {
assert!(samples_box.inflate(1.5, 1.5).contains_rect(node_box), "{what}: the layer {node_box:?}, the samples {samples_box:?}");
}
// The turn is a point of the stroke, where it was drawn.
if samples == back {
let xf = doc.world_transform(n.id);
assert!(
network.vertices.iter().any(|v| (xf * Point::new(v.x, v.y) - Point::new(q.0, q.1)).hypot() < 1e-6),
"{what}: no point at the turn"
);
}
}
}
}
+30 -5
View File
@@ -284,32 +284,57 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInse
let text = normalized;
edit(s, |t, te| {
let (a, b) = range(te);
// "- ", "* ", "1. " or "1) " typed at the start of a plain paragraph starts a list (the
// creation characters of Create bulleted and numbered lists).
// "- ", "* ", "<number>. " or "1) " typed at the start of a plain paragraph starts a list
// (the creation characters of Create bulleted and numbered lists). As measured in Figma
// (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number
// field). "0. " and a bracket after a number other than 1 are not measured: plain text.
if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
let chars: Vec<char> = t.characters.chars().collect();
let start = line_start(&chars, a);
let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect();
let mut first = 1_u32;
let list = match typed.as_str() {
"-" | "*" => ListStyle::Bulleted,
"1." | "1)" => ListStyle::Numbered,
_ => ListStyle::None,
"1)" => ListStyle::Numbered,
_ => match typed.strip_suffix('.').filter(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) {
Some(d) => match d.parse::<u32>() {
Ok(n) if (1..=MAX_TYPED_LIST_START).contains(&n) => {
first = n;
ListStyle::Numbered
}
_ => ListStyle::None,
},
None => ListStyle::None,
},
};
if list != ListStyle::None {
t.replace_range(start, a, "");
t.set_para_lists(start, start, |pl| pl.list = list);
t.set_para_lists(start, start, |pl| {
pl.list = list;
pl.start_offset = first - 1;
});
(te.caret, te.anchor) = (start, start);
outcome = ImeInsertion::Transformed;
return;
}
}
t.replace_range(a, b, &text);
// As measured in Figma (2026-11-11): an item made by Enter has no start of its own, so
// unlisting the item before it makes it restart at 1 rather than at the copied start.
// Every paragraph after the first that the insertion made loses the start it was copied.
if text.contains('\n') {
let end = a + text.chars().count();
t.clear_list_starts(t.para_of(a) + 1, t.para_of(end));
}
te.caret = a + text.chars().count();
te.anchor = te.caret;
})?;
Ok(outcome)
}
/// The largest number a typed `N. ` can start a numbered list at.
const MAX_TYPED_LIST_START: u32 = 9999;
/// What a list key does to the selected items.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ListMove {
+3 -2
View File
@@ -313,7 +313,8 @@ impl Session {
if points.len() < 2 {
return Ok(());
}
// Smooth: fit a curve through the samples.
// Smooth: fit a curve through the samples, kept from shooting past them where the stroke
// turns back or runs nearly straight (#1741).
let mut poly = figcraft_geom::BezPath::new();
for (k, p) in points.iter().enumerate() {
if k == 0 {
@@ -322,7 +323,7 @@ impl Session {
poly.line_to(*p);
}
}
let fitted = figcraft_geom::kurbo::simplify::simplify_bezpath(poly.iter(), 0.75, &Default::default());
let fitted = figcraft_geom::simplify_path(&poly, 0.75);
let d = fitted.to_svg();
if matches!(self.tool.tool, ToolId::Marker | ToolId::Highlighter) {
return self.ink_finish(&d);
+14 -7
View File
@@ -47,16 +47,23 @@ impl Session {
/// the layers it touches (`deep`: nested ones too); `additive` (Shift) toggles them.
pub(crate) fn marquee_selection(&self, r: Rect, within: Option<NodeId>, deep: bool, base: &[NodeId], additive: bool) -> Result<Vec<NodeId>> {
let (doc, page) = (self.doc()?, self.page()?);
let mut hits =
if deep { figcraft_doc::geometry::marquee_deep(doc, page, r) } else { figcraft_doc::geometry::marquee_select(doc, page, r, within) };
if let Some(f) = self.ds()?.focused() {
let focused = self.ds()?.focused();
let mut hits = match (deep, focused) {
(true, _) => figcraft_doc::geometry::marquee_deep(doc, page, r),
(false, Some(f)) => figcraft_doc::geometry::marquee(doc, page, r, Some(f)),
(false, None) => figcraft_doc::geometry::marquee_select(doc, page, r, within),
};
if let Some(f) = focused {
hits.retain(|h| *h != f && doc.is_ancestor(f, *h));
}
// A marquee over a frame from outside selects the frame only when it covers it fully.
if within.is_none() && !deep {
// A widget's layers are part of the widget: a marquee from outside never opens one.
if !deep {
hits.retain(|h| {
let full = doc.world_bounds(*h).is_some_and(|b| r.contains(b.origin()) && r.contains(Point::new(b.x1, b.y1)));
full || !doc.node(*h).is_some_and(|n| n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. }))
doc.node(*h)
.and_then(|n| n.parent)
.filter(|p| Some(*p) != within)
.and_then(|p| doc.node(p))
.is_none_or(|p| !crate::widgets::is_widget(p))
});
}
// Shift toggles: what was selected and is touched again comes out.
+1 -1
View File
@@ -638,7 +638,7 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result<usize> {
}
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
let doc = s.doc_mut()?;
for EditPart { id, vertices: verts, segments: segs } in parts {
edit(doc, id, |net| {
+9 -2
View File
@@ -24,8 +24,8 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res
pub(crate) use instance::{swap_at, swap_instance};
use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props};
pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props};
use variants::{add_variant, combine};
pub use variants::{can_add_variant, can_combine_variants};
use variants::{add_variant, combine, create_set};
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
/// `component.hideWhenPublishing`: the leading `.` of the names of this file's components and
/// sets (those `ids` are or are in), put on or taken off.
@@ -72,6 +72,13 @@ pub fn specs() -> Vec<CommandSpec> {
s.set_selection(out.iter().filter_map(id_of).collect());
Ok(json!({"ids": out}))
}),
spec!(
"component.createSet",
"Create component set",
"{ids? (layers, not components, sets or instances)} (each becomes a component, wrapped in place in a component set: variants \"Property 1=<name>\" left to right, 20 px around)",
true,
create_set
),
spec!(
"component.combineVariants",
"Combine as variants",
+3 -2
View File
@@ -8,7 +8,7 @@ use super::{
req_string, req_targets, set_boolean_default, slot_edited, slots_of, string, takes_value, targets, variant_conflicts, variant_name,
variant_options, variant_props, variant_set,
};
use crate::components::prop_list;
use crate::components::{instance_prop_list, prop_list};
/// Whether instance `id` has a component property `name` that a `kind` variable can drive (a
/// boolean property takes a boolean variable, a text or variant property a string one).
@@ -606,7 +606,8 @@ pub(crate) fn describe_props(doc: &Document, id: NodeId) -> Value {
}
// Slots: the frames (on a main) or this instance's copy, with whether it holds its own content.
let slots = slots_of(doc, if values.is_some() { id } else { variant_set(doc, comp).unwrap_or(comp) });
for (k, d) in prop_list(doc, comp) {
let defs = if values.is_some() { instance_prop_list(doc, comp) } else { prop_list(doc, comp) };
for (k, d) in defs {
let mut v = def_json(&k, &d);
if !takes_value(&d) {
let layers: Vec<NodeId> = slots.iter().filter(|(_, n)| *n == k).map(|(l, _)| *l).collect();
+71 -2
View File
@@ -1,6 +1,6 @@
use super::{
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, inside_instance, json, owning_instance,
req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, create, id_of, inside_instance, json,
owning_instance, req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
};
/// Wrap components in a new component set (named after the first) placed around them.
@@ -94,6 +94,75 @@ pub(super) fn combine(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"id": set}))
}
/// Why `ids` (distinct) can't each become a component of a new set (`component.createSet`), or
/// `None` when they can: layers inside an instance, library copies, instances, components and
/// component sets, and a layer inside another one of `ids`.
fn create_set_refusal(doc: &Document, ids: &[NodeId]) -> Option<&'static str> {
if ids.iter().any(|i| inside_instance(doc, *i)) {
Some("layers inside an instance can't become components")
} else if ids.iter().any(|i| doc.is_remote(*i)) {
Some(crate::library::READ_ONLY)
} else if ids.iter().any(|i| {
doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. } | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))
}) {
Some("select layers that aren't components, component sets or instances")
} else if roots(doc, ids).len() != ids.len() {
Some("a layer can't be in a set with one inside it")
} else {
None
}
}
/// Whether "Create component set" is on offer for `ids`: at least one layer that
/// [`create_set_refusal`] lets through.
pub fn can_create_set(doc: &Document, ids: &[NodeId]) -> bool {
let distinct: Vec<NodeId> = ids.iter().copied().collect::<BTreeSet<_>>().into_iter().collect();
!distinct.is_empty() && distinct.iter().all(|i| doc.contains(*i)) && create_set_refusal(doc, &distinct).is_none()
}
/// `component.createSet`: each target becomes a component (as `component.createMultiple` makes
/// them) and all are wrapped in place in a component set, 20 px around, named as Figma names them:
/// variants "Property 1=<layer name>" in left-to-right order (a name holding `=` is kept); layers
/// that all share a name give a set of that name with "Property 1=Default" variants; otherwise the
/// set is "Component N".
pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.createSet";
let mut seen = BTreeSet::new();
let ids: Vec<NodeId> = req_targets(cmd, s, p)?.into_iter().filter(|i| seen.insert(*i)).collect();
let doc = s.doc()?;
if let Some(why) = create_set_refusal(doc, &ids) {
return Err(EngineError::Disabled(cmd.into(), why.into()));
}
let mut made = Vec::new();
for i in roots(doc, &ids) {
let r = create(s, &json!({"ids": [i]}))?;
made.push(id_of(&r["id"]).ok_or_else(|| bad(cmd, "component creation failed"))?);
}
let doc = s.doc_mut()?;
// Left to right by world x, ties by y: the variants' order, and the values' order.
let mut by_x: Vec<(NodeId, f64, f64)> = made.iter().map(|i| doc.world_bounds(*i).map_or((*i, 0.0, 0.0), |b| (*i, b.x0, b.y0))).collect();
by_x.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.2.total_cmp(&b.2)));
let names: Vec<String> = by_x.iter().map(|(i, ..)| doc.node(*i).map(|n| n.name.clone()).unwrap_or_default()).collect();
let same = names.windows(2).all(|w| w.first() == w.get(1)) && names.first().is_some_and(|n| !n.is_empty() && !n.contains('='));
let set_name = match names.first() {
Some(n) if same => n.clone(),
_ => doc.next_name("Component"),
};
for ((i, ..), name) in by_x.iter().zip(&names) {
let node = doc.get_mut(*i)?;
if same {
node.name = "Property 1=Default".into();
} else if !name.contains('=') {
node.name = format!("Property 1={name}");
}
}
let ordered = z_sorted(doc, &made);
let set = wrap_in_set(cmd, doc, &ordered)?;
doc.get_mut(set)?.name = set_name;
s.set_selection(vec![set]);
Ok(json!({"id": set}))
}
/// Grow a component set so it wraps its variants with 20 px of padding (right and bottom).
pub(super) fn fit_set(doc: &mut Document, set: NodeId) {
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
+19 -3
View File
@@ -17,6 +17,10 @@ mod clipboard;
mod props;
pub(crate) use props::{edit_region_fills, fill_regions};
mod select;
mod vector_clipboard;
pub use vector_clipboard::clipboard_svg;
#[cfg(test)]
mod vector_clipboard_tests;
pub(crate) use clipboard::apply_copied_props;
pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into};
@@ -117,12 +121,24 @@ pub fn specs() -> Vec<CommandSpec> {
true,
duplicate
),
spec!("edit.copy", "Copy", "{ids?}", false, copy),
spec!("edit.cut", "Cut", "{ids?}", true, cut),
spec!(
"edit.copy",
"Copy",
"{ids?} in vector edit mode with points or segments selected (and no ids): just those, the segments touching a selected point, as a temporary vector on the clipboard (one per edited layer) with the edited layer's look, kept at its place on the page; points that touch no segment have nothing to copy, so Copy with only those is refused (Disabled). Returns {copied, segments}",
false,
copy
),
spec!(
"edit.cut",
"Cut",
"{ids?} in vector edit mode with points or segments selected (and no ids): copies them as Copy does, then removes them as Delete does; the path splits in the same layer and edit mode stays on. Returns {cut (layers), segments}. With only lone points (nothing to copy) it is refused (Disabled) and changes nothing, as Copy is; Delete removes lone points",
true,
cut
),
spec!(
"edit.paste",
"Paste",
"{parent?, x?, y? (page coordinates of the pasted top-left)} a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
"{parent?, x?, y? (page coordinates of the pasted top-left; give both or neither, one alone is refused)} in vector edit mode (and no parent): the copied vectors' segments and the outlines of shapes, booleans and lines join the edited vector's network (at x/y when given, else in place), their points selected, as one undo step; layers with no outline (text, images, instances, frames, groups) are skipped and named in `skipped` (present only when some were), and when none has an outline the paste is refused (Disabled), as it is past 500,000 segments in one vector. Returns {ids: [] (always empty: no layer is created), edited (the vector's id), vertices (points added), skipped?}, unlike a paste outside edit mode, which returns the new layers' `ids`; a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
true,
paste
),
+53 -11
View File
@@ -1,6 +1,6 @@
use super::{
Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, id, json, num, ok,
req_targets, roots, string, targets, z_sorted,
Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, get, id, json, num,
ok, req_targets, roots, string, targets, vector_clipboard, z_sorted,
};
/// The copied form of the selection.
@@ -12,6 +12,18 @@ pub fn copy_to_clipboard(s: &mut Session, cmd: &str, ids: &[NodeId]) -> Result<(
return Err(EngineError::Disabled(cmd.into(), "pages can't be copied; use page.duplicate".into()));
}
let (nodes, images, bounds) = copied(&ds.doc, &layers);
store_clipboard(s, cmd, nodes, images, bounds)
}
/// Make `nodes` (the copied layers, each root's transform in page space) the clipboard's layers.
pub(super) fn store_clipboard(
s: &mut Session,
cmd: &str,
nodes: Vec<(NodeId, Vec<Node>)>,
images: BTreeMap<String, ImageData>,
bounds: Option<figcraft_geom::Rect>,
) -> Result<()> {
let ds = s.ds()?;
let (source, source_path, uid) = (ds.doc.clone(), ds.path.clone(), ds.uid);
s.clipboard.source = Some(source);
s.clipboard.source_path = source_path;
@@ -43,21 +55,26 @@ fn copied(doc: &Document, ids: &[NodeId]) -> Copied {
if let Some(r) = sub.first_mut() {
r.transform = world;
}
for n in &sub {
for p in n.fills.iter().chain(n.strokes.iter()) {
if let figcraft_color::PaintKind::Image(img) = &p.kind
&& let Some(d) = doc.images.get(&img.image)
{
images.insert(img.image.clone(), d.clone());
}
}
}
collect_images(doc, &sub, &mut images);
nodes.push((*i, sub));
}
let bounds = doc.bounds_of(&ids);
(nodes, images, bounds)
}
/// The images the paints of `nodes` use, taken from `doc` into `images`.
pub(super) fn collect_images(doc: &Document, nodes: &[Node], images: &mut BTreeMap<String, ImageData>) {
for n in nodes {
for p in n.fills.iter().chain(n.strokes.iter()) {
if let figcraft_color::PaintKind::Image(img) = &p.kind
&& let Some(d) = doc.images.get(&img.image)
{
images.insert(img.image.clone(), d.clone());
}
}
}
}
/// The markers around the copied layers in the clipboard's HTML, spelt as that format spells them.
pub const CLIP_OPEN: &str = "(figma)";
@@ -167,13 +184,34 @@ fn layers_missing_images(doc: &figcraft_doc::Document, ids: &[NodeId]) -> Vec<St
names
}
/// Whether the command names its layers (`ids` / `id`): it then acts on them even in vector edit mode.
fn names_layers(p: &Value) -> bool {
get(p, "ids").is_some() || get(p, "id").is_some()
}
pub(super) fn copy(s: &mut Session, p: &Value) -> Result<Value> {
// In vector edit mode with points or segments selected, Copy takes just those (#1875).
if !names_layers(p)
&& let Some(sel) = vector_clipboard::edit_selection(s)
&& sel.any
{
// Only lone points selected: nothing to copy, and not the whole layer either.
return vector_clipboard::copy_selection(s, "edit.copy", sel);
}
let ids = req_targets("edit.copy", s, p)?;
copy_to_clipboard(s, "edit.copy", &ids)?;
Ok(json!({"copied": s.clipboard.nodes.len()}))
}
pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
// In vector edit mode with points or segments selected, Cut takes just those and stays in edit mode (#1875).
if !names_layers(p)
&& let Some(sel) = vector_clipboard::edit_selection(s)
&& sel.any
{
// Lone points with nothing to copy: `cut_selection` refuses, as Copy does.
return vector_clipboard::cut_selection(s, sel);
}
let ids = req_targets("edit.cut", s, p)?;
copy_to_clipboard(s, "edit.cut", &ids)?;
let doc = s.doc()?;
@@ -238,6 +276,10 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
}
pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
// While editing a vector, the copied layers join its network (#1875); `parent` asks for layers.
if id(p, "parent").is_none() && s.ds()?.vector_edit.is_some() {
return vector_clipboard::paste_into_vector(s, p);
}
let page = s.page()?;
// Figma pastes into the selected frame (if one is selected), at the same position when it fits,
// else in the frame's centre; otherwise in place on the page (or the viewport centre).
@@ -0,0 +1,303 @@
//! Copy, cut and paste in vector edit mode (#1875).
//!
//! With points or segments selected, Copy and Cut take just those: a temporary vector holding the
//! selected segments (and the segments touching a selected point) goes on the ordinary layer
//! clipboard, kept at its place on the page, so a paste outside edit mode is a plain layer paste
//! in place. Cut then removes the selection the way Delete does and stays in edit mode. Paste
//! while editing adds the clipboard's layers to the edited vector's network, in place: a vector
//! with its segments, a shape or boolean with its outline.
use crate::bad;
use figcraft_doc::{NodeKind, Region, VectorNetwork};
use super::clipboard::{collect_images, store_clipboard};
use super::{Affine, BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, Result, Session, Value, json, num};
use crate::canvas::vectoredit::{self, EditPart};
/// The most segments a vector network takes through a paste.
const MAX_SEGMENTS: usize = 500_000;
/// What the edited layers have selected.
pub(super) struct EditSelection {
/// Whether any edited layer has a point or a segment selected.
pub any: bool,
/// Each edited layer with something to copy, and the sub-network that is.
pub parts: Vec<(NodeId, VectorNetwork)>,
/// What Cut removes, per edited layer: the same points and segments the copy was built from.
pub delete: Vec<EditPart>,
}
/// The selection of the vector being edited (and the other layers edited with it), or `None` when
/// not in vector edit mode.
pub(super) fn edit_selection(s: &Session) -> Option<EditSelection> {
let ds = s.ds().ok()?;
let ve = ds.vector_edit.as_ref()?;
let mut sel = EditSelection { any: false, parts: Vec::new(), delete: Vec::new() };
for part in ve.parts() {
if part.vertices.is_empty() && part.segments.is_empty() {
continue;
}
sel.any = true;
let Some(net) = vectoredit::network(&ds.doc, part.id) else { continue };
let active = part.id == ve.id;
// Points selected only through a selected region don't pull in the segments touching
// them: the region's own segments are the selection.
let vertices: Vec<usize> = part.vertices.iter().copied().filter(|v| !active || !ve.region_vertices.contains(v)).collect();
let mut segments = part.segments.clone();
if active {
segments.extend(ve.regions.iter().filter_map(|r| net.regions.get(*r)).flat_map(|r| r.loops.iter().flatten().copied()));
}
sel.delete.push(EditPart { id: part.id, vertices: vertices.clone(), segments: segments.clone() });
if let Some(sub) = sub_network(net, &vertices, &segments) {
sel.parts.push((part.id, sub));
}
}
Some(sel)
}
/// The part of `net` that is the segments `segments` and those touching a point of `vertices`,
/// with the points they join; `None` when there are none (a lone point with no segment draws
/// nothing). The regions whose every segment is kept stay regions.
fn sub_network(net: &VectorNetwork, vertices: &[usize], segments: &[usize]) -> Option<VectorNetwork> {
let picked: BTreeSet<usize> = vertices.iter().copied().collect();
let mut keep: BTreeSet<usize> = segments.iter().copied().filter(|i| *i < net.segments.len()).collect();
for (i, sg) in net.segments.iter().enumerate() {
if picked.contains(&sg.a) || picked.contains(&sg.b) {
keep.insert(i);
}
}
let used: BTreeSet<usize> = keep.iter().filter_map(|i| net.segments.get(*i)).flat_map(|sg| [sg.a, sg.b]).collect();
let vmap: BTreeMap<usize, usize> = used.iter().enumerate().map(|(new, old)| (*old, new)).collect();
let smap: BTreeMap<usize, usize> = keep.iter().enumerate().map(|(new, old)| (*old, new)).collect();
let mut out = VectorNetwork {
vertices: used.iter().filter_map(|v| net.vertices.get(*v).cloned()).collect(),
segments: keep
.iter()
.filter_map(|i| net.segments.get(*i))
.filter_map(|sg| {
let mut sg = *sg;
sg.a = *vmap.get(&sg.a)?;
sg.b = *vmap.get(&sg.b)?;
Some(sg)
})
.collect(),
regions: Vec::new(),
};
if out.segments.is_empty() || out.segments.len() != keep.len() || out.vertices.len() != used.len() {
return None;
}
for r in &net.regions {
let loops: Option<Vec<Vec<usize>>> = r.loops.iter().map(|l| l.iter().map(|i| smap.get(i).copied()).collect::<Option<Vec<usize>>>()).collect();
if let Some(loops) = loops.filter(|l| !l.is_empty()) {
out.regions.push(Region { loops, ..r.clone() });
}
}
Some(out)
}
/// The clipboard's layer for edited vector `id` holding `sub`: it keeps the layer's look (fills,
/// strokes, effects, opacity, blend) and its place on the page. A variable width profile runs
/// along the whole path, so it stays only when every segment is copied.
fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option<Node> {
let mut n = doc.node(id)?.clone();
let whole = vectoredit::network(doc, id).is_some_and(|all| all.segments.len() == sub.segments.len());
let b = sub.bounds().filter(|b| b.x0.is_finite() && b.y0.is_finite() && b.width().is_finite() && b.height().is_finite())?;
sub.translate(-b.x0, -b.y0);
n.transform = doc.world_transform(id) * Affine::translate((b.x0, b.y0));
n.width = b.width();
n.height = b.height();
n.kind = NodeKind::Vector { network: sub };
n.parent = None;
n.children.clear();
n.name = "Vector".into();
if !whole {
n.stroke.width_profile = None;
}
Some(n)
}
/// Put the selection's sub-networks on the layer clipboard. Returns how many segments went.
fn copy_parts(s: &mut Session, cmd: &str, sel: &EditSelection) -> Result<usize> {
let doc = s.doc()?;
let mut nodes = Vec::new();
let mut images = BTreeMap::new();
let mut bounds: Option<figcraft_geom::Rect> = None;
let mut segments = 0;
for (id, sub) in &sel.parts {
segments += sub.segments.len();
let Some(n) = clip_node(doc, *id, sub.clone()) else { continue };
let r = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect());
bounds = Some(bounds.map_or(r, |b| b.union(r)));
collect_images(doc, std::slice::from_ref(&n), &mut images);
nodes.push((*id, vec![n]));
}
if nodes.is_empty() {
return Err(EngineError::Disabled(cmd.into(), "the selection has nothing to copy".into()));
}
store_clipboard(s, cmd, nodes, images, bounds)?;
Ok(segments)
}
/// Copy the selected segments (see [`edit_selection`]).
pub(super) fn copy_selection(s: &mut Session, cmd: &str, sel: EditSelection) -> Result<Value> {
let segments = copy_parts(s, cmd, &sel)?;
Ok(json!({"copied": s.clipboard.nodes.len(), "segments": segments}))
}
/// Cut: copy the selected segments, then remove the selection as Delete does (the path splits in
/// the same layer and edit mode stays on). Cut is Copy plus Delete, so it is refused exactly where
/// Copy is: a selection with nothing to copy (only lone points that touch no segment) is
/// `Disabled` and changes nothing, clipboard included. Delete removes such points.
pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result<Value> {
if sel.parts.is_empty() {
return Err(EngineError::Disabled("edit.cut".into(), "the selection has nothing to copy (Delete removes lone points)".into()));
}
let cut = sel.parts.len();
let segments = copy_parts(s, "edit.cut", &sel)?;
vectoredit::delete_selection(s, sel.delete, false)?;
Ok(json!({"cut": cut, "segments": segments}))
}
/// The SVG of the layers a partial vector-edit copy or cut put on the clipboard, for the system
/// clipboard: they are temporary layers that live only in the clipboard, so they are placed in a
/// scratch document to export. `None` when the clipboard holds none or the export fails.
pub fn clipboard_svg(s: &Session) -> Option<String> {
let mut scratch = Document::new("Clipboard");
let page = scratch.current_page?;
for (k, v) in &s.clipboard.images {
scratch.images.insert(k.clone(), v.clone());
}
let mut ids = Vec::new();
for (root, nodes) in &s.clipboard.nodes {
let map: BTreeMap<NodeId, NodeId> = nodes.iter().map(|n| (n.id, scratch.alloc_id())).collect();
ids.push(scratch.paste_nodes(nodes, &map, *root, page, None).ok()?);
}
let bytes = crate::cmd::file::export_bytes(&scratch, &ids, figcraft_doc::ExportFormat::Svg, 1.0).ok()?;
String::from_utf8(bytes).ok()
}
/// The network of the outline of copied layer `n` in its own coordinates: a vector's segments, a
/// shape's or boolean's outline. `None` for the layers with no outline to add (text, images,
/// frames, groups, instances, …). `doc` is the file the layer was copied from.
fn outline_network(doc: &Document, n: &Node) -> Option<VectorNetwork> {
let net = match &n.kind {
NodeKind::Vector { network } => network.clone(),
k if k.is_shape() || matches!(k, NodeKind::BooleanOp { .. }) => {
let (path, rule) = figcraft_render::node_outline(doc, n)?;
let mut net = VectorNetwork::from_path(&path);
if matches!(n.kind, NodeKind::Line) {
net.regions.clear();
}
if rule == figcraft_render::FillRule::EvenOdd {
for r in &mut net.regions {
r.winding = figcraft_doc::WindingRule::EvenOdd;
}
}
net
}
_ => return None,
};
(!net.segments.is_empty()).then_some(net)
}
/// `net` moved by `m` (points, handles, the regions' paint frames and the points' radii).
fn placed(mut net: VectorNetwork, m: Affine) -> Option<VectorNetwork> {
let c = m.as_coeffs();
if !c.iter().all(|x| x.is_finite()) {
return None;
}
let linear = Affine::new([c[0], c[1], c[2], c[3], 0.0, 0.0]);
let scale = m.determinant().abs().sqrt();
for v in &mut net.vertices {
let p = m * v.point();
(v.x, v.y) = (p.x, p.y);
v.radius *= scale;
}
for sg in &mut net.segments {
let (ta, tb) = (linear * figcraft_geom::Point::new(sg.ta.0, sg.ta.1), linear * figcraft_geom::Point::new(sg.tb.0, sg.tb.1));
sg.ta = (ta.x, ta.y);
sg.tb = (tb.x, tb.y);
}
for r in &mut net.regions {
if let Some(frame) = r.paint_space.as_mut() {
frame.transform = m * frame.transform;
}
}
let finite = net.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite())
&& net.segments.iter().all(|sg| [sg.ta.0, sg.ta.1, sg.tb.0, sg.tb.1].iter().all(|x| x.is_finite()));
finite.then_some(net)
}
/// Paste while editing a vector: the clipboard's layers join its network in place (with `x`, `y`:
/// the copied top-left moved there), their points selected. Layers with no outline are skipped
/// (named in `skipped`); when none has one, nothing is pasted.
pub(super) fn paste_into_vector(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "edit.paste";
if s.clipboard.nodes.is_empty() {
return Err(EngineError::Disabled(CMD.into(), "the clipboard is empty".into()));
}
let target = vectoredit::editing(s)?.id;
let shift = match (num(p, "x"), num(p, "y"), s.clipboard.bounds) {
(Some(x), Some(y), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
(None, None, _) | (Some(_), Some(_), None) => Affine::IDENTITY,
_ => return Err(bad(CMD, "give both x and y, or neither")),
};
let live = s.doc()?;
// Borrow the clipboard (it holds the source document and the images) to build the pieces.
let clip = &s.clipboard;
let source: &Document = clip.source.as_deref().unwrap_or(live);
let to_local = live.world_transform(target).inverse() * shift;
let mut pieces = Vec::new();
let mut skipped: Vec<String> = Vec::new();
for (_, nodes) in &clip.nodes {
let Some(root) = nodes.first() else { continue };
match outline_network(source, root).and_then(|net| placed(net, to_local * root.transform)) {
Some(net) => pieces.push(net),
None => skipped.push(root.name.clone()),
}
}
if pieces.is_empty() {
return Err(EngineError::Disabled(
CMD.into(),
"none of the copied layers has an outline to add to the vector (text, frames and groups have none)".into(),
));
}
let have = vectoredit::network(live, target).map_or(0, |n| n.segments.len());
if have.saturating_add(pieces.iter().map(|n| n.segments.len()).sum::<usize>()) > MAX_SEGMENTS {
return Err(EngineError::Disabled(CMD.into(), format!("a vector takes at most {MAX_SEGMENTS} segments")));
}
let mut pasted: Vec<usize> = Vec::new();
vectoredit::edit(s.doc_mut()?, target, |net| {
for piece in pieces {
let (vo, so) = (net.vertices.len(), net.segments.len());
pasted.extend(vo..vo + piece.vertices.len());
net.vertices.extend(piece.vertices);
net.segments.extend(piece.segments.into_iter().map(|mut sg| {
sg.a += vo;
sg.b += vo;
sg
}));
net.regions.extend(piece.regions.into_iter().map(|mut r| {
for i in r.loops.iter_mut().flatten() {
*i += so;
}
r
}));
}
})?;
let selected = pasted.clone();
vectoredit::set_state(s, |ve| {
ve.clear_selection();
ve.clear_regions();
ve.vertices = selected;
ve.anchor = None;
ve.pen_out = None;
ve.width_point = None;
})?;
// `ids` stays empty: no layer is created, the pasted outlines joined layer `edited`.
let mut out = json!({"ids": [], "edited": target, "vertices": pasted.len()});
if !skipped.is_empty() {
out["skipped"] = json!(skipped);
}
Ok(out)
}
@@ -0,0 +1,442 @@
//! Copy, cut and paste in vector edit mode (#1875), measured in Figma: Copy takes the selected
//! segments (a lone point: the segments touching it) and a paste outside is a new vector in place;
//! Cut removes them, splitting the path in the same layer; Paste while editing adds the clipboard's
//! segments or a copied layer's outline to the vector's network in place, selected.
use serde_json::{Value, json};
use crate::{EngineError, Session, params};
use figcraft_doc::{NodeId, NodeKind, VectorNetwork};
fn ex(s: &mut Session, c: &str, p: Value) -> Value {
s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}"))
}
fn id_of(v: &Value) -> NodeId {
params::id_of(&v["id"]).unwrap()
}
/// Open path A-B-C-D (three segments) with a look of its own, in edit mode.
fn path(s: &mut Session) -> NodeId {
let r = ex(s, "vector.create", json!({"points": [[100, 100], [200, 150], [300, 100], [400, 200]], "closed": false}));
let id = id_of(&r);
ex(s, "node.set", json!({"id": id, "props": {"strokeWeight": 7, "opacity": 0.5}}));
ex(s, "vector.edit.begin", json!({"id": id}));
id
}
fn net(s: &Session, id: NodeId) -> VectorNetwork {
crate::vectoredit::network(s.doc().unwrap(), id).unwrap().clone()
}
fn layers(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().node(s.page().unwrap()).unwrap().children.clone()
}
/// The network's points on the page, rounded, in vertex order.
fn page_points(s: &Session, id: NodeId) -> Vec<(i64, i64)> {
let w = s.doc().unwrap().world_transform(id);
net(s, id).vertices.iter().map(|v| w * v.point()).map(|p| (p.x.round() as i64, p.y.round() as i64)).collect()
}
/// The number of separate paths a network is made of.
fn subpaths(n: &VectorNetwork) -> usize {
let mut group: Vec<usize> = (0..n.vertices.len()).collect();
fn root(g: &[usize], mut i: usize) -> usize {
while g[i] != i {
i = g[i];
}
i
}
for sg in &n.segments {
let (a, b) = (root(&group, sg.a), root(&group, sg.b));
group[a] = b;
}
(0..n.vertices.len()).filter(|i| root(&group, *i) == *i && n.segments.iter().any(|sg| root(&group, sg.a) == *i)).count()
}
fn select(s: &mut Session, vertices: &[usize], segments: &[usize]) {
ex(s, "vector.edit.select", json!({"vertices": vertices, "segments": segments}));
}
fn leave(s: &mut Session) {
ex(s, "vector.edit.end", json!({}));
assert!(s.ds().unwrap().vector_edit.is_none());
}
fn world_rect(s: &Session, id: NodeId) -> (f64, f64, f64, f64) {
let b = s.doc().unwrap().world_bounds(id).unwrap();
(b.x0, b.y0, b.width(), b.height())
}
#[test]
fn a_copied_segment_pastes_outside_as_a_new_vector_in_place() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
let r = ex(&mut s, "edit.copy", json!({}));
assert_eq!(r["segments"], 1);
assert_eq!(net(&s, id).segments.len(), 3, "Copy changes nothing");
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let all = layers(&s);
assert_eq!(all.len(), 2);
let new = all[1];
let n = net(&s, new);
assert_eq!((n.vertices.len(), n.segments.len()), (2, 1));
assert_eq!(page_points(&s, new), vec![(200, 150), (300, 100)], "at the segment's own page position");
assert_eq!(world_rect(&s, new), (200.0, 100.0, 100.0, 50.0));
// The layer's look comes along (the width profile aside).
let node = s.doc().unwrap().node(new).unwrap();
assert_eq!((node.stroke.weight, node.opacity), (7.0, 0.5));
assert_eq!(s.selection(), vec![new]);
}
#[test]
fn a_copied_point_takes_the_segments_touching_it() {
let mut s = Session::new();
path(&mut s);
select(&mut s, &[1], &[]);
ex(&mut s, "edit.copy", json!({}));
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let new = *layers(&s).last().unwrap();
let n = net(&s, new);
assert_eq!((n.vertices.len(), n.segments.len()), (3, 2), "A-B and B-C");
assert_eq!(page_points(&s, new), vec![(100, 100), (200, 150), (300, 100)]);
}
#[test]
fn nothing_selected_still_copies_the_whole_layer() {
let mut s = Session::new();
path(&mut s);
ex(&mut s, "edit.copy", json!({}));
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let new = *layers(&s).last().unwrap();
assert_eq!(net(&s, new).segments.len(), 3);
}
#[test]
fn cut_removes_the_segment_in_the_same_layer_and_stays_in_edit_mode() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
ex(&mut s, "edit.cut", json!({}));
assert_eq!(layers(&s), vec![id], "no new layer");
let n = net(&s, id);
assert_eq!(n.segments.len(), 2);
assert_eq!(subpaths(&n), 2, "the path split in two");
let ve = s.ds().unwrap().vector_edit.clone().expect("edit mode stays on");
assert!(ve.segments.is_empty() && ve.vertices.is_empty());
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let all = layers(&s);
assert_eq!(all.len(), 2);
let new = all[1];
assert_eq!(net(&s, new).segments.len(), 1);
assert_eq!(page_points(&s, new), vec![(200, 150), (300, 100)]);
}
#[test]
fn cut_is_one_undo_step() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
ex(&mut s, "edit.cut", json!({}));
assert_eq!(net(&s, id).segments.len(), 2);
s.undo().unwrap();
assert_eq!(net(&s, id).segments.len(), 3);
assert_eq!(page_points(&s, id), vec![(100, 100), (200, 150), (300, 100), (400, 200)]);
}
#[test]
fn a_cut_point_takes_its_segments_with_it() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[1], &[]);
ex(&mut s, "edit.cut", json!({}));
assert_eq!(net(&s, id).segments.len(), 1, "only C-D is left");
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let new = *layers(&s).last().unwrap();
assert_eq!(net(&s, new).segments.len(), 2, "A-B and B-C");
}
#[test]
fn pasting_segments_while_editing_adds_them_to_the_same_network_in_place() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
ex(&mut s, "edit.copy", json!({}));
let r = ex(&mut s, "edit.paste", json!({}));
assert_eq!(r["vertices"], 2);
assert_eq!(layers(&s), vec![id], "no new layer");
let n = net(&s, id);
assert_eq!((n.vertices.len(), n.segments.len()), (6, 4));
assert_eq!(page_points(&s, id)[4..], [(200, 150), (300, 100)], "on top of the original");
let ve = s.ds().unwrap().vector_edit.clone().unwrap();
assert_eq!(ve.vertices, vec![4, 5], "the pasted points are selected");
assert!(ve.segments.is_empty());
// One undo reverts it.
s.undo().unwrap();
assert_eq!(net(&s, id).segments.len(), 3);
assert_eq!(net(&s, id).vertices.len(), 4);
}
#[test]
fn pasting_at_a_point_moves_the_copied_top_left_there() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "edit.paste", json!({"x": 0, "y": 0}));
assert_eq!(page_points(&s, id)[4..], [(0, 50), (100, 0)]);
}
#[test]
fn pasting_a_rectangle_while_editing_adds_its_outline_in_the_vectors_coordinates() {
let mut s = Session::new();
let rect = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 500, "y": 300, "width": 60, "height": 40})));
ex(&mut s, "select.set", json!({"ids": [rect]}));
ex(&mut s, "edit.copy", json!({}));
let id = path(&mut s);
let before = world_rect(&s, id);
ex(&mut s, "edit.paste", json!({}));
assert_eq!(layers(&s), vec![rect, id], "no new layer");
let n = net(&s, id);
assert_eq!((n.vertices.len(), n.segments.len()), (8, 7), "four corners, four sides, joined to the path");
let mut corners: Vec<(i64, i64)> = page_points(&s, id)[4..].to_vec();
corners.sort_unstable();
assert_eq!(corners, vec![(500, 300), (500, 340), (560, 300), (560, 340)]);
let ve = s.ds().unwrap().vector_edit.clone().unwrap();
assert_eq!(ve.vertices, vec![4, 5, 6, 7]);
let after = world_rect(&s, id);
assert!(after.2 > before.2 && after.3 > before.3, "the vector's bounds grow: {before:?} to {after:?}");
assert_eq!((after.0, after.1), (before.0, before.1));
assert_eq!(after.0 + after.2, 560.0);
s.undo().unwrap();
assert_eq!(net(&s, id).vertices.len(), 4);
assert_eq!(world_rect(&s, id), before);
}
#[test]
fn a_rotated_vector_takes_pasted_points_in_its_own_coordinates() {
let mut s = Session::new();
let id = path(&mut s);
ex(&mut s, "node.set", json!({"id": id, "props": {"rotation": 90}}));
select(&mut s, &[], &[1]);
ex(&mut s, "edit.copy", json!({}));
let before = page_points(&s, id);
assert_ne!(before[0], (100, 100), "the vector is rotated");
ex(&mut s, "edit.paste", json!({}));
let after = page_points(&s, id);
assert_eq!(after[4..], before[1..3]);
}
#[test]
fn layers_with_no_outline_are_skipped_and_named() {
let mut s = Session::new();
let rect = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 500, "y": 300, "width": 60, "height": 40})));
let text = id_of(&ex(&mut s, "text.create", json!({"text": "hello", "x": 500, "y": 400})));
let name = s.doc().unwrap().node(text).unwrap().name.clone();
// Only text: nothing to add, and nothing changes.
ex(&mut s, "select.set", json!({"ids": [text]}));
ex(&mut s, "edit.copy", json!({}));
let id = path(&mut s);
let err = s.execute("edit.paste", &json!({})).unwrap_err();
assert!(matches!(err, EngineError::Disabled(..)), "{err}");
assert_eq!(net(&s, id).vertices.len(), 4);
// The rectangle joins, the text is named as skipped.
leave(&mut s);
ex(&mut s, "edit.copy", json!({"ids": [rect, text]}));
ex(&mut s, "vector.edit.begin", json!({"id": id}));
let r = ex(&mut s, "edit.paste", json!({}));
assert_eq!(r["skipped"], json!([name]));
assert_eq!(net(&s, id).vertices.len(), 8);
}
#[test]
fn a_parent_still_pastes_layers_while_editing() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[1]);
ex(&mut s, "edit.copy", json!({}));
let page = s.page().unwrap();
ex(&mut s, "edit.paste", json!({"parent": page}));
assert_eq!(layers(&s).len(), 2);
assert_eq!(net(&s, id).segments.len(), 3);
}
#[test]
fn an_empty_clipboard_refuses_to_paste_while_editing() {
let mut s = Session::new();
path(&mut s);
assert!(matches!(s.execute("edit.paste", &json!({})), Err(EngineError::Disabled(..))));
}
#[test]
fn a_selected_face_copies_its_own_outline_with_the_fill() {
let mut s = Session::new();
let r = ex(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60}));
let id = id_of(&r);
ex(&mut s, "vector.edit.begin", json!({"id": id}));
select(&mut s, &[], &[0, 1, 2, 3]);
ex(&mut s, "edit.copy", json!({}));
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let new = *layers(&s).last().unwrap();
let n = net(&s, new);
assert_eq!((n.segments.len(), n.regions.len()), (4, 1), "the closed shape stays filled");
assert!(matches!(s.doc().unwrap().node(new).unwrap().kind, NodeKind::Vector { .. }));
}
/// Everything junk must not change when a command is refused: the vector, the layers, the edit
/// selection and what the clipboard holds.
fn state(s: &Session, id: NodeId) -> String {
let ve = s.ds().unwrap().vector_edit.clone();
let clip: Vec<String> = s.clipboard.nodes.iter().flat_map(|(_, n)| n).map(|n| format!("{:?}", n.kind)).collect();
format!("{:?}|{:?}|{:?}|{:?}|{}", net(s, id), layers(s), ve.map(|v| (v.vertices, v.segments)), clip, s.clipboard.layers_generation)
}
fn finite(n: &VectorNetwork) -> bool {
n.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite())
&& n.segments.iter().all(|sg| [sg.ta.0, sg.ta.1, sg.tb.0, sg.tb.1].iter().all(|x| x.is_finite()))
}
#[test]
fn copy_cut_and_paste_survive_junk_in_vector_edit_mode() {
let junk = [
json!({}),
json!(null),
json!([1, 2]),
json!({"ids": ["x", -1, 99999]}),
json!({"id": "nope", "x": "NaN", "y": 1e308}),
json!({"parent": "nope", "x": -1e308, "y": "x"}),
json!({"x": 1e308, "y": 1e308}),
json!({"x": 1e308}),
];
for cmd in ["edit.copy", "edit.cut", "edit.paste", "edit.pasteOver", "edit.pasteReplace"] {
for j in &junk {
// Both a selection with a text layer next to it, and after a copy from the selection.
for copied in [false, true] {
let mut s = Session::new();
let id = path(&mut s);
if copied {
select(&mut s, &[2], &[]);
let _ = s.execute("edit.copy", &json!({}));
} else {
select(&mut s, &[1], &[0]);
ex(&mut s, "text.create", json!({"text": "t"}));
ex(&mut s, "vector.edit.begin", json!({"id": id}));
select(&mut s, &[1], &[0]);
}
let before = state(&s, id);
match s.execute(cmd, j) {
Err(EngineError::Internal { cmd, msg }) => panic!("{cmd} panicked on {j}: {msg}"),
Err(_) => {
if cmd != "edit.pasteOver" && cmd != "edit.pasteReplace" {
assert_eq!(state(&s, id), before, "{cmd} {j} was refused but changed something");
}
}
// Accepted: whatever it made has finite coordinates.
Ok(_) => {
if let Some(n) = crate::vectoredit::network(s.doc().unwrap(), id) {
assert!(finite(n), "{cmd} {j} left non-finite coordinates");
}
}
}
}
}
}
}
#[test]
fn a_huge_paste_position_is_refused_or_stays_finite() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[0]);
ex(&mut s, "edit.copy", json!({}));
let before = state(&s, id);
match s.execute("edit.paste", &json!({"x": 1e308, "y": 1e308})) {
Err(e) => {
assert!(!matches!(e, EngineError::Internal { .. }), "{e}");
assert_eq!(state(&s, id), before, "a refused paste changed something");
}
// It is accepted here: 1e308 plus a few hundred is still finite, so the points are too.
Ok(_) => assert!(finite(&net(&s, id)), "the points are finite"),
}
}
#[test]
fn cut_with_only_lone_points_is_refused_like_copy_and_changes_nothing() {
let mut s = Session::new();
let id = path(&mut s);
// A point no segment touches.
crate::vectoredit::edit(s.doc_mut().unwrap(), id, |n| n.vertices.push(figcraft_doc::Vertex::new(50.0, 50.0))).unwrap();
// Something on the clipboard first, then only the lone point selected.
select(&mut s, &[0], &[]);
ex(&mut s, "edit.copy", json!({}));
select(&mut s, &[4], &[]);
let before = state(&s, id);
for cmd in ["edit.copy", "edit.cut"] {
let err = s.execute(cmd, &json!({})).expect_err(cmd);
assert!(matches!(err, EngineError::Disabled(..)), "{cmd}: {err}");
assert_eq!(state(&s, id), before, "{cmd} changed something");
}
// Delete is the way to remove it.
ex(&mut s, "vector.edit.delete", json!({}));
assert_eq!(net(&s, id).vertices.len(), 4);
}
#[test]
fn only_one_of_x_and_y_is_refused_and_pastes_nothing() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[], &[0]);
ex(&mut s, "edit.copy", json!({}));
let before = state(&s, id);
for p in [json!({"x": 10}), json!({"y": 10})] {
let err = s.execute("edit.paste", &p).expect_err("one coordinate");
assert!(err.to_string().contains("give both x and y, or neither"), "{err}");
assert_eq!(state(&s, id), before);
}
ex(&mut s, "edit.paste", json!({"x": 10, "y": 10}));
}
#[test]
fn a_partial_copy_has_an_svg_for_the_system_clipboard() {
let mut s = Session::new();
let r = ex(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60}));
assert!(crate::cmd::edit::clipboard_svg(&s).is_none(), "nothing copied yet");
ex(&mut s, "vector.edit.begin", json!({"id": id_of(&r)}));
select(&mut s, &[], &[0, 1, 2, 3]);
ex(&mut s, "edit.copy", json!({}));
let svg = crate::cmd::edit::clipboard_svg(&s).expect("svg");
assert!(svg.contains("<svg") && svg.contains("<path"), "{svg}");
}
#[test]
fn cutting_a_selected_region_deletes_exactly_the_segments_it_copies_and_keeps_a_tail() {
let mut s = Session::new();
let r = ex(&mut s, "vector.create", json!({"points": [[100, 100], [200, 100], [150, 200]], "closed": true}));
let id = id_of(&r);
// A tail: one open segment from the first corner to a new point.
crate::vectoredit::edit(s.doc_mut().unwrap(), id, |n| {
n.vertices.push(figcraft_doc::Vertex::new(20.0, 20.0));
let tail = n.vertices.len() - 1;
crate::vectoredit::ops::connect(n, 0, tail, (0.0, 0.0), (0.0, 0.0));
})
.unwrap();
assert_eq!((net(&s, id).segments.len(), net(&s, id).regions.len()), (4, 1));
ex(&mut s, "vector.edit.begin", json!({"id": id}));
ex(&mut s, "vector.edit.select", json!({"regions": [0]}));
ex(&mut s, "edit.cut", json!({}));
let n = net(&s, id);
assert_eq!(n.segments.len(), 1, "only the tail is left");
assert!(n.regions.is_empty());
leave(&mut s);
ex(&mut s, "edit.paste", json!({}));
let new = *layers(&s).last().unwrap();
assert_eq!(net(&s, new).segments.len(), 3, "the copy holds the region's three segments, not the tail");
}
+3 -2
View File
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"file.export",
"Export",
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, PDF and XML are always sRGB), quality? (JPG: 1-100, default 90)}",
"{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, XML and RGB PDF output are always sRGB; PDF with cmyk is DeviceCMYK), quality? (JPG: 1-100, default 90)}",
false,
export
),
@@ -372,7 +372,8 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal
&& !setting.include_bounding_box
&& !ids.iter().any(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Slice)));
match setting.format {
// SVG and PDF colours are sRGB: a Display P3 file exports converted (out-of-gamut colours clip).
// SVG and RGB PDF colors are sRGB: a Display P3 file exports converted (out-of-gamut colours clip).
// PDF with `cmyk` converts from those sRGB colors to DeviceCMYK.
ExportFormat::Svg => {
let opts = figcraft_svg::SvgOptions {
include_ids: setting.svg_id_attribute,
+110 -21
View File
@@ -399,11 +399,19 @@ pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option<Result<figcraft_forma
}))
}
/// The most layers all of a Penpot file's raw SVG placeholders may expand to together.
const MAX_PENPOT_SVG_LAYERS: usize = 100_000;
/// Turn Penpot raw SVG placeholders into editable FigCraft SVG content, using the
/// normal SVG importer. The parser (figcraft-format) only stores bounded XML so it
/// does not need to depend on the SVG crate; the engine does this second pass.
/// Any failure leaves the original placeholder and XML data intact for later use.
fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
expand_penpot_raw_svgs_within(doc, notes, MAX_PENPOT_SVG_LAYERS);
}
/// [`expand_penpot_raw_svgs`] with at most `room` layers made in all.
fn expand_penpot_raw_svgs_within(doc: &mut Document, notes: &mut Vec<String>, mut room: usize) {
let layers = doc
.nodes()
.filter_map(|node| {
@@ -413,12 +421,24 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
})
.collect::<Vec<_>>();
let mut ok_count = 0usize;
// The SVG importer caps its own layers per file; `room` is the cap over all of a file's placeholders.
for (id, name, width, height, xml, empty) in layers {
if room == 0 {
if let Some(n) = doc.node_mut(id) {
n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
}
if notes.len() < 100 {
notes.push(format!("Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"));
}
continue;
}
if !empty {
notes.push(format!("Penpot SVG '{name}': has separate child layers; the original tree was preserved to prevent duplicate rendering"));
continue;
}
match figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name) {
let before = doc.node_count();
let imported = figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name);
match imported {
Ok(imported) => {
// An SVG can be syntactically valid yet contain no supported drawable
// elements. Do not claim success or leave an empty extra frame.
@@ -432,6 +452,21 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
}
continue;
}
// Charged once the empty ones are gone; one that doesn't fit is taken out again.
let added = doc.node_count().saturating_sub(before);
if added > room {
let _ = doc.remove(imported.frame);
if let Some(n) = doc.node_mut(id) {
n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
}
if notes.len() < 100 {
notes.push(format!(
"Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"
));
}
continue;
}
room -= added;
let size = doc.node(imported.frame).map(|n| (n.width, n.height));
if let Some((svg_w, svg_h)) = size
&& svg_w.is_finite()
@@ -470,6 +505,28 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec<String>) {
}
}
/// Whether some of the first `len` characters are in none of `runs`. Where runs start and stop
/// covering is summed once, so runs overlapping any number of times cost no more than their count.
fn has_uncovered(len: usize, runs: &[figcraft_doc::StyleRun]) -> bool {
let mut change = vec![0i64; len + 1];
for run in runs {
let (start, end) = (run.start.min(len), run.end.min(len));
if start < end {
if let Some(c) = change.get_mut(start) {
*c += 1;
}
if let Some(c) = change.get_mut(end) {
*c -= 1;
}
}
}
let mut open = 0i64;
change.iter().take(len).any(|c| {
open += c;
open <= 0
})
}
/// Non-destructive font diagnostic for the action palette, CLI and control API.
/// Includes styled runs, not just the default typeface of each text layer.
pub(super) fn font_report(doc: &Document) -> Value {
@@ -485,21 +542,15 @@ fn font_report_with_families(doc: &Document, installed: &[String]) -> Value {
if text.characters.is_empty() {
continue;
}
let mut covered = vec![false; text.characters.chars().count().min(100_000)];
let len = text.characters.chars().count().min(100_000);
let mut used = BTreeSet::new();
for run in &text.runs {
let start = run.start.min(covered.len());
let end = run.end.min(covered.len());
if start < end {
if !run.style.font_family.trim().is_empty() {
used.insert(run.style.font_family.clone());
}
for entry in covered.iter_mut().take(end).skip(start) {
*entry = true;
}
if run.start.min(len) < run.end.min(len) && !run.style.font_family.trim().is_empty() {
used.insert(run.style.font_family.clone());
}
}
if covered.iter().any(|entry| !entry) {
let uncovered = has_uncovered(len, &text.runs);
if uncovered {
used.insert(text.style.font_family.clone());
}
for family in used {
@@ -599,19 +650,14 @@ fn missing_penpot_font_warnings(doc: &Document, families: &[String]) -> Vec<Stri
if text_len == 0 {
continue;
}
let mut covered = vec![false; text_len.min(100_000)];
let len = text_len.min(100_000);
let mut used = BTreeSet::new();
for run in &text.runs {
let start = run.start.min(covered.len());
let end = run.end.min(covered.len());
if start < end {
if run.start.min(len) < run.end.min(len) {
used.insert(run.style.font_family.clone());
for flag in covered.iter_mut().take(end).skip(start) {
*flag = true;
}
}
}
if covered.iter().any(|present| !present) {
if has_uncovered(len, &text.runs) {
used.insert(text.style.font_family.clone());
}
for family in used {
@@ -652,8 +698,10 @@ fn link_instances(doc: &mut Document) {
let mut insts: Vec<(usize, NodeId)> =
doc.nodes().filter(|n| matches!(n.kind, NodeKind::Instance { .. })).map(|n| (doc.ancestors(n.id).len(), n.id)).collect();
insts.sort_by_key(|a| std::cmp::Reverse(a.0));
// Rebasing leaves the mains alone, so each main's layer paths are worked out once.
let mut mains = crate::components::MainPaths::new();
for (_, i) in insts {
crate::components::rebase_instance(doc, i);
crate::components::rebase_instance_with(doc, i, &mut mains);
}
}
@@ -790,6 +838,47 @@ mod penpot_svg_v10_tests {
use super::*;
use figcraft_doc::TextData;
#[test]
fn placeholders_share_one_layer_allowance() {
let mut doc = Document::new("Two SVGs");
let page = doc.first_page().unwrap();
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="5" height="5" fill="red"/><rect x="5" width="5" height="5" fill="blue"/></svg>"#;
let ids: Vec<NodeId> = (0..2)
.map(|i| {
let id = doc.create(page, NodeKind::Frame, &format!("S{i}"), 0.0, 0.0, 10.0, 10.0).unwrap();
let layer = doc.node_mut(id).unwrap();
layer.plugin_data.insert("penpot.svgRawXml".into(), svg.into());
layer.plugin_data.insert("penpot.svgRawStatus".into(), "pending".into());
id
})
.collect();
let mut warnings = Vec::new();
let nodes = doc.node_count();
expand_penpot_raw_svgs_within(&mut doc, &mut warnings, 4);
assert!(doc.node_count() - nodes <= 4, "never more layers than the allowance");
let status = |i: usize| doc.node(ids[i]).unwrap().plugin_data.get("penpot.svgRawStatus").cloned();
assert_eq!(status(0).as_deref(), Some("expanded"), "the first uses the allowance");
assert_eq!(status(1).as_deref(), Some("not-expanded"));
assert!(doc.node(ids[1]).unwrap().children.is_empty());
assert!(warnings.iter().any(|w| w.contains("over the limit")), "{warnings:?}");
}
#[test]
fn many_overlapping_style_runs_are_summed_once() {
use figcraft_doc::StyleRun;
let mut doc = Document::new("Runs");
let page = doc.first_page().unwrap();
let mut t = TextData::new("x".repeat(100_000));
t.style.font_family = "Unused Base".into();
let mut run = t.style.clone();
run.font_family = "Run Font".into();
t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect();
doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap();
let report = font_report_with_families(&doc, &[]);
assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}");
assert_eq!(report["fonts"][0]["family"], "Run Font");
}
#[test]
fn expands_inline_svg_into_editable_shapes_without_discarding_source() {
let mut doc = Document::new("SVG fixture");
+3 -2
View File
@@ -30,8 +30,9 @@ pub(super) fn open_recent(s: &mut Session, p: &Value) -> Result<Value> {
allow(&path, Access::Read)?;
Some(path)
}
(None, Some(i)) => {
Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i.max(0.0) as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
(None, Some(_)) => {
let i = req_index(CMD, p, "index")?;
Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
}
_ => None,
};
+5 -2
View File
@@ -5,7 +5,7 @@ use figcraft_doc::{Document, ImagePreset, Node};
use serde_json::{Value, json};
use super::{CommandSpec, ok};
use crate::params::{f64_of, get, num, req_index, req_string, req_targets, string, targets};
use crate::params::{f64_of, get, req_index, req_string, req_targets, string, targets};
use crate::{EngineError, Result, Session, bad, spec};
pub fn specs() -> Vec<CommandSpec> {
@@ -236,7 +236,10 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => with_values(cmd, ImageFilters::NONE, v)?,
None => {
let stroke = strokes(cmd, p)?;
let index = num(p, "index").filter(|k| k.is_finite() && *k >= 0.0).map(|k| k as usize);
let index = match get(p, "index") {
None | Some(Value::Null) => None,
Some(_) => Some(req_index(cmd, p, "index")?),
};
let doc = s.doc()?;
targets(s, p)
.iter()
+4 -4
View File
@@ -799,7 +799,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
WindingRule::NonZero
};
let path = drawn.fill_path();
let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
let path = figcraft_geom::simplify_path(&path, tol);
let (path, output_winding) = match figcraft_pathops::simplify_with_rule(&path, winding == WindingRule::EvenOdd) {
Ok(path) => (path, WindingRule::EvenOdd),
Err(_) => (path, winding),
@@ -809,7 +809,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
} else {
for (index, region) in source.regions.iter().enumerate() {
let Some(path) = drawn.region_path(index) else { continue };
let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
let path = figcraft_geom::simplify_path(&path, tol);
let path = figcraft_pathops::simplify_with_rule(&path, region.winding == WindingRule::EvenOdd).unwrap_or(path);
append_region_path(&mut net, &path, region, region.winding);
}
@@ -826,7 +826,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
open.regions.clear();
if !open.segments.is_empty() {
let path = open.stroke_path();
let simplified = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
let simplified = figcraft_geom::simplify_path(&path, tol);
let mut loose = VectorNetwork::from_path(&simplified);
loose.regions.clear();
append_network(&mut net, loose);
@@ -834,7 +834,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
}
if source.regions.is_empty() {
let path = source.stroke_path();
let simplified = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default());
let simplified = figcraft_geom::simplify_path(&path, tol);
net = VectorNetwork::from_path(&simplified);
net.regions.clear();
}
@@ -7,6 +7,7 @@
use serde_json::{Value, json};
use crate::Session;
use crate::automation::params::id_of;
use crate::components::tests::{chars, copy_of, ex, fill, healthy, idv, kids, node};
use figcraft_doc::*;
@@ -1000,3 +1001,245 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() {
s.execute("edit.delete", &json!({"ids": [k.inst]})).unwrap();
assert!(s.doc().unwrap().node(k.inst).is_none());
}
/// Create multiple components (#2088): each selected layer becomes its own component in place,
/// keeping its name and position; all stay selected and one undo reverts them all.
#[test]
fn create_multiple_components_keeps_names_and_places_and_is_one_undo_step() {
let mut s = Session::new();
let mut frames = Vec::new();
for (i, name) in ["Card", "Badge", "Tile"].into_iter().enumerate() {
let x = 150.0 * i as f64;
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
let f = id_of(&v["id"]).unwrap();
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
frames.push(f);
}
let before = undo_len(&s);
let out = s.execute("component.createMultiple", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let made: Vec<NodeId> = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect();
assert_eq!(made.len(), 3);
assert_eq!(s.selection(), made, "all of them stay selected");
let doc = s.doc().unwrap();
for (i, (c, name)) in made.iter().zip(["Card", "Badge", "Tile"]).enumerate() {
let n = doc.node(*c).unwrap();
assert!(matches!(n.kind, NodeKind::Component { .. }), "{name} is a component");
assert_eq!(n.name, name);
let b = doc.world_bounds(*c).unwrap();
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "{name} stays in place");
}
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
}
/// Frames named `names` at x = 150 * i (mirrored when `reverse`), y 20, 100 x 60.
fn named_frames(s: &mut Session, names: &[&str], reverse: bool) -> Vec<NodeId> {
let n = names.len();
names
.iter()
.enumerate()
.map(|(i, name)| {
let x = 150.0 * if reverse { n - 1 - i } else { i } as f64;
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
let f = id_of(&v["id"]).unwrap();
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
f
})
.collect()
}
/// The set's name and its children's names in layer order.
fn set_names(s: &Session, set: NodeId) -> (String, Vec<String>) {
let doc = s.doc().unwrap();
let n = doc.node(set).unwrap();
(n.name.clone(), n.children.iter().map(|c| doc.node(*c).unwrap().name.clone()).collect())
}
/// The set's variant names ordered by world x.
fn names_by_x(s: &Session, set: NodeId) -> Vec<String> {
let doc = s.doc().unwrap();
let mut v: Vec<(f64, String)> =
doc.node(set).unwrap().children.iter().map(|c| (doc.world_bounds(*c).unwrap().x0, doc.node(*c).unwrap().name.clone())).collect();
v.sort_by(|a, b| a.0.total_cmp(&b.0));
v.into_iter().map(|(_, n)| n).collect()
}
/// Create component set (#2088, measured in Figma): variants "Property 1=<name>" in left-to-right
/// order, the set "Component 1", wrapped in place 20 px around, selected, one undo step.
#[test]
fn create_set_names_variants_by_layer_name_and_wraps_in_place() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Primary", "Secondary", "Ghost"], false);
let before = undo_len(&s);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let set = id_of(&out["id"]).unwrap();
assert_eq!(s.selection(), vec![set], "the set is selected");
assert_eq!(set_names(&s, set).0, "Component 1");
assert_eq!(names_by_x(&s, set), ["Property 1=Primary", "Property 1=Secondary", "Property 1=Ghost"]);
let doc = s.doc().unwrap();
for (i, c) in doc.node(set).unwrap().children.iter().enumerate() {
assert!(matches!(doc.node(*c).unwrap().kind, NodeKind::Component { .. }));
let b = doc.world_bounds(*c).unwrap();
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "frames stay put");
}
let sb = doc.world_bounds(set).unwrap();
assert_eq!((sb.x0, sb.y0, sb.x1, sb.y1), (-20.0, 0.0, 420.0, 100.0), "20 px on every side");
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(doc.node(set).is_none());
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
}
#[test]
fn create_set_orders_left_to_right_whatever_the_selection_order() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B", "C"], true);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
assert_eq!(names_by_x(&s, set), ["Property 1=C", "Property 1=B", "Property 1=A"]);
let (_, kids) = set_names(&s, set);
assert_eq!(kids.len(), 3);
}
#[test]
fn create_set_keeps_names_already_in_prop_value_form() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Size=Small", "Size=Large", "Size=Medium"], false);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
assert_eq!(set_names(&s, set).0, "Component 1");
assert_eq!(names_by_x(&s, set), ["Size=Small", "Size=Large", "Size=Medium"]);
}
#[test]
fn create_set_with_one_shared_name_names_the_set_and_makes_default_variants() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Card", "Card", "Card"], false);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
let (name, kids) = set_names(&s, set);
assert_eq!(name, "Card");
assert_eq!(kids, ["Property 1=Default", "Property 1=Default", "Property 1=Default"]);
}
#[test]
fn create_set_refuses_instances_and_leaves_the_document_alone() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B"], false);
let c = s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap();
let comp = id_of(&c["id"]).unwrap();
let inst = s.execute("instance.create", &json!({"component": comp})).unwrap();
let inst = id_of(&inst["id"]).unwrap();
let before = undo_len(&s);
let e = s.execute("component.createSet", &json!({"ids": [inst, frames[1]]})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(&s), before);
assert!(matches!(s.doc().unwrap().node(frames[1]).unwrap().kind, NodeKind::Frame));
}
#[test]
fn create_set_refuses_a_target_inside_another_target_and_leaves_the_document_alone() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Outer", "Inner"], false);
s.execute("node.reparent", &json!({"ids": [frames[1]], "parent": frames[0]})).unwrap();
let before = undo_len(&s);
let e = s.execute("component.createSet", &json!({"ids": [frames[0], frames[1]]})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(&s), before);
let doc = s.doc().unwrap();
assert!(matches!(doc.node(frames[0]).unwrap().kind, NodeKind::Frame));
assert!(matches!(doc.node(frames[1]).unwrap().kind, NodeKind::Frame));
}
/// Every node's id, parent, name and kind, to compare a document before and after a refused command.
fn snapshot(s: &Session) -> Vec<String> {
s.doc().unwrap().nodes().map(|n| format!("{:?}|{:?}|{}|{:?}", n.id, n.parent, n.name, n.kind)).collect()
}
/// A refused `component.createSet`: `Disabled`, no undo step, the document and the selection as they were.
fn assert_create_set_refused(s: &mut Session, ids: &[NodeId]) {
let (before, undo, selection) = (snapshot(s), undo_len(s), s.selection());
let e = s.execute("component.createSet", &json!({"ids": ids})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(s), undo, "no undo step");
assert_eq!(snapshot(s), before, "the document is unchanged");
assert_eq!(s.selection(), selection, "the selection is unchanged");
}
/// Nothing to wrap is refused before anything is created.
#[test]
fn create_set_refuses_no_layers_and_leaves_the_document_alone() {
let mut s = Session::new();
named_frames(&mut s, &["A"], false);
s.execute("select.set", &json!({"ids": []})).unwrap();
assert_create_set_refused(&mut s, &[]);
}
/// One layer is allowed: a set of one variant, as many layers would make.
#[test]
fn create_set_with_one_layer_makes_a_one_variant_set() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Solo"], false);
let before = undo_len(&s);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let set = id_of(&out["id"]).unwrap();
let doc = s.doc().unwrap();
assert_eq!(doc.node(set).unwrap().children.len(), 1);
assert_eq!(names_by_x(&s, set), ["Property 1=Default"], "a lone layer shares its name with itself");
assert!(matches!(doc.node(doc.node(set).unwrap().children[0]).unwrap().kind, NodeKind::Component { .. }));
s.undo().unwrap();
assert!(matches!(s.doc().unwrap().node(frames[0]).unwrap().kind, NodeKind::Frame));
}
/// Each refusal branch of `create_set`, with `can_create_set` agreeing with it.
#[test]
fn create_set_refuses_every_ineligible_selection_and_leaves_the_document_alone() {
use crate::cmd::component::can_create_set;
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B", "C"], false);
let comp = id_of(&s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap()["id"]).unwrap();
let inst = id_of(&s.execute("instance.create", &json!({"component": comp})).unwrap()["id"]).unwrap();
let set_frames = named_frames(&mut s, &["V1", "V2"], false);
let set = id_of(&s.execute("component.createSet", &json!({"ids": set_frames})).unwrap()["id"]).unwrap();
// A layer inside the instance (its copy of the card's content).
let in_inst = s.doc().unwrap().node(inst).unwrap().children.first().copied();
// A library copy.
let remote = {
let doc = s.doc_mut().unwrap();
let store = doc.ensure_library_store();
let remote = doc.alloc_id();
doc.insert(Node::new(remote, NodeKind::Frame, "Remote", 10.0, 10.0), store, None).unwrap();
remote
};
let ok = frames[1];
assert!(can_create_set(s.doc().unwrap(), &[ok, frames[2]]));
assert!(!can_create_set(s.doc().unwrap(), &[]));
let mut cases = vec![("instance", inst), ("library copy", remote), ("component", comp), ("component set", set)];
if let Some(i) = in_inst {
cases.push(("inside an instance", i));
}
for (what, bad) in cases {
assert!(!can_create_set(s.doc().unwrap(), &[ok, bad]), "{what}: not offered");
assert_create_set_refused(&mut s, &[ok, bad]);
assert_create_set_refused(&mut s, &[bad]);
}
}
/// A command that fails leaves no trace: the checks before the creation loop catch every
/// refusal the loop's own commands could hit, and `Session::execute` restores the document, the
/// selection and the undo stack on any error, so no half-made components can survive.
#[test]
fn a_failing_create_set_leaves_no_components_behind() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B"], false);
let (before, undo, selection) = (snapshot(&s), undo_len(&s), s.selection());
let e = s.execute("component.createSet", &json!({"ids": [frames[0], NodeId(u64::MAX)]}));
assert!(e.is_err());
assert_eq!(undo_len(&s), undo);
assert_eq!(snapshot(&s), before);
assert_eq!(s.selection(), selection);
}
+64
View File
@@ -106,3 +106,67 @@ fn other_content_is_refused_without_changes() {
assert_eq!(s.doc().unwrap().nodes().count(), before);
assert!(s.clipboard.nodes.is_empty());
}
// The next three pin the paste-placement rules measured in Figma's web app on 2026-11-08 (a
// synthetic file): in place when the original is in view, at the view's centre when it is off
// screen, and in a selected frame's centre when the frame is elsewhere. The fourth pins
// FigCraft's own branch for a selected frame that contains the original (in place inside it),
// which was not measured.
fn copied_rect(s: &mut Session) -> NodeId {
let r = id(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap());
s.execute("edit.copy", &json!({"ids": [r]})).unwrap();
r
}
fn pasted(s: &mut Session) -> NodeId {
let r = s.execute("edit.paste", &json!({})).unwrap();
params::id_of(&r["ids"][0]).unwrap()
}
#[test]
fn paste_with_the_original_in_view_lands_in_place_above_it() {
let mut s = Session::new();
let page = s.page().unwrap();
let r = copied_rect(&mut s);
s.execute("view.set", &json!({"zoom": 1, "cx": 125, "cy": 125})).unwrap();
let c = pasted(&mut s);
let b = s.doc().unwrap().world_bounds(c).unwrap();
assert_eq!((b.x0, b.y0), (100.0, 100.0));
assert_eq!(s.selection(), [c]);
assert_eq!(s.doc().unwrap().node(page).unwrap().children, [r, c]);
}
#[test]
fn paste_with_the_original_off_screen_lands_at_the_view_centre() {
let mut s = Session::new();
copied_rect(&mut s);
s.execute("view.set", &json!({"zoom": 1, "cx": 5000, "cy": 3000})).unwrap();
let c = pasted(&mut s);
let b = s.doc().unwrap().world_bounds(c).unwrap();
assert_eq!((b.center().x, b.center().y), (5000.0, 3000.0));
}
#[test]
fn paste_into_a_selected_far_frame_lands_at_its_centre() {
let mut s = Session::new();
copied_rect(&mut s);
let f = id(&s.execute("frame.create", &json!({"x": 2000, "y": 1000, "width": 300, "height": 300})).unwrap());
s.execute("select.set", &json!({"ids": [f]})).unwrap();
let c = pasted(&mut s);
assert_eq!(s.doc().unwrap().node(c).unwrap().parent, Some(f));
let b = s.doc().unwrap().world_bounds(c).unwrap();
assert_eq!((b.center().x, b.center().y), (2150.0, 1150.0));
}
#[test]
fn paste_into_a_selected_frame_holding_the_original_keeps_its_place() {
let mut s = Session::new();
copied_rect(&mut s);
let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 500, "height": 500})).unwrap());
s.execute("select.set", &json!({"ids": [f]})).unwrap();
let c = pasted(&mut s);
assert_eq!(s.doc().unwrap().node(c).unwrap().parent, Some(f));
let b = s.doc().unwrap().world_bounds(c).unwrap();
assert_eq!((b.x0, b.y0), (100.0, 100.0));
}
+45 -3
View File
@@ -41,6 +41,8 @@ const FIELD: &str = "figcraft.widget.field";
const HOVER: &str = "figcraft.widget.hover";
/// Images in a widget are at most this many pixels on a side.
const MAX_IMAGE_SIDE: u32 = 4096;
/// All images of one widget together are at most this many pixels once decoded (four of the largest).
const MAX_IMAGES_PIXELS: u64 = 4 * 4096 * 4096;
/// Whether `n` is a widget's own layer.
pub fn is_widget(n: &Node) -> bool {
@@ -259,8 +261,9 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<(
_ => n.plugin_data.remove(MENU),
};
set_hover(n, r.root.hover.as_ref());
let mut pixels = 0;
for c in &r.root.children {
add(doc, w, c, cmd)?;
add(doc, w, c, cmd, &mut pixels)?;
}
// An SVG brings as many layers as it describes.
if doc.subtree(w).len() > MAX_NODES {
@@ -271,7 +274,7 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<(
}
/// Add layer `d` (and what it holds) inside `parent`, locked.
fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<()> {
fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str, pixels: &mut u64) -> Result<()> {
let (kind, name) = match d.kind {
WidgetKind::Frame => (NodeKind::Frame, "Frame"),
WidgetKind::Text => (NodeKind::Text(TextData { characters: d.text.clone(), ..TextData::default() }), "Text"),
@@ -292,6 +295,16 @@ fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<
if bytes.len() > MAX_IMAGE_BYTES {
return Err(bad(cmd, format!("an image is larger than {} KB", MAX_IMAGE_BYTES / 1024)));
}
// From the header, before anything is decoded: a small file can hold billions of pixels.
if let Some((w, h)) = figcraft_render::images::dimensions(&bytes) {
if w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE {
return Err(bad(cmd, format!("an image is larger than {MAX_IMAGE_SIDE} pixels on a side")));
}
*pixels += u64::from(w) * u64::from(h);
if *pixels > MAX_IMAGES_PIXELS {
return Err(bad(cmd, format!("the images are larger than {MAX_IMAGES_PIXELS} pixels together")));
}
}
let (hash, iw, ih) = crate::cmd::create::add_readable_image(doc, bytes).map_err(|e| bad(cmd, e))?;
if iw > MAX_IMAGE_SIDE || ih > MAX_IMAGE_SIDE {
return Err(bad(cmd, format!("an image is larger than {MAX_IMAGE_SIDE} pixels on a side")));
@@ -302,7 +315,7 @@ fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str) -> Result<
}
doc.insert(n, parent, None)?;
crate::cmd::props::apply(cmd, doc, id, &props(d, false))?;
d.children.iter().try_for_each(|c| add(doc, id, c, cmd))
d.children.iter().try_for_each(|c| add(doc, id, c, cmd, pixels))
}
/// Add SVG layer `d` inside `parent`: a frame of the picture's own size holding its layers, locked
@@ -604,3 +617,32 @@ pub fn specs() -> Vec<CommandSpec> {
spec!("widget.list", "List widgets", "{} → {widgets: [{id, plugin, name, page, state, targets, fields, menu}]}", false, list),
]
}
#[cfg(test)]
mod pixel_budget_tests {
use super::*;
use base64::Engine as _;
/// A `side` x `side` blank PNG (a few KB however many pixels).
fn png(side: u32) -> String {
let pix = figcraft_render::Pixmap::new(side, side).unwrap();
base64::engine::general_purpose::STANDARD.encode(figcraft_render::encode_png(&pix).unwrap())
}
#[test]
fn images_of_a_widget_share_a_decoded_pixel_budget() {
let mut doc = Document::new("t");
let page = doc.first_page().unwrap();
let data = png(4096);
let image = |i: usize| serde_json::from_value::<WidgetNode>(json!({"type": "image", "name": format!("I{i}"), "data": data})).unwrap();
let mut pixels = 0;
for i in 0..4 {
add(&mut doc, page, &image(i), "widget.insert", &mut pixels).unwrap();
}
let err = add(&mut doc, page, &image(4), "widget.insert", &mut pixels).unwrap_err().to_string();
assert!(err.contains("together"), "{err}");
// A header past the side limit is refused before it is decoded.
let wide = serde_json::from_value::<WidgetNode>(json!({"type": "image", "data": png(4097)})).unwrap();
assert!(add(&mut doc, page, &wide, "widget.insert", &mut 0).unwrap_err().to_string().contains("pixels on a side"));
}
}
+2
View File
@@ -423,6 +423,8 @@ mod live_tests;
#[cfg(test)]
mod lock_behaviour_tests;
#[cfg(test)]
mod marquee_behaviour_tests;
#[cfg(test)]
mod mask_tests;
#[cfg(test)]
mod masks_behaviour_tests;
@@ -0,0 +1,218 @@
//! Marquee selection, as measured in Figma's web app (2026-11-11, the "marquee rules" and "confirming
//! pass" readings, and the two evening re-measures) and described in the help-center article "Select layers and objects": a drag
//! selects each top-level layer it touches; a partly covered frame or section gives the layers in it
//! the marquee touches, an enclosed one is selected itself; a drag started inside a frame selects that frame
//! only when the marquee also takes another top-level frame (then whole); selecting a frame whole keeps the marquee at the top level; a rotated shape is touched by
//! its outline, an unrotated one by its box.
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind};
use figcraft_doc::NodeId;
use figcraft_geom::Point;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, parent: Option<NodeId>) -> NodeId {
let mut p = json!({"x": x, "y": y, "width": w, "height": h});
if let Some(parent) = parent {
p["parent"] = json!(parent);
}
id(&ex(s, "shape.rectangle", p))
}
fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent {
PointerEvent::at(kind, x, y, 1.0)
}
fn drag(s: &mut Session, a: (f64, f64), b: (f64, f64)) {
s.pointer(&ev(PointerKind::Down, a.0, a.1)).unwrap();
s.pointer(&ev(PointerKind::Move, b.0, b.1)).unwrap();
s.pointer(&ev(PointerKind::Up, b.0, b.1)).unwrap();
}
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
#[allow(dead_code)]
struct Scene {
f1: NodeId,
r1: NodeId,
r2: NodeId,
e: NodeId,
u: NodeId,
rr: NodeId,
re: NodeId,
f2: NodeId,
g: NodeId,
s: NodeId,
r5: NodeId,
}
/// The confirming pass's layout: `f1` (0,0 300x200) holding `r1` (20,20) and `r2` (220,120), both 60x60;
/// ellipse `e` (500,0 200x200); rectangle `u` (900,0 100x100); `rr` rectangle (0,400 200x100) and ellipse
/// `re` (500,400 200x100) turned 45 degrees about their centres; the empty frame `f2` (0,700 200x150);
/// the group `g` of two rectangles (300,700) and (360,760); the section `s` (600,700 300x200) holding `r5`.
fn scene(s: &mut Session) -> Scene {
let f1 = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 200})));
let r1 = rect(s, 20.0, 20.0, 60.0, 60.0, Some(f1));
let r2 = rect(s, 220.0, 120.0, 60.0, 60.0, Some(f1));
let e = id(&ex(s, "shape.ellipse", json!({"x": 500, "y": 0, "width": 200, "height": 200})));
let u = rect(s, 900.0, 0.0, 100.0, 100.0, None);
let rr = rect(s, 0.0, 400.0, 200.0, 100.0, None);
ex(s, "node.set", json!({"id": rr, "props": {"rotation": 45}}));
let re = id(&ex(s, "shape.ellipse", json!({"x": 500, "y": 400, "width": 200, "height": 100})));
ex(s, "node.set", json!({"id": re, "props": {"rotation": 45}}));
let f2 = id(&ex(s, "frame.create", json!({"x": 0, "y": 700, "width": 200, "height": 150})));
let g1 = rect(s, 300.0, 700.0, 80.0, 80.0, None);
let g2 = rect(s, 360.0, 760.0, 80.0, 80.0, None);
let g = id(&ex(s, "object.group", json!({"ids": [g1, g2]})));
let sec = id(&ex(s, "node.create", json!({"type": "section", "x": 600, "y": 700, "width": 300, "height": 200})));
let r5 = rect(s, 20.0, 20.0, 60.0, 60.0, Some(sec));
ex(s, "select.none", json!({}));
Scene { f1, r1, r2, e, u, rr, re, f2, g, s: sec, r5 }
}
fn selected(s: &mut Session, a: (f64, f64), b: (f64, f64)) -> Vec<NodeId> {
ex(s, "select.none", json!({}));
drag(s, a, b);
let sel = sorted(s.selection());
ex(s, "select.none", json!({}));
sel
}
#[test]
fn a_partly_covered_frame_gives_the_layers_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (-50.0, -50.0), (60.0, 60.0)), vec![k.r1], "measured case 2: Rectangle 1, not F1");
}
#[test]
fn an_enclosed_frame_is_selected_itself() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (-20.0, -20.0), (320.0, 220.0)), vec![k.f1], "measured b");
}
#[test]
fn an_empty_frame_is_selected_on_touch() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (-20.0, 680.0), (50.0, 720.0)), vec![k.f2], "measured c: Frame 2");
}
#[test]
fn a_group_is_selected_whole_on_touch() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (290.0, 690.0), (310.0, 710.0)), vec![k.g], "measured c: Group 1, not the rectangle");
}
#[test]
fn a_partly_covered_section_gives_the_layers_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (590.0, 690.0), (650.0, 750.0)), vec![k.r5], "measured c: Rectangle 5, not the section");
}
#[test]
fn an_unrotated_shape_is_touched_by_its_box() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (490.0, -10.0), (505.0, 5.0)), vec![k.e], "measured case 3: the ellipse's box corner selects it");
assert_eq!(selected(&mut s, (890.0, -10.0), (905.0, 5.0)), vec![k.u], "control");
}
#[test]
fn a_rotated_rectangle_is_touched_by_its_outline() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (-30.0, 320.0), (4.0, 354.0)), Vec::<NodeId>::new(), "measured case 3: the box corner selects nothing");
assert_eq!(selected(&mut s, (-30.0, 320.0), (100.0, 450.0)), vec![k.rr]);
}
#[test]
fn a_rotated_ellipse_is_not_touched_by_its_axis_aligned_box() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(selected(&mut s, (470.0, 320.0), (504.0, 354.0)), Vec::<NodeId>::new(), "measured case 3: the box corner selects nothing");
assert_eq!(selected(&mut s, (470.0, 320.0), (600.0, 450.0)), vec![k.re]);
}
#[test]
fn a_rotated_ellipse_is_not_touched_through_the_corner_of_its_turned_box() {
let mut s = Session::new();
let k = scene(&mut s);
// The re-measure's literal marquees (evening, section 1): corner A, the deeper B, and the control.
let p = Point::new(692.0, 419.0);
let doc = s.doc().unwrap();
let n = doc.node(k.re).unwrap();
assert!(n.local_rect().contains(doc.world_transform(k.re).inverse() * p), "the probe is inside the turned box");
assert_eq!(selected(&mut s, (715.0, 411.0), (692.0, 419.0)), Vec::<NodeId>::new(), "measured marquee A");
assert_eq!(selected(&mut s, (715.0, 411.0), (683.0, 419.0)), Vec::<NodeId>::new(), "measured marquee B");
assert_eq!(selected(&mut s, (715.0, 411.0), (667.0, 419.0)), vec![k.re], "measured control");
}
#[test]
fn a_drag_from_inside_a_frame_selects_only_what_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
let start_x = |s: &Session| s.doc().unwrap().world_bounds(k.f1).map(|b| (b.x0, b.y0));
assert_eq!(selected(&mut s, (150.0, 100.0), (180.0, 150.0)), Vec::<NodeId>::new(), "measured e1");
assert_eq!(start_x(&s), Some((0.0, 0.0)));
assert_eq!(selected(&mut s, (150.0, 100.0), (180.0, 250.0)), Vec::<NodeId>::new(), "measured e2");
assert_eq!(start_x(&s), Some((0.0, 0.0)));
assert_eq!(selected(&mut s, (150.0, 100.0), (600.0, 100.0)), vec![k.e], "measured e3: the ellipse only");
assert_eq!(start_x(&s), Some((0.0, 0.0)));
assert_eq!(selected(&mut s, (150.0, 100.0), (250.0, 150.0)), vec![k.r2], "today's rule, not measured");
assert_eq!(start_x(&s), Some((0.0, 0.0)));
}
#[test]
fn selecting_a_frame_whole_keeps_the_marquee_at_the_top_level() {
let mut s = Session::new();
let k = scene(&mut s);
// Encloses the empty f2, covers rr, and partly covers f1 over r1: no frame opens, f1 comes whole.
assert_eq!(
selected(&mut s, (-20.0, 50.0), (210.0, 860.0)),
sorted(vec![k.f2, k.f1, k.rr]),
"the article: selecting a top-level frame selects only top-level layers; measured: a partly covered frame comes whole"
);
}
#[test]
fn a_marquee_enclosing_an_empty_frame_takes_a_partly_covered_frame_whole() {
let mut s = Session::new();
let f1 = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 200})));
let _r1 = rect(&mut s, 20.0, 20.0, 60.0, 60.0, Some(f1));
let f2 = id(&ex(&mut s, "frame.create", json!({"x": 400, "y": 0, "width": 200, "height": 150})));
assert_eq!(selected(&mut s, (650.0, 170.0), (40.0, -10.0)), sorted(vec![f1, f2]), "measured re-measure: F2 and F1, not R1");
}
#[test]
fn a_drag_from_inside_a_frame_takes_it_whole_when_it_takes_another_top_level_frame() {
let mut s = Session::new();
let f1 = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 200})));
let r1 = rect(&mut s, 20.0, 20.0, 60.0, 60.0, Some(f1));
let _r2 = rect(&mut s, 220.0, 120.0, 60.0, 60.0, Some(f1));
let f2 = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 400, "width": 200, "height": 150})));
let rr = rect(&mut s, 400.0, 400.0, 200.0, 100.0, None);
ex(&mut s, "select.none", json!({}));
assert_eq!(selected(&mut s, (150.0, 100.0), (90.0, 720.0)), sorted(vec![f1, f2]), "re-measure 2, case 1");
let sel = selected(&mut s, (150.0, 50.0), (50.0, 720.0));
assert_eq!(sel, sorted(vec![f1, f2]), "re-measure 2, case 2b: R1 is covered in part and still not selected");
assert!(!sel.contains(&r1));
assert_eq!(selected(&mut s, (150.0, 100.0), (450.0, 450.0)), sorted(vec![f1, f2, rr]), "re-measure 2, case 3");
assert_eq!(selected(&mut s, (290.0, 100.0), (450.0, 450.0)), vec![rr], "re-measure 2, case 3b: the frame only when another is taken");
}
+17
View File
@@ -84,3 +84,20 @@ fn outlined_layers_draw_as_outlines_and_the_rest_normally() {
assert_eq!(outlined.pixel(20, 20).unwrap(), empty, "only its outline");
assert_eq!(outlined.pixel(80, 20).unwrap(), plain.pixel(80, 20).unwrap(), "the other layer draws normally");
}
#[test]
fn open_recent_rejects_negative_and_fractional_index() {
let dir = std::env::temp_dir().join(format!("figcraft-recent-bad-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let a = dir.join("a.figcraft").to_string_lossy().to_string();
let b = dir.join("b.figcraft").to_string_lossy().to_string();
let mut s = Session::new();
s.execute("file.save", &json!({"path": a})).unwrap();
s.execute("file.saveAs", &json!({"path": b})).unwrap();
let recent = s.prefs.recent_files.clone();
for i in [json!(-1), json!(1.5), json!(-0.5)] {
assert!(s.execute("file.openRecent", &json!({"index": i})).is_err(), "index {i} must be an error");
}
assert_eq!(s.prefs.recent_files, recent);
let _ = std::fs::remove_dir_all(&dir);
}
+10
View File
@@ -135,6 +135,16 @@ fn image_adjust_refuses_what_it_cannot_do() {
assert_eq!(s.execute("image.adjust", &json!({"ids": [plain, r], "index": 1, "preset": "vivid"})).unwrap()["changed"], 1);
}
#[test]
fn save_preset_rejects_bad_index() {
let mut s = Session::new();
let r = image_rect(&mut s);
assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 0})).is_err());
assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": -1})).is_err(), "negative index accepted");
assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 1.5})).is_err(), "fractional index accepted");
assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 1})).is_ok());
}
#[test]
fn saved_image_presets() {
let mut s = Session::new();
+26 -1
View File
@@ -77,8 +77,9 @@ fn every_kind_of_property_keeps_its_place_on_rename() {
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon_f]})));
let nested = idv(&ex(&mut s, "instance.create", json!({"component": icon, "x": 60, "y": 10, "parent": f})));
let small = idv(&ex(&mut s, "component.create", json!({"ids": [f]})));
let zoom_layer = idv(&ex(&mut s, "shape.rectangle", json!({"x": 150, "y": 10, "width": 10, "height": 10, "parent": small})));
// Made in an order that isn't by name: Zoom (boolean), Label (text), Glyph (instance swap), Body (slot).
ex(&mut s, "component.addProperty", json!({"id": small, "name": "Zoom", "type": "boolean"}));
ex(&mut s, "component.addProperty", json!({"id": small, "name": "Zoom", "type": "boolean", "layer": zoom_layer}));
ex(&mut s, "component.addProperty", json!({"id": small, "name": "Label", "type": "text", "layer": label}));
ex(&mut s, "component.addProperty", json!({"id": small, "name": "Glyph", "type": "instanceSwap", "layer": nested}));
ex(&mut s, "component.makeSlot", json!({"id": body}));
@@ -133,3 +134,27 @@ fn make_slot_takes_the_name_typed() {
by_name.sort();
assert_eq!(listed, by_name);
}
/// An instance lists the properties its own variant's layers use (#2022): in Figma's data a set
/// has one text property per variant (and leftovers of deleted ones), measured: an instance of
/// variant A lists `State` and `A label`, never `B label` or a property no layer reads.
#[test]
fn an_instance_lists_only_the_properties_its_variant_uses() {
let mut s = Session::new();
let mut variants = Vec::new();
let mut texts = Vec::new();
for (k, name) in ["Type=Flag, State=Default", "Type=Flag, State=Selected"].iter().enumerate() {
let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": k * 60, "width": 120, "height": 40, "name": name})));
texts.push(idv(&ex(&mut s, "text.create", json!({"text": "Label", "x": 4, "y": 4, "parent": f, "name": "Label"}))));
variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [f]}))));
}
let set = idv(&ex(&mut s, "component.combineVariants", json!({"ids": variants})));
ex(&mut s, "component.addProperty", json!({"id": set, "name": "Default label", "type": "text", "layer": texts[0]}));
ex(&mut s, "component.addProperty", json!({"id": set, "name": "Selected label", "type": "text", "layer": texts[1]}));
ex(&mut s, "component.addProperty", json!({"id": set, "name": "Gone label", "type": "text"}));
assert_eq!(names(&mut s, set), ["Type", "State", "Default label", "Selected label", "Gone label"], "the set keeps every definition");
let inst = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 400, "y": 0})));
assert_eq!(names(&mut s, inst), ["Type", "State", "Default label"]);
ex(&mut s, "instance.setProperties", json!({"ids": [inst], "properties": {"State": "Selected"}}));
assert_eq!(names(&mut s, inst), ["Type", "State", "Selected label"]);
}
+4 -4
View File
@@ -1,6 +1,6 @@
//! `select.area`: what a marquee over a box selects, without a pointer (keyboard box selection in
//! the app, agents over MCP): top-level layers, a frame only when fully covered, the children of
//! the frame the box starts in, Shift-like toggling, Cmd/Ctrl-like nested layers; no box asks the
//! the app, agents over MCP): top-level layers, a frame only when fully covered (otherwise the
//! layers in it the box touches), the children of the frame the box starts in, Shift-like toggling, Cmd/Ctrl-like nested layers; no box asks the
//! app to draw one.
use serde_json::{Value, json};
@@ -40,8 +40,8 @@ fn a_box_selects_like_a_marquee() {
let inner = rect(&mut s, 20.0, 20.0, Some(frame));
let a = rect(&mut s, 0.0, 0.0, None);
let b = rect(&mut s, 100.0, 0.0, None);
// Top-level layers it touches; a frame only touched from outside isn't selected.
assert_eq!(area(&mut s, -10.0, -10.0, 340.0, 40.0, json!({})), sorted(vec![a, b]));
// Top-level layers it touches; a frame only touched from outside gives the layers in it the box touches.
assert_eq!(area(&mut s, -10.0, -10.0, 340.0, 40.0, json!({})), sorted(vec![a, b, inner]));
// A negative size draws the box the other way.
assert_eq!(area(&mut s, 130.0, 30.0, -140.0, -40.0, json!({})), sorted(vec![a, b]));
// Covering the frame selects it.
@@ -214,8 +214,8 @@ fn marquee_selects_what_it_touches() {
(450.0, 40.0),
NONE,
vec![],
vec![],
"from the canvas, a top-level frame is selected only when the marquee covers all of it",
vec![k.g, k.n],
"from the canvas, a partly covered top-level frame gives the layers in it the marquee touches (measured); the nested frame comes whole",
),
((-10.0, -10.0), (450.0, 310.0), NONE, vec![], vec![k.f], "a marquee covering a top-level frame selects the frame"),
(
+4 -4
View File
@@ -66,10 +66,10 @@ fn cmd_click_selects_the_nested_layer() {
#[test]
fn cmd_marquee_selects_nested_layers() {
let mut s = Session::new();
let (f, _, [a, b, c], out) = scene(&mut s);
// From empty canvas, a plain marquee across the frame only touches top-level layers (and the
// frame isn't fully covered).
assert_eq!(marquee(&mut s, (-10.0, 10.0), (500.0, 70.0), false, false), vec![out]);
let (f, g, [a, b, c], out) = scene(&mut s);
// From empty canvas, a plain marquee across the frame (not fully covered) gives the layers in it
// it touches (the group whole), plus the top-level layer.
assert_eq!(sorted(marquee(&mut s, (-10.0, 10.0), (500.0, 70.0), false, false)), sorted(vec![g, out]));
// Cmd/Ctrl: the innermost layers it touches, through the frame and the group.
assert_eq!(sorted(marquee(&mut s, (-10.0, 10.0), (500.0, 70.0), false, true)), sorted(vec![a, b, out]));
assert_eq!(sorted(marquee(&mut s, (-10.0, 10.0), (100.0, 190.0), false, true)), sorted(vec![a, b, c]));
+264
View File
@@ -376,6 +376,270 @@ fn slots_of_nested_instances_fill_from_the_outer_main_and_its_instances() {
assert_eq!(fill(&s, *kids(&s, nslot).first().unwrap()), "CCCCCC", "content no longer follows the Card main");
}
/// Wrap a component instance in another main, keeping the nested instance addressable.
fn slot_text_wrapper(s: &mut Session, component: NodeId, name: &str) -> (NodeId, NodeId) {
let frame = idv(&ex(s, "frame.create", json!({"width": 300, "height": 200, "name": name})));
let nested = idv(&ex(s, "instance.create", json!({"component": component, "parent": frame})));
(idv(&ex(s, "component.create", json!({"ids": [frame]}))), nested)
}
/// Content.Label binds Text; Composition holds Base, whose Body uses default or own Content.
/// Returns (Content main, Label, Base main, Composition main, nested Content instance).
fn slot_text_composition(s: &mut Session, own: bool) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
let frame = idv(&ex(s, "frame.create", json!({"width": 100, "height": 40, "name": "Content"})));
let label = idv(&ex(s, "text.create", json!({"text": "Default", "parent": frame, "props": {"name": "Label"}})));
let content = idv(&ex(s, "component.create", json!({"ids": [frame]})));
ex(s, "component.addProperty", json!({"id": content, "name": "Text", "type": "text", "default": "Default", "layer": label}));
let frame = idv(&ex(s, "frame.create", json!({"width": 200, "height": 100, "name": "Base"})));
let body = idv(&ex(s, "frame.create", json!({"width": 180, "height": 80, "name": "Body", "parent": frame})));
let default = (!own).then(|| idv(&ex(s, "instance.create", json!({"component": content, "parent": body}))));
let base = idv(&ex(s, "component.create", json!({"ids": [frame]})));
ex(s, "component.makeSlot", json!({"id": body}));
let (composition, nested_base) = slot_text_wrapper(s, base, "Composition");
let nested_content = if let Some(default) = default {
copy_of(s, nested_base, default)
} else {
idv(&ex(s, "instance.slotInsert", json!({"id": nested_base, "slot": "Body", "component": content})))
};
(content, label, base, composition, nested_content)
}
fn assert_slot_text(s: &mut Session, instance: NodeId, expected: &str) {
let children = kids(s, instance);
assert_eq!(children.len(), 1, "Content {instance} must have exactly one Label");
let label = children[0];
assert_eq!(node(s, label).name, "Label");
let characters = node(s, label).kind.text().expect("Content's only child must be text").characters.clone();
let html = ex(s, "inspect.code", json!({"id": instance, "language": "html"}))["code"].as_str().unwrap().to_string();
assert_eq!(characters, expected, "slot Label characters; HTML: {html}");
assert_eq!(html.matches("<p ").count(), 1, "slot Label HTML must contain exactly one paragraph: {html}");
assert_eq!(html.matches("</p>").count(), 1, "slot Label HTML must contain exactly one paragraph: {html}");
assert!(html.contains(&format!(">{expected}</p>")), "slot Label HTML: {html}");
}
fn assert_stored_slot_text(s: &Session, instance: NodeId, expected: &str) {
assert!(
matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Text") == Some(&json!(expected))),
"instance {instance} must store its own Text value {expected:?}: {:?}",
node(s, instance).kind
);
}
fn assert_local_slot_text(s: &mut Session, instance: NodeId, expected: &str) {
assert_stored_slot_text(s, instance, expected);
let properties = props_of(s, instance);
let text = properties.iter().find(|p| p["name"] == "Text").unwrap_or_else(|| panic!("instance {instance} has no Text property: {properties:?}"));
assert_eq!(text["value"], expected, "instance {instance} Text property");
}
/// Exercise the same ownership contract for default slot content and content supplied by the
/// Composition main; separate tests identify which route regresses.
fn check_slot_text_properties_stay_local(own: bool) {
let mut s = Session::new();
let (content, label, _base, composition, main_content) = slot_text_composition(&mut s, own);
let a = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
let b = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 800})));
let ac = copy_of(&s, a, main_content);
let bc = copy_of(&s, b, main_content);
ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
assert_local_slot_text(&mut s, ac, "Custom");
assert_slot_text(&mut s, ac, "Custom");
assert_local_slot_text(&mut s, bc, "Default");
assert_slot_text(&mut s, bc, "Default");
assert_local_slot_text(&mut s, main_content, "Default");
assert_slot_text(&mut s, main_content, "Default");
assert_eq!(node(&s, label).kind.text().unwrap().characters, "Default");
// Main property edits propagate without replacing another instance's local value.
ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
assert_slot_text(&mut s, ac, "Custom");
assert_slot_text(&mut s, bc, "Main value");
assert_slot_text(&mut s, main_content, "Main value");
ex(&mut s, "component.editProperty", json!({"id": content, "name": "Text", "default": "New default"}));
assert_slot_text(&mut s, ac, "Custom");
assert_slot_text(&mut s, bc, "Main value");
assert_local_slot_text(&mut s, main_content, "Main value");
assert_slot_text(&mut s, main_content, "Main value");
healthy(&s);
}
#[test]
fn slot_text_properties_stay_local_in_default_content() {
check_slot_text_properties_stay_local(false);
}
#[test]
fn slot_text_properties_stay_local_in_own_content() {
check_slot_text_properties_stay_local(true);
}
#[test]
fn slot_text_properties_do_not_read_an_unbound_base_property() {
let mut s = Session::new();
let (_content, _label, base, composition, main_content) = slot_text_composition(&mut s, true);
ex(&mut s, "component.addProperty", json!({"id": base, "name": "Text", "type": "text", "default": "Wrong owner"}));
let i = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
let nested_base = kids(&s, i)[0];
// Bound to no layer, the base's Text isn't listed on its instance (#2269); its value stays stored.
assert_stored_slot_text(&s, nested_base, "Wrong owner");
let nested = copy_of(&s, i, main_content);
assert_local_slot_text(&mut s, nested, "Default");
assert_slot_text(&mut s, nested, "Default");
ex(&mut s, "instance.setProperties", json!({"ids": [nested], "properties": {"Text": "Custom"}}));
assert_local_slot_text(&mut s, nested, "Custom");
assert_slot_text(&mut s, nested, "Custom");
assert_stored_slot_text(&s, nested_base, "Wrong owner");
assert_slot_text(&mut s, main_content, "Default");
healthy(&s);
}
#[test]
fn slot_text_properties_survive_inherited_own_content_and_persistence() {
let mut s = Session::new();
let (_content, _label, _base, composition, main_content) = slot_text_composition(&mut s, true);
let (outer, inherited) = slot_text_wrapper(&mut s, composition, "Outer composition");
let inherited_content = copy_of(&s, inherited, main_content);
let a = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 400})));
let b = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 800})));
let ac = copy_of(&s, a, inherited_content);
let bc = copy_of(&s, b, inherited_content);
ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
assert_local_slot_text(&mut s, ac, "Custom");
assert_local_slot_text(&mut s, bc, "Default");
assert_local_slot_text(&mut s, inherited_content, "Default");
assert_local_slot_text(&mut s, main_content, "Default");
let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
let mut s = Session::with_document(back);
assert_local_slot_text(&mut s, ac, "Custom");
assert_slot_text(&mut s, ac, "Custom");
assert_slot_text(&mut s, bc, "Default");
assert_slot_text(&mut s, inherited_content, "Default");
assert_slot_text(&mut s, main_content, "Default");
// Explicit characters override the bound property, even after a main update.
let alabel = kids(&s, ac)[0];
ex(&mut s, "text.set", json!({"id": alabel, "characters": "Explicit"}));
ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Later"}}));
ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
assert_local_slot_text(&mut s, ac, "Later");
assert_slot_text(&mut s, ac, "Explicit");
assert_slot_text(&mut s, bc, "Main value");
ex(&mut s, "component.resetOverride", json!({"id": alabel, "group": "characters"}));
assert_slot_text(&mut s, ac, "Later");
s.undo().unwrap();
assert_slot_text(&mut s, ac, "Explicit");
healthy(&s);
}
/// Check both the stored property and the Label it drives, not just one representation.
fn assert_slot_visibility(s: &mut Session, instance: NodeId, expected: bool) {
assert!(
matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Visible") == Some(&json!(expected))),
"instance {instance} must store Visible={expected}: {:?}",
node(s, instance).kind
);
let properties = props_of(s, instance);
let visible =
properties.iter().find(|p| p["name"] == "Visible").unwrap_or_else(|| panic!("instance {instance} has no Visible property: {properties:?}"));
assert_eq!(visible["value"], expected, "instance {instance} Visible property");
let children = kids(s, instance);
assert_eq!(children.len(), 1, "Content {instance} must have exactly one Label");
assert_eq!(node(s, children[0]).name, "Label");
assert_eq!(node(s, children[0]).visible, expected, "instance {instance} Label visibility");
}
#[test]
fn slot_boolean_properties_stay_local_in_inherited_own_content() {
let mut s = Session::new();
let (content, label, base, composition, main_content) = slot_text_composition(&mut s, true);
ex(&mut s, "component.addProperty", json!({"id": content, "name": "Visible", "type": "boolean", "default": true, "layer": label}));
ex(&mut s, "component.addProperty", json!({"id": base, "name": "Visible", "type": "boolean", "default": false}));
let (outer, inherited) = slot_text_wrapper(&mut s, composition, "Outer composition");
let inherited_base = kids(&s, inherited)[0];
let inherited_content = copy_of(&s, inherited, main_content);
let a = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 400})));
let b = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 800})));
let ac = copy_of(&s, a, inherited_content);
let bc = copy_of(&s, b, inherited_content);
let abase = copy_of(&s, a, inherited_base);
assert!(matches!(&node(&s, abase).kind, NodeKind::Instance { props, .. } if props.get("Visible") == Some(&json!(false))));
assert_slot_visibility(&mut s, ac, true);
assert_slot_visibility(&mut s, bc, true);
ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Visible": false}}));
assert_slot_visibility(&mut s, ac, false);
assert_slot_visibility(&mut s, bc, true);
assert_slot_visibility(&mut s, inherited_content, true);
assert_slot_visibility(&mut s, main_content, true);
// A main update must not replace either instance's local value with the Base's homonym.
ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Visible": false}}));
assert_slot_visibility(&mut s, ac, false);
assert_slot_visibility(&mut s, bc, false);
ex(&mut s, "instance.setProperties", json!({"ids": [bc], "properties": {"Visible": true}}));
ex(&mut s, "node.set", json!({"id": content, "props": {"fill": "#abcdef"}}));
assert_slot_visibility(&mut s, ac, false);
assert_slot_visibility(&mut s, bc, true);
assert_slot_visibility(&mut s, main_content, false);
healthy(&s);
let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
let mut s = Session::with_document(back);
assert_slot_visibility(&mut s, ac, false);
assert_slot_visibility(&mut s, bc, true);
assert_slot_visibility(&mut s, inherited_content, false);
assert_slot_visibility(&mut s, main_content, false);
ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Visible": true}}));
assert_slot_visibility(&mut s, ac, false);
assert_slot_visibility(&mut s, bc, true);
assert_slot_visibility(&mut s, main_content, true);
healthy(&s);
}
#[test]
fn same_component_in_own_slot_keeps_independent_text_properties() {
let mut s = Session::new();
let frame = idv(&ex(&mut s, "frame.create", json!({"width": 200, "height": 100, "name": "Card"})));
let label = idv(&ex(&mut s, "text.create", json!({"text": "Default", "parent": frame, "props": {"name": "Label"}})));
let body = idv(&ex(&mut s, "frame.create", json!({"width": 180, "height": 60, "y": 40, "name": "Body", "parent": frame})));
let card = idv(&ex(&mut s, "component.create", json!({"ids": [frame]})));
ex(&mut s, "component.addProperty", json!({"id": card, "name": "Text", "type": "text", "default": "Default", "layer": label}));
ex(&mut s, "component.makeSlot", json!({"id": body}));
// Only page instance content holds another Card: the main never contains itself.
let outer = idv(&ex(&mut s, "instance.create", json!({"component": card, "x": 400})));
let inner = idv(&ex(&mut s, "instance.slotInsert", json!({"id": outer, "slot": "Body", "component": card})));
let check = |s: &mut Session, outer_text: &str, inner_text: &str| {
assert_local_slot_text(s, outer, outer_text);
assert_local_slot_text(s, inner, inner_text);
assert_eq!(node(s, copy_of(s, outer, label)).kind.text().unwrap().characters, outer_text);
assert_eq!(node(s, copy_of(s, inner, label)).kind.text().unwrap().characters, inner_text);
let outer_body = copy_of(s, outer, body);
assert!(slot_edited(s.doc().unwrap(), outer_body));
assert_eq!(kids(s, outer_body), vec![inner]);
assert!(kids(s, copy_of(s, inner, body)).is_empty());
assert!(kids(s, body).is_empty(), "the main's slot must remain empty");
healthy(s);
};
ex(&mut s, "instance.setProperties", json!({"ids": [outer], "properties": {"Text": "Outer"}}));
check(&mut s, "Outer", "Default");
ex(&mut s, "instance.setProperties", json!({"ids": [inner], "properties": {"Text": "Inner"}}));
check(&mut s, "Outer", "Inner");
ex(&mut s, "text.set", json!({"id": label, "characters": "New default"}));
ex(&mut s, "node.set", json!({"id": card, "props": {"fill": "#abcdef"}}));
check(&mut s, "Outer", "Inner");
assert_eq!(fill(&s, outer), "ABCDEF");
assert_eq!(fill(&s, inner), "ABCDEF");
ex(&mut s, "instance.setProperties", json!({"ids": [outer], "properties": {"Text": "Outer updated"}}));
check(&mut s, "Outer updated", "Inner");
ex(&mut s, "instance.setProperties", json!({"ids": [inner], "properties": {"Text": "Inner updated"}}));
check(&mut s, "Outer updated", "Inner updated");
let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
let mut s = Session::with_document(back);
check(&mut s, "Outer updated", "Inner updated");
ex(&mut s, "node.set", json!({"id": card, "props": {"fill": "#123456"}}));
check(&mut s, "Outer updated", "Inner updated");
assert_eq!(fill(&s, outer), "123456");
assert_eq!(fill(&s, inner), "123456");
}
/// Random slot edits, main edits and resets keep every instance mirroring its main.
#[test]
fn random_slot_edits_keep_instances_consistent() {
+111 -1
View File
@@ -84,7 +84,11 @@ fn typed_list_starts() {
("- ", "", B, "hyphen and space: bullets"),
("* ", "", B, "asterisk and space: bullets"),
("1. ", "", N, "one, full stop, space: numbers"),
("2. ", "2. ", P, "silent: only 1. starts a numbered list"),
("2. ", "", N, "as measured in Figma: a typed number starts the list there"),
("0. ", "0. ", P, "zero is not measured: text"),
("12a. ", "12a. ", P, "digits only: text"),
("1) ", "", N, "one and a closing bracket: numbers"),
("2) ", "2) ", P, "silent: only 1) starts with a bracket"),
("a- ", "a- ", P, "not at the paragraph's start: text"),
("-x ", "-x ", P, "the space must follow the marker"),
];
@@ -108,6 +112,76 @@ fn typed_list_starts() {
assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("Intro\n- ", vec![(P, 0), (B, 0)]), "an item's own text stays text");
}
#[test]
fn typed_number_starts_the_list_there() {
// As measured in Figma (2026-11-11): typing "5. x", Enter, "y" reads 5. then 6.; the start
// is the typed number less one, and the next item goes on counting from it.
let mut s = Session::new();
let t = text(&mut s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(&mut s, t, Some(0), false).unwrap();
for c in "5. x".chars() {
insert(&mut s, &c.to_string()).unwrap();
}
assert_eq!(data(&s, t).para_list(0).start_offset, 4, "5 starts at offset 4");
key(&mut s, "Enter", false, false, false).unwrap();
insert(&mut s, "y").unwrap();
crate::textedit::end(&mut s).unwrap();
let d = data(&s, t);
assert_eq!(d.characters, "x\ny");
assert_eq!(lists(&s, t), [(N, 0), (N, 0)]);
// An item made by Enter has no start of its own and goes on counting: 5. then 6.
assert_eq!((d.para_list(0).start_offset, d.para_list(1).start_offset), (4, 0), "the new item has no start");
s.undo().unwrap();
assert_eq!(data(&s, t).characters, "", "one undo step for the session");
assert_eq!(data(&s, t).para_list(0).start_offset, 0);
}
/// Type `first` ("5. a" style), then Enter, "b", Enter, "c", leaving the caret in "c".
fn three_typed_items(s: &mut Session, first: &str) -> NodeId {
let t = text(s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(s, t, Some(0), false).unwrap();
for c in first.chars() {
insert(s, &c.to_string()).unwrap();
}
for step in ["Enter", "b", "Enter", "c"] {
if step == "Enter" {
key(s, step, false, false, false).unwrap();
} else {
insert(s, step).unwrap();
}
}
t
}
#[test]
fn a_list_split_by_unlisting_a_middle_item_restarts_at_one() {
// As measured in Figma (2026-11-11): typed "5. a", Enter, "b", Enter, "c" reads 5. 6. 7.;
// Backspace at the start of "b" takes its marker and "c" then reads 1., for "1. " too.
// `list_markers` counts on after a numbered item and restarts a numbered item that follows a
// plain paragraph at its own start, so the starts and the neighbours give the markers.
for (first, start) in [("5. a", 4), ("1. a", 0)] {
let mut s = Session::new();
let t = three_typed_items(&mut s, first);
assert_eq!(
data(&s, t).characters,
"a
b
c"
);
// The guard: unsplit, "b" and "c" go on counting (5. 6. 7.).
let d = data(&s, t);
assert_eq!(lists(&s, t), [(N, 0); 3], "{first}: no split");
assert_eq!((d.para_list(0).start_offset, d.para_list(1).start_offset, d.para_list(2).start_offset), (start, 0, 0), "{first}");
set_caret(&mut s, 2, false).unwrap();
key(&mut s, "Backspace", false, false, false).unwrap();
let d = data(&s, t);
assert_eq!(lists(&s, t), [(N, 0), (P, 0), (N, 0)], "{first}: split");
assert_eq!(d.para_list(2).start_offset, 0, "{first}: c restarts at 1 (the item made by Enter has no start)");
}
}
#[test]
fn list_keys_at_list_items() {
// (chars, lists before, caret, key, shift, chars after, lists after, derivation)
@@ -372,3 +446,39 @@ fn typing_a_creation_character_and_a_space_starts_a_list() {
}
assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("2) ", vec![(P, 0)]));
}
#[test]
fn splitting_a_plain_paragraph_that_kept_its_level_keeps_the_level() {
// Backspace at a nested item's start unlists it but keeps indent 1; Enter inside it then
// splits it, and neither half loses the level (the start reset changes only starts).
let mut s = Session::new();
let t = text(&mut s, "ab\ncd");
let ps = vec![ParaList { list: N, start_offset: 4, ..ParaList::default() }, ParaList { list: N, indent: 1, ..ParaList::default() }];
if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind {
td.paragraphs = ps;
}
begin(&mut s, t, Some(3), false).unwrap();
key(&mut s, "Backspace", false, false, false).unwrap();
assert_eq!(lists(&s, t), [(N, 0), (P, 1)], "unlisted, level kept");
set_caret(&mut s, 4, false).unwrap();
key(&mut s, "Enter", false, false, false).unwrap();
assert_eq!(data(&s, t).characters, "ab\nc\nd");
assert_eq!(lists(&s, t), [(N, 0), (P, 1), (P, 1)], "both halves keep indent 1");
}
#[test]
fn a_many_line_paste_clears_every_created_start() {
let mut s = Session::new();
let t = text(&mut s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(&mut s, t, Some(0), false).unwrap();
for c in "5. x".chars() {
insert(&mut s, &c.to_string()).unwrap();
}
let lines: Vec<String> = (0..2001).map(|i| format!("l{i}")).collect();
insert(&mut s, &lines.join("\n")).unwrap();
let d = data(&s, t);
assert_eq!(d.paragraph_count(), 2001);
assert_eq!(d.para_list(0).start_offset, 4, "the first item keeps its start");
assert!((1..d.paragraph_count()).all(|p| d.para_list(p).start_offset == 0 && d.para_list(p).list == N));
}
@@ -326,6 +326,58 @@ fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) {
doc.get_mut(id).unwrap().kind = NodeKind::Vector { network };
}
/// How far `path` strays from `from`: the largest distance from a point sampled along `path` to
/// the nearest segment of `from`.
pub(crate) fn strays(path: &BezPath, from: &BezPath) -> f64 {
use figcraft_geom::kurbo::ParamCurveNearest;
let segs: Vec<_> = from.segments().collect();
path.segments()
.flat_map(|seg| (0..=32).map(move |i| seg.eval(f64::from(i) / 32.0)))
.map(|p| segs.iter().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt())
.fold(0.0, f64::max)
}
/// Simplify path keeps nearly collinear points, and a stroke that goes out and back, near where
/// they were: kurbo's fit, which Simplify path and the Pencil share, ran a handle hundreds of units
/// on along the line (#1741). That holds for each way the command simplifies a layer: an open
/// stroke, a filled shape, a region with its own fill, and a stroke beside a filled shape.
#[test]
fn simplify_keeps_nearly_collinear_points_near_them() {
// The points exactly as sampled.
let straight = "M209.5986907940155 -204.90932811973988 L211.27791426387097 -207.1909740207534 L214.24650682872084 -211.22882759062324";
let back =
"M80 -160 L86.04356571908697 -173.74440234910094 L87.85185073933535 -179.20284644595452 L86.04356571908697 -173.74440234910094 L95 -185";
let shape = format!("{straight} L260 -150 Z");
let cases = [
("an open stroke", straight.to_string(), false),
("a filled shape", shape.clone(), false),
("a region with its own fill", shape.clone(), true),
("a stroke beside a filled shape", format!("{shape} {back}"), false),
];
for (what, d, own_fill) in cases {
let mut s = Session::new();
let id = id_of(&ex(&mut s, "vector.create", json!({"path": "M0 0 L10 10"}))["id"]).unwrap();
// At the page origin, as given (`vector.create` would move the points).
let mut network = VectorNetwork::from_path(&BezPath::from_svg(&d).unwrap());
if own_fill {
network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::from_hex("#FF0000").unwrap())]);
}
{
let n = s.doc_mut().unwrap().get_mut(id).unwrap();
n.transform = figcraft_geom::Affine::IDENTITY;
n.kind = NodeKind::Vector { network };
}
let before = net(&s, id);
ex(&mut s, "vector.simplify", json!({"ids": [id], "tolerance": 0.75}));
let after = s.doc().unwrap().world_transform(id) * net(&s, id).stroke_path();
let gone = strays(&after, &before.stroke_path());
assert!(gone <= 1.5, "{what}: strays {gone}: {}", after.to_svg());
let (b0, b1) = (before.stroke_path().bounding_box(), after.bounding_box());
assert!(b0.inflate(1.5, 1.5).contains_rect(b1), "{what}: {b1:?} past {b0:?}: {}", after.to_svg());
assert_eq!(net(&s, id).regions.len(), before.regions.len(), "{what}: the fill is kept");
}
}
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
+3 -1
View File
@@ -207,7 +207,9 @@ impl<'d> Exporter<'d> {
.enumerate()
.map(|(i, v)| {
let mut st: Fields = Vec::new();
if v.radius > 0.0 {
// A point without a radius of its own is drawn with the layer's, so a sharp
// point on a rounded layer says so.
if v.radius > 0.0 || n.corners.radii[0] > 0.0 {
st.push(("cornerRadius", fl(v.radius)));
}
if let Some(m) = v.mirror {
+19
View File
@@ -955,6 +955,25 @@ fn closed_vector_geometry_is_written_with_its_corner_smoothing() {
assert_eq!(radii, vec![20.0, 0.0, 10.0, 0.0], "each point keeps its own radius");
}
#[test]
fn sharp_points_on_a_rounded_vector_stay_sharp() {
// A point without a radius takes the layer's when read, so a sharp point on a vector with a
// layer radius is written with its own zero.
let mut doc = Document::new("sharp point");
let page = doc.first_page().unwrap();
let mut network = VectorNetwork::from_points(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)), true);
for (v, r) in network.vertices.iter_mut().zip([8.0, 0.0, 8.0, 0.0]) {
v.radius = r;
}
let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id).unwrap().corners.radii = [8.0; 4];
let (back, _) = round_trip(&doc, "sharp point");
let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap();
let NodeKind::Vector { network } = &v.kind else { panic!("vector") };
let radii: Vec<f64> = network.vertices.iter().map(|x| x.radius).collect();
assert_eq!(radii, vec![8.0, 0.0, 8.0, 0.0]);
}
#[test]
fn the_written_schema_parses_and_round_trips() {
let schema = Schema::parse(export::SCHEMA).unwrap();
+3 -2
View File
@@ -356,8 +356,9 @@ struct Mapper<'a> {
/// holding it) name it by `vectorNetworkRef`. Kept out of the JSON, where a large file's
/// networks took gigabytes.
networks: Vec<Option<VectorNetwork>>,
/// Index in `networks` by its blob, position scale, style table and point-radius scale.
network_ids: HashMap<(usize, u64, u64, usize, u64), usize>,
/// Index in `networks` by its blob, position scale, style table, point-radius scale and the
/// layer's corner radius (which points without one of their own take).
network_ids: HashMap<(usize, u64, u64, usize, u64, u64), usize>,
/// Region paint elements (paints and gradient stops) read so far: one budget for the whole
/// file, since layers with region paints don't share their network.
region_paint_elements: usize,
+5 -2
View File
@@ -668,6 +668,8 @@ impl<'a> Mapper<'a> {
size.zip(norm).filter(|(s, n)| s.is_finite() && *n > 1e-9).map_or(1.0, |(s, n)| s / n)
};
let (sx, sy) = (scale("x"), scale("y"));
// A point whose style doesn't set a radius takes the layer's, as the editor draws it.
let layer_radius = v.len("cornerRadius");
let vertices: Vec<Value> = net
.vertices
.iter()
@@ -676,7 +678,7 @@ impl<'a> Mapper<'a> {
let st = style(p.style);
// Point radii are lengths in this row's space, unlike the normalized positions.
// An override/derived row already carries the instance's scale.
if let Some(r) = st.and_then(|s| num(s, "cornerRadius")).and_then(|r| scaled(r, radius_scale)).filter(|r| *r > 0.0) {
if let Some(r) = st.and_then(|s| num(s, "cornerRadius")).and_then(|r| scaled(r, radius_scale)).or(layer_radius).filter(|r| *r > 0.0) {
out["radius"] = json!(r);
}
match st.and_then(|s| s.get("handleMirroring")).and_then(Kv::str) {
@@ -793,7 +795,8 @@ impl<'a> Mapper<'a> {
return true;
}
// A resized instance and a K-scaled one can have the same box but different radii.
let key = (blob_id, sx.to_bits(), sy.to_bits(), std::ptr::from_ref(vd) as usize, radius_scale.to_bits());
let key =
(blob_id, sx.to_bits(), sy.to_bits(), std::ptr::from_ref(vd) as usize, radius_scale.to_bits(), layer_radius.unwrap_or(0.0).to_bits());
let id = match self.network_ids.get(&key) {
Some(id) => *id,
None => {
+40
View File
@@ -186,3 +186,43 @@ fn property_values_written_only_as_variables_are_applied() {
assert_eq!(props.get("Hint"), Some(&Value::Bool(false)));
assert_eq!(props.get("Label"), Some(&Value::String("Name on card".into())));
}
/// #2022: a set keeps each named text definition under its own name (Figma writes one per variant,
/// plus leftovers of deleted variants), and each variant's text reads its own copy.
#[test]
fn a_set_keeps_each_named_text_definition_and_layers_read_their_own() {
let text = |chars: &str| o(vec![("textValue", o(vec![("characters", s(chars))]))]);
let names = ["Type=Flag / State=Default label", "Type=Flag / State=Selected label", "Type=Issue / State=Default label"];
let set_defs: Vec<Kv<'static>> =
names.iter().zip([70, 71, 72]).zip(["One", "Two", "Gone"]).map(|((n, id), c)| definition(id, n, "TEXT", text(c))).collect();
let copies = |first: u32| Kv::Array((0..3).map(|k| o(vec![("id", g(first + k)), ("parentPropDefId", g(70 + k))])).collect());
let msg = message(vec![
node(9, "FRAME", "Chip", Some(2), vec![("isStateGroup", Kv::Bool(true)), ("componentPropDefs", Kv::Array(set_defs))]),
node(10, "SYMBOL", "Type=Flag, State=Default", Some(9), vec![("componentPropDefs", copies(80))]),
node(11, "TEXT", "Label", Some(10), vec![bound("TEXT_DATA", 80)]),
node(20, "SYMBOL", "Type=Flag, State=Selected", Some(9), vec![("componentPropDefs", copies(90))]),
node(21, "TEXT", "Label", Some(20), vec![bound("TEXT_DATA", 91)]),
]);
let (rest, _, _) = to_rest(&msg, "Synthetic", crate::rest::MAX_NODES);
let defs = &by_id(&rest["document"], "9:9")["componentPropertyDefinitions"];
for (k, n) in names.iter().enumerate() {
assert_eq!(defs[format!("{n}#9:{}", 70 + k)]["type"], "TEXT", "{n}");
}
assert_eq!(defs.as_object().map(|d| d.len()), Some(3), "{defs}");
assert_eq!(by_id(&rest["document"], "9:11")["componentPropertyReferences"]["characters"], format!("{}#9:70", names[0]));
assert_eq!(by_id(&rest["document"], "9:21")["componentPropertyReferences"]["characters"], format!("{}#9:71", names[1]));
let (doc, _) = crate::rest::import_fig(&rest, &crate::rest::no_images).unwrap();
let refs: Vec<Option<String>> = doc
.ids()
.filter_map(|id| doc.node(id))
.filter(|n| n.name == "Label" && n.source.is_none())
.map(|n| n.prop_refs.get("characters").cloned())
.collect();
assert_eq!(refs.len(), 2, "{refs:?}");
assert!(refs.contains(&Some(names[0].to_string())) && refs.contains(&Some(names[1].to_string())), "{refs:?}");
for set in doc.ids().filter_map(|id| doc.node(id)).filter(|n| matches!(n.kind, NodeKind::Component { .. })) {
let NodeKind::Component { props, .. } = &set.kind else { continue };
assert!(names.iter().all(|n| props.contains_key(*n)), "{} holds {:?}", set.name, props.keys().collect::<Vec<_>>());
}
}
+90
View File
@@ -521,6 +521,96 @@ fn network_of<'d>(doc: &'d figcraft_doc::Document, name: &str) -> &'d figcraft_d
}
}
#[test]
fn vector_points_without_a_radius_of_their_own_take_the_layers() {
// A vector rounded from the layer's corner radius: the editor rounds every point whose
// style doesn't set a radius (no style, or one without `cornerRadius`) with the layer's,
// while a point's own radius, zero included, wins.
let mut message = tail_message();
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
let wave = nodes.iter_mut().find(|node| node.get("name").and_then(Kv::str) == Some("Wave")).unwrap();
let Kv::Object(fields) = wave else { panic!() };
fields.push(("cornerRadius", f(6.0)));
let vector_data = field_mut(wave, "vectorData").unwrap();
let Kv::Array(styles) = field_mut(vector_data, "styleOverrideTable").unwrap() else { panic!() };
let Kv::Object(sharp) = styles.get_mut(2).unwrap() else { panic!() };
sharp.push(("cornerRadius", f(0.0)));
let (doc, _) = import(&canvas(&schema(), &message), "Rounded").unwrap();
let radii: Vec<f64> = network_of(&doc, "Wave").vertices.iter().map(|v| v.radius).collect();
assert_eq!(radii, [6.0, 4.0, 6.0, 0.0], "no style, own radius, style without one, own zero");
// Without a layer radius, the points without one of their own stay sharp.
let (doc, _) = import(&tail_canvas(), "Tail").unwrap();
let radii: Vec<f64> = network_of(&doc, "Wave").vertices.iter().map(|v| v.radius).collect();
assert_eq!(radii, [0.0, 4.0, 0.0, 0.0]);
}
#[test]
fn an_instance_that_rounds_a_vector_keeps_its_own_points() {
// An instance's copy shares its main's vector data; overriding the layer's radius must not
// reuse the main's network, nor hand the instance's to the main.
let mut message = tail_message();
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
let wave = nodes.iter_mut().find(|node| node.get("name").and_then(Kv::str) == Some("Wave")).unwrap();
*field_mut(wave, "parentIndex").unwrap() = o(vec![("guid", g(50)), ("position", s("!"))]);
*field_mut(wave, "transform").unwrap() = at(0.0, 0.0);
let rounded = o(vec![("guidPath", o(vec![("guids", arr(vec![g(30)]))])), ("cornerRadius", f(6.0))]);
nodes.push(node(50, Some((1, "~")), "SYMBOL", "Mark", vec![("size", xy(200.0, 100.0)), ("transform", at(700.0, 0.0))]));
nodes.push(node(
51,
Some((1, "~!")),
"INSTANCE",
"Rounded mark",
vec![
("size", xy(200.0, 100.0)),
("transform", at(700.0, 400.0)),
("symbolData", o(vec![("symbolID", g(50)), ("symbolOverrides", arr(vec![rounded]))])),
],
));
let (doc, _) = import(&canvas(&schema(), &message), "Instance").unwrap();
let radii_under = |parent: &str| -> Vec<f64> {
let p = named(&doc, parent);
let wave = p.children.iter().map(|c| doc.node(*c).unwrap()).find(|n| n.name == "Wave").unwrap();
let NodeKind::Vector { network } = &wave.kind else { panic!() };
network.vertices.iter().map(|v| v.radius).collect()
};
assert_eq!(radii_under("Mark"), [0.0, 4.0, 0.0, 0.0]);
assert_eq!(radii_under("Rounded mark"), [6.0, 4.0, 6.0, 6.0]);
}
#[test]
fn a_scaled_instance_scales_its_vectors_point_radii() {
// Point radii are lengths: an instance scaled with the Scale tool draws its main's, from a
// point's own style or from the layer, times the factor (#2091).
let mut message = tail_message();
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
let wave = nodes.iter_mut().find(|node| node.get("name").and_then(Kv::str) == Some("Wave")).unwrap();
*field_mut(wave, "parentIndex").unwrap() = o(vec![("guid", g(50)), ("position", s("!"))]);
*field_mut(wave, "transform").unwrap() = at(0.0, 0.0);
let Kv::Object(fields) = wave else { panic!() };
fields.push(("cornerRadius", f(3.0)));
nodes.push(node(50, Some((1, "~")), "SYMBOL", "Mark", vec![("size", xy(200.0, 100.0)), ("transform", at(700.0, 0.0))]));
nodes.push(node(
51,
Some((1, "~!")),
"INSTANCE",
"Big mark",
vec![
("size", xy(400.0, 200.0)),
("transform", at(700.0, 400.0)),
("symbolData", o(vec![("symbolID", g(50)), ("uniformScaleFactor", f(2.0))])),
],
));
let (doc, _) = import(&canvas(&schema(), &message), "Scaled").unwrap();
let radii_under = |parent: &str| -> Vec<f64> {
let p = named(&doc, parent);
let wave = p.children.iter().map(|c| doc.node(*c).unwrap()).find(|n| n.name == "Wave").unwrap();
let NodeKind::Vector { network } = &wave.kind else { panic!() };
network.vertices.iter().map(|v| v.radius).collect()
};
assert_eq!(radii_under("Mark"), [3.0, 4.0, 3.0, 3.0]);
assert_eq!(radii_under("Big mark"), [6.0, 8.0, 6.0, 6.0]);
}
#[test]
fn vectors_import_as_editable_networks() {
let (doc, warnings) = import(&tail_canvas(), "Tail").unwrap();
+21 -5
View File
@@ -12,7 +12,9 @@ use kurbo::ParamCurve;
use std::f64::consts::{FRAC_PI_2, PI, TAU};
pub mod measure;
mod simplify;
mod transform;
pub use simplify::simplify_path;
pub use transform::*;
/// Corner radii in clockwise order from the top-left: `[tl, tr, br, bl]`.
@@ -472,15 +474,29 @@ pub fn ellipse(width: f64, height: f64, start: f64, sweep: f64, inner: f64) -> B
let mut path = BezPath::new();
// A whole turn as an arc with these radii: kurbo's `Ellipse` recovers its radii from an
// affine map, which overflows to infinity for radii near f64's limit (and infinite cubics).
let whole = |rx: f64, ry: f64| kurbo::Arc::new(c, (rx, ry), 0.0, TAU, 0.0);
// Four cubics through the right, bottom, left and top extremes (clockwise from 3 o'clock),
// the same four anchors an ellipse has when edited as a vector; an arc subdivided by
// tolerance would give five or six.
let whole = |rx: f64, ry: f64| {
const K: f64 = 0.552_284_749_830_793_4;
let (kx, ky) = (rx * K, ry * K);
let mut p = BezPath::new();
p.move_to(c + Vec2::new(rx, 0.0));
p.curve_to(c + Vec2::new(rx, ky), c + Vec2::new(kx, ry), c + Vec2::new(0.0, ry));
p.curve_to(c + Vec2::new(-kx, ry), c + Vec2::new(-rx, ky), c + Vec2::new(-rx, 0.0));
p.curve_to(c + Vec2::new(-rx, -ky), c + Vec2::new(-kx, -ry), c + Vec2::new(0.0, -ry));
p.curve_to(c + Vec2::new(kx, -ry), c + Vec2::new(rx, -ky), c + Vec2::new(rx, 0.0));
p.close_path();
p
};
if full && inner <= 0.0 {
return whole(rx, ry).to_path(tol);
return whole(rx, ry);
}
if full {
// A ring: outer clockwise, inner counter-clockwise.
path.extend(whole(rx, ry).path_elements(tol));
let inner_path = whole(rx * inner, ry * inner).to_path(tol);
path.extend(inner_path.reverse_subpaths());
path.extend(whole(rx, ry).elements().iter().copied());
let inner_path = whole(rx * inner, ry * inner);
path.extend(inner_path.reverse_subpaths().elements().iter().copied());
return path;
}
let outer = kurbo::Arc::new(c, (rx, ry), start, sweep, 0.0);
+140
View File
@@ -0,0 +1,140 @@
//! Path simplification that keeps to its input where kurbo's fit would shoot past it.
use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Vec2};
/// How far, as a multiple of the accuracy asked for, a fitted run may stray from the run it
/// replaces before the run is kept as it was. kurbo's own fits stay within about the accuracy; its
/// failures stray by tens to hundreds of units, so twice the accuracy tells them apart without
/// undoing fits that are merely a little over.
const STRAY: f64 = 2.0;
/// `path` simplified to within `accuracy` by kurbo's [`simplify_bezpath`], kept from straying
/// far from `path` where kurbo's fit does.
///
/// Two inputs made kurbo's fit shoot far past the path it simplified (#1741, a Pencil stroke with
/// a spike off it), and both are common in pointer samples:
/// - A join where the path turns straight back (samples going down and back up the same line):
/// kurbo keeps two segments in one smooth fit when their tangents are parallel whichever way
/// they point (`|cross| <= |dot| * angle_thresh`), so it fits a smooth curve through the cusp.
/// The path is cut where it turns back by more than a right angle, each run between the cuts is
/// simplified on its own, and the runs are joined again, so the turn stays a sharp corner. Any
/// other join that isn't straight within kurbo's threshold is a corner to kurbo already, so the
/// cut changes nothing there.
/// - A run of nearly collinear segments: kurbo measures its error across the path, not along it, so
/// a fitted cubic whose handle runs hundreds of units on along the line passes its check. Each
/// fitted run is measured against the run it replaces, and one that strays more than
/// twice `accuracy` from it is kept as it was instead.
///
/// Subpaths and closes are kept, and a closing segment stays implicit, as kurbo leaves it.
///
/// [`simplify_bezpath`]: kurbo::simplify::simplify_bezpath
pub fn simplify_path(path: &BezPath, accuracy: f64) -> BezPath {
let mut out = BezPath::new();
let mut run = BezPath::new();
// Where the current subpath started, where the pen is, and the last segment's end tangent.
let mut start = Point::ZERO;
let mut at = Point::ZERO;
let mut last_tan: Option<Vec2> = None;
// Whether the next run that draws anything has to start the subpath with its move.
let mut fresh = true;
for el in path.elements() {
let seg = match *el {
PathEl::MoveTo(p) => {
flush(&mut out, &mut run, accuracy, &mut fresh);
(start, at, last_tan, fresh) = (p, p, None, true);
run.move_to(p);
continue;
}
PathEl::ClosePath => {
flush(&mut out, &mut run, accuracy, &mut fresh);
if !fresh {
out.close_path();
}
// A segment after a close starts a new subpath at the closed one's start.
(at, last_tan, fresh) = (start, None, true);
run.move_to(start);
continue;
}
PathEl::LineTo(p) => PathSeg::Line(kurbo::Line::new(at, p)),
PathEl::QuadTo(p1, p2) => PathSeg::Quad(kurbo::QuadBez::new(at, p1, p2)),
PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(kurbo::CubicBez::new(at, p1, p2, p3)),
};
if run.elements().is_empty() {
run.move_to(at);
}
let Some((t0, t1)) = tangents(seg) else { continue };
if last_tan.is_some_and(|last| last.dot(t0) < 0.0) {
flush(&mut out, &mut run, accuracy, &mut fresh);
run.move_to(at);
}
run.push(*el);
at = seg.end();
last_tan = Some(t1);
}
flush(&mut out, &mut run, accuracy, &mut fresh);
out
}
/// Simplify `run` (one move and the segments after it) with kurbo and append it to `out`; the
/// run's move is kept only when it starts a subpath (`fresh`), else the run carries on from the
/// last point drawn. `run` is left empty.
fn flush(out: &mut BezPath, run: &mut BezPath, accuracy: f64, fresh: &mut bool) {
if run.elements().len() > 1 {
let fitted = kurbo::simplify::simplify_bezpath(run.iter(), accuracy, &Default::default());
let fitted = if keeps_to(&fitted, run, STRAY * accuracy) { fitted } else { std::mem::take(run) };
for el in fitted.elements() {
match el {
PathEl::MoveTo(_) if !*fresh => {}
_ => {
out.push(*el);
*fresh = false;
}
}
}
}
*run = BezPath::new();
}
/// Whether every point of `fitted` lies within `tol` of `source`: one subpath each, from the same
/// start to the same end, `fitted` being kurbo's simplification of `source`.
///
/// kurbo ends each fitted segment on the source, so the two are walked together: for each fitted
/// segment, the source segments from where it starts to the first one its end lies on are the only
/// ones its sample points are measured against. The work is linear in the two lengths. A fitted end
/// found on no source segment counts as straying.
fn keeps_to(fitted: &BezPath, source: &BezPath, tol: f64) -> bool {
/// Parts each fitted segment is cut into: the points between them are the ones measured.
const SAMPLES: u32 = 16;
let src: Vec<PathSeg> = source.segments().collect();
// kurbo puts each end on the source by evaluating it: off by rounding at most.
let on2 = (tol * 1e-3).powi(2);
let (tol2, mut cur) = (tol * tol, 0);
for seg in fitted.segments() {
let Some(last) = (cur..src.len()).find(|&i| src.get(i).is_some_and(|s| s.nearest(seg.end(), 1e-9).distance_sq <= on2)) else {
return false;
};
let near = src.get(cur..=last).unwrap_or_default();
for i in 1..SAMPLES {
let p = seg.eval(f64::from(i) / f64::from(SAMPLES));
if !near.iter().any(|s| s.nearest(p, 1e-6).distance_sq <= tol2) {
return false;
}
}
cur = last;
}
true
}
/// The directions `seg` leaves its start and reaches its end, skipping control points that sit on
/// an end; `None` for a segment of no length, which kurbo skips too.
fn tangents(seg: PathSeg) -> Option<(Vec2, Vec2)> {
let pts: Vec<Point> = match seg {
PathSeg::Line(l) => vec![l.p0, l.p1],
PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
};
let (first, last) = (*pts.first()?, *pts.last()?);
let t0 = pts.iter().map(|p| *p - first).find(|d| d.hypot2() > 0.0)?;
let t1 = pts.iter().rev().map(|p| last - *p).find(|d| d.hypot2() > 0.0)?;
Some((t0, t1))
}
+315 -1
View File
@@ -263,7 +263,7 @@ fn smoothed_polygon_smooths_every_corner() {
#[test]
fn ellipse_ring_area() {
let full = area(&ellipse(100.0, 100.0, 0.0, TAU, 0.0));
assert!((full - PI * 2500.0).abs() < 2.0);
assert!((full - PI * 2500.0).abs() < 5.0, "{full}");
let ring = ellipse(100.0, 100.0, 0.0, TAU, 0.5);
// Winding area of a ring with a reversed inner contour: outer - inner.
let a = ring.area().abs();
@@ -321,6 +321,46 @@ fn reverse_subpaths_preserves_open_and_closed() {
assert!(matches!(r.elements().last(), Some(kurbo::PathEl::ClosePath)), "{:?}", r.elements());
}
fn cubics(path: &BezPath) -> Vec<kurbo::CubicBez> {
path.segments()
.filter_map(|s| match s {
kurbo::PathSeg::Cubic(c) => Some(c),
_ => None,
})
.collect()
}
#[test]
fn a_whole_ellipse_is_four_cubics_through_the_extremes() {
for (w, h) in [(100.0, 100.0), (200.0, 60.0), (3.0, 900.0)] {
let segs = cubics(&ellipse(w, h, 0.0, TAU, 0.0));
assert_eq!(segs.len(), 4, "{w}x{h}");
let (rx, ry) = (w / 2.0, h / 2.0);
let want = [Point::new(rx, h), Point::new(0.0, ry), Point::new(rx, 0.0), Point::new(w, ry)];
for (i, s) in segs.iter().enumerate() {
assert!((s.p3 - want[i]).hypot() < 1e-9, "{w}x{h}: anchor {i} is {:?}", s.p3);
// Handle length is 0.5523 of the radius along the tangent.
let k = 0.552_284_749_830_793_4;
let r_along = if i % 2 == 0 { ry } else { rx };
assert!(((s.p1 - s.p0).hypot() - k * r_along).abs() < 1e-9, "{w}x{h}: handle {i}");
}
}
}
#[test]
fn a_whole_ring_is_four_cubics_per_contour() {
let segs = cubics(&ellipse(100.0, 100.0, 0.0, TAU, 0.5));
assert_eq!(segs.len(), 8);
}
#[test]
fn a_sliced_ellipse_still_builds_its_arc() {
let pie = ellipse(100.0, 100.0, 0.0, PI, 0.0);
assert!(!cubics(&pie).is_empty());
assert!(matches!(pie.elements().last(), Some(kurbo::PathEl::ClosePath)));
assert!((area(&pie) - PI * 1250.0).abs() < 2.0);
}
#[test]
fn a_huge_ellipse_arc_is_a_few_cubics() {
let big = ellipse(1e300, 1e300, 0.3, 2.0, 0.5);
@@ -366,3 +406,277 @@ fn svg_path_refuses_numbers_past_the_limit_before_parsing() {
assert!(number_past("M0 0L-2.5.5 1e-3-4e3z", 1e3));
assert!(number_past("M.5.5e10", 1e3));
}
/// A path through `pts` with straight lines (pencil samples).
fn polyline(pts: &[(f64, f64)]) -> BezPath {
let mut p = BezPath::new();
for (k, (x, y)) in pts.iter().enumerate() {
if k == 0 { p.move_to((*x, *y)) } else { p.line_to((*x, *y)) }
}
p
}
/// How far `out` strays from `input`: the largest distance from a point sampled along `out` to the
/// nearest segment of `input` (closing segments included).
fn deviation(out: &BezPath, input: &BezPath) -> f64 {
use kurbo::{ParamCurve, ParamCurveNearest};
let segs: Vec<kurbo::PathSeg> = input.segments().collect();
out.segments()
.flat_map(|seg| (0..=32).map(move |i| seg.eval(f64::from(i) / 32.0)))
.map(|p| segs.iter().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt())
.fold(0.0, f64::max)
}
/// Pencil strokes kurbo's fit shot far past keep to their samples (#1741): a stroke that goes out
/// and back to the very point it left, nearly collinear samples, and strokes that turn back along
/// their own line. The first two are from fuzzing pencil-like strokes, where kurbo's curve went
/// about 390 and 160 units off; at whole-pixel coordinates the same shapes happened to fit well.
#[test]
fn simplifying_keeps_to_strokes_kurbo_shot_past() {
let cases: [(&str, &[(f64, f64)]); 5] = [
(
"out and back to the same point",
&[
(86.043_565_719_086_97, -173.744_402_349_100_94),
(87.851_850_739_335_35, -179.202_846_445_954_52),
(86.043_565_719_086_97, -173.744_402_349_100_94),
],
),
(
"nearly collinear",
&[
(209.598_690_794_015_5, -204.909_328_119_739_88),
(211.277_914_263_870_97, -207.190_974_020_753_4),
(214.246_506_828_720_84, -211.228_827_590_623_24),
],
),
(
"a dip straight down and back up",
&[(0.0, 0.0), (10.0, 0.0), (20.0, 2.0), (30.0, 6.0), (30.0, 12.0), (30.0, 6.0), (40.0, 2.0), (50.0, 0.0)],
),
("a slip back at the end", &[(0.0, 0.0), (10.0, 3.0), (20.0, 8.0), (30.0, 15.0), (30.0, 25.0), (30.0, 22.0)]),
(
"a near reversal in a curve",
&[(0.0, 0.0), (8.0, 2.0), (16.0, 6.0), (24.0, 12.0), (32.0, 20.0), (24.0, 12.000_01), (16.0, 6.0), (8.0, 2.0)],
),
];
for (what, pts) in cases {
keeps_to_one_stroke(what, &polyline(pts));
}
}
/// Accuracies the simplification is checked at: fine, the Pencil's, and coarse.
const ACCURACIES: [f64; 3] = [0.1, 0.75, 8.0];
/// Check that `input` (one open subpath), simplified at each of [`ACCURACIES`], strays no more
/// than twice the accuracy from it and leaves no part of it further off than that, stays in its
/// box grown by as much, and is still one subpath from its start to its end.
fn keeps_to_one_stroke(what: &str, input: &BezPath) {
for accuracy in ACCURACIES {
let out = simplify_path(input, accuracy);
let (svg, limit) = (out.to_svg(), 2.0 * accuracy);
let d = deviation(&out, input);
assert!(d <= limit, "{what} at {accuracy}: strays {d} from the input: {svg}");
let left = deviation(input, &out);
assert!(left <= limit, "{what} at {accuracy}: leaves the input {left} off: {svg}");
let (inb, outb) = (input.bounding_box(), out.bounding_box());
assert!(inb.inflate(limit, limit).contains_rect(outb), "{what} at {accuracy}: {outb:?} past {inb:?}");
let moves = out.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count();
assert_eq!(moves, 1, "{what} at {accuracy}: {svg}");
// From its start to its end: kurbo evaluates a fitted end on the input, so it is off by
// rounding at most.
let ends = |p: &BezPath| p.segments().next().map(|s| s.start()).zip(p.segments().last().map(|s| s.end()));
let ((start, end), (start_in, end_in)) = (ends(&out).unwrap(), ends(input).unwrap());
assert!((start - start_in).hypot() < 1e-9 && (end - end_in).hypot() < 1e-9, "{what} at {accuracy}: {svg}");
}
}
/// Strokes made of curves keep to them as polylines do (#1741): a quadratic or a cubic that goes
/// out and comes straight back, one whose control points sit on its ends (so its direction is
/// read from the control point after them), and nearly collinear curves.
#[test]
fn simplifying_keeps_to_curves_that_turn_back_or_run_straight() {
let (p, q, r) = (
(209.598_690_794_015_5, -204.909_328_119_739_88),
(211.277_914_263_870_97, -207.190_974_020_753_4),
(214.246_506_828_720_84, -211.228_827_590_623_24),
);
// The nearly collinear samples, each line as a cubic with its handles a third of the way along.
let third = |a: (f64, f64), b: (f64, f64), t: f64| (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
let mut straight_cubics = BezPath::new();
straight_cubics.move_to(p);
for (a, b) in [(p, q), (q, r)] {
straight_cubics.curve_to(third(a, b, 1.0 / 3.0), third(a, b, 2.0 / 3.0), b);
}
let mut straight_quads = BezPath::new();
straight_quads.move_to(p);
straight_quads.quad_to(third(p, q, 0.5), q);
straight_quads.quad_to(third(q, r, 0.5), r);
let cases = [
("a quadratic out and back", BezPath::from_svg("M0 0 Q15 10 30 0 Q15 10 0 0 Q-15 10 -30 0").unwrap()),
("a cubic out and back", BezPath::from_svg("M0 0 C10 8 20 8 30 0 C20 8 10 8 0 0 C-10 8 -20 8 -30 0").unwrap()),
("handles on the ends", BezPath::from_svg("M0 0 C0 0 30 4 30 4 C30 4 0 0 0 0 L-30 -4").unwrap()),
("a cubic dip down and back up", BezPath::from_svg("M0 0 L10 0 C15 0 20 5 20 12 C20 5 25 0 30 0 L40 0").unwrap()),
("nearly collinear cubics", straight_cubics),
("nearly collinear quadratics", straight_quads),
];
for (what, input) in cases {
keeps_to_one_stroke(what, &input);
}
}
/// `sides` simplified by kurbo one at a time and joined into one subpath.
fn fitted_apart(sides: &[&BezPath], accuracy: f64) -> BezPath {
let mut out = BezPath::new();
for side in sides {
let fit = kurbo::simplify::simplify_bezpath(side.iter(), accuracy, &Default::default());
let skip = usize::from(!out.elements().is_empty());
out.extend(fit.elements().iter().copied().skip(skip));
}
out
}
/// `curve` cut into `n` cubics, drawn on from where `path` is: forwards, or back from its end.
fn in_pieces(path: &mut BezPath, curve: kurbo::CubicBez, n: u32, back: bool) {
use kurbo::ParamCurve;
for i in 0..n {
let i = if back { n - 1 - i } else { i };
let c = curve.subsegment(f64::from(i) / f64::from(n)..f64::from(i + 1) / f64::from(n));
if back { path.curve_to(c.p2, c.p1, c.p0) } else { path.curve_to(c.p1, c.p2, c.p3) }
}
}
/// Where a path turns straight back it is cut, so the result is kurbo's fit of each side on its
/// own, with a point of the path at the turn. Fitted as one, kurbo rounds the turn off: its curve
/// passes the stray check, but falls short of the turn or takes more segments. A cubic whose
/// control points sit on its ends turns back as a line does.
#[test]
fn simplifying_fits_each_side_of_a_turn_back_on_its_own() {
use kurbo::ParamCurve;
let svg = |d: &str| BezPath::from_svg(d).unwrap();
let s = kurbo::CubicBez::new((0.0, 0.0), (40.0, -60.0), (80.0, 60.0), (120.0, 0.0));
let (mut s_out, mut s_back) = (BezPath::new(), BezPath::new());
s_out.move_to(s.p0);
in_pieces(&mut s_out, s, 8, false);
s_back.move_to(s.p3);
in_pieces(&mut s_back, s, 8, true);
let cases = [
("lines", svg("M0 0 L10 0 L20 0 L30 0"), svg("M30 0 L20 0 L10 0")),
("handles on the ends", svg("M0 0 L10 0 L20 0 C20 0 30 0 30 0"), svg("M30 0 C30 0 20 0 20 0 L10 0")),
("a curve in pieces", s_out, s_back),
];
for (what, out_side, back_side) in cases {
let turn = out_side.segments().last().map(|seg| seg.end()).unwrap();
let mut input = out_side.clone();
input.extend(back_side.elements().iter().copied().skip(1));
for accuracy in ACCURACIES {
let ours = simplify_path(&input, accuracy);
let apart = fitted_apart(&[&out_side, &back_side], accuracy);
assert_eq!(ours.elements(), apart.elements(), "{what} at {accuracy}");
assert!(ours.segments().any(|seg| (seg.end() - turn).hypot() < 1e-9), "{what} at {accuracy}: {}", ours.to_svg());
}
}
}
/// Where a path never turns back and kurbo's fit holds, the result is kurbo's own, element for
/// element: smooth runs, corners sharper than a right angle, closed subpaths and several subpaths.
/// A fit counts as holding up to twice the accuracy asked for, whatever that is: the large wave's
/// is further off at the coarse accuracy than the Pencil's limit of 1.5.
#[test]
fn simplifying_is_kurbos_where_its_fit_holds() {
let wave: Vec<(f64, f64)> = (0..=60).map(|i| (f64::from(i) * 4.0, (f64::from(i) / 6.0).sin() * 30.0)).collect();
let zigzag: Vec<(f64, f64)> = (0..=8).map(|i| (f64::from(i) * 10.0, if i % 2 == 0 { 0.0 } else { 40.0 })).collect();
let mut closed = polyline(&wave[..20]);
closed.close_path();
let mut several = polyline(&wave);
several.extend(polyline(&zigzag).elements().iter().map(|e| match *e {
kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(p + Vec2::new(0.0, 100.0)),
kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(p + Vec2::new(0.0, 100.0)),
e => e,
}));
let curves = BezPath::from_svg("M0 0 C10 -20 30 -20 40 0 C50 20 70 20 80 0 Q100 -30 120 0 L140 10 Z M200 0 L240 0").unwrap();
// A sine 300 high in 40 smooth cubics.
let sine = |x: f64| ((x / 120.0).sin() * 300.0, (x / 120.0).cos() * 2.5);
let mut large = BezPath::new();
large.move_to((0.0, 0.0));
for i in 0..40 {
let (x0, x1) = (f64::from(i) * 40.0, f64::from(i + 1) * 40.0);
let ((y0, d0), (y1, d1)) = (sine(x0), sine(x1));
large.curve_to((x0 + 40.0 / 3.0, y0 + d0 * 40.0 / 3.0), (x1 - 40.0 / 3.0, y1 - d1 * 40.0 / 3.0), (x1, y1));
}
let coarse = simplify_path(&large, 8.0);
assert!(coarse.elements().len() < 10 && (1.5..=8.0).contains(&deviation(&coarse, &large)), "{}", deviation(&coarse, &large));
for (what, input) in [
("a wave", polyline(&wave)),
("a zigzag", polyline(&zigzag)),
("closed", closed),
("two subpaths", several),
("curves", curves),
("a large wave", large),
] {
for accuracy in ACCURACIES {
let ours = simplify_path(&input, accuracy);
let theirs = kurbo::simplify::simplify_bezpath(input.iter(), accuracy, &Default::default());
assert_eq!(ours.elements(), theirs.elements(), "{what} at {accuracy}");
}
}
}
/// A closed path with a reversal in it stays one closed subpath, and each subpath of several keeps
/// its own start.
#[test]
fn simplifying_keeps_closes_and_subpaths_across_a_reversal() {
let mut input = polyline(&[(0.0, 0.0), (40.0, 0.0), (40.0, 30.0), (40.0, 20.0), (0.0, 30.0)]);
input.close_path();
input.extend(polyline(&[(100.0, 0.0), (100.0, 20.0), (100.0, 10.0)]).elements().iter().copied());
let out = simplify_path(&input, 0.75);
let els = out.elements();
let moves: Vec<Point> = els.iter().filter_map(|e| if let kurbo::PathEl::MoveTo(p) = e { Some(*p) } else { None }).collect();
assert_eq!(moves, [Point::new(0.0, 0.0), Point::new(100.0, 0.0)], "{}", out.to_svg());
assert_eq!(els.iter().filter(|e| matches!(e, kurbo::PathEl::ClosePath)).count(), 1, "{}", out.to_svg());
let close = els.iter().position(|e| matches!(e, kurbo::PathEl::ClosePath)).unwrap();
assert!(matches!(els[close + 1], kurbo::PathEl::MoveTo(_)), "the first subpath closes before the second starts");
assert!(deviation(&out, &input) <= 1.5, "{}", out.to_svg());
// Nothing to draw: nothing out, not a stray move or close.
let mut empty = BezPath::new();
empty.move_to((5.0, 5.0));
empty.line_to((5.0, 5.0));
empty.close_path();
assert!(simplify_path(&empty, 0.75).elements().is_empty());
for d in ["", "M5 5", "M5 5 M6 6", "M5 5 Z"] {
let input = if d.is_empty() { BezPath::new() } else { BezPath::from_svg(d).unwrap() };
assert!(simplify_path(&input, 0.75).elements().is_empty(), "{d:?}");
}
}
/// The subpaths simplified keep their starts: a move with nothing drawn from it between two
/// subpaths leaves no trace, and a segment drawn on from a close starts a subpath where the closed
/// one started, as it does in the path given.
#[test]
fn simplifying_keeps_where_each_subpath_starts() {
let starts =
|p: &BezPath| -> Vec<Point> { p.elements().iter().filter_map(|e| if let kurbo::PathEl::MoveTo(p) = e { Some(*p) } else { None }).collect() };
let between = BezPath::from_svg("M0 0 L10 0 L20 5 M50 50 M100 0 L110 0 L120 5").unwrap();
let out = simplify_path(&between, 0.75);
assert_eq!(starts(&out), [Point::new(0.0, 0.0), Point::new(100.0, 0.0)], "{}", out.to_svg());
assert!(deviation(&out, &between) <= 1.5, "{}", out.to_svg());
// After the close, the pen is back at (0, 0): the next segments start there, also across a
// reversal.
use kurbo::PathEl::{ClosePath, LineTo, MoveTo};
let on = BezPath::from_vec(vec![
MoveTo(Point::new(0.0, 0.0)),
LineTo(Point::new(10.0, 0.0)),
LineTo(Point::new(10.0, 10.0)),
ClosePath,
LineTo(Point::new(20.0, 20.0)),
LineTo(Point::new(30.0, 20.0)),
LineTo(Point::new(20.0, 20.0)),
]);
let out = simplify_path(&on, 0.75);
let els = out.elements();
let close = els.iter().position(|e| matches!(e, kurbo::PathEl::ClosePath)).unwrap();
assert_eq!(els.get(close + 1), Some(&kurbo::PathEl::MoveTo(Point::new(0.0, 0.0))), "{}", out.to_svg());
assert_eq!(starts(&out), [Point::new(0.0, 0.0), Point::new(0.0, 0.0)], "{}", out.to_svg());
assert_eq!(out.segments().last().map(|s| kurbo::ParamCurve::end(&s)), Some(Point::new(20.0, 20.0)));
assert!(deviation(&out, &on) <= 1.5, "{}", out.to_svg());
}
+12
View File
@@ -93,3 +93,15 @@ fn deeply_nested_fill_frames_lay_out_without_running_out_of_stack() {
assert_eq!(width(&d, chain[DEEP - 1]), 10.0, "past the nesting the layout follows, layers stay");
});
}
#[test]
fn snap_lines_are_bounded_across_a_frames_grids() {
use figcraft_doc::{Document, GridKind, LayoutGrid, NodeKind};
let mut d = Document::new("t");
let p = d.first_page().unwrap();
let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 4000.0, 4000.0).unwrap();
d.get_mut(f).unwrap().grids = vec![LayoutGrid { kind: GridKind::Grid, size: 1.0, visible: true, ..LayoutGrid::default() }; 1000];
let (xs, ys) = crate::grid_snap_lines(&d, f);
assert!(xs.len() + ys.len() <= 200_000, "{}", xs.len() + ys.len());
assert!(xs.len() > 4000 && ys.len() > 4000, "the first grids still give their lines");
}
+10 -1
View File
@@ -1159,6 +1159,9 @@ pub fn grid_snap_lines(doc: &Document, frame: NodeId) -> (Vec<f64>, Vec<f64>) {
grid_snap_lines_in(doc, frame, doc.world_transform(frame))
}
/// The most snap coordinates a frame's grids give together (a few dozen grids' worth of lines).
const MAX_SNAP_LINES: usize = 200_000;
/// [`grid_snap_lines`] mapped from the frame's coordinates by `xf` (the frame's world transform
/// for page lines).
pub fn grid_snap_lines_in(doc: &Document, frame: NodeId, xf: Affine) -> (Vec<f64>, Vec<f64>) {
@@ -1166,7 +1169,13 @@ pub fn grid_snap_lines_in(doc: &Document, frame: NodeId, xf: Affine) -> (Vec<f64
let mut xs = Vec::new();
let mut ys = Vec::new();
for g in f.grids.iter().filter(|g| g.visible) {
for r in grid_lines(g, f.width, f.height) {
// A frame-wide budget: each grid adds up to ~17,000 lines, and a file can hold any number of grids;
// a grid that would pass it is left out whole.
let lines = grid_lines(g, f.width, f.height);
if xs.len() + ys.len() + 2 * lines.len() > MAX_SNAP_LINES {
break;
}
for r in lines {
let a = xf * Point::new(r.x0, r.y0);
let b = xf * Point::new(r.x1, r.y1);
match g.kind {
+1 -1
View File
@@ -280,7 +280,7 @@ fn tools() -> Vec<Value> {
"svgIdAttribute": boolean("SVG: layer names as unique `id` attributes (default false)"),
"svgSimplifyStroke": boolean("SVG: strokes as `stroke` attributes where exact (default true); false writes outlines"),
"vdCompat": {"type": "string", "enum": ["bestEffort", "exact", "ignore"], "description": "XML: what a Vector Drawable can't draw exactly is approximated with a warning (bestEffort, default), left out with a warning (exact), or written as far as it maps without warnings (ignore: overlapping layer opacity dropped, even-odd fills kept as fillType=evenOdd, diamond gradients left out)"},
"colorProfile": {"type": "string", "enum": ["sameAsFile", "srgb", "displayP3"], "description": "PNG, JPG and WebP: the color profile of the file (default sameAsFile: the document's); colors are converted and out-of-gamut ones clip. SVG, PDF and XML are always sRGB"},
"colorProfile": {"type": "string", "enum": ["sameAsFile", "srgb", "displayP3"], "description": "PNG, JPG and WebP: the color profile of the file (default sameAsFile: the document's); colors are converted and out-of-gamut ones clip. SVG, XML and RGB PDF output are always sRGB; PDF with cmyk is DeviceCMYK"},
"quality": {"type": "integer", "minimum": 1, "maximum": 100, "description": "JPG: the encoder's quality, 1 (smallest file) to 100; default 90"},
}),
&[],
+54 -16
View File
@@ -56,20 +56,61 @@ fn view(scale: f64) -> View {
View { origin: (-10.0, -10.0), scale, width: (440.0 * scale) as u32, height: (240.0 * scale) as u32 }
}
/// Per row: the mean channel difference and how many pixels differ by more than 2. A band artifact
/// differs along a whole row; edge antialiasing may differ in a few pixels per edge (a curve
/// clipped at a band's edge rasterises a hair differently, most where it runs nearly level).
/// A pixel whose largest channel differs by at most this much between two renders is edge
/// antialiasing noise (a curve clipped at a band's edge rasterises a hair differently, most where
/// it runs level, as at the top of an ellipse), not a band artifact.
const NOISE: u8 = 24;
/// One row of two renders: the channel differences of the pixels above noise (see `NOISE`) summed
/// and divided by the whole row's channel count, so noise pixels add nothing but still count in
/// the denominator; and how many pixels differ by more than 2 at all. A band artifact differs along
/// a whole row, by more than noise.
fn row_stats(x: &[u8], y: &[u8]) -> (f64, usize) {
let mut sum = 0.0;
let mut off = 0;
for (p, q) in x.chunks(4).zip(y.chunks(4)) {
let worst = p.iter().zip(q).map(|(c, d)| c.abs_diff(*d)).max().unwrap_or(0);
if worst > 2 {
off += 1;
}
if worst > NOISE {
sum += p.iter().zip(q).map(|(c, d)| f64::from(c.abs_diff(*d))).sum::<f64>();
}
}
(sum / x.len().max(1) as f64, off)
}
fn row_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> {
let row = a.width() as usize * 4;
a.data()
.chunks(row)
.zip(b.data().chunks(row))
.map(|(x, y)| {
let sum: f64 = x.iter().zip(y).map(|(p, q)| f64::from(p.abs_diff(*q))).sum();
let off = x.chunks(4).zip(y.chunks(4)).filter(|(p, q)| p.iter().zip(*q).any(|(c, d)| c.abs_diff(*d) > 2)).count();
(sum / row as f64, off)
})
.collect()
a.data().chunks(row).zip(b.data().chunks(row)).map(|(x, y)| row_stats(x, y)).collect()
}
/// Whether a row passes: the original 0.25 limit on the mean from `row_stats`, and at most a
/// twentieth of the row differing at all.
fn row_ok(mean: f64, off: usize, width: usize) -> bool {
mean < 0.25 && off * 20 <= width
}
#[test]
fn a_real_band_artifact_fails_but_edge_noise_passes() {
let width = 880; // scale 2
let flat = vec![100u8; width * 4];
// 44 pixels whose colour channels differ by 60 (alpha unchanged): the mean is
// 44 * 3 * 60 / (880 * 4) = 2.25, and the count, 44, is within a twentieth of the row. A real
// artifact, so it fails on the mean.
let mut artifact = flat.clone();
for px in artifact.chunks_mut(4).take(44) {
px.iter_mut().take(3).for_each(|c| *c += 60);
}
let (mean, off) = row_stats(&flat, &artifact);
assert!(!row_ok(mean, off, width), "{mean} {off}");
// 8 pixels differing by 16 (the ellipse top's antialiasing): forgiven.
let mut noise = flat.clone();
for px in noise.chunks_mut(4).take(8) {
px.iter_mut().for_each(|c| *c += 16);
}
let (mean, off) = row_stats(&flat, &noise);
assert!(row_ok(mean, off, width), "{mean} {off}");
}
#[test]
@@ -82,10 +123,7 @@ fn bands_match_one_piece_rendering() {
let banded = render_bands(&d, p, &v, &Options::default(), bands).unwrap();
assert_eq!((banded.width(), banded.height()), (one.width(), one.height()));
for (y, (mean, off)) in row_diffs(&one, &banded).into_iter().enumerate() {
assert!(
mean < 0.25 && off * 20 <= v.width as usize,
"scale {scale}, {bands} bands: row {y} differs ({off} pixels, {mean:.2} on average)"
);
assert!(row_ok(mean, off, v.width as usize), "scale {scale}, {bands} bands: row {y} differs ({off} pixels, {mean:.2} on average)");
}
}
}
+52 -5
View File
@@ -704,13 +704,36 @@ fn simple_hash(b: &[u8]) -> String {
/// Deepest element nesting the parser is given: deeper documents would exhaust the stack.
const MAX_NESTING: usize = 512;
/// The most attributes one element may have. The XML parser checks each attribute against the
/// earlier ones, so a huge count is quadratic work; real elements have a few dozen at most.
const MAX_ATTRIBUTES: usize = 4096;
/// How deep elements nest in `data`: a scan of its tags (comments, CDATA, declarations and quoted
/// attribute values skipped) that stops once past `limit`.
pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
scan(data, limit).0
}
/// The most the parser's duplicate-attribute checks may cost over a whole document, as the sum of
/// each element's attribute count squared (a real file with 100,000 elements of 20 attributes is
/// 40 million).
const MAX_ATTRIBUTE_WORK: usize = 1 << 28;
/// Whether an element of `data` has more than [`MAX_ATTRIBUTES`] attributes, or all of them cost
/// more than [`MAX_ATTRIBUTE_WORK`] (counted as quoted values, before the parser sees them; the
/// declarations of a DTD count as one element, as entities can hold elements).
pub(crate) fn too_wide(data: &[u8]) -> bool {
let (_, widest, work) = scan(data, usize::MAX);
widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK
}
/// [`nesting`], the most attribute values on one element and the attribute work (see
/// [`MAX_ATTRIBUTE_WORK`]); stops once any is past its limit.
fn scan(data: &[u8], limit: usize) -> (usize, usize, usize) {
let find = |from: usize, pat: &[u8]| -> usize {
data.get(from..).and_then(|r| r.windows(pat.len()).position(|w| w == pat)).map_or(data.len(), |p| from + p + pat.len())
};
let (mut depth, mut max, mut i) = (0usize, 0usize, 0usize);
let (mut depth, mut max, mut i, mut widest, mut work) = (0usize, 0usize, 0usize, 0usize, 0usize);
while let Some(off) = data.get(i..).and_then(|r| r.iter().position(|b| *b == b'<')) {
i += off;
let rest = data.get(i..).unwrap_or(&[]);
@@ -718,6 +741,19 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
i = find(i + 4, b"-->");
} else if rest.starts_with(b"<![CDATA[") {
i = find(i + 9, b"]]>");
} else if rest.starts_with(b"<!DOCTYPE") {
// To the `]>` closing its subset (the first `>` when it has none).
let end = match (rest.iter().position(|b| *b == b'['), rest.iter().position(|b| *b == b'>')) {
(Some(o), Some(g)) if o < g => find(i, b"]>"),
_ => find(i, b">"),
};
let quotes = data.get(i..end).unwrap_or(&[]).iter().filter(|b| matches!(**b, b'"' | b'\'')).count();
widest = widest.max(quotes / 2);
work = work.saturating_add((quotes / 2).saturating_mul(quotes / 2));
if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
return (max, widest, work);
}
i = end;
} else if rest.starts_with(b"<?") || rest.starts_with(b"<!") {
i = find(i + 2, b">");
} else if rest.starts_with(b"</") {
@@ -725,12 +761,15 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
i = find(i + 2, b">");
} else {
// A start tag: to its `>` outside quotes; `/>` closes it.
let (mut quote, mut j, mut closed) = (None, i + 1, false);
let (mut quote, mut j, mut closed, mut attrs) = (None, i + 1, false, 0usize);
while let Some(&c) = data.get(j) {
match quote {
Some(q) if c == q => quote = None,
Some(_) => {}
None if c == b'"' || c == b'\'' => quote = Some(c),
None if c == b'"' || c == b'\'' => {
quote = Some(c);
attrs += 1;
}
None if c == b'>' => {
closed = data.get(j.wrapping_sub(1)) == Some(&b'/');
break;
@@ -739,17 +778,22 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
}
j += 1;
}
widest = widest.max(attrs);
work = work.saturating_add(attrs * attrs);
if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
return (max, widest, work);
}
if !closed {
depth += 1;
max = max.max(depth);
if max > limit {
return max;
return (max, widest, work);
}
}
i = j + 1;
}
}
max
(max, widest, work)
}
/// Whether `data` nests elements more than [`MAX_NESTING`] deep: the byte scan first, then the
@@ -883,6 +927,9 @@ fn import_within(
) -> Result<Imported, ImportError> {
// SVGZ is unpacked here, within a budget, so every check below sees the real document.
let data = budget::document(data, &limits).map_err(ImportError)?;
if too_wide(&data) {
return Err(ImportError(format!("an element has more than {MAX_ATTRIBUTES} attributes")));
}
if too_deep(&data) {
return Err(ImportError(format!("elements nested more than {MAX_NESTING} deep")));
}
+1 -1
View File
@@ -87,7 +87,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], opts: &Options) -> Option
}
};
used.bytes.fetch_add(plain.len(), Ordering::Relaxed);
if super::too_deep(&plain) {
if super::too_wide(&plain) || super::too_deep(&plain) {
return None;
}
used.depth.fetch_add(1, Ordering::Relaxed);
+24
View File
@@ -181,3 +181,27 @@ fn entity_expansion_cannot_bypass_the_nesting_limit() {
let err = import_svg(&mut d, data.as_bytes(), p, 0.0, 0.0, "x").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("nested more than 512 deep"), "{err:?}");
}
#[test]
fn an_element_with_thousands_of_attributes_is_refused_before_parsing() {
use super::too_wide;
let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::<String>();
assert!(!too_wide(format!("<svg{}/>", many(4096)).as_bytes()));
assert!(too_wide(format!("<svg><g{}/></svg>", many(4097)).as_bytes()));
assert!(!too_wide(format!("<svg>{}</svg>", "<g a='1' b='2'/>".repeat(10_000)).as_bytes()), "per element, not per file");
let mut d = Document::new("t");
let p = d.first_page().unwrap();
assert!(import_svg(&mut d, &svg(&format!("<g{}/>", many(100_000))), p, 0.0, 0.0, "x").is_err());
}
#[test]
fn attribute_work_is_bounded_over_the_whole_document_and_its_dtd() {
use super::too_wide;
let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::<String>();
let tag = format!("<g{}/>", many(4000));
assert!(!too_wide(format!("<svg>{}</svg>", tag.repeat(10)).as_bytes()));
assert!(too_wide(format!("<svg>{}</svg>", tag.repeat(40)).as_bytes()), "each element is within the limit, all together are not");
let dtd = format!("<!DOCTYPE svg [<!ENTITY e '<g{}/>'>]><svg>&e;</svg>", many(5000));
assert!(too_wide(dtd.as_bytes()), "entities can hold elements");
assert!(!too_wide(b"<?xml version='1.0'?><!DOCTYPE svg [<!ENTITY ns 'http://www.w3.org/2000/svg'>]><svg/>"));
}
+28 -3
View File
@@ -195,7 +195,7 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
let x = chunk.x().map_or(pen_x, f64::from) + d(t.dx());
let y = chunk.y().map_or(pen_y, f64::from) + d(t.dy());
char_at += count;
let ci = |b: usize| text.get(..b).map_or(count, |p| p.chars().count());
let ci = char_index(text, chunk.spans().iter().flat_map(|sp| [sp.start(), sp.end()]));
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, s, fonts))).collect();
if spans.is_empty() {
continue;
@@ -229,6 +229,32 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
}
}
/// The characters of `text` before each of the byte `offsets` (all of them for an offset that is
/// past the end or inside a character): one pass over the text, whatever the number of spans.
fn char_index(text: &str, offsets: impl IntoIterator<Item = usize>) -> impl Fn(usize) -> usize {
let mut want: Vec<usize> = offsets.into_iter().collect();
want.sort_unstable();
want.dedup();
let mut found: Vec<(usize, usize)> = Vec::with_capacity(want.len());
let mut wanted = want.into_iter().peekable();
let mut count = 0;
for (i, _) in text.char_indices() {
while let Some(&o) = wanted.peek() {
match o.cmp(&i) {
std::cmp::Ordering::Equal => found.push((o, count)),
std::cmp::Ordering::Greater => break,
std::cmp::Ordering::Less => {}
}
wanted.next();
}
count += 1;
}
if wanted.any(|o| o == text.len()) {
found.push((text.len(), count));
}
move |b| found.binary_search_by_key(&b, |f| f.0).ok().and_then(|k| found.get(k)).map_or(count, |f| f.1)
}
/// The text of `lines` (one per line, stacked at their pitch; `s`: their scale): characters, the
/// first span's style and a run per span, fills still to come.
fn text_data(lines: &[Line], s: f64) -> TextData {
@@ -262,8 +288,7 @@ fn on_path(cx: &mut Ctx, t: &usvg::Text, world: Affine, parent: NodeId) -> bool
let Some(len) = figcraft_geom::measure::polylines(&path).and_then(|l| l.first().map(|l| l.length())).filter(|l| *l > 1e-9) else { return false };
let fonts = cx.fonts.get_or_insert_with(Fonts::load);
let text = chunk.text();
let count = text.chars().count();
let ci = |b: usize| text.get(..b).map_or(count, |p| p.chars().count());
let ci = char_index(text, chunk.spans().iter().flat_map(|sp| [sp.start(), sp.end()]));
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, 1.0, fonts))).collect();
let line = Line { x: 0.0, y: 0.0, anchor: chunk.anchor(), text: text.to_string(), spans };
let mut td = text_data(std::slice::from_ref(&line), 1.0);
+8
View File
@@ -30,3 +30,11 @@ fn css_system_font_names_keep_their_name_where_the_system_font_is() {
assert_eq!(family(&named(&["-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"]), &elsewhere), "Inter");
assert_eq!(family(&named(&["-apple-system"]), &elsewhere), "-apple-system", "nothing installed: the first name it gives");
}
#[test]
fn char_index_counts_the_characters_before_a_byte_offset() {
let t = "aé😀b";
let ci = super::char_index(t, [0, 1, 3, 7, 8, 2, 4, 99]);
assert_eq!([ci(0), ci(1), ci(3), ci(7), ci(8)], [0, 1, 2, 3, 4]);
assert_eq!([ci(2), ci(4), ci(99)], [4, 4, 4], "inside a character or past the end: all of them");
}
+27 -3
View File
@@ -92,6 +92,10 @@ pub struct Face {
pub italic: bool,
pub bytes: FontBytes,
pub index: u32,
/// 0 for a built-in or installed face; else the order it was loaded in with `text.loadFont`
/// ([`FontDb::add_loaded`]). A loaded face wins over any other of its family and style, the
/// latest load over earlier ones (#2092).
pub loaded: u32,
pub upem: f64,
/// Ascent and descent in font units, both positive.
pub ascent: f64,
@@ -207,6 +211,7 @@ impl Face {
family,
style,
index,
loaded: 0,
upem,
ascent,
descent,
@@ -620,6 +625,8 @@ pub struct FontDb {
loaded_files: std::collections::BTreeSet<(std::path::PathBuf, u32)>,
/// Font files added as bytes (hash and length → families), so loading one again adds nothing.
loaded_bytes: std::collections::HashMap<(u64, usize), Vec<String>>,
/// Loads so far ([`Face::loaded`]).
load_seq: u32,
system_scanned: bool,
/// Browser fonts text asked for and not yet taken by the browser layer.
wanted: Vec<usize>,
@@ -716,8 +723,20 @@ impl FontDb {
face
}
/// [`add`](Self::add) a face loaded explicitly (`text.loadFont`): it wins over the other faces
/// of its family and style, and over those loaded before it.
pub fn add_loaded(&mut self, mut face: Face) -> Arc<Face> {
self.load_seq += 1;
face.loaded = self.load_seq;
self.add(face)
}
/// Add font file bytes (all faces of a collection). Returns the faces added.
pub fn add_bytes(&mut self, bytes: Vec<u8>) -> Vec<Arc<Face>> {
self.add_bytes_with(bytes, false)
}
fn add_bytes_with(&mut self, bytes: Vec<u8>, loaded: bool) -> Vec<Arc<Face>> {
let shared = Arc::new(bytes);
let count = match FileRef::new(shared.as_slice()) {
// A collection's header may name any number of faces, each a few bytes pointing at
@@ -727,7 +746,10 @@ impl FontDb {
Ok(FileRef::Font(_)) => 1,
Err(_) => 0,
};
(0..count).filter_map(|i| Face::from_bytes(FontBytes::Shared(shared.clone()), i, None, None)).map(|f| self.add(f)).collect()
(0..count)
.filter_map(|i| Face::from_bytes(FontBytes::Shared(shared.clone()), i, None, None))
.map(|f| if loaded { self.add_loaded(f) } else { self.add(f) })
.collect()
}
/// The family and style of the face whose PostScript name is `ps` (ignoring case), loaded or
@@ -1035,7 +1057,9 @@ impl FontDb {
/// The loaded face of `family` nearest `style`.
fn best(&self, family: &str, style: &str) -> Option<Arc<Face>> {
let (_, idx) = self.families.get(&self.key(family))?;
let faces: Vec<&Arc<Face>> = idx.iter().filter_map(|i| self.faces.get(*i)).collect();
let mut faces: Vec<&Arc<Face>> = idx.iter().filter_map(|i| self.faces.get(*i)).collect();
// A loaded font comes first (the latest load first): of faces as near, the first wins.
faces.sort_by_key(|f| std::cmp::Reverse(f.loaded));
let want = norm_style(style);
if let Some(f) = faces.iter().find(|f| norm_style(&f.style) == want).or_else(|| faces.iter().find(|f| has_style(f, style))) {
return Some((*f).clone());
@@ -1595,7 +1619,7 @@ pub fn load_font_bytes(bytes: Vec<u8>) -> Vec<String> {
if let Some(families) = db.loaded_bytes.get(&key) {
return families.clone();
}
let faces = db.add_bytes(bytes);
let faces = db.add_bytes_with(bytes, true);
let mut families: Vec<String> = faces.iter().map(|f| f.family.clone()).collect();
families.dedup();
if !families.is_empty() {
+39
View File
@@ -382,6 +382,45 @@ fn font_bytes_load_into_the_db() {
}
}
/// #2092: a font loaded with `text.loadFont` wins over the built-in and installed faces of its family
/// and style, the latest load over earlier ones; other styles resolve as before.
#[test]
fn a_loaded_face_wins_over_the_built_in_one_of_its_family_and_style() {
// Any embedded or installed font stands in for the faces (none without craft-fonts on CI).
let stand_in = CRAFT_FONTS.first().map(|f| f.bytes.to_vec()).or_else(|| {
let mut installed = BTreeMap::new();
for dir in system_font_dirs() {
scan_dir(&dir, 0, &mut installed);
}
installed.values().flat_map(|(_, v)| v).find_map(|p| std::fs::read(&p.path).ok())
});
let Some(bytes) = stand_in.map(Arc::new) else {
eprintln!("skipping: no font to stand in");
return;
};
let face = |style: &str, name: &str| {
let mut f = Face::from_bytes(FontBytes::Shared(bytes.clone()), 0, Some("Brand Sans"), Some(style)).unwrap();
f.instances.clear();
f.postscript = Some(name.into());
f
};
let name = |db: &FontDb, style: &str| db.best("Brand Sans", style).and_then(|f| f.postscript.clone());
let mut db = FontDb::default();
db.add(face("Regular", "Built-in-Regular"));
db.add(face("Bold", "Built-in-Bold"));
assert_eq!(name(&db, "Regular").as_deref(), Some("Built-in-Regular"));
db.add_loaded(face("Regular", "Loaded-Regular"));
assert_eq!(name(&db, "Regular").as_deref(), Some("Loaded-Regular"));
// Bold wasn't loaded: the built-in one stays. Nor does the loaded Regular stand in for it.
assert_eq!(name(&db, "Bold").as_deref(), Some("Built-in-Bold"));
// The latest load wins.
db.add_loaded(face("Regular", "Loaded-Regular-2"));
assert_eq!(name(&db, "Regular").as_deref(), Some("Loaded-Regular-2"));
// A face added after a load, not loaded, doesn't displace it.
db.add(face("Regular", "Installed-Regular"));
assert_eq!(name(&db, "Regular").as_deref(), Some("Loaded-Regular-2"));
}
/// Apple's system font answers to the names designs and CSS use for it (SF Pro, SF UI Text,
/// system-ui, …), unless a font of that name is installed.
#[test]
+10 -2
View File
@@ -93,8 +93,16 @@ fn list_numbering_by_level() {
vec!["\u{2022}", "\u{2022}", "\u{2022}", "\u{2022}"],
"bullets keep the same styling at all levels of indentation",
),
(vec![pl(N, 0), pl(N, 0), pl(P, 0), pl(N, 0)], vec!["1.", "2.", "", "1."], "silent: a plain paragraph ends a list, the next starts at 1"),
(vec![pl(N, 0), pl(B, 0), pl(N, 0)], vec!["1.", "\u{2022}", "1."], "silent: the other kind of list at the same level starts the count again"),
(
vec![pl(N, 0), pl(N, 0), pl(P, 0), pl(N, 0)],
vec!["1.", "2.", "", "1."],
"as measured in Figma (2026-11-11): a plain paragraph ends a list, the next starts at 1",
),
(
vec![pl(N, 0), pl(B, 0), pl(N, 0)],
vec!["1.", "\u{2022}", "1."],
"as measured in Figma (2026-11-11): a bullet item between numbered ones starts the count again",
),
(vec![pl(N, 0), pl(N, 1), pl(N, 0), pl(N, 1)], vec!["1.", "a.", "2.", "a."], "a shallower item starts the deeper count again"),
(vec![pl(N, 2), pl(N, 2), pl(N, 2), pl(N, 2)], vec!["i.", "ii.", "iii.", "iv."], "roman numerals at the third level"),
];
+2 -1
View File
@@ -1496,7 +1496,7 @@ status = "draft — needs native review"
"Text styles" = "أنماط النص"
"Texts" = "النصوص"
"Texture" = "النسيج"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "تُعاين الألوان على لوحة الرسم بفضاء sRGB؛ وتُوسم ملفات PNG وJPG وWebP المصدّرة بملف Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "تُعاين الألوان على لوحة الرسم بفضاء sRGB؛ وملفات PNG وJPG وWebP المصدّرة بملف تعريف الألوان الخاص بالملف تُوسم بملف Display P3."
"The destination document is unavailable. Nothing was imported." = "المستند الوجهة غير متاح. لم يُستورد شيء."
"The destination document was closed. Nothing was imported." = "أُغلق المستند الوجهة. لم يُستورد شيء."
"The destination page was removed. Nothing was imported." = "أُزيلت الصفحة الوجهة. لم يُستورد شيء."
@@ -2009,6 +2009,7 @@ status = "draft — needs native review"
"component.combineVariants" = "جمع كتنويعات"
"component.create" = "إنشاء مكوّن"
"component.createMultiple" = "إنشاء مكونات متعددة"
"component.createSet" = "إنشاء مجموعة مكونات"
"component.deleteProperty" = "حذف خاصية المكوّن"
"component.detach" = "فصل النسخة المثيلة"
"component.editProperty" = "تحرير خاصية المكوّن"
+1 -1
View File
@@ -1453,7 +1453,7 @@ status = "draft — needs native review"
"Text styles" = "টেক্সট স্টাইলসমূহ"
"Texts" = "টেক্সটসমূহ"
"Texture" = "টেক্সচার"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "ক্যানভাস sRGB-তে রঙ প্রিভিউ করে; এক্সপোর্ট করা PNG, JPG এবং WebP ফাইলে Display P3 ট্যাগ করা থাকে।"
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "ক্যানভাস sRGB-তে রঙ প্রিভিউ করে; ফাইলের প্রোফাইল দিয়ে এক্সপোর্ট করা PNG, JPG এবং WebP ফাইলে Display P3 ট্যাগ করা থাকে।"
"The destination document is unavailable. Nothing was imported." = "গন্তব্য ডকুমেন্ট অনুপলব্ধ। কিছু ইম্পোর্ট করা হয়নি।"
"The destination document was closed. Nothing was imported." = "গন্তব্য ডকুমেন্ট বন্ধ করা হয়েছিল। কিছু ইম্পোর্ট করা হয়নি।"
"The destination page was removed. Nothing was imported." = "গন্তব্য পেজ সরানো হয়েছে। কিছু ইম্পোর্ট করা হয়নি।"
+2 -1
View File
@@ -1508,7 +1508,7 @@ status = "draft — needs native review"
"Text styles" = "Stilovi teksta"
"Texts" = "Tekstovi"
"Texture" = "Tekstura"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Platno prikazuje boje u sRGB-u; izvezene PNG, JPG i WebP datoteke su označene kao Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Platno prikazuje boje u sRGB-u; PNG, JPG i WebP datoteke izvezene s profilom datoteke su označene kao Display P3."
"The destination document is unavailable. Nothing was imported." = "Odredišni dokument nije dostupan. Ništa nije uvezeno."
"The destination document was closed. Nothing was imported." = "Odredišni dokument je zatvoren. Ništa nije uvezeno."
"The destination page was removed. Nothing was imported." = "Odredišna stranica je uklonjena. Ništa nije uvezeno."
@@ -2038,6 +2038,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Kombinuj kao varijante"
"component.create" = "Kreiraj komponentu"
"component.createMultiple" = "Kreiraj više komponenti"
"component.createSet" = "Kreiraj skup komponenti"
"component.deleteProperty" = "Izbriši svojstvo komponente"
"component.detach" = "Odvoji instancu"
"component.editProperty" = "Uredi svojstvo komponente"
+2 -1
View File
@@ -1428,7 +1428,7 @@ status = "draft — needs native review"
"Text styles" = "Textové styly"
"Texts" = "Texty"
"Texture" = "Textura"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Plátno zobrazuje barvy v sRGB; exportované soubory PNG, JPG a WebP mají profil Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Plátno zobrazuje barvy v sRGB; soubory PNG, JPG a WebP exportované s profilem souboru mají profil Display P3."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "Soubor se smaže ze serveru: nikdo ho odtud již neotevře ani se k němu nepřipojí a tuto akci nelze vrátit zpět. Otevřené kopie zůstanou těm, kteří je mají."
"The file now holds another library" = "Soubor nyní obsahuje jinou knihovnu"
"The file now holds another library (\"{name}\")" = "Soubor nyní obsahuje jinou knihovnu („{name}“)"
@@ -1913,6 +1913,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Sloučit jako varianty"
"component.create" = "Vytvořit komponentu"
"component.createMultiple" = "Vytvořit více komponent"
"component.createSet" = "Vytvořit sadu komponent"
"component.deleteProperty" = "Smazat vlastnost komponenty"
"component.detach" = "Odpojit instanci"
"component.editProperty" = "Upravit vlastnost komponenty"
+2 -1
View File
@@ -1398,7 +1398,7 @@ status = "draft — needs native review"
"Text styles" = "Textstile"
"Texts" = "Texte"
"Texture" = "Textur"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Die Arbeitsfläche zeigt Farben in sRGB an; exportierte PNG-, JPG- und WebP-Dateien werden als Display P3 gekennzeichnet."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Die Arbeitsfläche zeigt Farben in sRGB an; PNG-, JPG- und WebP-Exporte mit dem Profil der Datei werden als Display P3 gekennzeichnet."
"The destination document is unavailable. Nothing was imported." = "Das Zieldokument ist nicht verfügbar. Es wurde nichts importiert."
"The destination document was closed. Nothing was imported." = "Das Zieldokument wurde geschlossen. Es wurde nichts importiert."
"The destination page was removed. Nothing was imported." = "Die Zielseite wurde entfernt. Es wurde nichts importiert."
@@ -2079,6 +2079,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Als Varianten kombinieren"
"component.create" = "Komponente erstellen"
"component.createMultiple" = "Mehrere Komponenten erstellen"
"component.createSet" = "Komponentensatz erstellen"
"component.deleteProperty" = "Komponenteneigenschaft löschen"
"component.detach" = "Instanz lösen"
"component.editProperty" = "Komponenteneigenschaft bearbeiten"
+1 -1
View File
@@ -1577,7 +1577,7 @@ name = "English"
"Text styles" = "Text styles"
"Texts" = "Texts"
"Texture" = "Texture"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3."
"The destination document is unavailable. Nothing was imported." = "The destination document is unavailable. Nothing was imported."
"The destination document was closed. Nothing was imported." = "The destination document was closed. Nothing was imported."
"The destination page was removed. Nothing was imported." = "The destination page was removed. Nothing was imported."
+2 -1
View File
@@ -1491,7 +1491,7 @@ status = "draft — needs native review"
"Text styles" = "Estilos de texto"
"Texts" = "Textos"
"Texture" = "Textura"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "El lienzo muestra los colores en sRGB; los archivos PNG, JPG y WebP exportados se etiquetan como Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "El lienzo muestra los colores en sRGB; los archivos PNG, JPG y WebP exportados con el perfil del archivo se etiquetan como Display P3."
"The destination document is unavailable. Nothing was imported." = "El documento de destino no está disponible. No se importó nada."
"The destination document was closed. Nothing was imported." = "Se cerró el documento de destino. No se importó nada."
"The destination page was removed. Nothing was imported." = "Se eliminó la página de destino. No se importó nada."
@@ -2002,6 +2002,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combinar como variantes"
"component.create" = "Crear componente"
"component.createMultiple" = "Crear varios componentes"
"component.createSet" = "Crear conjunto de componentes"
"component.deleteProperty" = "Eliminar propiedad de componente"
"component.detach" = "Separar instancia"
"component.editProperty" = "Editar propiedad de componente"
+53 -2
View File
@@ -126,6 +126,7 @@ status = "draft — needs native review"
"Another server, or one that needs its key. The usual server is set in Preferences." = "Toinen palvelin tai avainta tarvitseva palvelin. Tavallinen palvelin asetetaan asetuksissa."
"Any status" = "Kaikki tilat"
"Anyone on your network with this code can edit the file, while this app stays open." = "Kuka tahansa lähiverkossasi voi muokata tiedostoa tällä koodilla niin kauan kuin sovellus on auki."
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Kuka tahansa verkossasi oleva voi tällä koodilla katsoa tiedostoa muttei muuttaa sitä, niin kauan kuin tämä sovellus on auki."
"Anyone with the edit link can change the file; the view link only lets people look. The links carry their secrets: share them like passwords. `figcraft-server links` makes more and revokes them." = "Kuka tahansa muokkauslinkin saanut voi muuttaa tiedostoa. Katselulinkillä voi vain katsella. Linkit sisältävät salaiset tunnisteet: jaa niitä kuin salasanoja. `figcraft-server links` luo lisää linkkejä ja peruu niitä."
"Anyone with this code can edit the file." = "Kuka tahansa tämän koodin saanut voi muokata tiedostoa."
"Anyone with this code can look at the file, not change it." = "Kuka tahansa tämän koodin saanut voi katsella tiedostoa, mutta ei muuttaa sitä."
@@ -160,6 +161,7 @@ status = "draft — needs native review"
"Auto layout" = "Automaattinen asettelu"
"Auto rows" = "Automaattiset rivit"
"Auto width" = "Automaattinen leveys"
"Auto: by the first letter with a direction" = "Automaattinen: ensimmäisen suunnallisen kirjaimen mukaan"
"Back" = "Takaisin"
"Back to Ready for dev" = "Palauta kehitysvalmiiksi"
"Back to Ready for dev: the next change compares with how it is now" = "Palauta kehitysvalmiiksi: seuraavaa muutosta verrataan nykyiseen tilaan"
@@ -224,6 +226,7 @@ status = "draft — needs native review"
"Changed {date}" = "Muutettu {date}"
"CMYK colour" = "CMYK-väri"
"CSS custom properties…" = "CSS:n mukautetut ominaisuudet…"
"Ctrl+click a padding field" = "Ctrl+napsauta sisämarginaalikenttää"
"Dart constants for Flutter…" = "Dart-vakiot Flutterille…"
"Calculated from other variables; it follows them" = "Lasketaan muista muuttujista ja seuraa niitä"
"Can edit" = "Voi muokata"
@@ -419,6 +422,7 @@ status = "draft — needs native review"
"Delete the style (layers keep their values)" = "Poista tyyli (tasojen arvot säilyvät)"
"Delete thread" = "Poista keskustelu"
"Delete variable" = "Poista muuttuja"
"Delete {n} variables" = { one = "Poista {n} muuttuja", other = "Poista {n} muuttujaa" }
"Delete “{name}”? This can't be undone." = "Poistetaanko ”{name}”? Tätä ei voi kumota."
"Density" = "Tiheys"
"Depth" = "Syvyys"
@@ -450,6 +454,9 @@ status = "draft — needs native review"
"Dimensions" = "Mitat"
"Direction" = "Suunta"
"Disconnect from code" = "Katkaise yhteys koodiin"
"Disconnected. Reconnecting…" = "Yhteys katkesi. Yhdistetään uudelleen…"
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Yhteys katkesi. Muokkauksesi säilyvät täällä ja synkronoituvat, kun yhteys palaa. Yhdistetään uudelleen…"
"Dismiss" = "Ohita"
"Dispersion" = "Hajonta"
"Display name" = "Näyttönimi"
"Dissolve" = "Häivytys"
@@ -489,6 +496,7 @@ status = "draft — needs native review"
"Edit dev resource" = "Muokkaa kehittäjäresurssia"
"Edit link" = "Muokkaa linkkiä"
"Edit link copied" = "Muokkauslinkki kopioitu"
"Edit padding on all sides" = "Muokkaa sisämarginaalia kaikilta sivuilta"
"Edit style" = "Muokkaa tyyliä"
"Edit variable" = "Muokkaa muuttujaa"
"Edit with the builder" = "Muokkaa rakentimella"
@@ -509,6 +517,7 @@ status = "draft — needs native review"
"End vote" = "Lopeta äänestys"
"Ends the session; everyone keeps their copy" = "Lopettaa istunnon. Kaikki säilyttävät oman kopionsa."
"Enter" = "Enter"
"Enter / Shift+Enter" = "Enter / Shift+Enter"
"Enter the address of a figcraft-server and press Browse to see the plugins it offers." = "Anna figcraft-server-palvelimen osoite ja näytä sen tarjoamat liitännäiset painamalla Selaa."
"Enter to save · Esc to cancel" = "Tallenna Enterillä · peruuta Escillä"
"Eraser" = "Pyyhekumi"
@@ -784,6 +793,7 @@ status = "draft — needs native review"
"Left padding" = "Vasen sisämarginaali"
"Left side" = "Vasen puoli"
"Left side width" = "Vasemman puolen leveys"
"Left to right" = "Vasemmalta oikealle"
"Letter case" = "Kirjainkoko"
"Letter spacing" = "Merkkiväli"
"Libraries" = "Kirjastot"
@@ -829,13 +839,36 @@ status = "draft — needs native review"
"Main menu" = "Päävalikko"
"Make a component" = "Luo komponentti"
"Make slot" = "Luo sisältöpaikka"
"Move out of any group" = "Siirrä pois kaikista ryhmistä"
"Move to group {group}" = "Siirrä ryhmään {group}"
"Move up or down while dragging its label" = "Siirrä ylös tai alas vetämällä sen otsikkoa"
"Nobody shares a file there now." = "Kukaan ei jaa siellä nyt tiedostoa."
"New collection" = "Uusi kokoelma"
"Not connected: {reason}. Your work is still in this tab." = "Ei yhteyttä: {reason}. Työsi on yhä tässä välilehdessä."
"Nothing to pick: the page is empty" = "Ei mitään poimittavaa: sivu on tyhjä"
"Pasted design layers" = "Liitetyt suunnittelutasot"
"Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Suunnittelutasot liitetty; leikepöydällä ei ollut näiden kuvia: {layers}"
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Poimintavalinta: Tab ja Shift+Tab siirtävät tasojen välillä, Enter siirtyy tason sisään, Shift+Enter ulos, välilyönti valitsee, Escape peruuttaa"
"Pick select: into a layer, out to its parent" = "Poimintavalinta: tason sisään, ulos sen ylätasoon"
"Pick select: next or previous layer" = "Poimintavalinta: seuraava tai edellinen taso"
"Pick select: select the picked layer" = "Poimintavalinta: valitse poimittu taso"
"Remove these results from the file" = "Poista nämä tulokset tiedostosta"
"Retry now" = "Yritä nyt uudelleen"
"Right to left" = "Oikealta vasemmalle"
"Same as file ({profile})" = "Sama kuin tiedostossa ({profile})"
"Save a copy…" = "Tallenna kopio…"
"Scope: all supported properties" = "Käyttöalue: kaikki tuetut ominaisuudet"
"Scope: hidden from pickers" = "Käyttöalue: piilotettu valitsimista"
"Scope: only {scope}" = "Käyttöalue: vain {scope}"
"Scroll wheel zoom" = "Zoomaus hiiren rullalla"
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Säädä kenttää vetämällä nopeammin (2x) tai hitaammin (1/2, 1/4)"
"Scrubbing at 1/2" = "Vetosäätö nopeudella 1/2"
"Scrubbing at 1/4" = "Vetosäätö nopeudella 1/4"
"Scrubbing at 1x" = "Vetosäätö nopeudella 1x"
"Scrubbing at 2x" = "Vetosäätö nopeudella 2x"
"Selection box: switch to pick select" = "Valintalaatikko: vaihda poimintavalintaan"
"Shared by your team on {server}" = "Tiimisi jakama palvelimella {server}"
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Näytä ja siirrä sijoitusristikkoa (sen työkalu valittuna, ei valintaa)"
"Slot name" = "Sisältöpaikan nimi"
"Mar" = "maalisk."
"Margin" = "Marginaali"
@@ -977,7 +1010,10 @@ status = "draft — needs native review"
"Check for updates…" = "Tarkista päivitykset…"
"Not checked yet" = "Ei vielä tarkistettu"
"Someone who left" = "Joku, joka lähti"
"Space" = "Välilyönti"
"Tab or Ctrl+Space again" = "Tab tai Ctrl+välilyönti uudelleen"
"Take the results off the board; they stay in the file" = "Poista tulokset taululta; ne jäävät tiedostoon"
"Text direction" = "Tekstin suunta"
"This file uses team libraries on servers you haven't used here. They aren't contacted until you check them." = "Tämä tiedosto käyttää tiimikirjastoja palvelimilla, joita et ole käyttänyt täällä. Niihin ei oteta yhteyttä ennen kuin tarkistat ne."
"Not shared" = "Ei jaettu"
"Note {n}" = "Huomautus {n}"
@@ -1522,7 +1558,7 @@ status = "draft — needs native review"
"Text styles" = "Tekstityylit"
"Texts" = "Tekstit"
"Texture" = "Tekstuuri"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Piirtoalue esikatselee värit sRGB-muodossa. Vietäviin PNG-, JPG- ja WebP-tiedostoihin merkitään Display P3 -profiili."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Piirtoalue esikatselee värit sRGB-muodossa. Tiedoston profiililla vietäviin PNG-, JPG- ja WebP-tiedostoihin merkitään Display P3 -profiili."
"The destination document is unavailable. Nothing was imported." = "Kohdeasiakirja ei ole käytettävissä. Mitään ei tuotu."
"The destination document was closed. Nothing was imported." = "Kohdeasiakirja suljettiin. Mitään ei tuotu."
"The destination page was removed. Nothing was imported." = "Kohdesivu poistettiin. Mitään ei tuotu."
@@ -1886,6 +1922,7 @@ status = "draft — needs native review"
"{name} · published version {v}" = "{name} · julkaistu versio {v}"
"{name} · version {v} on the server" = "{name} · versio {v} palvelimella"
"{name} ×{n}" = "{name} ×{n}"
"{name}, disconnected from its live session" = "{name}, irrotettu live-istunnostaan"
"{name}, in a live session" = "{name}, reaaliaikaisessa istunnossa"
"{name}, online, open only to you" = "{name}, verkossa, vain sinun käytössäsi"
"{name}, {kind}, {w} by {h}, selected" = "{name}, {kind}, {w} × {h}, valittu"
@@ -1944,9 +1981,12 @@ status = "draft — needs native review"
"← → ↑ ↓" = "← → ↑ ↓"
"→, Space or N" = "→, Space or N"
"↵" = "↵"
"↵ / ⇧↵" = "↵ / ⇧↵"
"⇥ / ⇧⇥" = "⇥ / ⇧⇥"
"⇥ or ⌥ Space again" = "⇥ tai ⌥ välilyönti uudelleen"
"⌘ arrows" = "⌘ arrows"
"⌘ click" = "⌘ click"
"⌘ click a padding field" = "⌘-napsauta sisämarginaalikenttää"
"⌘ scroll" = "⌘ scroll"
"⌥ drag" = "⌥ drag"
"1 year" = "1 vuosi"
@@ -1968,7 +2008,7 @@ status = "draft — needs native review"
"Hide UI" = "Piilota käyttöliittymä"
"Past 30 days" = "Viimeiset 30 päivää"
"Past 90 days" = "Viimeiset 90 päivää"
"Past year" = "Viimeinen vuosi"
"Past year" = "Viimeiset 12 kuukautta"
"Nothing counted yet" = "Mitään ei ole vielä laskettu"
"Rotate a degree (Shift: 15)" = "Kierrä asteen verran (Shift: 15)"
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
@@ -2057,6 +2097,7 @@ status = "draft — needs native review"
"collab.openFile" = "Avaa verkkotiedosto"
"collab.peers" = "Tämän tiedoston käyttäjät"
"collab.publish" = "Julkaise palvelimelle"
"collab.reconnect" = "Yhdistä live-istuntoon uudelleen"
"collab.recoverFile" = "Palauta verkkotiedosto"
"collab.registerLinks" = "Avaa kutsulinkit FigCraftissa"
"collab.removePerson" = "Poista istunnosta"
@@ -2086,6 +2127,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Yhdistä varianteiksi"
"component.create" = "Luo komponentti"
"component.createMultiple" = "Luo useita komponentteja"
"component.createSet" = "Luo komponenttijoukko"
"component.deleteProperty" = "Poista komponentin ominaisuus"
"component.detach" = "Irrota ilmentymä"
"component.editProperty" = "Muokkaa komponentin ominaisuutta"
@@ -2348,6 +2390,7 @@ status = "draft — needs native review"
"selection.applyColorStyle" = "Käytä valinnan värityyliä"
"selection.bindColorVariable" = "Käytä valinnan värimuuttujaa"
"selection.colors" = "Valinnan värit"
"selection.createColorStyle" = "Luo valinnan värityyli"
"selection.detachColor" = "Irrota valinnan väri"
"selection.selectColor" = "Valitse tämänväriset tasot"
"selection.setPaint" = "Muuta valinnan väriä"
@@ -2392,6 +2435,10 @@ status = "draft — needs native review"
"text.caseUpper" = "Isot kirjaimet"
"text.create" = "Teksti"
"text.decoration" = "Koristelu"
"text.direction" = "Tekstin suunta"
"text.directionAuto" = "Tekstin suunta: automaattinen"
"text.directionLtr" = "Tekstin suunta: vasemmalta oikealle"
"text.directionRtl" = "Tekstin suunta: oikealta vasemmalle"
"text.edit.begin" = "Muokkaa tekstiä"
"text.edit.caret" = "Aseta kohdistin"
"text.edit.end" = "Lopeta tekstin muokkaus"
@@ -2437,6 +2484,7 @@ status = "draft — needs native review"
"tool.arrow" = "Nuoli"
"tool.comment" = "Kommentti"
"tool.connector" = "Yhdistin"
"tool.crosshair" = "Siirrä sijoitusristikkoa"
"tool.ellipse" = "Ellipsi"
"tool.eraser" = "Pyyhekumi"
"tool.frame" = "Kehys"
@@ -2647,6 +2695,9 @@ status = "draft — needs native review"
"text.alignJustify" = "Tasaa tekstin molemmat reunat"
"text.alignLeft" = "Tasaa teksti vasemmalle"
"text.alignRight" = "Tasaa teksti oikealle"
"text.directionAuto" = "Automaattinen"
"text.directionLtr" = "Vasemmalta oikealle"
"text.directionRtl" = "Oikealta vasemmalle"
"view.assets" = "Resurssit"
"view.design" = "Suunnittelu"
"view.layers" = "Tasot"
+2 -1
View File
@@ -1457,7 +1457,7 @@ status = "draft — needs native review"
"Text styles" = "Styles de texte"
"Texts" = "Textes"
"Texture" = "Texture"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Le canevas affiche les couleurs en sRGB ; les fichiers PNG, JPG et WebP exportés sont balisés Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Le canevas affiche les couleurs en sRGB ; les fichiers PNG, JPG et WebP exportés avec le profil du fichier sont balisés Display P3."
"The destination document is unavailable. Nothing was imported." = "Le document de destination est indisponible. Rien n’a été importé."
"The destination document was closed. Nothing was imported." = "Le document de destination a été fermé. Rien n’a été importé."
"The destination page was removed. Nothing was imported." = "La page de destination a été supprimée. Rien n’a été importé."
@@ -1958,6 +1958,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combiner en variantes"
"component.create" = "Créer un composant"
"component.createMultiple" = "Créer plusieurs composants"
"component.createSet" = "Créer un ensemble de composants"
"component.deleteProperty" = "Supprimer la propriété de composant"
"component.detach" = "Détacher l’instance"
"component.editProperty" = "Modifier la propriété de composant"
+2 -1
View File
@@ -1434,7 +1434,7 @@ status = "draft — needs native review"
"Text styles" = "Gaya teks"
"Texts" = "Teks"
"Texture" = "Tekstur"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Kanvas mempratinjau warna dalam sRGB; file PNG, JPG, dan WebP yang diekspor ditandai Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Kanvas mempratinjau warna dalam sRGB; file PNG, JPG, dan WebP yang diekspor dengan profil file ditandai Display P3."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "File dihapus dari server: tidak ada yang dapat membuka atau bergabung ke file itu dari sana lagi, dan tindakan ini tidak dapat diurungkan. Salinan yang sedang terbuka tetap ada pada pemiliknya."
"The file now holds another library" = "File kini berisi pustaka lain"
"The file now holds another library (\"{name}\")" = "File kini berisi pustaka lain (\"{name}\")"
@@ -1917,6 +1917,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Gabungkan sebagai variant"
"component.create" = "Buat component"
"component.createMultiple" = "Buat beberapa component"
"component.createSet" = "Buat set component"
"component.deleteProperty" = "Hapus properti component"
"component.detach" = "Lepaskan instance"
"component.editProperty" = "Edit properti component"
+2 -1
View File
@@ -1389,7 +1389,7 @@ status = "draft — needs native review"
"Text styles" = "Stili di testo"
"Texts" = "Testi"
"Texture" = "Texture"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Il canvas mostra i colori in sRGB; i file PNG, JPG e WebP esportati sono contrassegnati come Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Il canvas mostra i colori in sRGB; i file PNG, JPG e WebP esportati con il profilo del file sono contrassegnati come Display P3."
"The destination document is unavailable. Nothing was imported." = "Il documento di destinazione non è disponibile. Non è stato importato nulla."
"The destination document was closed. Nothing was imported." = "Il documento di destinazione è stato chiuso. Non è stato importato nulla."
"The destination page was removed. Nothing was imported." = "La pagina di destinazione è stata rimossa. Non è stato importato nulla."
@@ -1861,6 +1861,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combina come varianti"
"component.create" = "Crea componente"
"component.createMultiple" = "Crea più componenti"
"component.createSet" = "Crea set di componenti"
"component.deleteProperty" = "Elimina proprietà del componente"
"component.detach" = "Scollega istanza"
"component.editProperty" = "Modifica proprietà del componente"
+2 -1
View File
@@ -1444,7 +1444,7 @@ status = "draft — needs native review"
"Text styles" = "テキストスタイル"
"Texts" = "テキスト"
"Texture" = "テクスチャ"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "キャンバスは sRGB で色をプレビュー。書き出した PNG、JPG、WebP ファイルには Display P3 のタグが付く。"
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "キャンバスは sRGB で色をプレビュー。ファイルのプロファイルで書き出した PNG、JPG、WebP ファイルには Display P3 のタグが付く。"
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "ファイルはサーバーから削除される:サーバーから開いたり参加したりすることは誰にもできなくなり、元に戻せない。開いているコピーは各自の手元に残る。"
"The file now holds another library" = "このファイルは別のライブラリになっている"
"The file now holds another library (\"{name}\")" = "このファイルは別のライブラリ(「{name}」)になっている"
@@ -1938,6 +1938,7 @@ status = "draft — needs native review"
"component.combineVariants" = "バリアントとして結合"
"component.create" = "コンポーネントを作成"
"component.createMultiple" = "複数のコンポーネントを作成"
"component.createSet" = "コンポーネントセットを作成"
"component.deleteProperty" = "コンポーネントプロパティを削除"
"component.detach" = "インスタンスを切り離す"
"component.editProperty" = "コンポーネントプロパティを編集"
+128 -1
View File
@@ -16,7 +16,10 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"({n} warnings: some entries were skipped)" = { one = "(გაფრთხილება: {n}; ზოგი ჩანაწერი გამოტოვებულია)", other = "(გაფრთხილება: {n}; ზოგი ჩანაწერი გამოტოვებულია)" }
"+ Create variable" = "+ ცვლადის შექმნა"
".fig (experimental)" = ".fig (ექსპერიმენტული)"
"1 year" = "1 წელი"
"1…9, 0" = "1…9, 0"
"30 days" = "30 დღე"
"90 days" = "90 დღე"
"@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" = "@{login}: PR: {prs}, კომიტი: {commits}, +{added} / −{deleted} სტრიქონი (Δ {delta}), +{bin_added} / −{bin_deleted} ბინარული რესურსი, {first} – {last}"
"A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "ამ ფაილის კოლექცია ამ რეჟიმებითა და ცვლადებით: შეცვალეთ მათი მნიშვნელობები თითოეული რეჟიმისთვის და დაამატეთ საკუთარი ცვლადები"
"A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "ამ სახელით .figcraft ფაილი უკვე არსებობს. ჩანაცვლების დასადასტურებლად აირჩიეთ მისი სრული სახელი."
@@ -105,6 +108,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"All supported properties" = "ყველა მხარდაჭერილი თვისება"
"All the fonts this file uses are installed" = "ამ ფაილის ყველა შრიფტი დაინსტალირებულია"
"All variables" = "ყველა ცვლადი"
"Allow and download" = "დაშვება და ჩამოტვირთვა"
"Allow downloading fonts?" = "დაიშვას შრიფტების ჩამოტვირთვა?"
"Along the bottom" = "ქვედა კიდის გასწვრივ"
"Along the left" = "მარცხენა კიდის გასწვრივ"
"Along the right" = "მარჯვენა კიდის გასწვრივ"
@@ -124,6 +129,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Another server, or one that needs its key. The usual server is set in Preferences." = "სხვა სერვერი ან სერვერი, რომელსაც გასაღები სჭირდება. ჩვეულებრივი სერვერი პარამეტრებში ირჩევა."
"Any status" = "ნებისმიერი სტატუსი"
"Anyone on your network with this code can edit the file, while this app stays open." = "თქვენს ქსელში ნებისმიერს, ვისაც ეს კოდი აქვს, შეუძლია ფაილის რედაქტირება, სანამ ეს აპი ღიაა."
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "თქვენს ქსელში ნებისმიერს, ვისაც ეს კოდი აქვს, შეუძლია ფაილის ნახვა, მაგრამ არა შეცვლა, სანამ ეს აპი ღიაა."
"Anyone with the edit link can change the file; the view link only lets people look. The links carry their secrets: share them like passwords. `figcraft-server links` makes more and revokes them." = "რედაქტირების ბმულის მქონე ნებისმიერს შეუძლია ფაილის შეცვლა; ნახვის ბმული მხოლოდ დათვალიერების საშუალებას იძლევა. ბმულები საიდუმლო გასაღებებს შეიცავს: გააზიარეთ ისინი პაროლების მსგავსად. `figcraft-server links` ქმნის ახალ ბმულებს და აუქმებს მათ."
"Anyone with this code can edit the file." = "ნებისმიერს, ვისაც ეს კოდი აქვს, შეუძლია ფაილის რედაქტირება."
"Anyone with this code can look at the file, not change it." = "ნებისმიერს, ვისაც ეს კოდი აქვს, შეუძლია ფაილის ნახვა, მაგრამ არა შეცვლა."
@@ -186,6 +192,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Blend mode" = "შერევის რეჟიმი"
"Blue" = "ლურჯი"
"Blur" = "გაბუნდოვნება"
"Board grid" = "დაფის ბადე"
"Boolean" = "ლოგიკური"
"Boolean groups" = "ლოგიკური ოპერაციების ჯგუფები"
"Both directions" = "ორივე მიმართულება"
@@ -217,6 +224,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Bulleted list" = "ბურთულებიანი სია"
"C or Shift+C" = "C ან Shift+C"
"C or ⇧C" = "C ან ⇧C"
"Changed {date}" = "შეცვლილია: {date}"
"CMYK colour" = "CMYK ფერი"
"Can view" = "შეუძლია ნახვა"
"Can comment" = "შეუძლია კომენტარი"
@@ -234,6 +242,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Connector" = "შემაერთებელი"
"Convert to frame" = "ჩარჩოდ გარდაქმნა"
"Convert to section" = "სექციად გარდაქმნა"
"Copy browser link" = "ბრაუზერის ბმულის კოპირება"
"Couldn't reach {server} for its team list." = "{server}-იდან გუნდის სიის მიღება ვერ მოხერხდა."
"CSS custom properties…" = "CSS-ის მორგებული თვისებები…"
"Can edit" = "შეუძლია რედაქტირება"
"Can't read this library: {e}" = "ამ ბიბლიოთეკის წაკითხვა ვერ მოხერხდა: {e}"
@@ -330,6 +340,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Copied as PNG" = "დაკოპირდა როგორც PNG"
"Copied as SVG" = "დაკოპირდა როგორც SVG"
"Copied as text" = "დაკოპირდა როგორც ტექსტი"
"Copied comments for AI" = "კომენტარები დაკოპირდა AI-სთვის"
"Copied {value}" = "დაკოპირდა: {value}"
"Copy" = "კოპირება"
"Copy as" = "კოპირება როგორც"
@@ -363,9 +374,12 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Create style from the selected text" = "სტილის შექმნა მონიშნული ტექსტიდან"
"Created" = "შექმნილია"
"Crop" = "ჩამოჭრა"
"Crop image" = "გამოსახულების ჩამოჭრა"
"Crop marks" = "ჭრის ნიშნები"
"Ctrl+arrows" = "Ctrl+ისრები"
"Ctrl+click" = "Ctrl+დაწკაპუნება"
"Ctrl+click a padding field" = "Ctrl+დაწკაპუნება შიდა დაშორების ველზე"
"⌘ click a padding field" = "⌘ დაწკაპუნება შიდა დაშორების ველზე"
"Ctrl+scroll" = "Ctrl+გადახვევა"
"Current name" = "მიმდინარე სახელი"
"Current version" = "მიმდინარე ვერსია"
@@ -385,12 +399,40 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Decoration style" = "გაფორმების სტილი"
"Decoration" = "გაფორმება"
"Deep select" = "ღრმა მონიშვნა"
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "ველის მნიშვნელობის გადათრევით ცვლა უფრო სწრაფად (2x) ან ნელა (1/2, 1/4)"
"Move up or down while dragging its label" = "ზემოთ ან ქვემოთ გადაადგილება მისი იარლიყის გადათრევისას"
"Scrubbing at 2x" = "გადათრევით ცვლა: 2x"
"Scrubbing at 1x" = "გადათრევით ცვლა: 1x"
"Scrubbing at 1/2" = "გადათრევით ცვლა: 1/2"
"Scrubbing at 1/4" = "გადათრევით ცვლა: 1/4"
"Delete {n} variables" = { one = "ცვლადის წაშლა: {n}", other = "ცვლადის წაშლა: {n}" }
"Move out of any group" = "ჯგუფიდან გამოტანა"
"Move to group {group}" = "ჯგუფში გადატანა: {group}"
"Scope: all supported properties" = "არე: ყველა მხარდაჭერილი თვისება"
"Scope: hidden from pickers" = "არე: ამომრჩევებში დამალული"
"Scope: only {scope}" = "არე: მხოლოდ {scope}"
"Disconnected. Reconnecting…" = "კავშირი გაწყდა. ხელახლა დაკავშირება…"
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "კავშირი გაწყდა. თქვენი ცვლილებები აქ რჩება და სინქრონიზდება, როცა კავშირი აღდგება. ხელახლა დაკავშირება…"
"Dismiss" = "უგულებელყოფა"
"Not connected: {reason}. Your work is still in this tab." = "კავშირი არ არის: {reason}. თქვენი ნამუშევარი ისევ ამ ჩანართშია."
"Retry now" = "ახლავე ხელახლა ცდა"
"Save a copy…" = "ასლის შენახვა…"
"Wrap style" = "გადატანის სტილი"
"Text direction" = "ტექსტის მიმართულება"
"Auto: by the first letter with a direction" = "ავტომატური: მიმართულების მქონე პირველი ასოს მიხედვით"
"Left to right" = "მარცხნიდან მარჯვნივ"
"Right to left" = "მარჯვნიდან მარცხნივ"
"Balance" = "დაბალანსებული"
"Pretty" = "მოწესრიგებული"
"Auto: as many words as fit on each line" = "ავტომატური: თითო სტრიქონში იმდენი სიტყვა, რამდენიც ეტევა"
"Balance: every line close to the same length" = "დაბალანსებული: ყველა სტრიქონი დაახლოებით ერთი სიგრძისაა"
"Pretty: full lines, no one word alone on the last" = "მოწესრიგებული: სავსე სტრიქონები, ბოლო სტრიქონზე ერთი სიტყვა მარტო არ რჩება"
"Set hug contents" = "ზომა: შიგთავსზე მორგება"
"Set fill container" = "ზომა: კონტეინერის შევსება"
"Double-click an edge of an auto layout frame" = "ორმაგი დაწკაპუნება ავტოგანლაგების ჩარჩოს კიდეზე"
"{name}, disconnected from its live session" = "{name}, ცოცხალ სესიასთან კავშირი გაწყვეტილია"
"⌥ double-click an edge of an auto layout child" = "⌥ ორმაგი დაწკაპუნება ავტოგანლაგების შვილობილი ელემენტის კიდეზე"
"Alt+double-click an edge of an auto layout child" = "Alt+ორმაგი დაწკაპუნება ავტოგანლაგების შვილობილი ელემენტის კიდეზე"
"Default" = "ნაგულისხმევი"
"Default content" = "ნაგულისხმევი შიგთავსი"
"Default value (the top-left variant)" = "ნაგულისხმევი მნიშვნელობა (ზედა მარცხენა ვარიანტი)"
@@ -420,6 +462,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Desktop" = "დესკტოპი"
"Destination" = "დანიშნულება"
"Detach alias" = "ალიასის გამოყოფა"
"Detach calculation" = "გამოთვლის გამოყოფა"
"Detach instance" = "ინსტანსის გამოყოფა"
"Detach property" = "თვისების გამოყოფა"
"Detach style" = "სტილის გამოყოფა"
@@ -451,6 +494,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Dots" = "წერტილები"
"Dotted" = "პუნქტირი"
"Down" = "ქვემოთ"
"Download" = "ჩამოტვირთვა"
"Downloading… {percent}%" = "ჩამოტვირთვა… {percent}%"
"Drafts" = "მონახაზები"
"Drag the stroke to add a width point" = "გადაათრიეთ კონტური სიგანის წერტილის დასამატებლად"
"Draw" = "ხატვა"
@@ -460,6 +505,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Drop to import" = "ჩააგდეთ იმპორტისთვის"
"Drop to open" = "ჩააგდეთ გასახსნელად"
"Drop shadow" = "ჩრდილი"
"Drop to use this image" = "ჩააგდეთ ამ გამოსახულების გამოსაყენებლად"
"Dual-licensed MIT OR Apache-2.0. Made by the ArtCraft team and community." = "ორმაგი ლიცენზია: MIT OR Apache-2.0. შექმნილია ArtCraft-ის გუნდისა და საზოგადოების მიერ."
"Duo" = "დუო"
"Duplicate" = "დუბლირება"
@@ -473,6 +519,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Edit dev resource" = "დეველოპერის რესურსის რედაქტირება"
"Edit link" = "რედაქტირების ბმული"
"Edit link copied" = "რედაქტირების ბმული დაკოპირდა"
"Edit padding on all sides" = "შიდა დაშორების რედაქტირება ყველა მხარეს"
"Edit style" = "სტილის რედაქტირება"
"Edit variable" = "ცვლადის რედაქტირება"
"Edit with the builder" = "კონსტრუქტორით რედაქტირება"
@@ -500,6 +547,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Essential" = "ძირითადი"
"Every conflict has a choice." = "ყველა კონფლიქტს არჩევანი აქვს."
"Every top-level frame already starts a flow" = "ყველა ზედა დონის ჩარჩო უკვე იწყებს ნაკადს"
"Everyone who reaches this server can open these files while they are shared." = "ამ სერვერთან წვდომის მქონე ყველას შეუძლია ამ ფაილების გახსნა, სანამ ისინი გაზიარებულია."
"Exact opacity (4 then 5: 45%)" = "ზუსტი გაუმჭვირვალობა (4, შემდეგ 5: 45%)"
"Exclude" = "გამორიცხვა"
"Excluded" = "გამორიცხული"
@@ -508,6 +556,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Exclusion" = "გამორიცხვა"
"Exit focus view (Esc)" = "ფოკუსის ხედიდან გასვლა (Esc)"
"Expand" = "გაშლა"
"Expand the interface" = "ინტერფეისის გაშლა"
"Export" = "ექსპორტირება"
"Export all" = "ყველაფრის ექსპორტირება"
"Export frames and layers as PNG, JPG, SVG or PDF" = "ჩარჩოები და შრეები PNG, JPG, SVG ან PDF ფორმატში"
@@ -534,6 +583,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Fetching from the server…" = "სერვერიდან მიღება…"
"FigCraft couldn't open its window: {error}" = "FigCraft-მა ფანჯრის გახსნა ვერ შეძლო: {error}"
"FigCraft doesn't support every feature of these files yet. The notes list what was left out or changed in the imported copy; the original file is unchanged." = "FigCraft ჯერ ამ ფაილების ყველა შესაძლებლობას არ უჭერს მხარს. შენიშვნებში ჩამოთვლილია, რა გამოტოვდა ან შეიცვალა იმპორტირებულ ასლში; ორიგინალი ფაილი უცვლელია."
"FigCraft stopped because of an internal error." = "FigCraft-ის მუშაობა შიდა შეცდომის გამო შეწყდა."
"File" = "ფაილი"
"File name" = "ფაილის სახელი"
"File not found" = "ფაილი ვერ მოიძებნა"
@@ -590,6 +640,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Frame selection" = "მონიშნულის ჩარჩოში მოქცევა"
"Frame tools" = "ჩარჩოს ხელსაწყოები"
"Frames" = "ჩარჩოები"
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "უფასო შრიფტები Google Fonts-იდან და Noto-დან მოდის, jsDelivr-ისა და GitHub-ის გავლით. თითოეული ფაილი შრიფტების ინდექსთან მოწმდება, სანამ Craft-აპების საერთო შრიფტების საქაღალდეში დაინსტალირდება. სანამ არ დაუშვებთ, არაფერი ჩამოიტვირთება."
"From the library \"{name}\": read-only" = "ბიბლიოთეკიდან „{name}“: მხოლოდ წასაკითხად"
"From {name}" = "წყარო: {name}"
"From {server}" = "წყარო: {server}"
@@ -605,6 +656,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Go to {name}" = "{name}-ზე გადასვლა"
"Grab bag" = "სხვადასხვა"
"Gradient" = "გრადიენტი"
"Graph paper" = "მილიმეტრიანი ქაღალდი"
"Gray" = "ნაცრისფერი"
"Green" = "მწვანე"
"Greyscale components and two example screens to sketch a flow with" = "ნაცრისფერი კომპონენტები ნაკადის ჩანახატისთვის"
@@ -627,6 +679,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Help page" = "დახმარების გვერდი"
"Here: {names}" = "აქ: {names}"
"Hidden" = "დამალული"
"Hide UI" = "ინტერფეისის დამალვა"
"Hide contents" = "შიგთავსის დამალვა"
"Hide from publishing" = "გამოქვეყნებისას დამალვა"
"Hide section contents" = "სექციის შიგთავსის დამალვა"
@@ -718,6 +771,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Join with a code" = "კოდით შეერთება"
"Joined" = "შეერთებულია"
"Joined {file}" = "შეერთებულია: {file}"
"Joining live session…" = "ცოცხალ სესიასთან შეერთება…"
"Joining…" = "შეერთება…"
"Join|stroke" = "შეერთება"
"Jul" = "ივლ"
@@ -779,6 +833,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Lines deleted" = "წაშლილი სტრიქონები"
"Link" = "ბმული"
"Link copied" = "ბმული დაკოპირდა"
"Link copied: it opens the file in FigCraft" = "ბმული დაკოპირდა: ის ფაილს FigCraft-ში ხსნის"
"Link copied: it opens the file in the browser" = "ბმული დაკოპირდა: ის ფაილს ბრაუზერში ხსნის"
"Link docs, code or tickets for developers." = "მიაბით დოკუმენტაცია, კოდი ან ტიკეტები დეველოპერებისთვის."
"Link frames on the Prototype tab, then present the flow" = "დააკავშირეთ ჩარჩოები და წარადგინეთ ნაკადი"
"Link this component to its code component: instances then show your real snippet with their values." = "დააკავშირეთ ეს კომპონენტი მის კოდის კომპონენტთან: ინსტანსები მაშინ თქვენს რეალურ ფრაგმენტს აჩვენებს მათი მნიშვნელობებით."
@@ -801,10 +857,15 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Make a component" = "შექმენით კომპონენტი"
"Make slot" = "სლოტად გადაქცევა"
"New collection" = "ახალი კოლექცია"
"Nobody shares a file there now." = "იქ ახლა არავინ აზიარებს ფაილს."
"Past 30 days" = "ბოლო 30 დღე"
"Past 90 days" = "ბოლო 90 დღე"
"Past year" = "ბოლო წელი"
"Pasted design layers" = "ჩასმული დიზაინის ფენები"
"Pasted design layers; the clipboard didn't carry the images of: {layers}" = "დიზაინის ფენები ჩაისვა; ბუფერში არ იყო შემდეგის სურათები: {layers}"
"Remove these results from the file" = "ამ შედეგების ფაილიდან წაშლა"
"Scroll wheel zoom" = "მასშტაბირება გადახვევის ბორბლით"
"Shared by your team on {server}" = "თქვენი გუნდის მიერ {server}-ზე გაზიარებული"
"Slot name" = "სლოტის სახელი"
"Mar" = "მარ"
"Margin" = "ველი"
@@ -890,6 +951,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"No color styles" = "ფერის სტილები არ არის"
"No colour variables fit here." = "აქ არცერთი ფერის ცვლადი არ ერგება."
"No colour variables yet. Create them in Local variables." = "ფერის ცვლადები ჯერ არ არის. შექმენით ისინი ლოკალურ ცვლადებში."
"No comments to copy" = "დასაკოპირებელი კომენტარები არ არის"
"No comments yet" = "კომენტარები ჯერ არ არის"
"No compatibility warnings reported" = "თავსებადობის გაფრთხილებები არ დაფიქსირებულა"
"No components yet. Select layers and press {keys}." = "კომპონენტები ჯერ არ არის. მონიშნეთ შრეები და დააჭირეთ {keys}."
@@ -938,15 +1000,18 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Not bound" = "მიბმული არ არის"
"Not in a live session" = "ცოცხალ სესიაში არ ხართ"
"Not in this font" = "ამ შრიფტში არ არის"
"Not now" = "ახლა არა"
"Not properties, kept as written: {names}" = "არ არის თვისებები, დარჩა დაწერილი სახით: {names}"
"Not read yet" = "ჯერ არ არის წაკითხული"
"Check for updates" = "განახლებების შემოწმება"
"Not checked yet" = "ჯერ არ არის შემოწმებული"
"Someone who left" = "ვინც წავიდა"
"Take the results off the board; they stay in the file" = "შედეგების დაფიდან მოხსნა; ფაილში დარჩება"
"Upload from computer" = "კომპიუტერიდან ატვირთვა"
"This file uses team libraries on servers you haven't used here. They aren't contacted until you check them." = "ეს ფაილი იყენებს გუნდის ბიბლიოთეკებს სერვერებზე, რომლებიც აქ არ გამოგიყენებიათ. მათ არ დავუკავშირდებით, სანამ არ შეამოწმებთ."
"Not shared" = "არ არის გაზიარებული"
"Note {n}" = "შენიშვნა {n}"
"Nothing counted yet" = "ჯერ არაფერი დათვლილა"
"Nothing changed since this version." = "ამ ვერსიის შემდეგ არაფერი შეცვლილა."
"Nothing changed since this was marked ready for dev." = "მას შემდეგ, რაც მზად დეველოპერისთვის მოინიშნა, არაფერი შეცვლილა."
"Nothing here yet. Set a frame's status to list it." = "აქ ჯერ არაფერია. ჩარჩოს სიაში გამოსაჩენად მიანიჭეთ სტატუსი."
@@ -955,6 +1020,9 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Nov" = "ნოე"
"Now" = "ახლა"
"Nudge (Shift: big nudge)" = "მცირედ გადაწევა (Shift: დიდი ბიჯით)"
"Rotate a degree (Shift: 15)" = "ერთი გრადუსით შემობრუნება (Shift: 15)"
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
"Nudge amount" = "მცირედ გადაწევის ბიჯი"
"Number" = "რიცხვი"
"Number ↑" = "რიცხვი ↑"
@@ -1031,6 +1099,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Pages: {pages}" = "გვერდი: {pages}"
"Paint bucket" = "საღებავის ვედრო"
"Pan the canvas" = "ტილოს გადაადგილება"
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "განთავსების ჯვრის ჩვენება და გადაადგილება (არჩეული ხელსაწყოთი, როცა არაფერია მონიშნული)"
"Pan with nothing selected (Shift: farther)" = "გადაადგილება, როცა არაფერია მონიშნული (Shift: უფრო შორს)"
"Panels" = "პანელები"
"Paper" = "ქაღალდი"
@@ -1140,9 +1209,13 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Regular expression" = "რეგულარული გამოსახულება"
"Relative to" = "მიმართ"
"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "სისტემის ეკრანის მასშტაბირებასთან მიმართებით (100% სისტემის საკუთარი ზომაა). დოკუმენტის მასშტაბი ცალკე რეგულირდება."
"Reload the page to get back the unsaved files the browser had room for." = "განაახლეთ გვერდი, რომ დაიბრუნოთ ის შეუნახავი ფაილები, რომლებიც ბრაუზერში დაეტია."
"Reload the page to get your unsaved files back." = "განაახლეთ გვერდი, რომ შეუნახავი ფაილები დაიბრუნოთ."
"Reload the page to start again." = "თავიდან დასაწყებად განაახლეთ გვერდი."
"Remove" = "წაშლა"
"Remove all" = "ყველას წაშლა"
"Remove annotation" = "ანოტაციის წაშლა"
"Remove all auto layout" = "ყველა ავტოგანლაგების მოხსნა"
"Remove auto layout" = "ავტოგანლაგების მოხსნა"
"Remove column" = "სვეტის წაშლა"
"Remove dev resource" = "დეველოპერის რესურსის წაშლა"
@@ -1194,6 +1267,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Reset adjustments" = "კორექციების ჩამოყრა"
"Reset all changes" = "ყველა ცვლილების ჩამოყრა"
"Reset all overrides on this layer" = "ამ შრის ყველა გადაფარვის ჩამოყრა"
"Reset grid" = "ბადის ჩამოყრა"
"Reset overrides" = "გადაფარვების ჩამოყრა"
"Reset slot" = "სლოტის ჩამოყრა"
"Reset this override" = "ამ გადაფარვის ჩამოყრა"
@@ -1248,6 +1322,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"See all templates" = "ყველა შაბლონის ნახვა"
"Select layers and they space themselves as their content changes" = "შრეები შიგთავსის ცვლილებისას თავად დაშორდება"
"SHA-256: {sha}…" = "SHA-256: {sha}…"
"Same as file ({profile})" = "როგორც ფაილში ({profile})"
"Same as layer" = "შრის მსგავსად"
"Saturation" = "გაჯერება"
"Save" = "შენახვა"
@@ -1273,6 +1348,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Search files and templates" = "ფაილებისა და შაბლონების ძიება"
"Search results" = "ძიების შედეგები"
"Search fonts" = "შრიფტების ძიება"
"This server doesn't count insertions" = "ეს სერვერი ჩასმებს არ ითვლის"
"This server doesn't count styles and variables" = "ეს სერვერი სტილებსა და ცვლადებს არ ითვლის"
"Use fonts installed on this computer…" = "ამ კომპიუტერზე დაყენებული შრიფტების გამოყენება…"
"Search layers" = "შრეების ძიება"
"Search shortcuts" = "მალსახმობების ძიება"
@@ -1332,6 +1409,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Show device frame" = "მოწყობილობის კორპუსის ჩვენება"
"Show dimensions on objects" = "ზომების ჩვენება ობიექტებზე"
"Show hotspot hints" = "აქტიური არეების მინიშნებების ჩვენება"
"The bars are hidden. {shortcut} shows them again" = "ზოლები დამალულია. {shortcut} ისევ აჩვენებს მათ"
"Show in Explorer" = "Explorer-ში ჩვენება"
"Show in Finder" = "Finder-ში ჩვენება"
"Show in folder" = "საქაღალდეში ჩვენება"
@@ -1435,6 +1513,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Stroke style" = "კონტურის სტილი"
"Stroke weight" = "კონტურის სისქე"
"Strokes" = "კონტურები"
"Strong line every" = "მუქი ხაზის ბიჯი"
"Style" = "სტილი"
"Styles" = "სტილები"
"Stylistic set 1" = "სტილისტური ნაკრები 1"
@@ -1477,7 +1556,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Text styles" = "ტექსტის სტილები"
"Texts" = "ტექსტები"
"Texture" = "ტექსტურა"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "ტილო ფერებს sRGB-ში აჩვენებს; ექსპორტირებულ PNG, JPG და WebP ფაილებს Display P3 ჭდე აქვს."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "ტილო ფერებს sRGB-ში აჩვენებს; ფაილის პროფილით ექსპორტირებულ PNG, JPG და WebP ფაილებს Display P3 ჭდე აქვს."
"The destination document is unavailable. Nothing was imported." = "დანიშნულების დოკუმენტი მიუწვდომელია. იმპორტი არ შესრულდა."
"The destination document was closed. Nothing was imported." = "დანიშნულების დოკუმენტი დაიხურა. იმპორტი არ შესრულდა."
"The destination page was removed. Nothing was imported." = "დანიშნულების გვერდი წაიშალა. იმპორტი არ შესრულდა."
@@ -1658,6 +1737,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Your copy stays open; the file stays on the server" = "თქვენი ასლი ღია რჩება; ფაილი სერვერზე რჩება"
"Your name" = "თქვენი სახელი"
"Your system asks for reduced motion: animations stay off." = "თქვენი სისტემა ითხოვს მოძრაობის შემცირებას: ანიმაციები გამორთული რჩება."
"Your unsaved files were too large for the browser to keep." = "თქვენი შეუნახავი ფაილები ბრაუზერისთვის შესანახად ზედმეტად დიდი იყო."
"Z" = "Z"
"Z to A" = "ჰ-დან ა-მდე"
"Zoom" = "მასშტაბი"
@@ -1691,6 +1771,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"connector label was skipped: text style data is missing" = "შემაერთებლის იარლიყი გამოტოვებულია: ტექსტის სტილის მონაცემები აკლია"
"connector label was skipped: text transform is invalid" = "შემაერთებლის იარლიყი გამოტოვებულია: ტექსტის გარდაქმნა არასწორია"
"connector labels were skipped" = "შემაერთებლების იარლიყები გამოტოვებულია"
"connector labels without a saved snapshot are centred on the line, without their background" = "შენახული სნეპშოტის გარეშე შემაერთებლის იარლიყები ხაზზე ცენტრდება, ფონის გარეშე"
"connector layers import as static frame/vector snapshots with labels when present; live endpoint bindings are not retained" = "შემაერთებლის შრეები იმპორტირდება ჩარჩოს ან ვექტორის სტატიკური სნეპშოტების სახით, იარლიყებით (თუ არის); ბოლოების ცოცხალი მიბმები არ ნარჩუნდება"
"connector snapshot vector data is missing; connector was left empty" = "შემაერთებლის სნეპშოტის ვექტორული მონაცემები აკლია; შემაერთებელი ცარიელი დარჩა"
"connectors whose ends can't be placed are empty" = "შემაერთებლები, რომელთა ბოლოების განთავსება ვერ ხერხდება, ცარიელია"
@@ -1702,6 +1783,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"duplicate grid track sizing entries use equal tracks" = "ბადის ტრეკის ზომის დუბლირებული ჩანაწერებისას ტრეკები თანაბარია"
"e.g. count + 1" = "მაგ. count + 1"
"e.g. count >= 3 and not done" = "მაგ. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "შენახული ტრაექტორიის გარეშე კუთხოვანი და მრუდი შემაერთებლები FigCraft-ის საკუთარ მარშრუტს მიჰყვება"
"entries without a node type were skipped" = "კვანძის ტიპის გარეშე ჩანაწერები გამოტოვებულია"
"figcraft:// links from a browser, chat or email open this app and join the session." = "ბრაუზერიდან, ჩატიდან ან ელფოსტიდან figcraft:// ბმულები ხსნის ამ აპს და უერთდება სესიას."
"from {server}" = "წყარო: {server}"
@@ -1723,12 +1805,15 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"invalid internal .fig text path data was ignored" = ".fig-ის შიდა ტექსტის ტრაექტორიის არასწორი მონაცემები იგნორირებულია"
"invalid or oversized vector networks import as outlines" = "არასწორი ან ზედმეტად დიდი ვექტორული ქსელები კონტურებად იმპორტირდება"
"invalid or oversized vector path data was skipped" = "ვექტორული ტრაექტორიის არასწორი ან ზედმეტად დიდი მონაცემები გამოტოვებულია"
"invalid vector region fill paint list; layer fill used" = "ვექტორული არის შევსების საღებავების სია არასწორია; გამოყენებულია შრის შევსება"
"invalid vector region paints were skipped" = "ვექტორული არის არასწორი საღებავები გამოტოვებულია"
"just now" = "ახლახან"
"key triggers without a supported key were skipped" = "მხარდაჭერილი კლავიშის გარეშე კლავიშის გამშვებები გამოტოვებულია"
"key up triggers import as key presses" = "კლავიშის აშვების გამშვებები კლავიშის დაჭერებად იმპორტირდება"
"layers without a position were placed at their parent's origin" = "პოზიციის გარეშე შრეები მშობლის საწყის წერტილში განთავსდა"
"layers without a type were skipped" = "ტიპის გარეშე შრეები გამოტოვებულია"
"legacy image filter container is unsupported; filter conversion was skipped" = "გამოსახულების ფილტრების ძველი კონტეინერი მხარდაუჭერელია; ფილტრების გარდაქმნა გამოტოვებულია"
"linked vector region fill styles keep resolved appearance; live style links were left out" = "ვექტორული არის მიბმული შევსების სტილები გამოთვლილ იერსახეს ინარჩუნებს; სტილების ცოცხალი კავშირები არ გადმოვიდა"
"links to shared styles that aren't in the file kept the layers' own values" = "ფაილში არარსებულ საერთო სტილებზე ბმულებმა შეინარჩუნეს ფენების საკუთარი მნიშვნელობები"
"locked" = "ჩაკეტილი"
"malformed image filters container was skipped" = "გამოსახულების ფილტრების დაზიანებული კონტეინერი გამოტოვებულია"
@@ -1737,6 +1822,10 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"no bleed" = "ჭრისპირა არის გარეშე"
"nobody else here yet" = "აქ ჯერ სხვა არავინაა"
"non-default slot settings are not represented and were skipped" = "სლოტის არანაგულისხმევი პარამეტრები არ არის წარმოდგენილი და გამოტოვებულია"
"note or shape generated child has invalid bounds; child skipped" = "შენიშვნის ან ფიგურის გენერირებულ შვილობილ ელემენტს არასწორი საზღვრები აქვს; ელემენტი გამოტოვებულია"
"note or shape generated child is missing its style or bounds; child skipped" = "შენიშვნის ან ფიგურის გენერირებულ შვილობილ ელემენტს სტილი ან საზღვრები აკლია; ელემენტი გამოტოვებულია"
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "შენიშვნის ან ფიგურის გენერირებული შვილობილი ელემენტები შრეების ან ჩადგმის ლიმიტს აჭარბებს; დანარჩენი ელემენტები გამოტოვებულია"
"note or shape generated layout is missing or unsupported; using its outer frame" = "შენიშვნის ან ფიგურის გენერირებული განლაგება აკლია ან მხარდაუჭერელია; გამოიყენება მისი გარე ჩარჩო"
"now" = "ახლა"
"offer files to save if it asks to (you choose where each one goes)" = "შესანახად ფაილების შეთავაზება, თუ ამას ითხოვს (თითოეულის ადგილს თქვენ ირჩევთ)"
"only in a text style or variable" = "მხოლოდ ტექსტის სტილში ან ცვლადში"
@@ -1760,6 +1849,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"set-variable actions with values that don't fit the variable were skipped" = "ცვლადის დაყენების მოქმედებები, რომელთა მნიშვნელობა ცვლადს არ შეესაბამება, გამოტოვებულია"
"set-variable actions without a value were skipped" = "მნიშვნელობის გარეშე ცვლადის დაყენების მოქმედებები გამოტოვებულია"
"set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "ცვლადის რეჟიმის დაყენების მოქმედებები იმ კოლექციებზე ან რეჟიმებზე, რომლებიც ცვლადების JSON-ში არ არის, გამოტოვებულია"
"shape generated outline is missing or damaged; using its rectangle" = "ფიგურის გენერირებული კონტური აკლია ან დაზიანებულია; გამოიყენება მისი მართკუთხედი"
"slot content assignment target is missing or is not slot content" = "სლოტის შიგთავსის მინიჭების სამიზნე აკლია ან სლოტის შიგთავსი არ არის"
"slot content assignment uses the empty GUID sentinel and was skipped" = "სლოტის შიგთავსის მინიჭება ცარიელ GUID მარკერს იყენებს და გამოტოვებულია"
"slot layers without a matching slot property were imported as frames" = "სლოტის შრეები, რომლებსაც შესაბამისი სლოტის თვისება არ აქვს, ჩარჩოებად იმპორტირდა"
@@ -1785,10 +1875,13 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"variable modes of collections that aren't in the file were skipped" = "იმ კოლექციების ცვლადის რეჟიმები, რომლებიც ფაილში არ არის, გამოტოვებულია"
"variable modes of collections that aren't in the variables JSON were skipped" = "იმ კოლექციების ცვლადის რეჟიმები, რომლებიც ცვლადების JSON-ში არ არის, გამოტოვებულია"
"variable values that don't match their type (or composed colours) were skipped" = "ცვლადის მნიშვნელობები, რომლებიც თავიანთ ტიპს არ შეესაბამება (ან შედგენილი ფერები), გამოტოვებულია"
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "ცვლადებზე მიბმული ვექტორული არის საღებავები გამოთვლილ იერსახეს ინარჩუნებს; ცოცხალი მიბმები არ გადმოვიდა"
"variables of unknown types were skipped" = "უცნობი ტიპის ცვლადები გამოტოვებულია"
"variables whose collection isn't in the variables JSON were skipped" = "ცვლადები, რომელთა კოლექცია ცვლადების JSON-ში არ არის, გამოტოვებულია"
"variables without readable values were skipped" = "წაკითხვადი მნიშვნელობების გარეშე ცვლადები გამოტოვებულია"
"vector points with unknown stroke joins use the layer join" = "უცნობი კონტურის შეერთების მქონე ვექტორული წერტილები შრის შეერთებას იყენებს"
"vector region paint data exceeded import limits and was skipped" = "ვექტორული არის საღებავის მონაცემებმა იმპორტის ლიმიტებს გადააჭარბა და გამოტოვებულია"
"vector region references a missing fill style; layer fill used" = "ვექტორული არე მიუთითებს შევსების არარსებულ სტილზე; გამოყენებულია შრის შევსება"
"vectors without geometry are empty" = "გეომეტრიის გარეშე ვექტორები ცარიელია"
"vectors without geometry are empty (export the file JSON with geometry=paths)" = "გეომეტრიის გარეშე ვექტორები ცარიელია (ფაილის JSON-ის ექსპორტი გააკეთეთ geometry=paths პარამეტრით)"
"very long text was cut to 1,048,576 characters" = "ძალიან გრძელი ტექსტი 1 048 576 სიმბოლომდე შემოკლდა"
@@ -1796,6 +1889,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"video actions are not supported and were skipped" = "ვიდეოს მოქმედებები მხარდაუჭერელია და გამოტოვებულია"
"video triggers are not supported and were skipped" = "ვიდეოს გამშვებები მხარდაუჭერელია და გამოტოვებულია"
"yesterday" = "გუშინ"
"{count} in it now · Changed {date}" = "ახლა მასშია: {count} · შეცვლილია: {date}"
"{insertions} · {detachments}" = "{insertions} · {detachments}"
"{instances} in {files}" = "{instances} — {files}"
"{language}: draft translation, waiting for a native speaker's review." = "{language}: თარგმანის მონახაზი, ელოდება მშობლიური ენის მცოდნის განხილვას."
"{length} bleed" = "ჭრისპირა არე: {length}"
@@ -1831,8 +1926,10 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"{n} components and styles have newer versions" = { one = "ახალი ვერსია აქვს კომპონენტს ან სტილს: {n}", other = "ახალი ვერსია აქვს კომპონენტს ან სტილს: {n}" }
"{n} conflicts to resolve" = { one = "გადასაწყვეტი კონფლიქტი: {n}", other = "გადასაწყვეტი კონფლიქტი: {n}" }
"{n} days ago" = { one = "{n} დღის წინ", other = "{n} დღის წინ" }
"{n} detached" = { one = "გამოყოფილი: {n}", other = "გამოყოფილი: {n}" }
"{n} files" = { one = "ფაილი: {n}", other = "ფაილი: {n}" }
"{n} hours ago" = { one = "{n} საათის წინ", other = "{n} საათის წინ" }
"{n} inserted" = { one = "ჩასმული: {n}", other = "ჩასმული: {n}" }
"{n} instances" = { one = "ინსტანსი: {n}", other = "ინსტანსი: {n}" }
"{n} layers" = { one = "შრე: {n}", other = "შრე: {n}" }
"{n} layers as one file" = { one = "შრე: {n}, ერთ ფაილად", other = "შრე: {n}, ერთ ფაილად" }
@@ -1863,12 +1960,15 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"{n}w" = "{n} კვ"
"{page}, nothing selected" = "{page}, არაფერია მონიშნული"
"{percent}%" = "{percent}%"
"{period}: {counts}" = "{period}: {counts}"
"{profile} (current)" = "{profile} (მიმდინარე)"
"{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written." = "{property} მისი მნიშვნელობაა; {property ? \"a\" : \"b\"} ირჩევს სტრიქონს. ნებისმიერი სხვა {…} რჩება დაწერილი სახით."
"{server} can't say what became of your files (it is older than this app)." = "{server} ვერ გეტყვით, რა მოუვიდა თქვენს ფაილებს (ის ამ აპზე ძველია)."
"{server} · No longer on the server" = "{server} · სერვერზე აღარ არის"
"{server} · {shared} · Opened {date}" = "{server} · {shared} · გაიხსნა {date}"
"{tool} hold {key}" = "{tool} დააჭირეთ {key}"
"{used} · {detached}" = "{used} · {detached}"
"{used} · {inserted}" = "{used} · {inserted}"
"{value} isn't a colour" = "{value} ფერი არ არის"
"{when} · edited" = "{when} · რედაქტირებულია"
"← ↑ → ↓" = "← ↑ → ↓"
@@ -1881,14 +1981,27 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"⌘ click" = "⌘ დაწკაპუნება"
"⌘ scroll" = "⌘ გადახვევა"
"⌥ drag" = "⌥ გადათრევა"
"Selection box: switch to pick select" = "მონიშვნის ჩარჩო: შრის არჩევაზე გადართვა"
"Pick select: next or previous layer" = "შრის არჩევა: შემდეგი ან წინა შრე"
"Pick select: into a layer, out to its parent" = "შრის არჩევა: შრეში შესვლა, მშობელზე გასვლა"
"Pick select: select the picked layer" = "შრის არჩევა: არჩეული შრის მონიშვნა"
"⇥ or ⌥ Space again" = "⇥ ან ხელახლა ⌥ Space"
"Tab or Ctrl+Space again" = "Tab ან ხელახლა Ctrl+Space"
"↵ / ⇧↵" = "↵ / ⇧↵"
"Enter / Shift+Enter" = "Enter / Shift+Enter"
"Space" = "Space"
"Nothing to pick: the page is empty" = "ასარჩევი არაფერია: გვერდი ცარიელია"
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "შრის არჩევა: Tab და Shift+Tab შრეებს შორის გადაადგილდება, Enter შრეში შედის, Shift+Enter გამოდის, Space მონიშნავს, Escape გააუქმებს"
"Android Vector Drawable" = "Android Vector Drawable"
"Best effort" = "მაქსიმალური მიახლოება"
"Check for Updates" = "განახლებების შემოწმება"
"Check for updates…" = "განახლებების შემოწმება…"
"Compatibility" = "თავსებადობა"
"Dart constants for Flutter…" = "Dart-ის კონსტანტები Flutter-ისთვის…"
"Calculated from other variables; it follows them" = "გამოითვლება სხვა ცვლადებიდან და მათ მიჰყვება"
"Copy effect" = "ეფექტის კოპირება"
"Copy fill" = "შევსების კოპირება"
"Copy for AI" = "კოპირება AI-სთვის"
"Copy stroke" = "კონტურის კოპირება"
"Couldn't download {name}" = "{name} ვერ ჩამოიტვირთა"
"Don't show this again" = "აღარ აჩვენო"
@@ -1905,6 +2018,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"Set corner smoothing to 60%" = "კუთხეების დარბილების 60%-ზე დაყენება"
"Text on a path" = "ტექსტი ტრაექტორიაზე"
"This link opens a website outside the prototype:" = "ეს ბმული პროტოტიპის გარეთ ვებსაიტს ხსნის:"
"This link opens your mail app to write a message:" = "ეს ბმული წერილის დასაწერად თქვენს საფოსტო აპს ხსნის:"
"This server doesn't count detached instances" = "ეს სერვერი გამოყოფილ ინსტანსებს არ ითვლის"
"Update check is not supported in the web browser." = "ვებბრაუზერში განახლებების შემოწმება მხარდაჭერილი არ არის."
"instance swap properties whose default component was past the layer limit were skipped" = "ინსტანსის ჩანაცვლების თვისებები, რომელთა ნაგულისხმევი კომპონენტი შრეების ზღვარს მიღმა იყო, გამოტოვებულია"
"instances whose component was past the layer limit were imported as frames" = "ინსტანსები, რომელთა კომპონენტი შრეების ზღვარს მიღმა იყო, ჩარჩოებად იმპორტირდა"
@@ -1938,10 +2053,12 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"arrange.tidy" = "მოწესრიგება"
"board.addConnected" = "დაკავშირებული ფიგურის დამატება"
"board.connector" = "შემაერთებელი"
"board.grid" = "დაფის ბადე"
"board.ink" = "მარკერის შტრიხი"
"board.label" = "შემაერთებლის წარწერა"
"board.nextSticky" = "შემდეგი სტიკერი"
"board.reattach" = "შემაერთებლის ხელახლა მიმაგრება"
"board.reshape" = "შემაერთებლის ფორმის შეცვლა"
"board.setColor" = "დაფის ფერი"
"board.setStyle" = "დაფის სტილი"
"board.shape" = "ფიგურა ტექსტით"
@@ -2003,6 +2120,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"comment.next" = "შემდეგი კომენტარი"
"comment.open" = "კომენტარის გახსნა"
"comment.people" = "კომენტარებში მონაწილე ადამიანები"
"comment.prompt" = "კომენტარების კოპირება AI-სთვის"
"comment.react" = "კომენტარზე რეაგირება"
"comment.reply" = "კომენტარზე პასუხი"
"comment.resolve" = "კომენტარის გადაწყვეტა"
@@ -2013,6 +2131,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"component.combineVariants" = "ვარიანტებად გაერთიანება"
"component.create" = "კომპონენტის შექმნა"
"component.createMultiple" = "რამდენიმე კომპონენტის შექმნა"
"component.createSet" = "კომპონენტების ნაკრების შექმნა"
"component.deleteProperty" = "კომპონენტის თვისების წაშლა"
"component.detach" = "ინსტანსის გამოყოფა"
"component.editProperty" = "კომპონენტის თვისების რედაქტირება"
@@ -2081,6 +2200,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"file.exportFramesPdf" = "ჩარჩოების PDF-ად ექსპორტირება"
"file.exportLayers" = "შრეების ექსპორტირება"
"file.exportSvg" = "მონიშნულის SVG-ად ექსპორტირება"
"file.fontReport" = "დოკუმენტის შრიფტების ინსპექტირება"
"file.import" = "იმპორტი"
"file.moveTab" = "ჩანართის გადატანა"
"file.new" = "ახალი დიზაინის ფაილი"
@@ -2101,6 +2221,8 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"fill.pattern" = "პატერნით შევსება"
"fill.remove" = "შევსების წაშლა"
"fill.set" = "შევსების დაყენება"
"font.download" = "შრიფტის ჩამოტვირთვა"
"font.downloads" = "შრიფტების ჩამოტვირთვები"
"frame.create" = "ჩარჩოს შექმნა"
"frame.presets" = "ჩარჩოს პრესეტების სია"
"frame.swapOrientation" = "ორიენტაციის შეცვლა"
@@ -2117,9 +2239,11 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"help.page" = "დახმარების გვერდი"
"help.shortcuts" = "კლავიატურის მალსახმობები"
"image.adjust" = "გამოსახულების კორექცია"
"image.crop" = "გამოსახულების ჩამოჭრა"
"image.deletePreset" = "გამოსახულების პრესეტის წაშლა"
"image.place" = "გამოსახულების განთავსება"
"image.presets" = "გამოსახულების პრესეტები"
"image.replace" = "გამოსახულების ჩანაცვლება"
"image.savePreset" = "გამოსახულების პრესეტის შენახვა"
"inspect.assets" = "რესურსების ინსპექტირება"
"inspect.code" = "შრის კოდი"
@@ -2146,6 +2270,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"library.aliasVariable" = "ბიბლიოთეკის ცვლადის ალიასი"
"library.applyStyle" = "ბიბლიოთეკის სტილის გამოყენება"
"library.bindVariable" = "ბიბლიოთეკის ცვლადის მიბმა"
"library.check" = "გუნდის ბიბლიოთეკების განახლებების შემოწმება"
"library.extendCollection" = "ბიბლიოთეკის კოლექციის გაფართოება"
"library.import" = "ბიბლიოთეკის კომპონენტის იმპორტი"
"library.importVariable" = "ბიბლიოთეკის ცვლადის იმპორტი"
@@ -2407,6 +2532,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"variable.deleteCollection" = "კოლექციის წაშლა"
"variable.duplicate" = "ცვლადის დუბლირება"
"variable.export" = "ცვლადების ექსპორტირება"
"variable.extendCollection" = "კოლექციის გაფართოება"
"variable.import" = "ცვლადების იმპორტი"
"variable.list" = "ცვლადების სია"
"variable.moveMode" = "რეჟიმის გადატანა"
@@ -2516,6 +2642,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"view.zoomOut" = "დაპატარავება"
"view.zoomSelection" = "მონიშნულის მასშტაბირება"
"widget.click" = "ვიჯეტზე დაწკაპუნება"
"widget.hover" = "ვიჯეტზე მაჩვენებლის მიტანა"
"widget.insert" = "ვიჯეტის ჩასმა"
"widget.list" = "ვიჯეტების სია"
"widget.menu" = "ვიჯეტის მენიუ"
+2 -1
View File
@@ -1379,7 +1379,7 @@ status = "draft — needs native review"
"Text styles" = "텍스트 스타일"
"Texts" = "텍스트"
"Texture" = "텍스처"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "캔버스는 sRGB로 색상을 미리 보여 줌. 내보낸 PNG, JPG, WebP 파일에는 Display P3 태그가 붙음."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "캔버스는 sRGB로 색상을 미리 보여 줌. 파일의 프로필로 내보낸 PNG, JPG, WebP 파일에는 Display P3 태그가 붙음."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "파일이 서버에서 삭제됨: 누구도 서버에서 다시 열거나 참여할 수 없으며 되돌릴 수 없음. 열려 있는 사본은 각자에게 남음."
"The file now holds another library" = "이 파일은 이제 다른 라이브러리를 담고 있음"
"The file now holds another library (\"{name}\")" = "이 파일은 이제 다른 라이브러리(\"{name}\")를 담고 있음"
@@ -1978,6 +1978,7 @@ status = "draft — needs native review"
"component.combineVariants" = "배리언트로 결합"
"component.create" = "컴포넌트 만들기"
"component.createMultiple" = "여러 컴포넌트 만들기"
"component.createSet" = "컴포넌트 세트 만들기"
"component.deleteProperty" = "컴포넌트 속성 삭제"
"component.detach" = "인스턴스 분리"
"component.editProperty" = "컴포넌트 속성 편집"
+2 -1
View File
@@ -1458,7 +1458,7 @@ status = "draft — needs native review"
"Text styles" = "Tekststijlen"
"Texts" = "Teksten"
"Texture" = "Texture"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Het canvas toont de kleuren als voorvertoning in sRGB; geëxporteerde PNG-, JPG- en WebP-bestanden worden gelabeld als Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Het canvas toont de kleuren als voorvertoning in sRGB; PNG-, JPG- en WebP-bestanden die met het profiel van het bestand worden geëxporteerd, worden gelabeld als Display P3."
"The destination document is unavailable. Nothing was imported." = "Het doeldocument is niet beschikbaar. Er is niets geïmporteerd."
"The destination document was closed. Nothing was imported." = "Het doeldocument is gesloten. Er is niets geïmporteerd."
"The destination page was removed. Nothing was imported." = "De doelpagina is verwijderd. Er is niets geïmporteerd."
@@ -1956,6 +1956,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combineren als varianten"
"component.create" = "Component maken"
"component.createMultiple" = "Meerdere componenten maken"
"component.createSet" = "Componentenset maken"
"component.deleteProperty" = "Componenteigenschap verwijderen"
"component.detach" = "Instance loskoppelen"
"component.editProperty" = "Componenteigenschap bewerken"
+2 -1
View File
@@ -1465,7 +1465,7 @@ name = "Polski"
"Text styles" = "Style tekstu"
"Texts" = "Teksty"
"Texture" = "Tekstura"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Płótno wyświetla podgląd kolorów w sRGB; wyeksportowane pliki PNG, JPG i WebP są oznaczane profilem Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Płótno wyświetla podgląd kolorów w sRGB; pliki PNG, JPG i WebP wyeksportowane z profilem pliku są oznaczane profilem Display P3."
"The destination document is unavailable. Nothing was imported." = "Dokument docelowy jest niedostępny. Nic nie zostało zaimportowane."
"The destination document was closed. Nothing was imported." = "Dokument docelowy został zamknięty. Nic nie zostało zaimportowane."
"The destination page was removed. Nothing was imported." = "Strona docelowa została usunięta. Nic nie zostało zaimportowane."
@@ -1970,6 +1970,7 @@ name = "Polski"
"component.combineVariants" = "Połącz jako warianty"
"component.create" = "Utwórz komponent"
"component.createMultiple" = "Utwórz wiele komponentów"
"component.createSet" = "Utwórz zestaw komponentów"
"component.deleteProperty" = "Usuń właściwość komponentu"
"component.detach" = "Odłącz instancję"
"component.editProperty" = "Edytuj właściwość komponentu"
+2 -1
View File
@@ -1377,7 +1377,7 @@ status = "draft — needs native review"
"Text styles" = "Estilos de texto"
"Texts" = "Textos"
"Texture" = "Textura"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "A tela exibe as cores em sRGB; os arquivos PNG, JPG e WebP exportados são marcados como Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "A tela exibe as cores em sRGB; os arquivos PNG, JPG e WebP exportados com o perfil do arquivo são marcados como Display P3."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "O arquivo é excluído do servidor: ninguém poderá abri-lo nem entrar nele a partir de lá de novo, e isso não pode ser desfeito. As cópias abertas ficam com quem as tem."
"The file now holds another library" = "O arquivo agora contém outra biblioteca"
"The file now holds another library (\"{name}\")" = "O arquivo agora contém outra biblioteca (\"{name}\")"
@@ -1975,6 +1975,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combinar como variantes"
"component.create" = "Criar componente"
"component.createMultiple" = "Criar vários componentes"
"component.createSet" = "Criar conjunto de componentes"
"component.deleteProperty" = "Excluir propriedade de componente"
"component.detach" = "Desvincular instância"
"component.editProperty" = "Editar propriedade de componente"
+2 -1
View File
@@ -1465,7 +1465,7 @@ name = "Русский"
"Text styles" = "Текстовые стили"
"Texts" = "Тексты"
"Texture" = "Текстура"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "На холсте цвета отображаются в sRGB; экспортированные PNG, JPG и WebP помечены профилем Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "На холсте цвета отображаются в sRGB; PNG, JPG и WebP, экспортированные с профилем файла, помечены профилем Display P3."
"The destination document is unavailable. Nothing was imported." = "Документ назначения недоступен. Ничего не импортировано."
"The destination document was closed. Nothing was imported." = "Документ назначения закрыт. Ничего не импортировано."
"The destination page was removed. Nothing was imported." = "Страница назначения удалена. Ничего не импортировано."
@@ -1970,6 +1970,7 @@ name = "Русский"
"component.combineVariants" = "Объединить в варианты"
"component.create" = "Создать компонент"
"component.createMultiple" = "Создать несколько компонентов"
"component.createSet" = "Создать набор компонентов"
"component.deleteProperty" = "Удалить свойство компонента"
"component.detach" = "Отсоединить экземпляр"
"component.editProperty" = "Изменить свойство компонента"
+71 -1
View File
@@ -128,6 +128,7 @@ name = "Svenska"
"Another server, or one that needs its key. The usual server is set in Preferences." = "En annan server, eller en som kräver sin nyckel. Standardservern anges i Inställningar."
"Any status" = "Valfri status"
"Anyone on your network with this code can edit the file, while this app stays open." = "Alla i ditt nätverk som har den här koden kan redigera filen så länge appen är öppen."
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Alla i ditt nätverk som har den här koden kan titta på filen, men inte ändra den, så länge appen är öppen."
"Anyone with the edit link can change the file; the view link only lets people look. The links carry their secrets: share them like passwords. `figcraft-server links` makes more and revokes them." = "Alla med redigeringslänken kan ändra filen; visningslänken låter bara andra titta. Länkarna innehåller sina hemligheter: dela dem som lösenord. `figcraft-server links` skapar fler och återkallar dem."
"Anyone with this code can edit the file." = "Alla med den här koden kan redigera filen."
"Anyone with this code can look at the file, not change it." = "Alla med den här koden kan titta på filen, men inte ändra den."
@@ -388,6 +389,8 @@ name = "Svenska"
"Crop marks" = "Skärmärken"
"Ctrl+arrows" = "Ctrl+piltangenter"
"Ctrl+click" = "Ctrl+klick"
"Ctrl+click a padding field" = "Ctrl+klicka på ett padding-fält"
"⌘ click a padding field" = "⌘ klicka på ett padding-fält"
"Ctrl+scroll" = "Ctrl+rullning"
"Current name" = "Aktuellt namn"
"Current version" = "Aktuell version"
@@ -407,6 +410,40 @@ name = "Svenska"
"Decoration style" = "Dekorationsstil"
"Decoration" = "Dekoration"
"Deep select" = "Djupmarkering"
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Dragjustera ett fält snabbare (2x) eller långsammare (1/2, 1/4)"
"Move up or down while dragging its label" = "Flytta upp eller ned medan du drar dess etikett"
"Scrubbing at 2x" = "Dragjustering med 2x hastighet"
"Scrubbing at 1x" = "Dragjustering med 1x hastighet"
"Scrubbing at 1/2" = "Dragjustering med 1/2 hastighet"
"Scrubbing at 1/4" = "Dragjustering med 1/4 hastighet"
"Delete {n} variables" = { one = "Radera {n} variabel", other = "Radera {n} variabler" }
"Move out of any group" = "Flytta ut ur alla grupper"
"Move to group {group}" = "Flytta till gruppen {group}"
"Scope: all supported properties" = "Omfång: alla egenskaper som stöds"
"Scope: hidden from pickers" = "Omfång: dold i väljare"
"Scope: only {scope}" = "Omfång: endast {scope}"
"Disconnected. Reconnecting…" = "Frånkopplad. Återansluter…"
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Frånkopplad. Dina redigeringar finns kvar här och synkas när anslutningen är tillbaka. Återansluter…"
"Dismiss" = "Stäng"
"Not connected: {reason}. Your work is still in this tab." = "Inte ansluten: {reason}. Ditt arbete finns kvar i den här fliken."
"Retry now" = "Försök igen nu"
"Save a copy…" = "Spara en kopia…"
"Wrap style" = "Radbrytningsstil"
"Text direction" = "Textriktning"
"Auto: by the first letter with a direction" = "Auto: efter den första bokstaven som har en riktning"
"Left to right" = "Vänster till höger"
"Right to left" = "Höger till vänster"
"Balance" = "Balans"
"Pretty" = "Snygg"
"Auto: as many words as fit on each line" = "Auto: så många ord som får plats på varje rad"
"Balance: every line close to the same length" = "Balans: alla rader ungefär lika långa"
"Pretty: full lines, no one word alone on the last" = "Snygg: fulla rader, inget ensamt ord på den sista"
"Set hug contents" = "Ställ in Omslut innehåll"
"Set fill container" = "Ställ in Fyll behållaren"
"Double-click an edge of an auto layout frame" = "Dubbelklicka på en kant av en auto layout-frame"
"{name}, disconnected from its live session" = "{name}, frånkopplad från sin livesession"
"⌥ double-click an edge of an auto layout child" = "⌥ dubbelklicka på en kant av ett underordnat objekt i auto layout"
"Alt+double-click an edge of an auto layout child" = "Alt+dubbelklicka på en kant av ett underordnat objekt i auto layout"
"Default" = "Standard"
"Default content" = "Standardinnehåll"
"Default value (the top-left variant)" = "Standardvärde (varianten längst upp till vänster)"
@@ -494,6 +531,7 @@ name = "Svenska"
"Edit dev resource" = "Redigera utvecklarresurs"
"Edit link" = "Redigeringslänk"
"Edit link copied" = "Redigeringslänken har kopierats"
"Edit padding on all sides" = "Redigera padding på alla sidor"
"Edit style" = "Redigera stil"
"Edit variable" = "Redigera variabel"
"Edit with the builder" = "Redigera med byggaren"
@@ -531,6 +569,7 @@ name = "Svenska"
"Exclusion" = "Uteslutning"
"Exit focus view (Esc)" = "Lämna fokusvyn (Esc)"
"Expand" = "Expandera"
"Expand the interface" = "Expandera gränssnittet"
"Export" = "Exportera"
"Export all" = "Exportera alla"
"Export frames and layers as PNG, JPG, SVG or PDF" = "Exportera frames och lager som PNG, JPG, SVG eller PDF"
@@ -1073,6 +1112,7 @@ name = "Svenska"
"Pages: {pages}" = "Sidor: {pages}"
"Paint bucket" = "Färghink"
"Pan the canvas" = "Panorera arbetsytan"
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Visa och flytta placeringshårkorset (med dess verktyg valt och inget markerat)"
"Pan with nothing selected (Shift: farther)" = "Panorera när inget är markerat (Shift: längre)"
"Panels" = "Paneler"
"Paper" = "Papper"
@@ -1297,6 +1337,7 @@ name = "Svenska"
"See all templates" = "Se alla mallar"
"Select layers and they space themselves as their content changes" = "Markera lager så fördelar de avståndet själva när innehållet ändras"
"SHA-256: {sha}…" = "SHA-256: {sha}…"
"Same as file ({profile})" = "Samma som filen ({profile})"
"Same as layer" = "Samma som lagret"
"Saturation" = "Mättnad"
"Save" = "Spara"
@@ -1537,7 +1578,7 @@ name = "Svenska"
"Text styles" = "Textstilar"
"Texts" = "Texter"
"Texture" = "Textur"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Arbetsytan förhandsgranskar färger i sRGB; exporterade PNG-, JPG- och WebP-filer märks med Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Arbetsytan förhandsgranskar färger i sRGB; PNG-, JPG- och WebP-filer som exporteras med filens profil märks med Display P3."
"The destination document is unavailable. Nothing was imported." = "Måldokumentet är inte tillgängligt. Ingenting importerades."
"The destination document was closed. Nothing was imported." = "Måldokumentet stängdes. Ingenting importerades."
"The destination page was removed. Nothing was imported." = "Målsidan togs bort. Ingenting importerades."
@@ -1969,6 +2010,17 @@ name = "Svenska"
"⌘ click" = "⌘ klicka"
"⌘ scroll" = "⌘ rulla"
"⌥ drag" = "⌥ dra"
"Selection box: switch to pick select" = "Markeringsruta: växla till plockmarkering"
"Pick select: next or previous layer" = "Plockmarkering: nästa eller föregående lager"
"Pick select: into a layer, out to its parent" = "Plockmarkering: in i ett lager, ut till dess överordnade"
"Pick select: select the picked layer" = "Plockmarkering: markera det valda lagret"
"⇥ or ⌥ Space again" = "⇥ eller ⌥ Blanksteg igen"
"Tab or Ctrl+Space again" = "Tab eller Ctrl+Blanksteg igen"
"↵ / ⇧↵" = "↵ / ⇧↵"
"Enter / Shift+Enter" = "Enter / Shift+Enter"
"Space" = "Blanksteg"
"Nothing to pick: the page is empty" = "Inget att välja: sidan är tom"
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Plockmarkering: Tab och Shift+Tab flyttar mellan lager, Enter går in i ett, Shift+Enter ut, Blanksteg markerar, Esc avbryter"
[commands]
@@ -2005,6 +2057,7 @@ name = "Svenska"
"board.label" = "Kopplingsetikett"
"board.nextSticky" = "Nästa lapp"
"board.reattach" = "Koppla om koppling"
"board.reshape" = "Omforma koppling"
"board.setColor" = "Whiteboardfärg"
"board.setStyle" = "Whiteboardstil"
"board.shape" = "Form med text"
@@ -2047,6 +2100,7 @@ name = "Svenska"
"collab.openFile" = "Öppna onlinefil"
"collab.peers" = "Personer i den här filen"
"collab.publish" = "Publicera på server"
"collab.reconnect" = "Återanslut livesessionen"
"collab.recoverFile" = "Återställ onlinefil"
"collab.registerLinks" = "Öppna inbjudningslänkar i FigCraft"
"collab.removePerson" = "Ta bort från session"
@@ -2077,6 +2131,7 @@ name = "Svenska"
"component.combineVariants" = "Kombinera som varianter"
"component.create" = "Skapa komponent"
"component.createMultiple" = "Skapa flera komponenter"
"component.createSet" = "Skapa komponentuppsättning"
"component.deleteProperty" = "Radera komponentegenskap"
"component.detach" = "Koppla bort instans"
"component.editProperty" = "Redigera komponentegenskap"
@@ -2194,6 +2249,7 @@ name = "Svenska"
"image.deletePreset" = "Radera förinställning"
"image.place" = "Placera bild"
"image.presets" = "Bildförinställningar"
"image.replace" = "Ersätt bild"
"image.savePreset" = "Spara förinställning"
"inspect.assets" = "Resurser"
"inspect.code" = "Kod"
@@ -2211,6 +2267,7 @@ name = "Svenska"
"layers.collapseAll" = "Fäll ihop alla"
"layout.add" = "Lägg till auto layout"
"layout.remove" = "Ta bort auto layout"
"layout.removeAll" = "Ta bort all auto layout"
"layout.setTrack" = "Ange spår"
"layout.suggest" = "Föreslå layout"
"libraries.open" = "Öppna bibliotek"
@@ -2305,6 +2362,9 @@ name = "Svenska"
"pref.showDimensions" = "Visa dimensioner på objekt"
"pref.startOnHome" = "Börja på Start"
"pref.uiScale" = "Gränssnittsstorlek"
"pref.uiScaleDown" = "Mindre gränssnitt"
"pref.uiScaleReset" = "Standardstorlek för gränssnittet"
"pref.uiScaleUp" = "Större gränssnitt"
"pref.userName" = "Ditt namn"
"proto.action.add" = "Lägg till prototypåtgärd"
"proto.action.move" = "Ändra ordning på prototypåtgärd"
@@ -2352,6 +2412,7 @@ name = "Svenska"
"selection.applyColorStyle" = "Använd färgformatmall på markeringen"
"selection.bindColorVariable" = "Använd färgvariabel på markeringen"
"selection.colors" = "Markeringsfärger"
"selection.createColorStyle" = "Skapa färgstil från markeringen"
"selection.detachColor" = "Koppla bort markeringsfärg"
"selection.selectColor" = "Markera lager med den här färgen"
"selection.setPaint" = "Ändra markeringens färg"
@@ -2398,6 +2459,10 @@ name = "Svenska"
"text.caseUpper" = "Versaler"
"text.create" = "Text"
"text.decoration" = "Dekoration"
"text.direction" = "Textriktning"
"text.directionAuto" = "Textriktning: auto"
"text.directionLtr" = "Textriktning: vänster till höger"
"text.directionRtl" = "Textriktning: höger till vänster"
"text.edit.begin" = "Redigera text"
"text.edit.caret" = "Placera markören"
"text.edit.end" = "Sluta redigera text"
@@ -2422,6 +2487,7 @@ name = "Svenska"
"text.missingFonts" = "Saknade typsnitt"
"text.numberList" = "Numrerad lista"
"text.onPath" = "Text på bana"
"text.openLink" = "Öppna länk"
"text.paragraphIndent" = "Styckeindrag"
"text.paragraphSpacing" = "Styckeavstånd"
"text.pathOptions" = "Alternativ för textbana"
@@ -2441,9 +2507,11 @@ name = "Svenska"
"text.underline" = "Understrykning"
"text.weightDown" = "Minska teckenvikten"
"text.weightUp" = "Öka teckenvikten"
"text.wrapStyle" = "Radbrytningsstil"
"tool.arrow" = "Pil"
"tool.comment" = "Kommentar"
"tool.connector" = "Koppling"
"tool.crosshair" = "Flytta placeringshårkorset"
"tool.ellipse" = "Ellips"
"tool.eraser" = "Suddgummi"
"tool.frame" = "Frame"
@@ -2487,6 +2555,7 @@ name = "Svenska"
"variable.deleteCollection" = "Radera samling"
"variable.duplicate" = "Duplicera variabel"
"variable.export" = "Exportera variabler"
"variable.extendCollection" = "Utöka samlingen"
"variable.import" = "Importera variabler"
"variable.list" = "Lista variabler"
"variable.moveMode" = "Flytta läge"
@@ -2560,6 +2629,7 @@ name = "Svenska"
"view.layoutGrids" = "Layoutrutnät"
"view.leftSidebar" = "Visa/dölj vänster sidofält"
"view.maskOutlines" = "Konturlinjer för masker"
"view.minimize" = "Minimera gränssnittet"
"view.multiplayerCursors" = "Samarbetsmarkörer"
"view.nextFrame" = "Zooma till nästa frame"
"view.nextPage" = "Nästa sida"
-1
View File
@@ -1575,7 +1575,6 @@ status = "draft — needs native review"
"Texts" = "உரைகள்"
"Texture" = "அமைப்பு"
"The bars are hidden. {shortcut} shows them again" = "பட்டைகள் மறைக்கப்பட்டுள்ளன. {shortcut} அவற்றை மீண்டும் காட்டும்"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "கேன்வாஸ் நிறங்களை sRGB இல் காட்டுகிறது; ஏற்றுமதி செய்த PNG, JPG, WebP கோப்புகள் Display P3 எனக் குறிக்கப்படும்."
"The destination document is unavailable. Nothing was imported." = "இலக்கு ஆவணம் கிடைக்கவில்லை. எதுவும் இறக்குமதி செய்யப்படவில்லை."
"The destination document was closed. Nothing was imported." = "இலக்கு ஆவணம் மூடப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
"The destination page was removed. Nothing was imported." = "இலக்குப் பக்கம் அகற்றப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
+2 -1
View File
@@ -1446,7 +1446,7 @@ status = "draft — needs native review"
"Text styles" = "สไตล์ข้อความ"
"Texts" = "ข้อความ"
"Texture" = "เท็กซ์เจอร์"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "แคนวาสแสดงตัวอย่างสีใน sRGB ส่วนไฟล์ PNG, JPG และ WebP ที่ส่งออกจะติดแท็ก Display P3"
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "แคนวาสแสดงตัวอย่างสีใน sRGB ส่วนไฟล์ PNG, JPG และ WebP ที่ส่งออกด้วยโปรไฟล์ของไฟล์จะติดแท็ก Display P3"
"The destination document is unavailable. Nothing was imported." = "เอกสารปลายทางใช้ไม่ได้ ไม่มีอะไรถูกนำเข้า"
"The destination document was closed. Nothing was imported." = "เอกสารปลายทางถูกปิดแล้ว ไม่มีอะไรถูกนำเข้า"
"The destination page was removed. Nothing was imported." = "หน้าปลายทางถูกลบแล้ว ไม่มีอะไรถูกนำเข้า"
@@ -1934,6 +1934,7 @@ status = "draft — needs native review"
"component.combineVariants" = "รวมเป็นแวเรียนต์"
"component.create" = "สร้างคอมโพเนนต์"
"component.createMultiple" = "สร้างหลายคอมโพเนนต์"
"component.createSet" = "สร้างชุดคอมโพเนนต์"
"component.deleteProperty" = "ลบพร็อพเพอร์ตีของคอมโพเนนต์"
"component.detach" = "ถอดอินสแตนซ์"
"component.editProperty" = "แก้ไขพร็อพเพอร์ตีของคอมโพเนนต์"
+2 -1
View File
@@ -1433,7 +1433,7 @@ name = "Türkçe"
"Text styles" = "Metin stilleri"
"Texts" = "Metinler"
"Texture" = "Doku"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Tuval renkleri sRGB olarak önizler; dışa aktarılan PNG, JPG ve WebP dosyaları Display P3 olarak etiketlenir."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Tuval renkleri sRGB olarak önizler; dosyanın profiliyle dışa aktarılan PNG, JPG ve WebP dosyaları Display P3 olarak etiketlenir."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "Dosya sunucudan silinir: artık kimse onu oradan açamaz veya ona katılamaz ve bu işlem geri alınamaz. Açık olan kopyalar, kimdeyse onda kalır."
"The file now holds another library" = "Dosya artık başka bir kitaplık içeriyor"
"The file now holds another library (\"{name}\")" = "Dosya artık başka bir kitaplık içeriyor (“{name}”)"
@@ -1918,6 +1918,7 @@ name = "Türkçe"
"component.combineVariants" = "Varyant olarak birleştir"
"component.create" = "Bileşen oluştur"
"component.createMultiple" = "Birden çok bileşen oluştur"
"component.createSet" = "Bileşen kümesi oluştur"
"component.deleteProperty" = "Bileşen özelliğini sil"
"component.detach" = "Örneği ayır"
"component.editProperty" = "Bileşen özelliğini düzenle"
+2 -1
View File
@@ -1390,7 +1390,7 @@ status = "draft — needs native review"
"Text styles" = "Kiểu văn bản"
"Texts" = "Văn bản"
"Texture" = "Kết cấu"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "Vùng vẽ xem trước màu theo sRGB; các tệp PNG, JPG và WebP xuất ra được gắn thẻ Display P3."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Vùng vẽ xem trước màu theo sRGB; các tệp PNG, JPG và WebP xuất ra theo hồ sơ màu của tệp được gắn thẻ Display P3."
"The destination document is unavailable. Nothing was imported." = "Tài liệu đích không khả dụng. Không có nội dung nào được nhập."
"The destination document was closed. Nothing was imported." = "Tài liệu đích đã đóng. Không có nội dung nào được nhập."
"The destination page was removed. Nothing was imported." = "Trang đích đã bị xóa. Không có nội dung nào được nhập."
@@ -1862,6 +1862,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Kết hợp thành các biến thể"
"component.create" = "Tạo thành phần"
"component.createMultiple" = "Tạo nhiều thành phần"
"component.createSet" = "Tạo bộ thành phần"
"component.deleteProperty" = "Xóa thuộc tính thành phần"
"component.detach" = "Tách bản thể"
"component.editProperty" = "Chỉnh sửa thuộc tính thành phần"
+2 -1
View File
@@ -1387,7 +1387,7 @@ status = "draft — needs native review"
"Text styles" = "文本样式"
"Texts" = "文本"
"Texture" = "纹理"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "画布以 sRGB 预览颜色;导出的 PNG、JPG 和 WebP 文件标记为 Display P3。"
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "画布以 sRGB 预览颜色;使用文件配置文件导出的 PNG、JPG 和 WebP 文件标记为 Display P3。"
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "文件将从服务器删除:任何人都无法再从服务器打开或加入它,且无法撤销。已打开的副本仍归各自持有者所有。"
"The file now holds another library" = "该文件现在包含另一个库"
"The file now holds another library (\"{name}\")" = "该文件现在包含另一个库(“{name}”)"
@@ -1871,6 +1871,7 @@ status = "draft — needs native review"
"component.combineVariants" = "合并为变体"
"component.create" = "创建组件"
"component.createMultiple" = "创建多个组件"
"component.createSet" = "创建组件集"
"component.deleteProperty" = "删除组件属性"
"component.detach" = "分离实例"
"component.editProperty" = "编辑组件属性"
+2 -1
View File
@@ -1542,7 +1542,7 @@ status = "draft — needs native review"
"Texts" = "文字"
"Texture" = "材質"
"The bars are hidden. {shortcut} shows them again" = "工具列已隱藏。按 {shortcut} 可再次顯示"
"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "畫布以 sRGB 預覽顏色;匯出的 PNG、JPG 與 WebP 檔案會標記為 Display P3。"
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "畫布以 sRGB 預覽顏色;使用檔案描述檔匯出的 PNG、JPG 與 WebP 檔案會標記為 Display P3。"
"The destination document is unavailable. Nothing was imported." = "目的地文件無法使用。未匯入任何內容。"
"The destination document was closed. Nothing was imported." = "目的地文件已關閉。未匯入任何內容。"
"The destination page was removed. Nothing was imported." = "目的地頁面已移除。未匯入任何內容。"
@@ -2089,6 +2089,7 @@ status = "draft — needs native review"
"component.combineVariants" = "合併為變體"
"component.create" = "建立元件"
"component.createMultiple" = "建立多個元件"
"component.createSet" = "建立元件集"
"component.deleteProperty" = "刪除元件屬性"
"component.detach" = "分離實例"
"component.editProperty" = "編輯元件屬性"
+55 -7
View File
@@ -119,7 +119,7 @@ fn segment_distance(a: Pos2, b: Pos2, q: Pos2) -> f32 {
}
/// Handle centres of the selected layers (right edge, vertically centred).
fn handles(app: &FigApp, doc: &Document, sel: &[NodeId]) -> Vec<(NodeId, Pos2)> {
pub(crate) fn handles(app: &FigApp, doc: &Document, sel: &[NodeId]) -> Vec<(NodeId, Pos2)> {
sel.iter()
.take(32)
.filter(|i| doc.node(**i).is_some_and(|n| !n.is_page()))
@@ -135,6 +135,52 @@ fn frame_at(app: &FigApp, doc: &Document, page: NodeId, p: Pos2) -> Option<NodeI
doc.top_frames(page).into_iter().rev().find(under).or_else(|| doc.sections_in(page).into_iter().rev().find(under))
}
/// Where a dragged connection would land.
#[derive(Clone, Copy)]
enum Target {
/// A top-level frame or section: a Navigate to it.
Navigate(NodeId),
/// A sibling variant of the source's own variant: a Change to it.
ChangeTo(NodeId),
}
impl Target {
fn node(self) -> NodeId {
match self {
Target::Navigate(n) | Target::ChangeTo(n) => n,
}
}
}
/// The variant (a child of a component set) the layer is, or sits inside.
fn variant_of(doc: &Document, source: NodeId) -> Option<NodeId> {
let is_set = |i: NodeId| doc.node(i).is_some_and(|n| matches!(n.kind, figcraft_doc::NodeKind::ComponentSet { .. }));
std::iter::once(source).chain(doc.ancestors(source)).find(|v| doc.node(*v).and_then(|n| n.parent).is_some_and(is_set))
}
/// What a connection dragged from `source` and released at screen point `p` targets: a sibling
/// variant of the source's own variant (Change to), else a frame other than the source's own
/// (Navigate to). `None` over the source's own variant, over the rest of its set (its background),
/// and where no frame or section is under the pointer.
fn target_at(app: &FigApp, doc: &Document, page: NodeId, source: NodeId, p: Pos2) -> Option<Target> {
if let Some(v) = variant_of(doc, source)
&& let Some(set) = doc.node(v).and_then(|n| n.parent)
&& doc.node(set).is_some_and(|n| matches!(n.kind, figcraft_doc::NodeKind::ComponentSet { .. }))
{
let pt = app.to_page(p);
let siblings = doc.node(set).map(|n| n.children.clone()).unwrap_or_default();
if let Some(w) = siblings.into_iter().rev().find(|w| doc.world_bounds(*w).is_some_and(|b| b.contains(pt))) {
return (w != v).then_some(Target::ChangeTo(w));
}
// The set's own background: nothing, as in Figma, whatever holds the set. (A set in a
// group has no top-level frame, so the fallback below would offer a section around it.)
if doc.world_bounds(set).is_some_and(|b| b.contains(pt)) {
return None;
}
}
frame_at(app, doc, page, p).filter(|f| doc.top_level_frame(source) != Some(*f)).map(Target::Navigate)
}
fn arrow(painter: &egui::Painter, pts: &[Pos2; 4], col: Color32) {
let tip = pts[3];
let dir = (pts[3] - bezier(pts, 0.9)).normalized();
@@ -200,9 +246,8 @@ pub fn draw(app: &FigApp, painter: &egui::Painter) {
}
match dragging {
Some(d) => {
if let Some(f) = frame_at(app, doc, page, d.pos)
&& doc.top_level_frame(d.source) != Some(f)
&& let Some(r) = screen_rect(app, doc, f)
if let Some(t) = target_at(app, doc, page, d.source, d.pos)
&& let Some(r) = screen_rect(app, doc, t.node())
{
painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(2.0, crate::theme::canvas_accent(painter.ctx())), StrokeKind::Outside);
}
@@ -259,9 +304,12 @@ pub fn input(app: &mut FigApp, ui: &egui::Ui, resp: &egui::Response) -> bool {
ctx.request_repaint();
if released || !down {
ctx.data_mut(|m| m.remove::<Drag>(drag_id()));
if let Some(dest) = frame_at(app, &doc, page, d.pos)
&& doc.top_level_frame(d.source) != Some(dest)
&& let Some(r) = app.run("proto.interaction.add", json!({"ids": [d.source], "dest": dest}))
let params = target_at(app, &doc, page, d.source, d.pos).map(|t| match t {
Target::Navigate(dest) => json!({"ids": [d.source], "dest": dest}),
Target::ChangeTo(dest) => json!({"ids": [d.source], "action": {"type": "changeTo", "dest": dest}}),
});
if let Some(params) = params
&& let Some(r) = app.run("proto.interaction.add", params)
{
let k = r.get("index").and_then(Value::as_u64).unwrap_or(0) as usize;
crate::proto_panel::open_editor(&ctx, Some((d.source, k)));
@@ -19,12 +19,19 @@ fn id(v: serde_json::Value) -> NodeId {
fn setup() -> (Ui, NodeId, NodeId) {
let mut s = Session::new();
let mut variants = Vec::new();
let mut icons = Vec::new();
for (k, name) in ["Size=Small, State=Default", "Size=Large, State=Default", "Size=Small, State=Hover"].iter().enumerate() {
let f = id(s.execute("frame.create", &json!({"x": 0, "y": k * 60, "width": 80, "height": 40, "name": name})).unwrap());
// A layer in every variant reads "Icon": an instance lists only the properties its variant uses.
let icon = id(s.execute("shape.rectangle", &json!({"x": 4, "y": 4, "width": 10, "height": 10, "parent": f})).unwrap());
icons.push(icon);
variants.push(id(s.execute("component.create", &json!({"ids": [f]})).unwrap()));
}
let set = id(s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
s.execute("component.addProperty", &json!({"id": set, "name": "Icon", "type": "boolean", "default": true})).unwrap();
s.execute("component.addProperty", &json!({"id": set, "name": "Icon", "type": "boolean", "default": true, "layer": icons[0]})).unwrap();
for icon in &icons[1..] {
s.execute("component.bindProperty", &json!({"layer": icon, "property": "Icon"})).unwrap();
}
let inst = id(s.execute("instance.create", &json!({"component": set, "x": 400, "y": 0})).unwrap());
s.execute("select.set", &json!({"ids": [set]})).unwrap();
(Ui::new(s), set, inst)
@@ -123,3 +130,25 @@ fn escape_cancels_a_property_drag_and_keeps_the_selection() {
assert_eq!(undo_len(&u), undo);
assert_eq!(u.app.session.ds().unwrap().selection, [set], "the Escape only cancels the drag");
}
/// A long property name is cut to one line inside its label box instead of wrapping over the rows
/// above and below (#2022); the name itself stays whole.
#[test]
fn a_long_property_name_stays_on_one_line() {
let long = "Flag Default label with a long name";
let mut s = Session::new();
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 120, "height": 40, "name": "Chip"})).unwrap());
let t = id(s.execute("text.create", &json!({"text": "Label", "x": 4, "y": 4, "parent": f})).unwrap());
let c = id(s.execute("component.create", &json!({"ids": [f]})).unwrap());
s.execute("component.addProperty", &json!({"id": c, "name": long, "type": "text", "layer": t})).unwrap();
let inst = id(s.execute("instance.create", &json!({"component": c, "x": 400, "y": 0})).unwrap());
s.execute("select.set", &json!({"ids": [inst]})).unwrap();
let mut u = Ui::new(s);
let texts = crate::export_name_tests::painted(&mut u);
let panel = u.app.ui.right_panel_rect.expect("the right panel shows");
let labels: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, r)| t.starts_with("Flag") && r.min.x >= panel.min.x).collect();
let [(text, rect)] = labels.as_slice() else { panic!("one property label: {labels:?}") };
assert!(text.ends_with('…'), "cut with an ellipsis, not {text:?}");
assert!(rect.height() <= crate::widgets::FIELD_H, "one line, not {} tall", rect.height());
assert_eq!(names(&mut u, inst), [long], "the name itself stays whole");
}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more