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

This commit is contained in:
bflatastic committed 2026-11-27 15:21:54 +07:00
commit 43b632c32b
113 files changed
+8079 -392

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ env:
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }}
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
+2
View File
@@ -367,7 +367,9 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
| 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. |
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged |
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
+48 -22
View File
@@ -344,6 +344,14 @@ fn main() -> eframe::Result {
let mut session = Session::empty();
// Live sessions: the network threads wake the window when something arrives.
session.live.install(Box::new(figcraft_collab_net::NetLink::new(Arc::new(wake(&ctx_slot)))));
// The preferences first: a file named on the command line opens where it was left and goes to
// the top of the recent files, and they hold the online files a recovered document may be one of.
let recovery = recovery::Shared::default();
let svc = services::Desktop::load(recovery.clone());
svc.follow_system_dark(wake(&ctx_slot));
if let Some(prefs) = svc.prefs.clone() {
session.prefs = prefs;
}
// A file that won't open is said in the window too: it may have been double-clicked.
let mut failed_open = None;
for f in &args.files {
@@ -353,16 +361,9 @@ fn main() -> eframe::Result {
failed_open = Some(format!("{name}: {e}"));
}
}
let opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
let mut opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
// Documents a crashed or killed run left unsaved come back; this run keeps its own copies.
let recovery_root = services::config_dir().map(|d| d.join("Recovery"));
// The preferences first: they hold the online files a recovered document may be one of.
let recovery = recovery::Shared::default();
let svc = services::Desktop::load(recovery.clone());
svc.follow_system_dark(wake(&ctx_slot));
if let Some(prefs) = svc.prefs.clone() {
session.prefs = prefs;
}
let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, &mut session)).unwrap_or_default();
let mut copies = recovery_root.as_deref().and_then(recovery::Recovery::start);
// Copies of online files stay until their files arrive from their servers.
@@ -380,7 +381,20 @@ fn main() -> eframe::Result {
session.invite_links_startup();
}
let first_run = svc.prefs.is_none() && args.join.is_none();
if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) {
if reopens_files(first_run, session.prefs.start_on_home) {
let before: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
for (path, e) in session.reopen_files() {
log::error!("{path}: {e}");
let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
failed_open = Some(format!("{name}: {e}"));
}
// A file named on the command line stays in front.
if let Some(i) = opened.last().and_then(|uid| session.docs.iter().position(|d| d.uid == *uid)) {
session.active = i;
}
opened.extend(session.docs.iter().map(|d| d.uid).filter(|u| !before.contains(u)));
}
if session.docs.is_empty() && opens_new_file(first_run, port.is_some()) {
let _ = session.execute("file.new", &json!({}));
}
// The interface language from the first frame on, and for the message when the window can't
@@ -395,7 +409,8 @@ fn main() -> eframe::Result {
}
fig.automation_roots = roots;
fig.ui.home = false;
// Files named on the command line are the user's too: their missing fonts are listed.
// Files named on the command line or reopened are the user's too: their missing fonts are
// listed.
fig.ui.font_checks = opened;
fig.note_recovered(recovered.copies);
if let Some(message) = failed_open {
@@ -516,12 +531,17 @@ fn main() -> eframe::Result {
graphics.finish(result, frames, port.is_some())
}
/// With nothing to open, whether the window starts in a new file rather than on the home screen.
/// A first run (no settings kept yet) shows the home screen's tips and templates, and later runs
/// start in a new file unless the preference asks for Home, which `--control` overrides: its
/// callers expect a document to act on.
fn opens_new_file(first_run: bool, start_on_home: bool, control: bool) -> bool {
!first_run && (!start_on_home || control)
/// Whether the files open when the app last quit open again: not on a first run (no settings kept
/// yet), nor when the preference asks for the Home screen.
fn reopens_files(first_run: bool, start_on_home: bool) -> bool {
!first_run && !start_on_home
}
/// With nothing open, whether the window starts in a new file rather than on the home screen: only
/// with a control port open (`--control`), whose callers expect a document to act on. A first run
/// shows the home screen's tips and templates whatever the port.
fn opens_new_file(first_run: bool, control: bool) -> bool {
!first_run && control
}
/// The title bar FigCraft starts with, decided by the shared craft-window crate so every Craft app
@@ -617,14 +637,20 @@ mod title_bar_tests {
#[cfg(test)]
mod start_tests {
use super::opens_new_file;
use super::{opens_new_file, reopens_files};
#[test]
fn the_home_preference_starts_on_home_except_for_control_callers() {
assert!(opens_new_file(false, false, false), "a new file by default");
assert!(!opens_new_file(false, true, false), "Home when the preference asks");
assert!(opens_new_file(false, true, true), "--control still starts with a document");
assert!(!opens_new_file(true, false, false), "a first run shows the home screen");
fn the_last_files_reopen_unless_the_home_preference_asks_or_on_a_first_run() {
assert!(reopens_files(false, false), "by default");
assert!(!reopens_files(false, true), "Home when the preference asks");
assert!(!reopens_files(true, false), "a first run has nothing to reopen");
}
#[test]
fn with_nothing_open_only_control_callers_start_in_a_new_file() {
assert!(!opens_new_file(false, false), "the home screen, not an empty file");
assert!(opens_new_file(false, true), "--control starts with a document");
assert!(!opens_new_file(true, true), "a first run shows the home screen");
}
}
+4 -1
View File
@@ -357,9 +357,12 @@ fn open_directory(file: &std::fs::File) -> Result<(), String> {
const STATE: &str = "state.json";
/// Everything quitting keeps, all done when it returns (macOS then ends the process): the
/// preferences in `dir`, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
/// preferences in `dir` with the files open now, which the next start reopens, and where each was
/// left, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
/// and the live sessions' ends (one this app hosts tells everyone and stops; a joined one leaves).
pub fn shutdown(app: &mut FigApp, dir: Option<&Path>, recovery: Option<crate::recovery::Recovery>) {
app.session.remember_open_files();
app.session.remember_views();
if let Some(dir) = dir {
write_prefs(dir, &app.session.prefs);
}
+9
View File
@@ -250,6 +250,15 @@ pub struct CodeLink {
pub name: String,
/// The snippet with `{property}` and `{property ? "a" : "b"}` placeholders.
pub template: String,
/// Where the code component lives, relative to the code repository.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub source: String,
/// What a property's design values are called in code: property → design value → code value.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub values: BTreeMap<String, BTreeMap<String, String>>,
/// Notes for whoever uses the component.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub notes: String,
}
/// A dev resource: a link for developers attached to a layer. The URL is data only: it is shown
+2
View File
@@ -338,6 +338,8 @@ pub fn prop_default_value(d: &PropDef) -> Value {
}
}
#[cfg(test)]
mod nested_binding_tests;
#[cfg(test)]
mod rebase_source_tests;
@@ -35,6 +35,38 @@ pub(super) fn bindings_of<'a>(n: &'a Node, g: &'a str) -> impl Iterator<Item = (
n.bound.iter().filter(move |(k, _)| binding_group(k) == Some(g))
}
/// Whether `n` binds group `g` to other variables than `src` does. Keys are compared by what they
/// bind, so `fill` and `fills/0/color` are the same binding.
pub(super) fn bound_differently(n: &Node, src: &Node, g: &str) -> bool {
let canonical = |m: &Node| -> std::collections::BTreeSet<(String, String)> {
bindings_of(m, g)
.map(|(k, v)| {
let key = crate::cmd::lists::list_binding(k).map_or_else(|| k.clone(), |(l, i, f)| format!("{}/{i}/{f}", l.prefix()));
(key, v.clone())
})
.collect()
};
canonical(n) != canonical(src)
}
/// The property groups whose variable bindings differ between layer `n` and its main layer `src`:
/// overrides even where both resolve to the same value.
pub(super) fn rebound_groups(n: &Node, src: &Node) -> Vec<&'static str> {
let mut compared = Vec::new();
let mut out = Vec::new();
for k in n.bound.keys().chain(src.bound.keys()) {
let Some(g) = binding_group(k) else { continue };
if compared.contains(&g) {
continue;
}
compared.push(g);
if bound_differently(n, src, g) {
out.push(g);
}
}
out
}
/// Property groups that differ between two versions of a node.
pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> {
let mut out = Vec::new();
@@ -0,0 +1,51 @@
use serde_json::json;
use super::rebase_instance;
use super::tests::{button, copy_of, ex, fill, idv, node};
use crate::{NodeId, Session};
fn bound_shape_in_button() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let mut s = Session::new();
let (_, shape, button, nested) = button(&mut s);
ex(&mut s, "variable.createCollection", json!({"name": "T"}));
ex(&mut s, "variable.create", json!({"collection": "T", "name": "ink", "type": "color", "value": "#111111"}));
let inner = copy_of(&s, nested, shape);
ex(&mut s, "variable.bind", json!({"ids": [inner.0], "field": "fill", "variable": "ink"}));
assert!(node(&s, inner).overrides.contains("fills"));
(s, shape, button, nested, inner)
}
#[test]
fn relinking_an_instance_keeps_a_binding_its_main_lacks_as_an_override() {
let (mut s, shape, button, nested, inner) = bound_shape_in_button();
let doc = s.ds_mut().unwrap().doc_mut();
doc.get_mut(inner).unwrap().overrides.clear();
rebase_instance(doc, nested);
assert!(node(&s, inner).overrides.contains("fills"), "the same colour from a variable the main doesn't bind");
ex(&mut s, "node.set", json!({"id": shape, "props": {"fill": "#FF0000"}}));
assert_eq!(fill(&s, inner), "111111", "an edit of the icon's main leaves the bound colour");
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
let copy = copy_of(&s, placed, inner);
assert_eq!(node(&s, copy).bound.values().collect::<Vec<_>>(), [&node(&s, inner).bound["fill"]]);
}
#[test]
fn hiding_and_showing_a_bound_fill_keeps_its_override() {
let (mut s, _, _, _, inner) = bound_shape_in_button();
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": false}));
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": true}));
let n = node(&s, inner);
assert!(n.bound.contains_key("fill"));
assert!(n.overrides.contains("fills"), "the binding still differs from the main's");
}
#[test]
fn a_top_level_instance_s_own_resizing_binding_is_not_an_override() {
let mut s = Session::new();
let (_, _, button, _) = button(&mut s);
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
let doc = s.ds_mut().unwrap().doc_mut();
doc.get_mut(placed).unwrap().bound.insert("minWidth".into(), "VariableID:1:1".into());
rebase_instance(doc, placed);
assert!(!node(&s, placed).overrides.contains("resizing"), "a top-level instance's resizing is its own");
}
+8 -3
View File
@@ -1,4 +1,4 @@
use super::diff::{binding_group, bindings_of, diff_groups, follow_boolean_defaults, geometry_derived, variable_groups};
use super::diff::{binding_group, bound_differently, diff_groups, follow_boolean_defaults, geometry_derived, rebound_groups, variable_groups};
use super::guard::{own_slot_content, relink_copy};
use super::instances::{copy_group, field_group, sync_instance};
use super::sync::insert_linked;
@@ -179,12 +179,17 @@ fn override_groups(doc: &Document, before: &Document, id: NodeId, n: &Node, b: &
// Binding another variable (or none) where the main binds one is an override.
for (k, _) in b.bound.iter().chain(n.bound.iter()) {
let Some(g) = binding_group(k) else { continue };
let rebound = b.bound.get(k) != n.bound.get(k) && !bindings_of(n, g).eq(bindings_of(src, g));
let rebound = b.bound.get(k) != n.bound.get(k) && bound_differently(n, src, g);
if rebound && !groups.contains(&g) {
groups.push(g);
}
}
cleared = raw.iter().filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && n.overrides.contains(**g)).copied().collect();
let rebound = rebound_groups(n, src);
cleared = raw
.iter()
.filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && !rebound.contains(g) && n.overrides.contains(**g))
.copied()
.collect();
if top_root {
cleared.retain(|g| !matches!(*g, "component" | "props"));
}
@@ -1,4 +1,4 @@
use super::diff::{diff_groups, variable_groups};
use super::diff::{diff_groups, rebound_groups, variable_groups};
use super::instances::{field_group, path_map};
use super::{BTreeMap, BTreeSet, Document, MAX_DEPTH, Node, NodeId, NodeKind, default_instance_name, holds_content};
@@ -216,6 +216,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
let mut bound: Vec<&str> = m.prop_refs.keys().map(|f| field_group(f)).collect();
bound.extend(variable_groups(n, m));
overrides.extend(value_groups(m, n).into_iter().filter(|g| !bound.contains(&g.as_str())));
overrides.extend(rebound_groups(n, m).into_iter().map(str::to_string));
if matches!((&m.kind, &n.kind), (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) if a != b) {
overrides.insert("component".into());
}
@@ -233,6 +234,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
let mut groups: Vec<String> = value_groups(m, n)
.into_iter()
.filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str()))
.chain(rebound_groups(n, m).into_iter().map(str::to_string))
.filter(|g| placed_source.is_some() || !matches!(g.as_str(), "resizing" | "modes"))
.collect();
let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) };
@@ -115,9 +115,65 @@ fn match_layers(
}
m.map.insert(*s, nid);
}
match_text_by_name(doc, inst, component, src, old, &mut m);
m
}
/// Main text layers nothing matched take the unmatched old text layer of the same name, when
/// exactly one of each has it: text typed into an instance stays when it switches to a variant that
/// nests the same text layer in other frames (its name path differs). Only layers outside nested
/// instances, which rebuild from their own mains. Names are counted over all those text layers,
/// matched ones too, so a name two layers share on either side never pairs by elimination.
fn match_text_by_name(
doc: &Document,
inst: NodeId,
component: NodeId,
src: &[NodeId],
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
m: &mut Matched,
) {
fn unique<K: Ord>(pairs: impl Iterator<Item = (K, NodeId)>) -> BTreeMap<K, NodeId> {
let mut seen: BTreeMap<K, Option<NodeId>> = BTreeMap::new();
for (k, id) in pairs {
seen.entry(k).and_modify(|e| *e = None).or_insert(Some(id));
}
seen.into_iter().filter_map(|(k, id)| Some((k, id?))).collect()
}
let text = |n: &Node| matches!(n.kind, NodeKind::Text(_));
let mut mains =
unique(src.iter().filter_map(|s| doc.node(*s)).filter(|s| text(s) && outside_nested(doc, s.id, component)).map(|s| (s.name.clone(), s.id)));
mains.retain(|_, s| m.fresh.contains(s));
if mains.is_empty() {
return;
}
let olds = unique(
old.iter()
.filter(|(id, o)| text(o) && outside_nested(doc, **id, inst))
.map(|(id, o)| (o.source.and_then(|s| doc.node(s)).map_or(&o.name, |s| &s.name).clone(), *id)),
);
for (name, s) in mains {
if let Some(o) = olds.get(&name).filter(|o| !m.used.contains(*o)) {
m.used.insert(*o);
m.map.insert(s, *o);
m.fresh.retain(|f| *f != s);
}
}
}
/// Whether layer `id` is below `root` with no instance between them.
fn outside_nested(doc: &Document, id: NodeId, root: NodeId) -> bool {
let mut cur = doc.node(id).and_then(|n| n.parent);
for _ in 0..=1_000_000 {
match cur.and_then(|c| doc.node(c)) {
Some(n) if n.id == root => return true,
Some(n) if matches!(n.kind, NodeKind::Instance { .. }) => return false,
Some(n) => cur = n.parent,
None => return false,
}
}
false
}
/// A rebuild's copies of the main's layers, pre-order (parents first).
struct Copies {
nodes: Vec<Node>,
@@ -282,6 +282,50 @@ fn variant_switch_keeps_compatible_overrides() {
healthy(&s);
}
#[test]
fn typed_text_stays_across_variants_that_nest_it_differently() {
let mut s = Session::new();
// Each variant's Label layers, by the frames holding them.
let shapes: [(&str, &[&[&str]]); 4] =
[("Kind=Plain", &[&["text"]]), ("Kind=Boxed", &[&["div", "text"]]), ("Kind=Twice", &[&["a"], &["b"]]), ("Kind=Moved", &[&["a"], &["c"]])];
let mut labels = Vec::new();
let mut variants = Vec::new();
for (k, (name, paths)) in shapes.into_iter().enumerate() {
let v = idv(&ex(&mut s, "frame.create", json!({"x": k as f64 * 300.0, "y": 0, "width": 200, "height": 60, "name": name})));
for frames in paths {
let mut parent = v;
for f in *frames {
parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "parent": parent, "name": f})));
}
labels.push(idv(&ex(&mut s, "text.create", json!({"text": "I agree", "x": 0, "y": 0, "parent": parent, "props": {"name": "Label"}}))));
}
variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [v]}))));
}
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
let i = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 0, "y": 300})));
let typed = copy_of(&s, i, labels[0]);
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Boxed"}}));
healthy(&s);
assert_eq!(chars(&s, copy_of(&s, i, labels[1])), "Architect", "one frame deeper, same name");
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Plain"}}));
assert_eq!(chars(&s, copy_of(&s, i, labels[0])), "Architect", "and back");
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Twice"}}));
healthy(&s);
let texts: Vec<String> = labels[2..4].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
assert_eq!(texts, ["I agree", "I agree"], "two layers of that name: neither is the one typed into");
// `a › Label` matches by path; the leftover `b › Label` and `c › Label` still share a name with it.
let typed = copy_of(&s, i, labels[3]);
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Moved"}}));
healthy(&s);
let texts: Vec<String> = labels[4..].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
assert_eq!(texts, ["I agree", "I agree"], "a name two layers share doesn't pair what path matching left over");
}
#[test]
fn detach_keeps_the_look() {
let mut s = Session::new();
+40 -19
View File
@@ -1422,25 +1422,7 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
remote.extend(merge_components(doc, src, &BTreeMap::new(), Some(&foreign))?);
}
// Components `src` publishes: from its library.
if let Some(lib) = src.published.as_ref().filter(|l| own.as_deref() != Some(l.manifest.id.as_str())) {
let keys: Vec<NodeId> =
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
if !keys.is_empty() {
remote.extend(import(doc, lib, &keys, false)?);
let m = &lib.manifest;
if doc.libraries.link(&m.id).is_none()
&& let Some(path) = src_path
{
doc.libraries_mut().enabled.push(LibraryLink {
id: m.id.clone(),
name: m.name.clone(),
path: path.to_string(),
version: m.version,
relative: String::new(),
});
}
}
}
remote.extend(from_published(doc, src, src_path, &roots)?);
// Point the pasted layers at those mains; what stays behind gets ids of its own.
let mut behind: BTreeMap<NodeId, NodeId> = BTreeMap::new();
let mut follow = |doc: &mut Document, id: NodeId| -> NodeId {
@@ -1479,6 +1461,45 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
Ok(())
}
/// `doc`'s copies of the components among `roots` (assets of `src`) that `src` publishes as a
/// library (`src`'s ids → `doc`'s), taken from that library, which gets enabled in `doc` when `src`
/// is saved at `src_path`. Empty when `src` publishes no library, or publishes `doc`'s own.
fn from_published(doc: &mut Document, src: &Document, src_path: Option<&str>, roots: &[NodeId]) -> Result<BTreeMap<NodeId, NodeId>> {
let own = doc.published.as_ref().map(|p| p.manifest.id.as_str());
let Some(lib) = src.published.as_ref().filter(|l| own != Some(l.manifest.id.as_str())) else { return Ok(BTreeMap::new()) };
let keys: Vec<NodeId> =
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
if keys.is_empty() {
return Ok(BTreeMap::new());
}
let remote = import(doc, lib, &keys, false)?;
let m = &lib.manifest;
if doc.libraries.link(&m.id).is_none()
&& let Some(path) = src_path
{
doc.libraries_mut().enabled.push(LibraryLink {
id: m.id.clone(),
name: m.name.clone(),
path: path.to_string(),
version: m.version,
relative: String::new(),
});
}
Ok(remote)
}
/// The main in `doc` that pasting main component `main`, copied from another document `src`,
/// makes an instance of: `doc`'s copy of it from the library `src` publishes, as
/// [`adopt_pasted`] uses for instances. `None` when `src` doesn't offer it, so the paste copies
/// the main itself: also when the library holds it only because an offered component uses it.
pub fn published_main(doc: &mut Document, src: &Document, src_path: Option<&str>, main: NodeId) -> Result<Option<NodeId>> {
let Some(root) = asset_root(src, main) else { return Ok(None) };
if !src.published.as_ref().and_then(|l| l.manifest.component(root)).is_some_and(|a| a.published) {
return Ok(None);
}
Ok(from_published(doc, src, src_path, &[root])?.get(&main).copied())
}
/// Refuse edits of library copies, except by library commands (and imports of other files,
/// which bring their copies along).
pub fn check_read_only(cmd: &str, before: &Document, after: &Document) -> std::result::Result<(), String> {
+69
View File
@@ -695,3 +695,72 @@ fn library_links_follow_a_moved_folder() {
link_found(&mut s, &lid);
let _ = std::fs::remove_dir_all(&d);
}
/// A main component copied from a library file and pasted into another file is an instance of it
/// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance
/// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the
/// library holds because an offered component uses it.
#[test]
fn a_main_pasted_from_its_library_file_is_an_instance_of_it() {
let d = dir("paste-main");
let lib_path = path_str(&d.join("kit.figcraft"));
let mut s = Session::new();
let k = kit(&mut s);
let sizes: Vec<NodeId> = ["Size=S", "Size=L"]
.iter()
.enumerate()
.map(|(n, name)| {
idv(&ex(
&mut s,
"node.create",
json!({"type": "component", "name": name, "x": 600.0 + n as f64 * 100.0, "y": 0, "width": 40, "height": 20}),
))
})
.collect();
ex(&mut s, "component.combineVariants", json!({"ids": sizes.clone()}));
let spare = idv(&ex(&mut s, "frame.create", json!({"x": 300, "y": 300, "width": 10, "height": 10, "name": "_Spare"})));
let spare = idv(&ex(&mut s, "component.create", json!({"ids": [spare]})));
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 400, "y": 300, "width": 10, "height": 10, "name": "_Icon"})));
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon]})));
let badge = idv(&ex(&mut s, "frame.create", json!({"x": 500, "y": 300, "width": 30, "height": 30, "name": "Badge"})));
ex(&mut s, "instance.create", json!({"component": icon, "x": 5, "y": 5, "parent": badge}));
ex(&mut s, "component.create", json!({"ids": [badge]}));
let lid = publish_to(&mut s, &lib_path);
assert!(s.doc().unwrap().published.as_ref().unwrap().manifest.component(icon).is_some_and(|a| !a.published));
let at = s.doc().unwrap().world_bounds(k.button).unwrap();
ex(&mut s, "file.new", json!({"name": "Design"}));
let paste = |s: &mut Session, main: NodeId| -> NodeId {
ex(s, "doc.switch", json!({"index": 0}));
ex(s, "edit.copy", json!({"ids": [main]}));
ex(s, "doc.switch", json!({"index": 1}));
id_of(&ex(s, "edit.paste", json!({}))["ids"][0]).unwrap()
};
let main_of = |s: &Session, id: NodeId| match node(s, id).kind {
NodeKind::Instance { component, .. } => component,
k => panic!("not an instance: {k:?}"),
};
let button = paste(&mut s, k.button);
let doc = s.doc().unwrap();
assert_eq!(library_source(doc, main_of(&s, button)), Some((lid.as_str(), k.button)));
assert_eq!(doc.libraries.enabled.iter().map(|l| l.path.as_str()).collect::<Vec<_>>(), [lib_path.as_str()]);
assert_eq!(doc.world_bounds(button), Some(at), "where the main was");
let label = node(&s, button).children[0];
assert_eq!(chars(&s, label), "OK");
healthy(&s);
let copies = s.doc().unwrap().libraries.components.len();
let again = paste(&mut s, k.button);
assert_eq!(main_of(&s, again), main_of(&s, button), "the same library copy");
assert_eq!(s.doc().unwrap().libraries.components.len(), copies);
let large = paste(&mut s, sizes[1]);
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, large)), Some((lid.as_str(), sizes[1])));
let card = paste(&mut s, k.card);
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, card)), Some((lid.as_str(), k.card)));
let copy = paste(&mut s, spare);
assert!(matches!(node(&s, copy).kind, NodeKind::Component { .. }), "not offered by the library: a copy");
assert!(!s.doc().unwrap().is_remote(copy));
let icon_copy = paste(&mut s, icon);
assert!(matches!(node(&s, icon_copy).kind, NodeKind::Component { .. }), "only used by an offered component: a copy");
assert!(!s.doc().unwrap().is_remote(icon_copy));
healthy(&s);
let _ = std::fs::remove_dir_all(d);
}
+20 -1
View File
@@ -4,13 +4,32 @@
//! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to
//! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide).
use figcraft_doc::{BoardItem, Document, NodeId};
use figcraft_doc::{BoardItem, Document, Node, NodeId, NodeKind};
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
use serde::Serialize;
use crate::guides;
use crate::tools::UNMEASURED_SNAP_PX;
/// Whether `n` lands on whole pixels when dragged whatever Snap to pixel grid says: frames,
/// sections, components, component sets and instances. Figma's help: they "always snap to the
/// pixel grid, even if Snap to pixel grid is disabled". Other layers follow the setting.
pub fn always_on_pixels(n: &Node) -> bool {
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })
}
/// Put `id`'s position in its parent on whole pixels when its axes are its parent's: returns
/// whether it moved. A layer turned off its parent's axes keeps its position.
pub fn settle_on_pixels(doc: &mut Document, id: NodeId) -> crate::Result<bool> {
let n = doc.get_mut(id)?;
let [a, b, c, d, e, f] = n.transform.as_coeffs();
if !guides::axis_aligned(n.transform) || (e.round() == e && f.round() == f) {
return Ok(false);
}
n.transform = Affine::new([a, b, c, d, e.round(), f.round()]);
Ok(true)
}
/// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label
/// (a distance) at its middle; `dashed` marks a measurement's extension line.
#[derive(Clone, Debug, PartialEq, Serialize)]
+194 -2
View File
@@ -1,8 +1,9 @@
//! On-canvas text editing: caret, selection, typing. A whole editing session is one undo step.
use std::collections::BTreeMap;
use std::sync::{LazyLock, Mutex};
use figcraft_doc::{Document, ListStyle, NodeId, NodeKind, TextData};
use figcraft_doc::{Document, ImageData, ListStyle, NodeId, NodeKind, TextData};
use crate::{EngineError, Preedit, Result, Session, TextEdit};
@@ -401,6 +402,94 @@ pub fn list_indent(s: &mut Session, out: bool) -> Result<bool> {
Ok(text_of(s, id)? != before)
}
/// Whether Tab in text layer `id` moves between text layers: not in a board object's text (a
/// sticky's note, a table cell, a code block) or a widget's field, where it types as before.
fn tabs_between_texts(doc: &Document, id: NodeId) -> bool {
!in_board_object(doc, id) && crate::widgets::field_of(doc, id).is_none()
}
fn in_board_object(doc: &Document, id: NodeId) -> bool {
std::iter::once(id).chain(doc.ancestors(id)).any(|a| doc.node(a).is_some_and(|n| n.board.is_some()))
}
/// Tab (Shift+Tab: `back`) while editing text layer `from`: editing it ends as Escape ends it, and
/// the next (previous) text layer in reading order is edited with all of its text selected. At the
/// last (first) one nothing happens.
fn tab_to_next_text(s: &mut Session, from: NodeId, back: bool) -> Result<()> {
let order = reading_order(s.doc()?, tab_stops(s.doc()?, from));
let Some(at) = order.iter().position(|t| *t == from) else { return Ok(()) };
let next = if back { at.checked_sub(1).and_then(|i| order.get(i)) } else { order.get(at + 1) };
let Some(&next) = next else { return Ok(()) };
end(s)?;
begin(s, next, None, false)
}
/// The text layers Tab moves between from text layer `from`: those in the top-level layer holding
/// it (the frame or group on the page or in a section), at any depth and inside instances, that are
/// visible and unlocked with every layer around them and not in a board object; for a text on the
/// page or in a section itself, the text layers beside it there. `from` is always one of them.
fn tab_stops(doc: &Document, from: NodeId) -> Vec<NodeId> {
let is_section = |id: &NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }));
let chain: Vec<NodeId> = std::iter::once(from).chain(doc.ancestors(from)).collect();
let Some(page_at) = chain.iter().position(|c| doc.node(*c).is_some_and(|n| n.is_page())) else { return vec![from] };
let top = chain.get(..page_at).and_then(|below| below.iter().rev().copied().find(|c| !is_section(c)));
let stop = |n: &figcraft_doc::Node| n.visible && !n.locked && n.board.is_none();
let mut out = Vec::new();
match top {
Some(top) if top != from => {
let mut stack = vec![top];
let mut seen = 0usize;
while let Some(id) = stack.pop() {
seen += 1;
if seen > 1_000_000 {
break;
}
let Some(n) = doc.node(id).filter(|n| stop(n)) else { continue };
if matches!(n.kind, NodeKind::Text(_)) {
out.push(id);
}
stack.extend(n.children.iter().copied());
}
}
_ => {
let beside = doc.node(from).and_then(|n| n.parent).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default();
out.extend(beside.into_iter().filter(|c| doc.node(*c).is_some_and(|n| stop(n) && matches!(n.kind, NodeKind::Text(_)))));
}
}
if !out.contains(&from) {
out.push(from);
}
out
}
/// `ids` in reading order by their boxes on the page: rows top to bottom, each row left to right.
/// Rows are made from the top down: a layer joins the row of the topmost layer before it when the
/// two overlap vertically by more than nothing and by at least half the height of the shorter one,
/// else it starts the next row. Layers without bounds are left out.
fn reading_order(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
let mut boxes: Vec<(NodeId, figcraft_geom::Rect)> = ids.into_iter().filter_map(|i| Some((i, doc.world_bounds(i)?))).collect();
boxes.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0).then(a.1.x0.total_cmp(&b.1.x0)));
let mut rows: Vec<Vec<(NodeId, figcraft_geom::Rect)>> = Vec::new();
for (id, b) in boxes {
let joins = |row: &Vec<(NodeId, figcraft_geom::Rect)>| {
row.first().is_some_and(|(_, a)| {
let overlap = a.y1.min(b.y1) - a.y0.max(b.y0);
overlap > 0.0 && overlap >= 0.5 * a.height().min(b.height())
})
};
match rows.last_mut() {
Some(row) if joins(row) => row.push((id, b)),
_ => rows.push(vec![(id, b)]),
}
}
rows.into_iter()
.flat_map(|mut row| {
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.1.y0.total_cmp(&b.1.y0)));
row.into_iter().map(|(id, _)| id)
})
.collect()
}
/// The kind of word char `i` belongs to: 0 for spaces and punctuation, else its script, so a word
/// ends where the script changes (Han, hiragana, katakana and Hangul runs are words of their own in
/// text without spaces). Combining marks and voicing marks belong to the char before them.
@@ -459,7 +548,9 @@ fn word_right(chars: &[char], mut i: usize) -> usize {
i
}
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Escape, SelectAll.
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Tab, Escape, SelectAll.
/// Tab and Shift+Tab outside a list, a code block, a board object and a widget's field edit the
/// next or previous text layer ([`tab_to_next_text`]).
/// `word` moves or deletes by word, `line` to the line's ends (Up/Down, Home/End: the text's ends);
/// [`crate::keymap::text_motion`] gives them for the platform's keys. `ArrowLeft` etc. also work.
pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> Result<()> {
@@ -484,6 +575,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
match key {
"Escape" => return end(s),
"Enter" => return insert(s, "\n"),
"Tab" if !word && !line && tabs_between_texts(s.doc()?, te.id) => return tab_to_next_text(s, te.id, shift),
"Tab" => return insert(s, "\t"),
"Backspace" | "Delete" => {
return edit(s, |t, te| {
@@ -856,6 +948,106 @@ pub fn selected_text(s: &Session) -> Option<String> {
Some(t.characters.chars().skip(a).take(b.saturating_sub(a)).collect())
}
/// Copied characters with their formatting, for a paste into a text edit that keeps it.
#[derive(Clone, Debug, PartialEq)]
pub struct RichText {
pub text: String,
/// Styled runs as `(from, to, style)` char ranges of `text`. Each style carries its fills,
/// the layer's own where the run had none, so the characters keep their colour elsewhere.
pub spans: Vec<(usize, usize, figcraft_doc::TextStyle)>,
/// The data of the images the runs' fills use, so they resolve in another file.
pub images: BTreeMap<String, ImageData>,
}
/// The selected characters while editing, with their formatting (for copy).
pub fn selected_rich_text(s: &Session) -> Option<RichText> {
let (id, a, b) = selected_range(s)?;
rich_text_of(s.doc().ok()?, id, a, b)
}
/// The characters of the text layers `ids`, one per line, with their formatting; None when one of
/// them isn't a text layer or there are no characters.
pub fn layers_rich_text(doc: &Document, ids: &[NodeId]) -> Option<RichText> {
let mut joined = RichText { text: String::new(), spans: Vec::new(), images: BTreeMap::new() };
let mut offset = 0;
for (i, id) in ids.iter().enumerate() {
let layer = rich_text_of(doc, *id, 0, usize::MAX)?;
if i > 0 {
joined.text.push('\n');
offset += 1;
}
joined.text.push_str(&layer.text);
joined.spans.extend(layer.spans.into_iter().map(|(from, to, style)| (from + offset, to + offset, style)));
joined.images.extend(layer.images);
offset += layer.text.chars().count();
}
(!joined.text.is_empty()).then_some(joined)
}
/// Chars `a..b` of the text layer `id` (`b` past the end means to the end), with their formatting.
fn rich_text_of(doc: &Document, id: NodeId, a: usize, b: usize) -> Option<RichText> {
let n = doc.node(id)?;
let t = n.kind.text()?;
let b = b.min(t.char_count());
let text: String = t.characters.chars().skip(a).take(b.saturating_sub(a)).collect();
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = t
.spans()
.into_iter()
.filter(|(from, to, _)| *to > a && *from < b)
.map(|(from, to, style)| {
let mut style = style.clone();
style.fills.get_or_insert_with(|| n.fills.clone());
(from.max(a) - a, to.min(b) - a, style)
})
.collect();
let mut images = BTreeMap::new();
for paint in spans.iter().flat_map(|(_, _, style)| style.fills.iter().flatten()) {
if let figcraft_color::PaintKind::Image(img) = &paint.kind
&& let Some(d) = doc.images.get(&img.image)
{
images.insert(img.image.clone(), d.clone());
}
}
Some(RichText { text, spans, images })
}
/// Replace the selection in the text edit with `rich`, keeping its formatting. A link to a style
/// this file doesn't have is dropped, a fill equal to the layer's is left to the layer, and the
/// copied image data is added where this file lacks the key, as a pasted layer's is.
pub fn insert_rich(s: &mut Session, rich: &RichText) -> Result<()> {
if s.ds()?.text_edit.is_some() {
let doc = s.doc_mut()?;
for (k, v) in &rich.images {
doc.images.entry(k.clone()).or_insert_with(|| v.clone());
}
}
let doc = s.doc()?;
let layer_fills = s.ds()?.text_edit.as_ref().and_then(|te| doc.node(te.id)).map(|n| n.fills.clone());
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = rich
.spans
.iter()
.map(|(from, to, style)| {
let mut style = style.clone();
if style.style_id.as_deref().is_some_and(|id| doc.style(id).is_none()) {
style.style_id = None;
}
if style.fills == layer_fills {
style.fills = None;
}
(*from, *to, style)
})
.collect();
edit(s, |t, te| {
let (a, b) = range(te);
t.replace_range(a, b, &rich.text);
for (from, to, style) in &spans {
t.restyle(a + from, a + to, |x| *x = style.clone());
}
te.caret = a + rich.text.chars().count();
te.anchor = te.caret;
})
}
/// The selected range while editing (for styling commands), or None.
pub fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> {
let te = s.ds().ok()?.text_edit.clone()?;
@@ -569,3 +569,52 @@ fn an_empty_ime_commit_ends_the_composition_without_inserting_text() {
end(&mut s).unwrap();
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
}
#[test]
fn rich_text_pastes_its_runs_and_drops_a_link_to_a_style_this_file_lacks() {
let (mut s, id) = setup("ab");
begin(&mut s, id, Some(2), false).unwrap();
let mut bold = data(&s, id).style.clone();
bold.font_style = "Bold".into();
bold.style_id = Some("from another file".into());
let plain = data(&s, id).style.clone();
insert_rich(&mut s, &RichText { text: "XY".into(), spans: vec![(0, 1, bold), (1, 2, plain)], images: Default::default() }).unwrap();
let t = data(&s, id);
assert_eq!(t.characters, "abXY");
assert_eq!(t.style_at(2).font_style, "Bold");
assert_eq!(t.style_at(2).style_id, None, "a link to a style this file doesn't have");
assert_eq!(t.style_at(3).font_style, "Regular");
assert_eq!(sel(&s), (4, 4));
set_caret(&mut s, 2, false).unwrap();
set_caret(&mut s, 4, true).unwrap();
let copied = selected_rich_text(&s).unwrap();
assert_eq!(copied.text, "XY");
assert_eq!(copied.spans.iter().map(|(a, b, st)| (*a, *b, st.font_style.as_str())).collect::<Vec<_>>(), [(0, 1, "Bold"), (1, 2, "Regular")]);
}
#[test]
fn copied_characters_bring_the_image_their_fill_uses_into_another_file() {
let (mut source, id) = setup("ab");
let data = figcraft_doc::ImageData { bytes: std::sync::Arc::new(vec![1, 2, 3]), width: 2, height: 2 };
{
let doc = source.doc_mut().unwrap();
doc.images.insert("pic".into(), data.clone());
doc.get_mut(id).unwrap().fills = vec![figcraft_color::Paint::image("pic", figcraft_color::ImageScaleMode::Fill)];
}
begin(&mut source, id, Some(0), false).unwrap();
set_caret(&mut source, 2, true).unwrap();
let copied = selected_rich_text(&source).unwrap();
let (mut s, target) = setup("cd");
begin(&mut s, target, Some(2), false).unwrap();
insert_rich(&mut s, &copied).unwrap();
assert_eq!(s.doc().unwrap().images.get("pic"), Some(&data), "the run's image fill resolves here");
}
#[test]
fn copied_text_layers_join_one_per_line_with_their_runs_in_place() {
let (mut s, first) = setup("ab");
let second = crate::params::id_of(&s.execute("text.create", &json!({"text": "cdé", "x": 0, "y": 50})).unwrap()["id"]).unwrap();
let joined = layers_rich_text(s.doc().unwrap(), &[first, second]).unwrap();
assert_eq!(joined.text, "ab\ncdé");
assert_eq!(joined.spans.iter().map(|(a, b, _)| (*a, *b)).collect::<Vec<_>>(), [(0, 2), (3, 6)]);
}
+4
View File
@@ -649,6 +649,10 @@ pub struct ToolState {
pub place_at: Option<Point>,
/// The document (uid) and page the crosshair was shown on.
pub(crate) place_on: Option<(u64, NodeId)>,
/// The last two Move or Scale presses, oldest first: where each was and the selection just
/// before it. A Shift double-click works from the selection its first click found. A press
/// with another tool clears them, and so does the double-click that uses them.
pub(crate) selections_before_last_two_presses: [Option<(Point, Vec<NodeId>)>; 2],
}
impl ToolState {
+45 -1
View File
@@ -139,6 +139,38 @@ impl Session {
return crate::vectoredit::begin_many(self, &ids);
}
// Groups, frames and boolean groups: select one level deeper (the layer under the pointer).
if ev.shift && !ev.cmd {
// Both presses recorded here are this double-click's; without them (the presses came in
// one frame with the double-click, or with another tool) the current selection stands in.
let before_the_clicks = match std::mem::take(&mut self.tool.selections_before_last_two_presses) {
[Some((first, before)), Some((second, _))] if within_slop(ev, first) && within_slop(ev, second) => before,
_ => sel.clone(),
};
let entered_here = before_the_clicks.iter().any(|s| *s == leaf || doc.is_ancestor(*s, leaf));
let deeper = if entered_here {
figcraft_doc::geometry::enter_target(&doc, leaf, &before_the_clicks)
} else {
let mut branch = doc.ancestors(leaf);
branch.reverse();
branch.push(leaf);
let clicked = select_target(&doc, leaf, &before_the_clicks, false);
let beside_the_selection = before_the_clicks
.iter()
.filter_map(|s| branch.iter().rposition(|b| doc.is_ancestor(*b, *s)))
.max()
.and_then(|shared| branch.get(shared + 1))
.copied();
let start = beside_the_selection.filter(|b| doc.is_ancestor(clicked, *b)).unwrap_or(clicked);
figcraft_doc::geometry::enter_target(&doc, leaf, &[start])
};
let mut alongside: Vec<NodeId> = before_the_clicks
.into_iter()
.filter(|s| doc.contains(*s) && *s != deeper && !doc.is_ancestor(*s, deeper) && !doc.is_ancestor(deeper, *s))
.collect();
alongside.push(deeper);
self.set_selection(alongside);
return Ok(());
}
let deeper = figcraft_doc::geometry::enter_target(&doc, leaf, &sel);
if deeper != target || !sel.contains(&deeper) {
self.set_selection(vec![deeper]);
@@ -382,7 +414,15 @@ impl Session {
// and what to call it; nothing is applied).
self.request_ui("dialog.createFromColor", json!({"color": c.to_css_hex()}));
} else if !sel.is_empty() {
self.execute("node.set", &json!({"ids": sel, "props": {"fill": c.to_css_hex()}}))?;
let (stroked, filled): (Vec<NodeId>, Vec<NodeId>) = sel.iter().partition(|id| doc.node(**id).is_some_and(takes_pick_on_stroke));
self.grouped("Pick color", |s| {
for (ids, key) in [(filled, "fill"), (stroked, "stroke")] {
if !ids.is_empty() {
s.execute("node.set", &json!({"ids": ids, "props": {key: c.to_css_hex()}}))?;
}
}
Ok(())
})?;
}
self.recent_colors.retain(|x| *x != c);
self.recent_colors.insert(0, c);
@@ -392,3 +432,7 @@ impl Session {
Ok(())
}
}
fn takes_pick_on_stroke(n: &Node) -> bool {
!n.fills.iter().any(|p| p.visible) && n.strokes.iter().any(|p| p.visible)
}
+231 -46
View File
@@ -79,15 +79,22 @@ impl Session {
// layers in it is like the canvas (a press starts a marquee inside it) unless the frame is
// selected; stepping out from a selected descendant is handled by the marquee below.
// An empty frame (or a widget, or a board object such as a sticky) is picked and dragged.
let in_section = |n: &figcraft_doc::Node| n.parent.and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Section { .. }));
let board_background = |leaf: NodeId| {
!sel.contains(&leaf)
(ev.cmd || !sel.contains(&leaf))
&& doc.node(leaf).is_some_and(|n| {
n.parent == Some(page) && n.kind.is_frame_like() && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom()
let board = match n.kind {
NodeKind::Section { contents_hidden } => !contents_hidden,
ref k => k.is_frame_like() && (n.parent == Some(page) || in_section(n)),
};
board && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom()
})
};
let label = label_at(&doc, page, &self.tool.labels, ev.p());
let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0));
let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
let leaf = self.hit(&doc, page, ev.p(), ev.tol() * 2.0);
let hit = label.or(leaf);
let background_under_cmd = leaf.filter(|l| ev.cmd && label.is_none() && board_background(*l));
let target = label.or_else(|| leaf.filter(|leaf| !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
// A press inside the selection's box that reaches nothing above it (an unfilled shape's
// inside, the frame or canvas behind it, or a layer stacked below the selected layer the
// press is in) drags the selection. In a gap between selected layers, what's there is hit.
@@ -105,8 +112,15 @@ impl Session {
// selects just it. A press that reaches nothing above the selection uses the selection as
// its drag target instead; that fallback is not a clicked layer.
let clicked = target;
let marks_out_a_selected_board = background_under_cmd.is_some_and(|b| sel.contains(&b));
let target = match sel.iter().copied().find(|s| !locked_in(&doc, *s)) {
Some(first) if label.is_none() && !ev.shift && behind_sel(target) && selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) => {
Some(first)
if label.is_none()
&& !ev.shift
&& !marks_out_a_selected_board
&& behind_sel(target)
&& selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) =>
{
Some(first)
}
_ => target,
@@ -186,7 +200,7 @@ impl Session {
if let Some(f) = parent {
self.set_selection(vec![f]);
} else if !ev.shift {
self.set_selection(vec![]);
self.set_selection(background_under_cmd.into_iter().collect());
}
self.tool.gesture = Gesture::Marquee {
start: ev.p(),
@@ -249,7 +263,11 @@ impl Session {
let raw = d;
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
let mut guides = Vec::new();
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
let boards = {
let doc = self.doc()?;
ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
};
if boards || self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one);
// snapping to layers comes after, so it wins on the axes it snaps.
d = targets.round_move(d);
@@ -259,6 +277,11 @@ impl Session {
d += c;
guides = g2;
}
if boards {
// Frames, sections and components stay on whole pixels even where a layer
// they snap to doesn't.
d = targets.round_move(d);
}
let ids = ids.clone();
let dup = *duplicate;
let page = self.page()?;
@@ -343,6 +366,9 @@ impl Session {
doc.reparent(*m, page, None)?;
}
move_world(doc, *m, d.x, d.y)?;
if doc.node(*m).is_some_and(crate::snap::always_on_pixels) {
shifted &= !crate::snap::settle_on_pixels(doc, *m)?;
}
}
drop_target = (flow && target != page).then_some(target);
Ok(())
@@ -521,7 +547,13 @@ impl Session {
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
// scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes
// it snaps.
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
// Frames, sections and components land on whole pixels whatever the setting, also where a
// layer they snap to doesn't.
let boards = {
let doc = self.doc()?;
!scale_tool && crate::guides::axis_aligned(frame) && ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
};
if boards || !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
p = Point::new(p.x.round(), p.y.round());
}
if let Some(t) = &targets {
@@ -530,6 +562,9 @@ impl Session {
p.y += dy;
guides = g;
}
if boards {
p = Point::new(p.x.round(), p.y.round());
}
let q = frame.inverse() * p;
let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false);
if scale_tool {
@@ -557,9 +592,16 @@ impl Session {
self.tool.overlay.guides = guides;
return Ok(());
}
// Constrain proportions (Shift, or the node's lock).
let keep = ev.shift || r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
let (x0, y0, x1, y1) = resized_box(r.handle, q, w0, h0, keep, ev.alt);
let image_box = ids.first().filter(|_| ev.cmd && r.single).and_then(|i| self.image_box(*i));
// Constrain proportions (Shift, or the node's lock; cropping an image ignores the lock).
let locked =
r.single && image_box.is_none() && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
let keep = ev.shift || locked;
let resized = resized_box(r.handle, q, w0, h0, keep, ev.alt);
let (x0, y0, x1, y1) = match image_box {
Some(image) => within_the_image(resized, image, (w0, h0), keep),
None => resized,
};
let (flip_x, flip_y) = (x1 < x0, y1 < y0);
let (nx0, ny0) = (x0.min(x1), y0.min(y1));
let (nw, nh) = ((x1 - x0).abs(), (y1 - y0).abs());
@@ -571,46 +613,30 @@ impl Session {
let keeps = |doc: &Document, id: NodeId| {
doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }) || (ev.cmd && single && n.kind.is_frame_like()))
};
let dragged_box = |world: Affine, (ox, oy): (f64, f64)| {
let mut t = world * Affine::translate((ox, oy));
if flip_x {
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
}
if flip_y {
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
}
t
};
self.preview(|doc, _| {
if single {
let Some((id, world, _, _)) = nodes.first() else { return Ok(()) };
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
let mut t = *world * Affine::translate((nx0, ny0));
if flip_x {
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
}
if flip_y {
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
}
let t = dragged_box(*world, (nx0, ny0));
// Text reflow and auto layout can recompute this box after the preview (a size bound
// to a variable lets go of it: the resize is an explicit edit).
// to a variable lets go of it: the resize is an explicit edit). A text keeps its
// fills; any other layer's image is cropped again for the box layout leaves
// (`crop_to_the_laid_out_box`).
let n = doc.get(*id)?;
let crop_images = ev.cmd
&& !matches!(n.kind, NodeKind::Text(_))
&& !std::iter::once(*id).chain(doc.ancestors(*id)).any(|a| doc.node(a).is_some_and(|n| n.layout.is_some()));
if crop_images {
// Crop the layer's image fills without moving their pixels on the page.
// Work from the interaction snapshot, just like the geometry on every move.
let (w, h) = (n.width.max(1e-6), n.height.max(1e-6));
let to_old =
Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * t * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
let mut fills = n.fills.clone();
for paint in &mut fills {
let PaintKind::Image(img) = &mut paint.kind else { continue };
// A repeating image cannot be represented by a single Crop placement.
if img.scale_mode == ImageScaleMode::Tile {
continue;
}
let Some(data) = doc.images.get(&img.image) else { continue };
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_old).as_coeffs();
if !crop.iter().all(|c| c.is_finite()) {
continue;
}
img.crop = Some(crop);
img.scale_mode = ImageScaleMode::Crop;
}
// Crop the layer's image fills without moving their pixels on the page.
// Work from the interaction snapshot, just like the geometry on every move.
if ev.cmd && !matches!(n.kind, NodeKind::Text(_)) {
let fills = cropped_image_fills(doc, n, *world, t, (nw, nh));
doc.get_mut(*id)?.fills = fills;
}
doc.set_world_transform(*id, t)?;
@@ -650,16 +676,81 @@ impl Session {
let lin = (mirror * local).with_translation(Vec2::ZERO);
let origin = Point::new(x0 + center.x * sx, y0 + center.y * sy) - lin * Point::new(w2 / 2.0, h2 / 2.0);
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
doc.set_world_transform(*id, frame * lin.with_translation(origin))?;
let (t, w2, h2) = if boards {
on_whole_pixels(doc, *id, frame * lin.with_translation(origin), w2, h2)
} else {
(frame * lin.with_translation(origin), w2, h2)
};
doc.set_world_transform(*id, t)?;
crate::cmd::props::resize_node(doc, *id, w2, h2)?;
if boards {
crate::snap::settle_on_pixels(doc, *id)?;
}
crate::cmd::props::restore_worlds(doc, &kept)?;
}
Ok(())
})?;
if single
&& ev.cmd
&& let Some((id, world, _, _)) = nodes.first()
{
let laid_out_box = |(fw, fh): (f64, f64)| {
let origin = match image_box {
Some((ix0, iy0, ix1, iy1)) => {
(slid_onto_the_image(nx0, fw, flip_x, (ix0, ix1), w0), slid_onto_the_image(ny0, fh, flip_y, (iy0, iy1), h0))
}
None => (nx0, ny0),
};
dragged_box(*world, origin)
};
self.crop_to_the_laid_out_box(*id, *world, laid_out_box, (nw, nh))?;
}
self.tool.overlay.guides = guides;
Ok(())
}
/// The box `(x0, y0, x1, y1)` of the first visible, untiled image fill of `id` in the layer's
/// own axes, as it was when the gesture began; `None` for a text or a layer without one.
fn image_box(&self, id: NodeId) -> Option<(f64, f64, f64, f64)> {
let snapshot = self.ds().ok()?.interaction.as_ref()?.doc.clone();
let n = snapshot.node(id)?;
if matches!(n.kind, NodeKind::Text(_)) {
return None;
}
n.fills.iter().filter(|p| p.visible).find_map(|p| match &p.kind {
PaintKind::Image(img) if img.scale_mode != ImageScaleMode::Tile => {
let data = snapshot.images.get(&img.image)?;
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
let (x0, y0, x1, y1) = figcraft_doc::color::ImagePaint::crop_rect(crop);
Some((x0 * n.width, y0 * n.height, x1 * n.width, y1 * n.height))
}
_ => None,
})
}
/// After the preview's layout: when the layer didn't keep the dragged size `(nw, nh)` (a
/// minimum size, a Hug frame), crop its image fills again from the snapshot for the size it
/// has, the box placed by `laid_out_box` (given that size) in the layer's starting axes.
fn crop_to_the_laid_out_box(
&mut self,
id: NodeId,
world: Affine,
laid_out_box: impl Fn((f64, f64)) -> Affine,
(nw, nh): (f64, f64),
) -> Result<()> {
let ds = self.ds_mut()?;
let Some(snapshot) = ds.interaction.as_ref().map(|it| it.doc.clone()) else { return Ok(()) };
let Some(before) = snapshot.node(id).filter(|n| !matches!(n.kind, NodeKind::Text(_))) else { return Ok(()) };
let Some((fw, fh)) = ds.doc.node(id).map(|n| (n.width, n.height)) else { return Ok(()) };
if (fw - nw.max(0.01)).abs() < 1e-9 && (fh - nh.max(0.01)).abs() < 1e-9 {
return Ok(());
}
let fills = cropped_image_fills(&snapshot, before, world, laid_out_box((fw, fh)), (fw, fh));
std::sync::Arc::make_mut(&mut ds.doc).get_mut(id)?.fills = fills;
ds.revision += 1;
Ok(())
}
/// Scale tool handle drag (`q`: the snapped pointer in the handle box's axes): everything
/// scales by one factor about the anchor point (Alt: the centre), strokes, effects, radii and
/// text included, children by the same factor whatever their constraints.
@@ -697,6 +788,25 @@ impl Session {
}
}
/// `world` and the size `w` x `h` a layer of a resized selection takes, moved so its box in its
/// parent has its edges on whole pixels, each on the nearest one and the box at least a pixel
/// wide: a frame resized with others lands on whole pixels as one resized alone does. A layer
/// turned or scaled in its parent keeps them.
fn on_whole_pixels(doc: &Document, id: NodeId, world: Affine, w: f64, h: f64) -> (Affine, f64, f64) {
let pw = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p));
let local = pw.inverse() * world;
let [a, b, c, d, e, f] = local.as_coeffs();
if !crate::guides::axis_aligned(local) || (a.abs() - 1.0).abs() > 1e-9 || (d.abs() - 1.0).abs() > 1e-9 {
return (world, w, h);
}
let edges = |at: f64, flip: bool, len: f64| if flip { (at - len, at) } else { (at, at + len) };
let ((x0, x1), (y0, y1)) = (edges(e, a < 0.0, w), edges(f, d < 0.0, h));
let (x0, y0) = (x0.round(), y0.round());
let (w, h) = ((x1.round() - x0).max(1.0), (y1.round() - y0).max(1.0));
let (e, f) = (if a < 0.0 { x0 + w } else { x0 }, if d < 0.0 { y0 + h } else { y0 });
(pw * Affine::new([a, b, c, d, e, f]), w, h)
}
/// Moving `moving` by the same offset moves nothing else and changes nothing about them but where
/// they are: none is inside another (it would move twice) or placed by its parent's auto layout
/// (the layout would put it back, or close the gap it leaves).
@@ -714,3 +824,78 @@ fn only_shifted(doc: &Document, moving: &[NodeId]) -> bool {
!in_flow && !nested
})
}
/// `before`'s fills (from the snapshot `doc`) with each image cropped to the box `dragged` (the
/// layer's new transform, `nw` × `nh`), its pixels left where they were on the page (`world`:
/// the layer's transform before the drag).
fn cropped_image_fills(
doc: &Document,
before: &figcraft_doc::Node,
world: Affine,
dragged: Affine,
(nw, nh): (f64, f64),
) -> Vec<figcraft_doc::color::Paint> {
let (w, h) = (before.width.max(1e-6), before.height.max(1e-6));
let to_before = Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * dragged * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
let mut fills = before.fills.clone();
for paint in &mut fills {
let PaintKind::Image(img) = &mut paint.kind else { continue };
// A repeating image cannot be represented by a single Crop placement.
if img.scale_mode == ImageScaleMode::Tile {
continue;
}
let Some(data) = doc.images.get(&img.image) else { continue };
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_before).as_coeffs();
if !crop.iter().all(|c| c.is_finite()) {
continue;
}
img.crop = Some(crop);
img.scale_mode = ImageScaleMode::Crop;
}
fills
}
/// The extent `lo..hi` an image of extent `image` lets a crop reach on one axis of a layer that
/// started `len` long: the image's, or the layer's where that reaches further (a Fit image is
/// smaller than its layer).
fn crop_reach(image: (f64, f64), len: f64) -> (f64, f64) {
(image.0.min(image.1).min(0.0), image.0.max(image.1).max(len))
}
/// The dragged box `(x0, y0, x1, y1)` drawn back towards the starting box `(0, 0, w0, h0)` until
/// its sides stop at the image's box `image` (see [`crop_reach`]). Both ends of an axis go back by
/// the same fraction, so an Alt resize stays centred, and with `keep` (Shift) both axes do, so the
/// ratio holds. A flipped axis stays as dragged.
fn within_the_image((x0, y0, x1, y1): (f64, f64, f64, f64), image: (f64, f64, f64, f64), (w0, h0): (f64, f64), keep: bool) -> (f64, f64, f64, f64) {
let fraction = |a: f64, b: f64, image: (f64, f64), len: f64| {
if b < a {
return 1.0;
}
let (lo, hi) = crop_reach(image, len);
let mut t: f64 = 1.0;
if a < lo {
t = t.min(lo / a);
}
if b > hi {
t = t.min((hi - len) / (b - len));
}
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
};
let (tx, ty) = (fraction(x0, x1, (image.0, image.2), w0), fraction(y0, y1, (image.1, image.3), h0));
let (tx, ty) = if keep { (tx.min(ty), tx.min(ty)) } else { (tx, ty) };
(x0 * tx, y0 * ty, w0 + (x1 - w0) * tx, h0 + (y1 - h0) * ty)
}
/// Where a crop box `len` long, placed at `start` on one axis, starts once it is slid back onto
/// the image (see [`crop_reach`]): layout can make a layer longer than it was dragged (a minimum
/// size), and the crop then moves along the image rather than past its edge. A flipped axis, or
/// a box longer than the reach, stays where it is.
fn slid_onto_the_image(start: f64, len: f64, flipped: bool, image: (f64, f64), len0: f64) -> f64 {
let (lo, hi) = crop_reach(image, len0);
if flipped || len.is_nan() || len > hi - lo {
return start;
}
start.max(lo).min(hi - len)
}
+15 -1
View File
@@ -30,7 +30,10 @@ impl Session {
let tool = self.tool.tool;
let mut p = ev.p();
let mut guides = Vec::new();
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
// Frames and sections land on whole pixels whatever the setting, also where a layer they
// snap to doesn't (see `snap::always_on_pixels`).
let board = matches!(tool, ToolId::Frame | ToolId::Section);
let pixel = board || self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
// The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps.
if pixel {
p = Point::new(p.x.round(), p.y.round());
@@ -41,6 +44,9 @@ impl Session {
p.y += dy;
guides = g;
}
if board {
p = Point::new(p.x.round(), p.y.round());
}
let mut created = id;
let page = self.page()?;
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
@@ -100,6 +106,9 @@ impl Session {
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
}
doc.insert(n, parent, None)?;
if board {
crate::snap::settle_on_pixels(doc, nid)?;
}
if let Some(d) = &defaults {
// Best effort: a default the shape can't take leaves it as drawn.
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
@@ -156,6 +165,11 @@ impl Session {
}
// A layer can't go into itself; it stays where it is.
let _ = d.reparent(*m, target, None);
// Frames, sections and components land on whole pixels of the frame
// they are dropped into too.
if d.node(*m).is_some_and(crate::snap::always_on_pixels) {
crate::snap::settle_on_pixels(d, *m)?;
}
}
crate::normalize(ds.doc_mut(), &before);
}
+37 -3
View File
@@ -38,11 +38,34 @@ impl Session {
/// (its children), or the focus view's frame.
pub(crate) fn marquee_within(&self, p: Point) -> Result<Option<NodeId>> {
let (doc, page) = (self.doc()?, self.page()?);
let within = frame_at(doc, page, p, &[]).filter(|f| doc.node(*f).is_some_and(|n| n.parent == Some(page)));
let within = within.filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p)));
let deepest = frame_at(doc, page, p, &[]).filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p)));
let mut chain = deepest.map(|f| doc.ancestors(f)).unwrap_or_default();
chain.reverse();
chain.extend(deepest);
let mut within = None;
for c in chain.into_iter().filter(|c| *c != page) {
let Some(n) = doc.node(c) else { break };
match &n.kind {
NodeKind::Section { contents_hidden: false } => within = Some(c),
k if k.is_frame_like() => {
within = Some(c);
break;
}
_ => break,
}
}
Ok(self.ds()?.focused().or(within))
}
fn marquee_root(&self, within: Option<NodeId>) -> Result<(NodeId, Option<NodeId>)> {
let (doc, page) = (self.doc()?, self.page()?);
Ok(match within.and_then(|w| doc.node(w)) {
Some(n) if matches!(n.kind, NodeKind::Section { .. }) => (n.id, None),
Some(n) => (n.parent.unwrap_or(page), Some(n.id)),
None => (page, None),
})
}
/// The selection a marquee over page rect `r` makes from `base` (what was selected before):
/// 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>> {
@@ -51,7 +74,10 @@ impl Session {
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),
(false, None) => {
let (root, start_inside) = self.marquee_root(within)?;
figcraft_doc::geometry::marquee_select(doc, root, r, start_inside)
}
};
if let Some(f) = focused {
hits.retain(|h| *h != f && doc.is_ancestor(f, *h));
@@ -136,6 +162,11 @@ impl Session {
}
let tool = self.acting_tool();
let edits = matches!(tool, ToolId::Move | ToolId::Scale) && !self.tool.dev_mode;
// Presses with another tool don't record the selection: the ones from before them aren't
// this double-click's.
if ev.kind == PointerKind::Down && !matches!(tool, ToolId::Move | ToolId::Scale) {
self.tool.selections_before_last_two_presses = Default::default();
}
if edits && self.origin_pointer(ev)? {
return Ok(());
}
@@ -155,6 +186,9 @@ impl Session {
}
// A click on the canvas deselects a ruler guide (the UI selects guides itself).
self.ds_mut()?.guide = None;
let now = self.ds()?.selection.clone();
let [_, last] = std::mem::take(&mut self.tool.selections_before_last_two_presses);
self.tool.selections_before_last_two_presses = [last, Some((ev.p(), now))];
self.move_down(ev)
}
ToolId::Hand => {
+43 -4
View File
@@ -642,10 +642,12 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result<usize> {
}
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
pub(crate) 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, then_select_next: bool) -> Result<()> {
let doc = s.doc_mut()?;
let mut next = Vec::new();
for EditPart { id, vertices: verts, segments: segs } in parts {
edit(doc, id, |net| {
let following = edit(doc, id, |net| {
let following = if then_select_next { points_following(net, &verts) } else { Vec::new() };
// Segments first (their indices refer to the network before points go).
let segs: Vec<usize> =
segs.into_iter().filter(|si| net.segments.get(*si).is_some_and(|x| !verts.contains(&x.a) && !verts.contains(&x.b))).collect();
@@ -654,15 +656,52 @@ pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool
// Point indices may have shifted: find them again by position.
let now: Vec<usize> = pts.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect();
ops::delete_vertices(net, &now, heal);
following.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect::<Vec<usize>>()
})?;
next.push((id, following));
}
set_state(s, |ve| {
ve.clear_selection();
ve.anchor = None;
ve.pen_out = None;
for (id, following) in next {
if id == ve.id {
ve.vertices = following;
} else if let Some(o) = ve.others.iter_mut().find(|o| o.id == id) {
o.vertices = following;
}
}
})
}
fn points_following(net: &VectorNetwork, deleted: &[usize]) -> Vec<Point> {
let step = |from: usize, forward: bool| {
net.segments.iter().find_map(|sg| match forward {
true => (sg.a == from).then_some(sg.b),
false => (sg.b == from).then_some(sg.a),
})
};
let mut out: Vec<Point> = Vec::new();
for &v in deleted {
let found = [true, false].into_iter().find_map(|forward| {
let mut at = v;
for _ in 0..net.vertices.len() {
at = step(at, forward)?;
if !deleted.contains(&at) {
return Some(at);
}
}
None
});
if let Some(p) = found.and_then(|i| net.vertices.get(i)).map(|x| x.point())
&& !out.contains(&p)
{
out.push(p);
}
}
out
}
/// The points a command acts on, per layer: `vertices` names points of the active layer; without
/// it, every edited layer's selected points (with `ends`, the ends of selected segments too).
fn point_sets(s: &Session, p: &Value, ends: bool) -> Result<Vec<(NodeId, Vec<usize>)>> {
@@ -1112,7 +1151,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
spec!("vector.deleteHeal", "Delete and heal selection", "{vertices?} (default the selected points of every edited layer)", true, |s, p| {
let parts = point_sets(s, p, false)?.into_iter().map(|(id, vertices)| EditPart { id, vertices, segments: vec![] }).collect();
delete_selection(s, parts, true)?;
delete_selection(s, parts, true, true)?;
Ok(json!({"ok": true}))
}),
spec!("vector.edit.delete", "Delete points", "{vertices?, segments?} (default the selection in every edited layer)", true, |s, p| {
@@ -1121,7 +1160,7 @@ pub fn specs() -> Vec<CommandSpec> {
(None, None) => ve.parts(),
(v, sg) => vec![EditPart { id: ve.id, vertices: v.unwrap_or_default(), segments: sg.unwrap_or_default() }],
};
delete_selection(s, parts, false)?;
delete_selection(s, parts, false, true)?;
Ok(json!({"ok": true}))
}),
spec!("vector.edit.cornerRadius", "Point corner radius", "{radius, vertices?}", true, |s, p| {
+1
View File
@@ -24,6 +24,7 @@ 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};
pub(crate) use variants::fit_set;
use variants::{add_variant, combine, create_set};
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
+1 -1
View File
@@ -166,7 +166,7 @@ pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
}
/// 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) {
pub(crate) fn fit_set(doc: &mut Document, set: NodeId) {
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
let (mut w, mut h) = (0.0f64, 0.0f64);
for c in kids {
+191 -20
View File
@@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
// A design-app paste replaces the copied layers, not the copied rows: a `fill.copy` before it
// still pastes afterwards.
let props = s.clipboard.props.take();
let props_source_doc = s.clipboard.props_source_doc;
let paint = s.clipboard.paint.take();
let stroke = s.clipboard.stroke.take();
let paint_images = std::mem::take(&mut s.clipboard.paint_images);
@@ -138,6 +139,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
nodes,
images,
props,
props_source_doc,
paint,
stroke,
paint_images,
@@ -219,8 +221,18 @@ pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
delete(s, &json!({"ids": layers}))
}
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords).
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). A
/// copied main is pasted as an instance of it; in another file, as an instance of it from the
/// library the source file publishes, and as a copy of it when that library doesn't offer it.
pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Result<Vec<NodeId>> {
paste_layers(s, parent, at, false)
}
/// [`paste_into`]. With `as_variants`, copied variants pasted into `parent`, their own set, are
/// deep copies (new variants, as Duplicate makes) and the set grows to hold them. Only a plain
/// paste with that set, or a layer in it, selected asks for this; every other paste of a copied
/// main, into another set too, still makes an instance.
fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_variants: bool) -> Result<Vec<NodeId>> {
let clip = s.clipboard.clone();
if clip.nodes.is_empty() {
return Err(EngineError::Disabled("edit.paste".into(), "the clipboard is empty".into()));
@@ -238,15 +250,20 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
(Some((x, y)), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
_ => Affine::IDENTITY,
};
let into_set = as_variants && copy_local && copied_variants_set(doc, &clip.nodes) == Some(parent);
let mut out = Vec::new();
let mut all = BTreeMap::new();
for (root, nodes) in &clip.nodes {
if copy_local
&& clip.copied_components.contains(root)
&& let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. }))
&& doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))
{
let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?;
let copied_main = nodes.first().filter(|n| clip.copied_components.contains(root) && matches!(n.kind, NodeKind::Component { .. }));
let main = match (copied_main, foreign) {
(Some(_), _) if copy_local => {
(!into_set && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))).then_some(*root)
}
(Some(_), Some(src)) => crate::library::published_main(doc, src, clip.source_path.as_deref(), *root)?,
_ => None,
};
if let (Some(main), Some(n)) = (main, copied_main) {
let instance = crate::components::create_instance(doc, main, parent, 0.0, 0.0)?;
doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform;
keep_a_cropped_images_proportions(doc, instance, parent);
out.push(instance);
@@ -267,6 +284,9 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
out.push(pasted);
all.extend(map);
}
if into_set {
crate::cmd::component::fit_set(doc, parent);
}
// Board connectors pasted with what they join join the pasted copies.
let originals: Vec<(NodeId, figcraft_doc::BoardItem)> =
clip.nodes.iter().flat_map(|(_, nodes)| nodes).filter_map(|n| Some((*all.get(&n.id)?, n.board.clone()?))).collect();
@@ -307,7 +327,16 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let sel = s.selection();
let doc = s.doc()?;
let copy_local = s.ds()?.uid == s.clipboard.source_doc;
let target = id(p, "parent").or_else(|| {
let variants_set = copied_variants_set(doc, &s.clipboard.nodes)
.filter(|set| copy_local && id(p, "parent").is_none() && !sel.is_empty() && sel.iter().all(|i| doc.is_ancestor(*set, *i)));
// Where the copied variants are now, not where they were copied: the set may have moved since.
let below_the_variants = variants_set.and_then(|set| {
let copied: Vec<NodeId> = s.clipboard.nodes.iter().map(|(root, _)| *root).collect();
let left = doc.bounds_of(&copied)?.x0;
let bottom = doc.node(set)?.children.iter().filter_map(|c| doc.world_bounds(*c)).map(|r| r.y1).reduce(f64::max)?;
Some((left, bottom + 20.0))
});
let target = id(p, "parent").or(variants_set).or_else(|| {
sel.first()
.copied()
.filter(|i| {
@@ -322,6 +351,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let parent = target.unwrap_or(page);
let at = match (num(p, "x"), num(p, "y")) {
(Some(x), Some(y)) => Some((x, y)),
_ if below_the_variants.is_some() => below_the_variants,
_ => {
let b = s.clipboard.bounds;
match (target, b) {
@@ -344,7 +374,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
}
}
};
let ids = paste_into(s, parent, at)?;
let ids = paste_layers(s, parent, at, variants_set.is_some())?;
if let Some(sel) = sibling_of {
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
move_above(s, &ids, parent, above)?;
@@ -381,14 +411,27 @@ fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usi
Ok(())
}
/// The set the copied layers are variants of: every copied root is a main component in `doc` whose
/// parent is that one component set. `None` for anything else.
fn copied_variants_set(doc: &Document, copied: &[(NodeId, Vec<Node>)]) -> Option<NodeId> {
let mut sets = copied.iter().map(|(root, _)| {
let n = doc.node(*root).filter(|n| matches!(n.kind, NodeKind::Component { .. }))?;
n.parent.filter(|set| doc.node(*set).is_some_and(|p| matches!(p.kind, NodeKind::ComponentSet { .. })))
});
let first = sets.next()??;
sets.all(|set| set == Some(first)).then_some(first)
}
/// Paste over selection (Shift+Cmd/Ctrl+V): the copies go into the parent of the selected layer
/// [`last_seen`] picks, just above it, at the place it gives.
pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
let sel = s.selection();
let page = s.page()?;
let doc = s.doc()?;
let (parent, at, above) = match sel.first() {
Some(i) => {
let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page);
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1))
let (parent, at, above) = match last_seen(doc, &sel) {
Some((i, at)) => {
let parent = doc.node(i).and_then(|n| n.parent).unwrap_or(page);
(parent, at, doc.index_in_parent(i).map(|ix| ix + 1))
}
None => (page, None, None),
};
@@ -398,6 +441,38 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({"ids": ids}))
}
/// The selected layer Paste over selection pastes after, and where the copies' top-left goes.
///
/// One layer: that layer, at its position. Several in one auto layout frame's flow (none absolutely
/// positioned): the last of them in the flow, which the layout follows. Several elsewhere: the lowest (then rightmost), with the copies
/// below it, as far below as it is from the selected layers above it. A selection with nothing above
/// its lowest layer is a row: the copies go right of the rightmost, as far as it is from its
/// neighbour on the left. Layers that overlap every way get the copies right under the lowest.
fn last_seen(doc: &Document, sel: &[NodeId]) -> Option<(NodeId, Option<(f64, f64)>)> {
let first = *sel.first()?;
let top_left = |i: NodeId| doc.world_bounds(i).map(|b| (b.x0, b.y0));
if sel.len() == 1 {
return Some((first, top_left(first)));
}
let parent = doc.node(first).and_then(|n| n.parent);
let one_flow = parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
&& sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent == parent && !n.child_layout.absolute));
if one_flow {
let last = sel.iter().copied().max_by_key(|i| doc.index_in_parent(*i))?;
return Some((last, top_left(last)));
}
let boxes: Vec<(NodeId, figcraft_geom::Rect)> = sel.iter().filter_map(|i| Some((*i, doc.world_bounds(*i)?))).collect();
let (lowest, low) = *boxes.iter().max_by(|(_, a), (_, b)| a.y1.total_cmp(&b.y1).then(a.x1.total_cmp(&b.x1)))?;
if let Some(above) = boxes.iter().filter(|(_, o)| o.y1 <= low.y0).map(|(_, o)| o.y1).max_by(f64::total_cmp) {
return Some((lowest, Some((low.x0, low.y1 + (low.y0 - above)))));
}
let (rightmost, right) = *boxes.iter().max_by(|(_, a), (_, b)| a.x1.total_cmp(&b.x1).then(a.y1.total_cmp(&b.y1)))?;
match boxes.iter().filter(|(_, o)| o.x1 <= right.x0).map(|(_, o)| o.x1).max_by(f64::total_cmp) {
Some(left) => Some((rightmost, Some((right.x1 + (right.x0 - left), right.y0)))),
None => Some((lowest, Some((low.x0, low.y1)))),
}
}
pub(super) fn paste_replace(s: &mut Session, p: &Value) -> Result<Value> {
let targets = req_targets("edit.pasteReplace", s, p)?;
let mut out = Vec::new();
@@ -438,7 +513,19 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
v["cornerRadius"] = json!(n.corners.radii);
v["cornerSmoothing"] = json!(n.corners.smoothing);
}
// A frame's layout grids go with its look, as its fills do.
if n.kind.is_frame_like() {
v["grids"] = json!(n.grids);
v["gridStyle"] = json!(n.styles.grid);
}
// The links behind the values: the styles and the variables they come from, so the pasted
// layer follows them as the copied one does.
v["fillStyle"] = json!(n.styles.fill);
v["strokeStyle"] = json!(n.styles.stroke);
v["effectStyle"] = json!(n.styles.effect);
v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect());
if let NodeKind::Text(t) = &n.kind {
v["textStyle"] = json!(n.styles.text);
v["fontFamily"] = json!(t.style.font_family);
v["fontStyle"] = json!(t.style.font_style);
v["fontSize"] = json!(t.style.font_size);
@@ -453,26 +540,110 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.copyProperties", "select one layer"))?;
let v = copy_props_of(s.doc()?, id);
s.clipboard.props = Some(v.clone());
s.clipboard.props_source_doc = s.ds()?.uid;
Ok(v)
}
/// Copied properties `props` without their style and variable links, for a paste into another
/// file: the copied ids name the source file's styles and variables, and the same ids here can
/// name unrelated ones. The values paste unlinked, and the layer's own links on them go.
fn without_links(mut props: Value) -> Value {
if let Some(m) = props.as_object_mut() {
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") {
*v = Value::Null;
} else if k == "boundVariables" {
*v = json!({});
}
}
}
props
}
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
/// properties only to text, the corners only to a layer with corners.
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
let mut m = props.as_object().cloned().unwrap_or_default();
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
if !is_text {
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
let n = doc.get(id)?;
let (is_text, corners, frame) = (matches!(n.kind, NodeKind::Text(_)), n.kind.has_corner_radius(), n.kind.is_frame_like());
let takes = |k: &str| {
let text = k.starts_with("font") || k.starts_with("paragraph") || matches!(k, "lineHeight" | "letterSpacing" | "textStyle");
let corner = k == "cornerSmoothing" || k.ends_with("Radius");
let grid = k == "gridStyle" || k == "grids" || k.starts_with("layoutGrids/");
(is_text || !text) && (corners || !corner) && (frame || !grid)
};
m.retain(|k, _| takes(k));
// A style or variable the file doesn't have (deleted since the copy) isn't here to link to: the
// values it gave are pasted without a link, so the layer's own link goes too.
let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some());
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") && !here(v) {
*v = Value::Null;
}
}
if !doc.get(id)?.kind.has_corner_radius() {
m.remove("cornerRadius");
m.remove("cornerSmoothing");
if let Some(Value::Object(copied)) = m.get_mut("boundVariables") {
copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some()));
}
// The layer's own bindings on what is pasted give way to the copied layer's: kept, a binding
// would hold the old value over the pasted one. A binding on what the copy doesn't carry (a
// text layer's font size, pasted from a frame) stays.
if let Some(Value::Object(copied)) = m.get("boundVariables") {
let mut bound: serde_json::Map<String, Value> =
n.bound.keys().filter(|f| copied_binding(f) && m.contains_key(pasted_key(f))).map(|f| (f.clone(), Value::Null)).collect();
bound.extend(copied.iter().filter(|(f, _)| takes(f)).map(|(f, v)| (f.clone(), v.clone())));
m.insert("boundVariables".into(), Value::Object(bound));
}
crate::cmd::props::apply(cmd, doc, id, &m)
}
/// The key of the properties [`copy_props_of`] copies that sets what a variable bound to `field`
/// sets: a corner's radius is `cornerRadius`, a side's stroke weight `strokeWeight`, the font
/// weight `fontStyle`, a layout grid's field `grids` and a paint's or effect's field its list.
fn pasted_key(field: &str) -> &str {
match field {
"topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "cornerRadius",
f if crate::cmd::props::STROKE_SIDES.contains(&f) => "strokeWeight",
"fontWeight" => "fontStyle",
f => match f.split_once('/') {
Some(("layoutGrids", _)) => "grids",
Some((list, _)) => list,
None => f,
},
}
}
/// Whether a variable bound to `field` goes with the properties [`copy_props_of`] copies: not a
/// size, auto layout spacing, visibility or text content.
fn copied_binding(field: &str) -> bool {
!matches!(
field,
"width"
| "height"
| "minWidth"
| "maxWidth"
| "minHeight"
| "maxHeight"
| "gap"
| "columnGap"
| "rowGap"
| "crossGap"
| "padding"
| "paddingHorizontal"
| "paddingVertical"
| "paddingTop"
| "paddingRight"
| "paddingBottom"
| "paddingLeft"
| "visible"
| "characters"
)
}
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
let mut props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
if s.ds()?.uid != s.clipboard.props_source_doc {
props = without_links(props);
}
let ids = req_targets("edit.pasteProperties", s, p)?;
let doc = s.doc_mut()?;
for i in ids {
@@ -154,7 +154,7 @@ pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result<Value
}
let cut = sel.parts.len();
let segments = copy_parts(s, "edit.cut", &sel)?;
vectoredit::delete_selection(s, sel.delete, false)?;
vectoredit::delete_selection(s, sel.delete, false, false)?;
Ok(json!({"cut": cut, "segments": segments}))
}
+1
View File
@@ -462,6 +462,7 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
}
let uid = ds.uid;
let active_uid = s.docs.get(s.active).map(|d| d.uid);
s.remember_view(i);
s.remove_tabs(|d| d.uid == uid);
// Removing a tab before the active one shifts its index; keep the same document selected.
s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1)));
+1
View File
@@ -107,6 +107,7 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
ds.on_disk = on_disk.filter(|_| native);
s.docs.push(ds);
s.active = s.docs.len() - 1;
s.restore_view();
let mut out = json!({"index": s.active, "summary": summary});
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
Ok(out)
+2 -3
View File
@@ -173,7 +173,8 @@ fn wants_data(p: &Value) -> bool {
/// Save the file of the active tab (the main file for a branch tab, with its branches), or export
/// the active document as an experimental `.fig` copy without changing its native save state.
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969).
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). Saved
/// to another file, the document takes that file's name, as its tab does.
fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
if let Some(path) = path.as_deref().filter(|p| ext(p) == "fig") {
return export_fig(s, &json!({"path": path}));
@@ -185,9 +186,7 @@ fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
refuse_dropping_images(ds, path)?;
}
let mut snapshot = FileSnapshot::of(ds);
let follows_path = ds.path.as_deref().map_or(ds.doc.name == "Untitled", |old| ds.doc.name == file_stem(old));
if let Some(path) = path.as_deref()
&& follows_path
&& ds.path.as_deref() != Some(path)
{
Arc::make_mut(&mut snapshot.doc).name = file_stem(path);
+3
View File
@@ -234,6 +234,9 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
// Like any paint edit, the layer leaves its paint style.
n.styles.fill = None;
}
if s.ds()?.vector_edit.is_some() {
crate::vectoredit::end(s)?;
}
s.request_ui(cmd, json!({"id": id, "index": index}));
Ok(json!({"id": id, "index": index}))
}
+1
View File
@@ -238,6 +238,7 @@ fn wrap(s: &mut Session, p: &Value, cmd: &str, w: Wrap) -> Result<Value> {
}
if let Wrap::Frame = w {
g.clip = true;
g.fills.clear();
}
// Insert the container where the topmost layer is.
doc.insert(g, parent, index)?;
+1 -1
View File
@@ -642,7 +642,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"text.edit.key",
"Text key",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent; elsewhere Tab and Shift+Tab edit the next or previous text layer of the frame in reading order (rows top to bottom, each left to right), all of it selected, and do nothing at the last and the first (in a board object or a widget's field Tab types a tab)",
true,
|s, p| {
let k = req_string("text.edit.key", p, "key")?;
+204
View File
@@ -298,3 +298,207 @@ fn many_entries_for_one_component_each_link() {
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500})));
assert_eq!(code(&mut s, i, "react"), "<Button />\n");
}
#[test]
fn a_link_names_its_source_and_translates_variant_values() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button state={State} />",
"source": "src/ui/button.tsx", "values": {"State": {"Hover": "hovered"}}, "notes": "Primary action"}),
);
let instance = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, instance, "react").contains(r#"state="hovered""#), "{}", code(&mut s, instance, "react"));
// A value without a mapping keeps the design's name.
let plain = idv(&ex(&mut s, "instance.create", json!({"component": set})));
assert!(code(&mut s, plain, "react").contains(r#"state="Default""#));
}
#[test]
fn a_source_outside_the_repository_is_refused() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let c = card(&mut s);
for source in ["../up.tsx", "/etc/passwd", "a\\b.tsx", "a/../../b.tsx"] {
let e = s.execute("codeConnect.set", &json!({"id": c, "source": source})).unwrap_err();
assert!(e.to_string().contains("source"), "{source}: {e}");
}
assert!(s.execute("codeConnect.set", &json!({"id": c, "values": 3})).is_err());
assert!(s.execute("codeConnect.set", &json!({"id": c, "source": "src/card.tsx"})).is_ok());
}
#[test]
fn the_new_fields_survive_a_trip_through_the_file() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button />", "source": "src/b.tsx", "values": {"State": {"Hover": "h"}}, "notes": "n"}),
);
let text = ex(&mut s, "codeConnect.export", json!({}))["text"].as_str().unwrap().to_string();
let mut other = Session::new();
ex(&mut other, "file.new", json!({}));
let (set2, _) = button(&mut other);
assert_eq!(ex(&mut other, "codeConnect.import", json!({"json": text}))["linked"], 1);
let link = &other.doc().unwrap().node(set2).unwrap().code_links[0];
assert_eq!((link.source.as_str(), link.notes.as_str()), ("src/b.tsx", "n"));
assert_eq!(link.values["State"]["Hover"], "h");
}
#[test]
fn a_file_from_before_stays_as_it_was() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let v = ex(&mut s, "codeConnect.export", json!({}));
let parsed: Value = serde_json::from_str(v["text"].as_str().unwrap()).unwrap();
let keys: Vec<&String> = parsed["links"][0].as_object().unwrap().keys().collect();
assert_eq!(keys, ["component", "importPath", "language", "name", "template"], "no new keys unless they're used");
}
#[test]
fn listing_answers_what_an_agent_asks() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-list-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/button.tsx"), "").unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let c = card(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button />", "source": "src/button.tsx"}),
);
let v = ex(&mut s, "codeConnect.list", json!({"root": dir}));
assert_eq!((v["mapped"].as_u64(), v["unmapped"].as_u64()), (Some(1), Some(1)));
let b = v["components"].as_array().unwrap().iter().find(|e| e["id"] == json!(set)).unwrap();
assert_eq!(b["links"][0]["import"], r#"import { Button } from "@/ui/button";"#);
assert_eq!(b["links"][0]["sourceFound"], true);
assert!(b["links"][0]["snippet"].as_str().unwrap().contains("<Button"));
assert!(b["properties"].as_array().unwrap().iter().any(|p| p["type"] == "variant"));
let only = ex(&mut s, "codeConnect.list", json!({"unmapped": true}));
assert_eq!(only["components"][0]["id"], json!(c));
// A layer leads to the component it uses, a frame to those it holds.
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"ids": [i]}))["components"][0]["id"], json!(set));
ex(&mut s, "codeConnect.set", json!({"id": set, "source": "src/gone.tsx"}));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"root": dir, "ids": [set]}))["components"][0]["links"][0]["sourceFound"], false);
}
#[test]
fn exporting_keeps_what_other_designs_put_in_the_file() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-others-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("figcraft.connect.json");
std::fs::write(&path, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Other","language":"react","name":"Other","template":"<Other />"},{"component":"Button","language":"react","name":"Old","template":"<Old />"}]}"#).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
ex(&mut s, "codeConnect.export", json!({"path": path}));
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let names: Vec<&str> = v["links"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Button", "Other"], "this design's link wins, the other design's stays");
assert_eq!(v["project"]["name"], "shop", "keys the command doesn't own stay");
}
#[test]
fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "select.set", json!({"ids": [set]}));
for p in [json!({"id": "not-an-id"}), json!({"ids": [set, "nope"]}), json!({"ids": "1"}), json!({"ids": [999_999]})] {
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
}
}
/// A set called `name` with a variant `prop=value` for each of `values`. Returns (set, variants).
fn set_of(s: &mut Session, name: &str, prop: &str, values: &[&str]) -> (NodeId, Vec<NodeId>) {
let variants: Vec<NodeId> = values
.iter()
.enumerate()
.map(|(k, v)| {
let f = idv(&ex(s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 40, "name": format!("{prop}={v}")})));
idv(&ex(s, "component.create", json!({"ids": [f]})))
})
.collect();
let set = idv(&ex(s, "component.combineVariants", json!({"ids": variants.clone()})));
ex(s, "node.set", json!({"id": set, "props": {"name": name}}));
(set, variants)
}
#[test]
fn a_condition_reads_the_designs_value_not_its_name_in_code() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, variants) = set_of(&mut s, "Toggle", "State", &["On", "Off"]);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Toggle", "template": "{State ? \"enabled\" : \"disabled\"} {State}"}));
let off = idv(&ex(&mut s, "instance.create", json!({"component": variants[1]})));
assert!(code(&mut s, off, "react").starts_with("disabled"), "{}", code(&mut s, off, "react"));
// `inactive` reads as true, but the condition is about the design's Off.
ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Off": "inactive"}}}));
let out = code(&mut s, off, "react");
assert!(out.starts_with("disabled") && out.contains("inactive"), "{out}");
}
#[test]
fn a_mapping_keyed_by_a_name_it_cant_use_is_reported() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let r = ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button state={State} />", "values": {"state": {"Hover": "hovered"}}}),
);
assert!(r.to_string().contains("\"state\""), "the lowercase key does nothing, so it's named: {r}");
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, i, "react").contains(r#"state="Hover""#));
let r = ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Hover": "hovered"}}}));
assert!(!r.to_string().contains("\"State\""), "{r}");
}
#[test]
fn an_import_with_malformed_values_keeps_the_link_there() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />", "values": {"State": {"Hover": "h"}}}));
let links = json!([{"component": "Button", "language": "react", "name": "Other", "template": "<Other />", "values": {"State": {"Hover": 7}}}]);
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
assert_eq!(r["linked"], 0, "{r}");
assert!(r["warnings"][0].as_str().unwrap().contains("values"), "{r}");
let link = &s.doc().unwrap().node(set).unwrap().code_links[0];
assert_eq!((link.name.as_str(), link.values["State"]["Hover"].as_str()), ("Button", "h"));
}
#[test]
fn exporting_over_a_file_it_cant_read_is_refused() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-unread-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let big = vec![b' '; 4 * 1024 * 1024 + 1];
for (name, bytes) in [("broken.json", b"{\"links\": [".to_vec()), ("list.json", b"[]".to_vec()), ("big.json", big)] {
let path = dir.join(name);
std::fs::write(&path, &bytes).unwrap();
assert!(s.execute("codeConnect.export", &json!({"path": path})).is_err(), "{name}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{name} is left as it was");
}
// A file that isn't there yet is written.
let new = dir.join("figcraft.connect.json");
let _ = std::fs::remove_file(&new);
ex(&mut s, "codeConnect.export", json!({"path": new}));
assert!(new.exists());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -115,6 +115,7 @@ fn copying_a_variant_pastes_an_instance_but_copying_its_set_keeps_the_components
let (set, _, hover) = button_set(&mut s);
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "select.set", json!({"ids": []}));
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).name, node(&s, set).name);
@@ -241,6 +242,108 @@ fn alt_dragging_a_main_component_copies_an_instance() {
healthy(&s);
}
#[test]
fn pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
let named = |s: &Session, i: NodeId, name: &str| kids(s, i).into_iter().find(|c| node(s, *c).name == name).unwrap();
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
let bottom = kids(&s, set).iter().map(|k| bounds(&s, *k).y1).fold(f64::MIN, f64::max);
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert!(matches!(node(&s, pasted).kind, NodeKind::Component { .. }));
assert_eq!(node(&s, pasted).parent, Some(set));
assert_eq!(kids(&s, set).len(), 3);
assert_eq!(chars(&s, named(&s, pasted, "Label")), "Hover");
let (b, h) = (bounds(&s, pasted), bounds(&s, hover));
assert_eq!((b.x0, b.y0), (h.x0, bottom + 20.0));
assert!(bounds(&s, set).y1 >= b.y1, "the set grows to hold it");
let label = named(&s, hover, "Label");
ex(&mut s, "select.set", json!({"ids": [label]}));
let second = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert_eq!(node(&s, second).parent, Some(set), "a layer inside a variant selected");
assert_eq!(bounds(&s, second).y0, b.y1 + 20.0);
ex(&mut s, "edit.undo", json!({}));
assert_eq!(kids(&s, set).len(), 3);
healthy(&s);
}
#[test]
fn a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
let x = bounds(&s, set).x0;
ex(&mut s, "node.set", json!({"id": set, "props": {"x": x + 1000.0}}));
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
let (b, h, sb) = (bounds(&s, pasted), bounds(&s, hover), bounds(&s, set));
assert_eq!(b.x0, h.x0, "under the copied variant where it is now, not where it was copied");
assert!(sb.x0 <= b.x0 && sb.x1 >= b.x1 && sb.y1 >= b.y1, "inside the set");
healthy(&s);
}
/// Copy `main`, select `selected` and run `command` with `params`; the first pasted layer.
fn copy_then(s: &mut Session, main: NodeId, selected: &[NodeId], command: &str, params: Value) -> NodeId {
ex(s, "select.set", json!({"ids": [main]}));
ex(s, "edit.copy", json!({}));
ex(s, "select.set", json!({"ids": selected}));
crate::params::id_of(&ex(s, command, params)["ids"][0]).unwrap()
}
// Only a plain paste with the copied variants' own set, or a layer in it, selected makes new
// variants. Every other paste of a copied main into a set makes an instance of it there, as
// before: the tests below.
#[test]
fn a_variant_pasted_with_another_set_selected_is_an_instance() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let (other, ..) = button_set(&mut s);
ex(&mut s, "node.set", json!({"id": other, "props": {"y": 300}}));
let pasted = copy_then(&mut s, hover, &[other], "edit.paste", json!({}));
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).parent, Some(other));
assert_eq!((kids(&s, set).len(), kids(&s, other).len()), (2, 3));
healthy(&s);
}
#[test]
fn a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance() {
let mut s = Session::new();
let (set, ..) = button_set(&mut s);
let k = kit(&mut s);
let pasted = copy_then(&mut s, k.card, &[set], "edit.paste", json!({}));
assert_eq!(component_of(&s, pasted), k.card);
assert_eq!(node(&s, pasted).parent, Some(set));
healthy(&s);
}
#[test]
fn a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let pasted = copy_then(&mut s, hover, &[hover], "edit.paste", json!({"parent": set}));
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).parent, Some(set));
healthy(&s);
}
#[test]
fn pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant() {
for command in ["edit.pasteOver", "edit.pasteReplace"] {
let mut s = Session::new();
let (set, default, hover) = button_set(&mut s);
let pasted = copy_then(&mut s, hover, &[default], command, json!({}));
assert_eq!(component_of(&s, pasted), hover, "{command} on a variant of the copied variant's set");
assert_eq!(node(&s, pasted).parent, Some(set), "{command}");
healthy(&s);
}
}
#[test]
fn duplicating_a_variant_adds_a_variant_to_its_set() {
let mut s = Session::new();
+20 -8
View File
@@ -83,10 +83,12 @@ pub fn normalize(doc: &mut Document, before: &Document) {
&& ((w - n.width).abs() > 1e-6 || (h - n.height).abs() > 1e-6)
{
let dw = w - n.width;
let anchor_right = keeps_right_edge(doc, before, n);
let left_share = share_of_growth_to_the_left(doc, before, n);
figcraft_layout::set_size(doc, id, w, h);
if anchor_right && let Some(n) = doc.node_mut(id) {
n.transform *= figcraft_geom::kurbo::Affine::translate((-dw, 0.0));
if left_share > 0.0
&& let Some(n) = doc.node_mut(id)
{
n.transform *= figcraft_geom::kurbo::Affine::translate((-dw * left_share, 0.0));
}
}
}
@@ -218,13 +220,23 @@ pub(crate) fn only_moved_layers(doc: &mut Document, before: &Document, touched:
out
}
/// Whether auto-width text `n` keeps its right edge when its width changes: it was already
/// right-aligned auto-width text before the edit and no auto layout flow places it.
fn keeps_right_edge(doc: &Document, before: &Document, n: &Node) -> bool {
/// How much of a width change auto-width text `n` takes on its left: all of it when right
/// aligned (it keeps its right edge), half when centred (it keeps its middle), none otherwise.
/// Only when it had the same alignment as auto-width text before the edit and no auto layout
/// flow places it.
fn share_of_growth_to_the_left(doc: &Document, before: &Document, n: &Node) -> f64 {
use figcraft_doc::{TextAlignH, TextAutoResize};
let right_auto = |n: &Node| n.kind.text().is_some_and(|t| t.align_h == TextAlignH::Right && t.auto_resize == TextAutoResize::WidthAndHeight);
let auto_width_align = |n: &Node| n.kind.text().filter(|t| t.auto_resize == TextAutoResize::WidthAndHeight).map(|t| t.align_h);
let in_flow = !n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some() && p.kind.is_frame_like());
right_auto(n) && before.node(n.id).is_some_and(right_auto) && !in_flow
let align = auto_width_align(n);
if in_flow || align != before.node(n.id).and_then(auto_width_align) {
return 0.0;
}
match align {
Some(TextAlignH::Right) => 1.0,
Some(TextAlignH::Center) => 0.5,
_ => 0.0,
}
}
/// Whether layer `id` changed (since `before`) in a way that can move or resize layers in an auto
+26
View File
@@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() {
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
assert_eq!((some.len(), complete), (3, false), "{some:?}");
}
#[test]
fn code_links_keep_their_value_names_and_carry_source_and_notes() {
let mut s = session();
let variants: Vec<_> = ["small", "extra_large"]
.iter()
.map(|v| {
let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32}));
id(&s.execute("component.create", &json!({"ids": [f]})).unwrap())
})
.collect();
let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
s.execute(
"codeConnect.set",
&json!({"id": set, "name": "Button", "template": "<Button size={Size} />", "source": "src/button.tsx",
"notes": "Use for main actions", "values": {"Size": {"extra_large": "xl"}}}),
)
.unwrap();
let instance = id(&s.execute("instance.create", &json!({"component": variants[1]})).unwrap());
let v = context(&mut s, json!({"ids": [instance]}));
let link = &v["components"][set.to_string()]["codeLinks"][0];
assert_eq!(link["values"]["Size"]["extra_large"], "xl", "a design value keeps its name: {link}");
let code = &only(&v)["code"][0];
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
}
+181 -16
View File
@@ -26,6 +26,11 @@ pub const MAX_TEMPLATE: usize = 4_000;
pub const MAX_NAME: usize = 100;
/// Longest import path (chars).
pub const MAX_IMPORT: usize = 300;
/// Longest source path, and notes (chars).
pub const MAX_SOURCE: usize = 300;
pub const MAX_NOTES: usize = 2_000;
/// Most properties with mapped values on a link, and values on each.
const MAX_MAPPED: usize = 100;
/// Most links a connect file holds.
pub const MAX_FILE_LINKS: usize = 5_000;
/// Largest connect file read (bytes).
@@ -377,6 +382,8 @@ fn html_text(s: &str) -> String {
/// `link`'s template with `values` (one per parameter of `c`), every line prefixed by `pad`.
pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)], link: &CodeLink, lang: CodeLang, pad: &str) -> String {
// A value is written as code calls it; a condition reads the design's own value.
let coded = &in_code(values, link);
let mut out = String::new();
// A quoted attribute stays open across substitutions: `title="{a} {b}"` must treat both
// placeholders as attribute values, not text after the first one.
@@ -391,7 +398,7 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
vue_attr = None;
}
}
Piece::Value { name, inner } => match find(c, values, name) {
Piece::Value { name, inner } => match find(c, coded, name) {
Some((p, v)) => {
let e = expr(doc, c, p, v, lang);
// JSX and `view!`: a plain string reads best as an attribute value, anything
@@ -454,6 +461,12 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
out.lines().map(|l| if l.is_empty() { "\n".to_string() } else { format!("{pad}{l}\n") }).collect()
}
/// `values` with each design value the link names turned into what code calls it.
fn in_code(values: &[(String, Value)], link: &CodeLink) -> Vec<(String, Value)> {
let code = |prop: &str, v: &Value| link.values.get(prop)?.get(v.as_str()?).cloned();
values.iter().map(|(prop, v)| (prop.clone(), code(prop, v).map_or_else(|| v.clone(), Value::String))).collect()
}
/// A starting template: the code component called with every property (but slots) passed.
fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
let params: Vec<&str> = c.params.iter().filter(|p| p.kind != ParamKind::Slot).map(|p| p.ident.as_str()).collect();
@@ -469,6 +482,15 @@ fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
}
}
/// Why `source` can't name a file in a code repository: it goes down from the repository's root.
fn check_source(source: &str) -> std::result::Result<(), String> {
let plain = source.chars().count() <= MAX_SOURCE
&& !source.contains('\\')
&& !source.chars().any(char::is_control)
&& std::path::Path::new(source).components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir));
if plain { Ok(()) } else { Err(format!("source: a path inside the code repository, up to {MAX_SOURCE} characters")) }
}
/// Checks a link: its name, import path and template. Returns the placeholder names that aren't
/// properties of `c` (kept as written).
pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Result<Vec<String>, String> {
@@ -500,6 +522,14 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
_ => format!("importPath: a module or package name (letters, digits, _ and .), up to {MAX_IMPORT} characters"),
});
}
check_source(&link.source)?;
if link.notes.chars().count() > MAX_NOTES {
return Err(format!("notes: up to {MAX_NOTES} characters"));
}
let long = |s: &String| s.chars().count() > MAX_NAME;
if link.values.len() > MAX_MAPPED || link.values.values().any(|m| m.len() > MAX_MAPPED || m.iter().any(|(k, v)| long(k) || long(v))) {
return Err(format!("values: at most {MAX_MAPPED} properties of {MAX_MAPPED} values, each up to {MAX_NAME} characters"));
}
let t = &link.template;
if t.trim().is_empty() || t.chars().count() > MAX_TEMPLATE || t.chars().any(|ch| ch.is_control() && !"\n\t\r".contains(ch)) {
return Err(format!("template: the snippet, up to {MAX_TEMPLATE} characters"));
@@ -515,6 +545,12 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
unknown.push(name.to_string());
}
}
// `in_code` reads a mapping by property name, so a key that is only a parameter name does nothing.
for prop in link.values.keys() {
if !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
unknown.push(prop.clone());
}
}
Ok(unknown)
}
@@ -557,12 +593,103 @@ fn store(doc: &mut Document, owner: NodeId, link: CodeLink) -> Result<()> {
Ok(())
}
/// The variant properties of component or set `owner`, with their values.
pub fn variants(doc: &Document, owner: NodeId) -> Vec<(String, Vec<String>)> {
main_of(doc, owner)
.and_then(|m| describe(doc, m))
.map(|c| c.params.iter().filter_map(|p| if let ParamKind::Variant(v) = &p.kind { Some((p.prop.clone(), v.clone())) } else { None }).collect())
.unwrap_or_default()
}
/// A link as the connect file holds it.
fn link_json(component: &str, l: &CodeLink) -> Value {
let mut v = link_fields(l);
v["component"] = json!(component);
v
}
/// A link's own fields, as the connect file and `inspect.designContext` give them: its keys are
/// the file's, and a mapping's property names and values stay as written.
pub(crate) fn link_fields(l: &CodeLink) -> Value {
let mut v = json!({"language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template});
if !l.source.is_empty() {
v["source"] = json!(l.source);
}
if !l.values.is_empty() {
v["values"] = json!(l.values);
}
if !l.notes.is_empty() {
v["notes"] = json!(l.notes);
}
v
}
/// The components and sets `ids` are, use or hold (every one in the file without `ids`).
fn listed(doc: &Document, ids: Option<&[NodeId]>) -> Vec<NodeId> {
let mut out: Vec<NodeId> = match ids {
None => doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.id).collect(),
Some(ids) => ids.iter().flat_map(|i| doc.subtree(*i)).filter_map(|i| owner(doc, i)).collect(),
};
out.sort_unstable();
out.dedup();
out
}
/// What an agent needs to use a component: its code link for each language, or that it has none.
fn entry(doc: &Document, id: NodeId, root: Option<&str>) -> Option<Value> {
let n = doc.node(id)?;
let links: Vec<Value> = n
.code_links
.iter()
.map(|l| {
let lang = CodeLang::from_id(&l.language);
let mut v = link_fields(l);
v["import"] = json!(lang.map(|k| import_line(l, k)));
v["snippet"] = json!(lang.and_then(|k| connected_code(doc, id, k, l)));
if let Some(root) = root.filter(|_| !l.source.is_empty()) {
v["sourceFound"] = json!(crate::file_access::exists(std::path::Path::new(root).join(&l.source)));
}
v
})
.collect();
Some(json!({
"id": id,
"name": n.name,
"type": n.kind.type_name(),
"mapped": !links.is_empty(),
"properties": crate::cmd::component::describe_props(doc, id)["properties"],
"links": links,
}))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.list";
let doc = s.doc()?;
// Anything named must be layers; nothing named lists every component in the file.
let named = get(p, "ids").is_some() || get(p, "id").is_some();
let ids = if named { Some(crate::params::req_targets(cmd, s, p)?) } else { None };
let root = text(cmd, p, "root")?;
let unmapped = crate::params::boolean(p, "unmapped").unwrap_or(false);
let all: Vec<Value> = listed(doc, ids.as_deref()).into_iter().filter_map(|id| entry(doc, id, root.as_deref())).collect();
let count = |m: bool| all.iter().filter(|e| e["mapped"] == m).count();
let (mapped, missing) = (count(true), count(false));
let components: Vec<Value> = all.into_iter().filter(|e| !unmapped || e["mapped"] == false).collect();
Ok(json!({"components": components, "mapped": mapped, "unmapped": missing}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!(
"codeConnect.list",
"List code connections",
"{ids? | id? (the components those layers are, use or hold; default every component in the file), unmapped? (only those without a link), root? (the code repository: says if each link's source is there)} → {components: [{id, name, type, mapped, properties, links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, notes?}]}], mapped, unmapped}",
false,
list
),
spec!(
"codeConnect.set",
"Connect to code",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property)} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property), source? (the file, relative to the code repository), values? ({property: {design value: code value}}), notes?} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
true,
|s, p| {
let cmd = "codeConnect.set";
@@ -578,7 +705,13 @@ pub fn specs() -> Vec<CommandSpec> {
None => old.template,
};
let import_path = text(cmd, p, "importPath")?.map_or(old.import_path, |i| i.trim().to_string());
let link = CodeLink { language: lang.id().into(), import_path, name, template };
let source = text(cmd, p, "source")?.map_or(old.source, |v| v.trim().to_string());
let notes = text(cmd, p, "notes")?.unwrap_or(old.notes);
let values = match get(p, "values") {
None => old.values,
Some(v) => serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "values: {property: {design value: code value}}"))?,
};
let link = CodeLink { language: lang.id().into(), import_path, name, template, source, values, notes };
let unknown = check(&c, &link, lang).map_err(|e| bad(cmd, e))?;
let code = connected_code(doc, id, lang, &link);
store(s.doc_mut()?, owner, link)?;
@@ -610,27 +743,34 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"codeConnect.export",
"Export code connections",
"{path? (write it there, e.g. figcraft.connect.json in the code repository)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template}]}, sorted → {text, links} or {path, links}",
"{path? (write it there, e.g. figcraft.connect.json in the code repository; other top-level keys of a file already there stay, and so do the links of components this file doesn't have; a file there it can't read is left alone and the export refused)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template, source?, values?, notes?}]}, sorted → {text, links} or {path, links}",
false,
|s, p| {
let cmd = "codeConnect.export";
let path = text(cmd, p, "path")?;
let doc = s.doc()?;
let mut links: Vec<Value> = doc
.nodes()
.filter(|n| owner(doc, n.id) == Some(n.id))
.flat_map(|n| {
n.code_links.iter().map(|l| {
json!({"component": n.name, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template})
})
})
.collect();
let mut links: Vec<Value> =
doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).flat_map(|n| n.code_links.iter().map(|l| link_json(&n.name, l))).collect();
let key =
|v: &Value| (v["component"].as_str().unwrap_or_default().to_string(), v["language"].as_str().unwrap_or_default().to_string());
links.sort_by_key(key);
let count = links.len();
let text =
serde_json::to_string_pretty(&json!({"version": VERSION, "links": links})).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
// The file also holds the project's settings and the links of other designs: only
// the links of this file's components are this command's.
let old = match path.as_deref() {
Some(path) => kept_keys(cmd, path)?,
None => serde_json::Map::new(),
};
let here: Vec<&str> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.name.as_str()).collect();
let others = old.get("links").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
links.extend(others.iter().filter(|l| !l.get("component").and_then(Value::as_str).is_some_and(|c| here.contains(&c))).cloned());
links.sort_by_key(key);
let mut file = json!({"version": VERSION, "links": links});
if let Some(fields) = file.as_object_mut() {
for (k, v) in old {
fields.entry(k).or_insert(v);
}
}
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
match path {
Some(path) => {
crate::cmd::file::write(&path, text.as_bytes())?;
@@ -650,6 +790,18 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The top-level keys of the connect file at `path`, none when there is no file. A file that
/// can't be read as one is an error: writing over it would lose what it holds.
fn kept_keys(cmd: &str, path: &str) -> Result<serde_json::Map<String, Value>> {
if !crate::file_access::exists(path) {
return Ok(serde_json::Map::new());
}
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE)?) {
Ok(Value::Object(fields)) => Ok(fields),
_ => Err(bad(cmd, format!("{path} isn't a connect file it can read, so it was left as it is"))),
}
}
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.import";
let parse_json = |b: &[u8]| serde_json::from_slice::<Value>(b).map_err(|e| bad(cmd, format!("not JSON: {e}")));
@@ -688,11 +840,24 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
));
continue;
};
let values = match e.get("values") {
None | Some(Value::Null) => Default::default(),
Some(v) => match serde_json::from_value(v.clone()) {
Ok(values) => values,
Err(_) => {
warnings.push(format!("link {}: values: {{property: {{design value: code value}}}}, all strings", i + 1));
continue;
}
},
};
let link = CodeLink {
language: lang.id().into(),
import_path: field("importPath").unwrap_or_default().to_string(),
name: name.into(),
template: template.into(),
source: field("source").unwrap_or_default().to_string(),
values,
notes: field("notes").unwrap_or_default().to_string(),
};
let matches = owners.get(component).cloned().unwrap_or_default();
if matches.is_empty() {
+1 -1
View File
@@ -651,7 +651,7 @@ mod tests {
let badge = id_of(
&s.execute(
"vector.create",
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}}),
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 4}}),
)
.unwrap()["id"],
)
+9 -2
View File
@@ -178,7 +178,14 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
.filter_map(|l| {
let lang = CodeLang::from_id(&l.language)?;
let snippet = code_connect::connected_code(doc, id, lang, l)?;
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
// The snippet already holds the template and the values it maps.
let mut v = code_connect::link_fields(l);
if let Some(o) = v.as_object_mut() {
o.remove("template");
o.remove("values");
}
v["code"] = json!(snippet);
Some(v)
})
.collect()
}
@@ -355,7 +362,7 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
v["description"] = json!(description);
}
if !n.code_links.is_empty() {
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
v["codeLinks"] = json!(n.code_links.iter().map(code_connect::link_fields).collect::<Vec<_>>());
}
out.insert(id.to_string(), v);
}
+27
View File
@@ -119,6 +119,9 @@ pub struct DocState {
/// Where each page's view was left in this session (its centre and zoom; see
/// [`Self::open_page`]; not saved).
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
/// The canvas fits the page's content when it first gets its size. Off when the view was
/// restored from where the file was left ([`Session::restore_view`]).
pub fit_when_sized: bool,
}
/// A version shown on the canvas in place of the document: read-only until it's restored or the
@@ -184,6 +187,7 @@ impl DocState {
images_left_in_file: None,
on_disk: None,
page_views: BTreeMap::new(),
fit_when_sized: true,
};
st.zoom_to_fit();
st
@@ -332,6 +336,29 @@ impl DocState {
}
}
/// Each page's view as left: the one shown now at its current view, the others shown in this
/// session at theirs.
pub(crate) fn page_views(&self) -> impl Iterator<Item = (NodeId, (f64, f64, f64))> + '_ {
let shown = (self.page, (self.view.cx, self.view.cy, self.view.zoom));
self.page_views.iter().filter(|(p, _)| **p != self.page).map(|(p, v)| (*p, *v)).chain(std::iter::once(shown))
}
/// Take `views` as where their pages were left, and show `page` (or the page shown now) at
/// its view. With one, the canvas keeps it instead of fitting the page when it gets its size.
pub(crate) fn show_views(&mut self, page: Option<NodeId>, views: impl IntoIterator<Item = (NodeId, (f64, f64, f64))>) {
self.page_views.extend(views);
if let Some(page) = page {
self.page = page;
}
match self.page_views.get(&self.page) {
Some(&(cx, cy, zoom)) => {
(self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom);
self.fit_when_sized = false;
}
None => self.zoom_to_fit(),
}
}
pub fn zoom_to_fit(&mut self) {
match self.doc.page_content_bounds(self.page) {
Some(b) => self.view.fit(b, 1.0),
@@ -0,0 +1,58 @@
use figcraft_doc::NodeId;
use serde_json::json;
use crate::Session;
use crate::tools::{PointerEvent, PointerKind};
fn rect(s: &mut Session, x: f64, props: serde_json::Value) -> NodeId {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 100, "height": 100, "props": props})).unwrap();
crate::params::id_of(&r["id"]).unwrap()
}
fn hex(paints: &[figcraft_color::Paint]) -> Vec<String> {
paints.iter().map(|p| p.solid_color().map(|c| c.to_hex()).unwrap_or_default()).collect()
}
fn pick_red_onto(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids})).unwrap();
s.execute("edit.pickColor", &json!({})).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Down, 50.0, 50.0, 1.0)).unwrap();
}
fn scene() -> Session {
let mut s = Session::new();
s.execute("page.setBackground", &json!({"color": "#FFFFFF"})).unwrap();
rect(&mut s, 0.0, json!({"fills": ["#FF0000"]}));
s
}
#[test]
fn a_layer_with_only_a_stroke_takes_the_pick_on_its_stroke() {
let mut s = scene();
let outline = rect(&mut s, 200.0, json!({"fills": [], "strokes": ["#0000FF"], "strokeWeight": 2}));
pick_red_onto(&mut s, &[outline]);
let n = s.doc().unwrap().node(outline).unwrap().clone();
assert!(n.fills.is_empty(), "no fill appears: {:?}", n.fills);
assert_eq!(hex(&n.strokes), ["FF0000"]);
assert_eq!(n.stroke.weight, 2.0, "the stroke keeps its weight");
}
#[test]
fn a_hidden_fill_counts_as_none_and_a_visible_one_takes_the_pick() {
let mut s = scene();
let hidden = rect(&mut s, 200.0, json!({"fills": [{"type": "solid", "color": "#00FF00", "visible": false}], "strokes": ["#0000FF"]}));
let filled = rect(&mut s, 400.0, json!({"fills": ["#00FF00"], "strokes": ["#0000FF"]}));
let bare = rect(&mut s, 600.0, json!({"fills": [], "strokes": []}));
let undo = s.undo_depth().0;
pick_red_onto(&mut s, &[hidden, filled, bare]);
let d = s.doc().unwrap();
let (h, f, b) = (d.node(hidden).unwrap(), d.node(filled).unwrap(), d.node(bare).unwrap());
assert_eq!((hex(&h.strokes), h.fills.iter().any(|p| p.visible)), (vec!["FF0000".to_string()], false));
assert_eq!((hex(&f.fills), hex(&f.strokes)), (vec!["FF0000".to_string()], vec!["0000FF".to_string()]));
assert_eq!(hex(&b.fills), ["FF0000"], "with neither, the fill as before");
assert_eq!(s.undo_depth().0, undo + 1, "one step for the whole selection");
s.execute("edit.undo", &json!({})).unwrap();
let d = s.doc().unwrap();
assert_eq!(hex(&d.node(hidden).unwrap().strokes), ["0000FF"]);
assert_eq!(hex(&d.node(filled).unwrap().fills), ["00FF00"]);
}
+74
View File
@@ -0,0 +1,74 @@
//! Files open again where they were left: when a file's tab closes or the app quits, the page it
//! showed and each page's view (its centre and zoom) are kept for that file, and opening it again
//! shows them, as Figma opens a file where you were. They live in the preferences, not in the
//! file, so looking around never changes a file.
use serde::{Deserialize, Serialize};
use crate::{NodeId, Session, ViewState};
/// How many files' views are kept, the most recently left first.
pub const MAX_FILE_VIEWS: usize = 100;
/// Where a file was left.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FileView {
pub path: String,
/// The page shown.
pub page: NodeId,
/// The view of each page shown while it was open.
pub pages: Vec<PageView>,
}
/// A page's view: the page point at the canvas's centre, and the zoom.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct PageView {
pub page: NodeId,
pub cx: f64,
pub cy: f64,
pub zoom: f64,
}
impl Session {
/// Keep where tab `i`'s file is left. A tab without a file of its own (a new or imported file,
/// a branch) keeps nothing.
pub(crate) fn remember_view(&mut self, i: usize) {
let Some(ds) = self.docs.get(i).filter(|d| d.branch_of.is_none()) else { return };
let Some(path) = ds.path.clone() else { return };
let pages = ds.page_views().map(|(page, (cx, cy, zoom))| PageView { page, cx, cy, zoom }).collect();
let view = FileView { path, page: ds.page, pages };
let views = &mut self.prefs.file_views;
views.retain(|v| v.path != view.path);
views.insert(0, view);
views.truncate(MAX_FILE_VIEWS);
self.prefs_unsaved = true;
}
/// [`remember_view`](Self::remember_view) for every open tab, before the app quits.
pub fn remember_views(&mut self) {
for i in 0..self.docs.len() {
self.remember_view(i);
}
}
/// Show the active tab's file where it was left, if it was: its page, if the file still has
/// it as a page that isn't a divider, at its view, and each other page at its view when it is
/// shown. A view that isn't a finite centre with a zoom the canvas takes is left out.
pub(crate) fn restore_view(&mut self) {
let Ok(ds) = self.ds() else { return };
let Some(kept) = ds.path.as_deref().and_then(|p| self.prefs.file_views.iter().find(|v| v.path == p)).cloned() else { return };
let Ok(ds) = self.ds_mut() else { return };
let doc = ds.doc.clone();
let views = kept
.pages
.iter()
.filter(|v| doc.pages.contains(&v.page) && [v.cx, v.cy, v.zoom].iter().all(|x| x.is_finite()))
.filter(|v| (ViewState::MIN_ZOOM..=ViewState::MAX_ZOOM).contains(&v.zoom))
.map(|v| (v.page, (v.cx, v.cy, v.zoom)));
let page = Some(kept.page).filter(|p| doc.pages.contains(p) && !doc.is_divider(*p));
ds.show_views(page, views);
}
}
#[cfg(test)]
mod tests;
+136
View File
@@ -0,0 +1,136 @@
//! Files open again where they were left.
use serde_json::{Value, json};
use super::*;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
}
/// A test's folder, removed when the test ends, a failing one too.
struct Dir(std::path::PathBuf);
impl std::ops::Deref for Dir {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn dir(name: &str) -> Dir {
let d = std::env::temp_dir().join(format!("figcraft-file-views-{}-{name}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
Dir(d)
}
/// A saved file at `path` with two pages, each holding a rectangle, the first page shown.
fn two_pages(s: &mut Session, path: &str) -> (NodeId, NodeId) {
ex(s, "file.new", json!({}));
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100}));
ex(s, "page.add", json!({"name": "Second"}));
let pages = s.doc().unwrap().pages.clone();
ex(s, "page.select", json!({"id": pages[1].0}));
ex(s, "shape.rectangle", json!({"x": 2000, "y": 2000, "width": 50, "height": 50}));
ex(s, "page.select", json!({"id": pages[0].0}));
ex(s, "file.saveAs", json!({"path": path}));
(pages[0], pages[1])
}
fn view(s: &Session) -> (NodeId, f64, f64, f64) {
let ds = s.ds().unwrap();
(ds.page, ds.view.cx, ds.view.cy, ds.view.zoom)
}
fn look(s: &mut Session, cx: f64, cy: f64, zoom: f64) {
let v = &mut s.ds_mut().unwrap().view;
(v.cx, v.cy, v.zoom) = (cx, cy, zoom);
}
/// Closed and opened again, a file shows the page it showed, at its view, and its other page at
/// the view that page was left at; looking around leaves the file unchanged.
#[test]
fn a_file_opens_again_where_it_was_left() {
let d = dir("left");
let path = d.join("two.figcraft").to_string_lossy().into_owned();
let mut s = Session::new();
let (first, second) = two_pages(&mut s, &path);
let saved = std::fs::read(&path).unwrap();
look(&mut s, 40.0, 60.0, 2.5);
ex(&mut s, "page.select", json!({"id": second.0}));
look(&mut s, 2010.0, 2020.0, 0.5);
assert!(!s.ds().unwrap().is_dirty(), "looking around is no change to the file");
ex(&mut s, "file.close", json!({}));
assert_eq!(std::fs::read(&path).unwrap(), saved, "nothing written to the file");
assert!(s.prefs_unsaved, "kept in the preferences");
ex(&mut s, "file.open", json!({"path": path}));
assert_eq!(view(&s), (second, 2010.0, 2020.0, 0.5));
assert!(!s.ds().unwrap().fit_when_sized, "the canvas keeps the view instead of fitting");
ex(&mut s, "page.select", json!({"id": first.0}));
assert_eq!(view(&s), (first, 40.0, 60.0, 2.5));
// Through the preferences file, as the next start reads them.
let prefs: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
let mut next = Session::new();
next.prefs = prefs;
ex(&mut next, "file.open", json!({"path": path}));
assert_eq!(view(&next), (second, 2010.0, 2020.0, 0.5));
}
/// Quitting keeps every open file's view; a file never saved keeps none.
#[test]
fn quitting_keeps_each_open_files_view() {
let d = dir("quit");
let (a, b) = (d.join("a.figcraft").to_string_lossy().into_owned(), d.join("b.figcraft").to_string_lossy().into_owned());
let mut s = Session::new();
let (a_page, _) = two_pages(&mut s, &a);
look(&mut s, 1.0, 2.0, 3.0);
let (b_page, _) = two_pages(&mut s, &b);
look(&mut s, 4.0, 5.0, 0.25);
ex(&mut s, "file.new", json!({}));
s.remember_views();
let kept: Vec<&str> = s.prefs.file_views.iter().map(|v| v.path.as_str()).collect();
assert_eq!(kept.len(), 2, "{kept:?}");
let mut next = Session::new();
next.prefs = s.prefs.clone();
ex(&mut next, "file.open", json!({"path": a}));
assert_eq!(view(&next), (a_page, 1.0, 2.0, 3.0));
ex(&mut next, "file.open", json!({"path": b}));
assert_eq!(view(&next), (b_page, 4.0, 5.0, 0.25));
}
/// A kept page the file no longer has, or a view the canvas can't show, is left out: the file
/// opens fitted as before.
#[test]
fn a_view_that_no_longer_fits_the_file_is_left_out() {
let d = dir("stale");
let path = d.join("one.figcraft").to_string_lossy().into_owned();
let mut s = Session::new();
let (first, _) = two_pages(&mut s, &path);
ex(&mut s, "file.close", json!({}));
s.prefs.file_views[0].page = NodeId(999_999);
s.prefs.file_views[0].pages = vec![PageView { page: first, cx: f64::NAN, cy: 0.0, zoom: 1.0 }];
ex(&mut s, "file.open", json!({"path": path}));
let ds = s.ds().unwrap();
assert_eq!(ds.page, first);
assert!(ds.fit_when_sized, "fitted as a file never left");
assert!(ds.view.cx.is_finite());
}
/// The views kept are bounded, the most recently left first.
#[test]
fn the_most_recently_left_files_are_kept() {
let mut s = Session::new();
for k in 0..MAX_FILE_VIEWS + 5 {
ex(&mut s, "file.new", json!({}));
s.ds_mut().unwrap().path = Some(format!("/nowhere/{k}.figcraft"));
ex(&mut s, "file.close", json!({"force": true}));
}
assert_eq!(s.prefs.file_views.len(), MAX_FILE_VIEWS);
assert_eq!(s.prefs.file_views[0].path, format!("/nowhere/{}.figcraft", MAX_FILE_VIEWS + 4));
}
@@ -188,6 +188,7 @@ fn frame_selection_wraps_the_layers_where_the_topmost_was() {
assert_eq!(doc.node(page).unwrap().children, vec![other, f, top], "where b (the topmost selected) was");
assert_eq!((wb(&s, a), wb(&s, b)), ((10.0, 10.0, 20.0, 20.0), (50.0, 40.0, 30.0, 30.0)));
assert_eq!(s.selection(), vec![f]);
assert!(doc.node(f).unwrap().fills.is_empty(), "no fill over what it frames: {:?}", doc.node(f).unwrap().fills);
// Inside a frame, the new frame nests there.
let outer = frame(&mut s, 500.0, 0.0, 200.0, 200.0, None);
let c = rect(&mut s, 20.0, 20.0, 10.0, 10.0, Some(outer));
+1
View File
@@ -368,6 +368,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[
(Selection, "Pick select: next or previous layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
(Selection, "Pick select: into a layer, out to its parent", "↵ / ⇧↵", "Enter / Shift+Enter"),
(Selection, "Pick select: select the picked layer", "Space", "Space"),
(Text, "While editing text: next or previous text layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
(Edit, "Duplicate by dragging", "⌥ drag", "Alt+drag"),
(Transform, "Nudge (Shift: big nudge)", "← ↑ → ↓", "← ↑ → ↓"),
(Transform, "Resize by the nudge amount", "⌘ arrows", "Ctrl+arrows"),
+17
View File
@@ -107,13 +107,16 @@ use serde_json::{Value, json};
mod derived;
mod doc_state;
mod error;
mod file_views;
mod prefs;
mod reopen;
mod session;
mod view_state;
pub use derived::{changed_nodes, normalize};
pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview};
pub use error::{EngineError, Result, bad};
pub use file_views::{FileView, MAX_FILE_VIEWS, PageView};
pub use prefs::{Clipboard, DefaultProps, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale};
pub use session::Forward;
pub use view_state::ViewState;
@@ -339,6 +342,8 @@ mod eyedropper_create_tests;
#[cfg(test)]
mod eyedropper_image_tests;
#[cfg(test)]
mod eyedropper_stroke_tests;
#[cfg(test)]
mod facilitate_tests;
#[cfg(test)]
mod fig_export_assets_tests;
@@ -489,6 +494,8 @@ mod panels_behaviour_tests;
#[cfg(test)]
mod paste_missing_image_tests;
#[cfg(test)]
mod paste_over_tests;
#[cfg(test)]
mod paste_sibling_tests;
#[cfg(test)]
mod path_read_caps_tests;
@@ -549,6 +556,8 @@ mod proto_run_tests;
#[cfg(test)]
mod proto_tail_tests;
#[cfg(test)]
mod reopen_tests;
#[cfg(test)]
mod rest_slot_tests;
#[cfg(test)]
mod retained_walk_tests;
@@ -571,6 +580,8 @@ mod scaled_instance_tests;
#[cfg(test)]
mod section_contents_tests;
#[cfg(test)]
mod section_marquee_tests;
#[cfg(test)]
mod section_tests;
#[cfg(test)]
mod select_area_tests;
@@ -587,6 +598,8 @@ mod shapebuilder_tests;
#[cfg(test)]
mod shapes_behaviour_tests;
#[cfg(test)]
mod shift_double_click_tests;
#[cfg(test)]
mod shortcut_parity_tests;
#[cfg(test)]
mod sketch_import_tests;
@@ -625,6 +638,8 @@ mod text_motion_tests;
#[cfg(test)]
mod text_style_picker_tests;
#[cfg(test)]
mod text_tab_tests;
#[cfg(test)]
mod text_tail_tests;
#[cfg(test)]
mod text_weight_step_tests;
@@ -698,6 +713,8 @@ mod export_bounds_tests;
#[cfg(test)]
mod page_view_tests;
#[cfg(test)]
mod paste_properties_tests;
#[cfg(test)]
mod selection_reorder_tests;
#[cfg(test)]
mod selection_spacing_tests;
+95
View File
@@ -0,0 +1,95 @@
//! Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen.
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
id(&s.execute("frame.create", &json!({"x": x, "y": y, "width": 200, "height": 100})).unwrap())
}
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
s.doc().unwrap().node(parent).unwrap().children.clone()
}
fn paste_over(s: &mut Session, sel: Vec<NodeId>) -> Vec<NodeId> {
s.set_selection(sel);
s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
}
fn top_left(s: &Session, n: NodeId) -> (f64, f64) {
let b = s.doc().unwrap().world_bounds(n).unwrap();
(b.x0, b.y0)
}
#[test]
fn several_rows_of_an_auto_layout_selected_get_the_copy_after_the_last_row() {
let mut s = Session::new();
let rows: Vec<NodeId> =
(0..4).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
let r = s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
let list = id_of(&r["ids"][0]).unwrap();
assert_eq!(kids(&s, list), rows);
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
// Clicked from the middle down and back: the click order isn't the order on screen.
let pasted = paste_over(&mut s, vec![rows[1], rows[3], rows[2]]);
assert_eq!(pasted.len(), 1);
assert_eq!(kids(&s, list), vec![rows[0], rows[1], rows[2], rows[3], pasted[0]], "after the last selected row");
assert_eq!(s.selection(), pasted);
}
#[test]
fn several_artboards_in_a_column_get_the_copy_below_the_lowest_with_their_gap() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 0.0, 140.0), frame(&mut s, 0.0, 280.0));
let source = frame(&mut s, 1000.0, 0.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![a, c, b]);
assert_eq!(pasted.len(), 1);
assert_eq!(top_left(&s, pasted[0]), (0.0, 420.0), "below the lowest artboard, 40 below it like the others");
let page = s.doc().unwrap().node(c).unwrap().parent.unwrap();
let order = kids(&s, page);
let at = |n: NodeId| order.iter().position(|i| *i == n).unwrap();
assert_eq!(at(pasted[0]), at(c) + 1, "just above the lowest artboard");
}
#[test]
fn several_artboards_in_a_row_get_the_copy_right_of_the_rightmost_with_their_gap() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 260.0, 0.0), frame(&mut s, 520.0, 0.0));
let source = frame(&mut s, 0.0, 1000.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![b, a, c]);
assert_eq!(top_left(&s, pasted[0]), (780.0, 0.0), "right of the rightmost, 60 from it like the others");
}
#[test]
fn several_overlapping_layers_get_the_copy_right_under_the_lowest() {
let mut s = Session::new();
let (a, b) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 50.0, 30.0));
let source = frame(&mut s, 1000.0, 0.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![b, a]);
assert_eq!(top_left(&s, pasted[0]), (50.0, 130.0));
}
#[test]
fn several_absolute_layers_of_an_auto_layout_get_the_copy_below_the_lowest() {
let mut s = Session::new();
let rows: Vec<NodeId> =
(0..3).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
s.execute("node.set", &json!({"ids": rows, "props": {"absolute": true}})).unwrap();
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
let (x, y0) = top_left(&s, rows[1]);
let (_, y1) = top_left(&s, rows[2]);
let pasted = paste_over(&mut s, vec![rows[2], rows[0], rows[1]]);
assert_eq!(pasted.len(), 1);
assert_eq!(top_left(&s, pasted[0]), (x, y1 + 20.0 + (y1 - y0 - 20.0)), "the layout doesn't place them, so below the lowest");
}
+116
View File
@@ -0,0 +1,116 @@
//! Copy properties and Paste properties (Alt+Cmd/Ctrl+C and V) carry what a layer's look comes
//! from as well as its values: its colour, effect and grid styles, the variables bound to what is
//! copied and a frame's layout grids. A link the file pasted into doesn't have is left out.
use figcraft_doc::{LayoutGrid, NodeId};
use serde_json::{Value, json};
use crate::Session;
fn id(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn frame(s: &mut Session, x: f64) -> NodeId {
id(s.execute("frame.create", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap())
}
fn copy_onto(s: &mut Session, from: NodeId, to: NodeId) {
s.execute("edit.copyProperties", &json!({"id": from})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [to]})).unwrap();
}
#[test]
fn a_frame_pastes_its_styles_variables_and_layout_grids() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0), frame(&mut s, 200.0), frame(&mut s, 400.0));
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
for (name, value) in [("surface", "#FF0000"), ("other", "#0000FF")] {
s.execute("variable.create", &json!({"collection": "Tokens", "name": name, "type": "color", "value": value})).unwrap();
}
s.execute("variable.create", &json!({"collection": "Tokens", "name": "radius", "type": "number", "value": 16})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "cornerRadius", "variable": "radius"})).unwrap();
s.execute("node.set", &json!({"ids": [a], "props": {"grids": [serde_json::to_value(LayoutGrid::default()).unwrap()]}})).unwrap();
// B is bound to another colour, which the paste replaces.
s.execute("variable.bind", &json!({"ids": [b], "field": "fills/0/color", "variable": "other"})).unwrap();
let shadow = s.execute("style.create", &json!({"type": "effect", "name": "Shadow", "value": [{"type": "dropShadow"}]})).unwrap()["id"].clone();
let green = s.execute("style.create", &json!({"type": "paint", "name": "Green", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [c], "style": green})).unwrap();
s.execute("style.apply", &json!({"ids": [c], "style": shadow})).unwrap();
copy_onto(&mut s, a, b);
let (na, nb) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(b).unwrap().clone());
assert_eq!(nb.bound.get("fills/0/color"), na.bound.get("fills/0/color"), "the fill follows the same variable");
assert_eq!(nb.bound.get("cornerRadius"), na.bound.get("cornerRadius"), "and so do the corners");
assert_eq!(nb.corners.radii, [16.0; 4]);
assert_eq!(nb.grids, na.grids, "a frame's layout grids come along");
copy_onto(&mut s, c, a);
let (na, nc) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(c).unwrap().clone());
assert_eq!(na.styles.fill, nc.styles.fill, "the fill style is linked");
assert!(nc.styles.effect.is_some() && na.styles.effect == nc.styles.effect, "the effect style too");
assert!(!na.bound.contains_key("fills/0/color"), "the style replaces the fill's variable");
assert!(!na.bound.contains_key("cornerRadius"), "C's corners aren't bound, so A's aren't any more");
assert!(na.grids.is_empty(), "nor has it layout grids");
assert_eq!(na.fills, nc.fills);
}
#[test]
fn links_another_file_lacks_paste_as_values() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "surface", "type": "color", "value": "#FF0000"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
let st = s.execute("style.create", &json!({"type": "paint", "name": "Line", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("node.set", &json!({"ids": [a], "props": {"strokes": [{"type": "solid", "color": "#000000"}]}})).unwrap();
s.execute("style.apply", &json!({"ids": [a], "style": st, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
let copied = s.doc().unwrap().node(a).unwrap().clone();
s.execute("file.new", &json!({})).unwrap();
let b = frame(&mut s, 0.0);
// This file's own style and variable come out with the copied ids: they are not the copied ones.
s.execute("variable.createCollection", &json!({"name": "Theirs"})).unwrap();
s.execute("variable.create", &json!({"collection": "Theirs", "name": "ink", "type": "color", "value": "#0000FF"})).unwrap();
s.execute("style.create", &json!({"type": "paint", "name": "Ink", "value": "#0000FF"})).unwrap();
let doc = s.doc().unwrap();
let vid = copied.bound["fills/0/color"].as_str();
assert!(doc.style(st.as_str().unwrap()).is_some() && doc.variables.get_by_id(vid).is_some(), "the ids are taken here");
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert_eq!((nb.fills.clone(), nb.strokes.clone()), (copied.fills, copied.strokes), "the values arrive");
assert!(nb.bound.is_empty() && nb.styles.fill.is_none() && nb.styles.stroke.is_none(), "{:?} {:?}", nb.bound, nb.styles);
}
#[test]
fn a_missing_style_unlinks_the_layers_own() {
let mut s = Session::new();
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
// B's own style gives the same colour, so the paste changes no value that would unlink it.
let gone = s.execute("style.create", &json!({"type": "paint", "name": "Gone", "value": "#00FF00"})).unwrap()["id"].clone();
let own = s.execute("style.create", &json!({"type": "paint", "name": "Own", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [a], "style": gone, "target": "stroke"})).unwrap();
s.execute("style.apply", &json!({"ids": [b], "style": own, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
s.execute("style.delete", &json!({"style": gone})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert!(nb.styles.stroke.is_none(), "A's strokes had no style here, so B's aren't linked: {:?}", nb.styles);
}
#[test]
fn a_binding_on_what_the_copy_doesnt_carry_stays() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
let t = id(s.execute("text.create", &json!({"text": "Hi", "x": 0, "y": 200})).unwrap());
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "body", "type": "number", "value": 18})).unwrap();
s.execute("variable.bind", &json!({"ids": [t], "field": "fontSize", "variable": "body"})).unwrap();
let before = s.doc().unwrap().node(t).unwrap().bound.get("fontSize").cloned();
copy_onto(&mut s, a, t);
let nt = s.doc().unwrap().node(t).unwrap();
assert!(before.is_some() && nt.bound.get("fontSize") == before.as_ref(), "a frame carries no font size: {:?}", nt.bound);
}
+20 -1
View File
@@ -63,7 +63,8 @@ pub struct Prefs {
/// Files that have a path are saved by themselves a few seconds after they change (the app's
/// timer; off: only File ▸ Save writes them).
pub auto_save: bool,
/// The desktop app starts on the Home screen instead of in a new file.
/// The desktop app starts on the Home screen instead of reopening the files open when it last
/// quit.
pub start_on_home: bool,
/// `figcraft://` invite links open this app (`collab.registerLinks`); `None`: on for installed
/// builds, off for development builds.
@@ -85,6 +86,18 @@ pub struct Prefs {
/// Recently opened or saved files, newest first (File ▸ Open recent; at most
/// [`cmd::file::MAX_RECENT`]).
pub recent_files: Vec<String>,
/// The files open when the desktop app last quit, in tab order: the next start opens them again
/// ([`Session::reopen_files`](crate::Session::reopen_files)).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub open_files: Vec<String>,
/// Which of [`open_files`](Self::open_files) was in front.
#[serde(skip_serializing_if = "Option::is_none")]
pub front_file: Option<String>,
/// Where each file was left when its tab closed or the app quit, the most recently left first,
/// at most [`MAX_FILE_VIEWS`](crate::MAX_FILE_VIEWS): opening it again shows that page at that
/// view ([`Session::remember_views`](crate::Session::remember_views)).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub file_views: Vec<crate::FileView>,
/// The files you put on a server without its key, with their owner tokens (passwords: see
/// [`online`]), most recently opened first, at most [`online::MAX_ONLINE_FILES`].
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "online::read")]
@@ -158,6 +171,9 @@ impl Default for Prefs {
plugin_directory: None,
publish_server: live::DEFAULT_SERVER.into(),
recent_files: Vec::new(),
open_files: Vec::new(),
front_file: None,
file_views: Vec::new(),
online_files: Vec::new(),
getting_started_dismissed: false,
link_notice_skipped: false,
@@ -201,6 +217,9 @@ pub struct Clipboard {
pub images: std::collections::BTreeMap<String, figcraft_doc::ImageData>,
/// Copied properties (Copy properties / Paste properties).
pub props: Option<Value>,
/// The file the copied properties came from: their style and variable ids name its styles and
/// variables, and in another file the same ids can name unrelated ones.
pub props_source_doc: u64,
/// A copied fill or stroke row (`fill.copy`, `stroke.copy`): whether it's a fill, and the paint.
pub paint: Option<(bool, figcraft_color::Paint)>,
/// The stroke settings (`weight`, alignment, sides…) copied with a stroke's paint.
+38
View File
@@ -0,0 +1,38 @@
//! The files open when the desktop app quit open again at its next start, in their tabs' order
//! with the same one in front, as Figma's desktop app reopens its tabs.
use serde_json::json;
use crate::{EngineError, Session};
impl Session {
/// Keep the open files to reopen at the next start: each tab's file that has a path, in tab
/// order, and the one in front. Files without one (new, imported, joined from a live session)
/// and branch tabs are left out.
pub fn remember_open_files(&mut self) {
let path = |i: usize| self.docs.get(i).filter(|d| d.branch_of.is_none()).and_then(|d| d.path.clone());
self.prefs.open_files = (0..self.docs.len()).filter_map(path).collect();
self.prefs.front_file = path(self.active);
}
/// Open the files [`remember_open_files`](Self::remember_open_files) kept, then bring the one
/// that was in front forward. A file that is no longer there is skipped; the others that don't
/// open come back with why. A file already open (a recovered copy, one named at start) keeps
/// its tab.
pub fn reopen_files(&mut self) -> Vec<(String, EngineError)> {
let mut failed = Vec::new();
for path in self.prefs.open_files.clone() {
if !crate::file_access::exists(&path) {
continue;
}
if let Err(e) = self.execute("file.open", &json!({"path": path})) {
failed.push((path, e));
}
}
let front = self.prefs.front_file.as_deref();
if let Some(i) = self.docs.iter().position(|d| front.is_some() && d.path.as_deref() == front) {
self.active = i;
}
failed
}
}
+115
View File
@@ -0,0 +1,115 @@
//! The files open when the desktop app quit open again at its next start.
use std::path::{Path, PathBuf};
use serde_json::json;
use crate::Session;
/// A fresh folder for a test's files, removed when the test ends, a failing one too.
struct Folder(PathBuf);
impl std::ops::Deref for Folder {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for Folder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn folder(name: &str) -> Folder {
let dir = std::env::temp_dir().join(format!("figcraft-reopen-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Folder(dir)
}
fn saved(s: &mut Session, dir: &Path, name: &str) -> String {
let path = dir.join(format!("{name}.figcraft")).to_string_lossy().into_owned();
s.execute("file.new", &json!({"name": name})).unwrap();
s.execute("file.save", &json!({"path": path})).unwrap();
path
}
fn paths(s: &Session) -> Vec<Option<String>> {
s.docs.iter().map(|d| d.path.clone()).collect()
}
/// The next start: the preferences the last run kept, nothing open yet.
fn next_start(last: &Session) -> Session {
let mut s = Session::empty();
s.prefs = last.prefs.clone();
s
}
#[test]
fn the_files_open_at_quit_reopen_in_their_order_with_the_same_one_in_front() {
let dir = folder("order");
let mut s = Session::empty();
let a = saved(&mut s, &dir, "A");
s.execute("file.new", &json!({"name": "Untitled"})).unwrap();
let b = saved(&mut s, &dir, "B");
let c = saved(&mut s, &dir, "C");
s.execute("doc.switch", &json!({"index": 2})).unwrap();
s.remember_open_files();
assert_eq!(s.prefs.open_files, vec![a.clone(), b.clone(), c.clone()], "the new file without a path is left out");
assert_eq!(s.prefs.front_file.as_deref(), Some(b.as_str()));
let mut t = next_start(&s);
assert!(t.reopen_files().is_empty());
assert_eq!(paths(&t), vec![Some(a), Some(b.clone()), Some(c)]);
assert_eq!(t.docs[t.active].path.as_deref(), Some(b.as_str()), "B is in front again");
}
#[test]
fn a_file_gone_since_is_skipped_and_one_that_wont_open_says_why() {
let dir = folder("gone");
let mut s = Session::empty();
let kept = saved(&mut s, &dir, "Kept");
let gone = saved(&mut s, &dir, "Gone");
let broken = saved(&mut s, &dir, "Broken");
s.remember_open_files();
std::fs::remove_file(&gone).unwrap();
std::fs::write(&broken, b"not a figcraft file").unwrap();
let mut t = next_start(&s);
let failed = t.reopen_files();
assert_eq!(failed.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>(), vec![broken]);
assert_eq!(paths(&t), vec![Some(kept)]);
}
#[test]
fn a_file_already_open_at_start_keeps_its_one_tab() {
let dir = folder("twice");
let mut s = Session::empty();
let a = saved(&mut s, &dir, "A");
let b = saved(&mut s, &dir, "B");
s.execute("doc.switch", &json!({"index": 0})).unwrap();
s.remember_open_files();
// B was named on the command line (or came back as a recovered copy).
let mut t = next_start(&s);
t.execute("file.open", &json!({"path": b})).unwrap();
assert!(t.reopen_files().is_empty());
assert_eq!(paths(&t), vec![Some(b), Some(a.clone())]);
assert_eq!(t.docs[t.active].path.as_deref(), Some(a.as_str()));
}
#[test]
fn quitting_with_nothing_open_leaves_nothing_to_reopen() {
let dir = folder("none");
let mut s = Session::empty();
saved(&mut s, &dir, "A");
s.remember_open_files();
s.execute("file.close", &json!({"index": 0})).unwrap();
s.remember_open_files();
assert!(s.prefs.open_files.is_empty());
assert_eq!(s.prefs.front_file, None);
let saved = serde_json::to_value(&s.prefs).unwrap();
assert!(saved.get("open_files").is_none() && saved.get("front_file").is_none(), "not written when empty");
}
+13 -3
View File
@@ -94,7 +94,7 @@ fn assert_save_state_unchanged(s: &Session, before: &DocState, recent: &[String]
}
#[test]
fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
fn saving_to_another_file_names_the_document_after_it() {
let mut files = SaveFiles::new();
let path = files.path("Redis.figcraft");
let copy = files.path("Redis copy.figcraft");
@@ -111,9 +111,19 @@ fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
s.execute("file.saveAs", &json!({"path": copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Redis copy");
s.execute("file.rename", &json!({"name": "Chosen title"})).unwrap();
s.execute("file.rename", &json!({"name": "Chosen: title"})).unwrap();
s.execute("file.save", &json!({})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen: title", "saving to the same file keeps a name given here");
s.execute("file.saveAs", &json!({"path": manual_copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen title");
assert_eq!(s.ds().unwrap().doc.name, "Other", "a name given here too");
assert_eq!(figcraft_format::load_bytes(&std::fs::read(&manual_copy).unwrap()).unwrap().0.name, "Other");
// A file without one on disk yet: imported, here with its source's name.
let imported = files.path("Imported.figcraft");
let mut i = Session::new();
i.execute("file.rename", &json!({"name": "ШИМ"})).unwrap();
i.execute("file.saveAs", &json!({"path": imported.to_string_lossy()})).unwrap();
assert_eq!(i.ds().unwrap().doc.name, "Imported");
}
#[test]
+115
View File
@@ -0,0 +1,115 @@
use figcraft_doc::NodeId;
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind};
fn ex(s: &mut Session, cmd: &str, p: Value) -> NodeId {
id_of(&s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))["id"]).unwrap()
}
fn rect(s: &mut Session, x: f64, y: f64, parent: NodeId) -> NodeId {
ex(s, "shape.rectangle", json!({"x": x, "y": y, "width": 40, "height": 40, "parent": parent}))
}
struct Scene {
section: NodeId,
left: NodeId,
right: NodeId,
in_left: [NodeId; 2],
in_right: NodeId,
}
fn scene(s: &mut Session) -> Scene {
let section = ex(s, "node.create", json!({"type": "section", "x": 0, "y": 0, "width": 1000, "height": 600}));
let left = ex(s, "frame.create", json!({"x": 50, "y": 50, "width": 300, "height": 300, "parent": section}));
let right = ex(s, "frame.create", json!({"x": 400, "y": 50, "width": 300, "height": 300, "parent": section}));
let in_left = [rect(s, 20.0, 20.0, left), rect(s, 120.0, 120.0, left)];
let in_right = rect(s, 20.0, 20.0, right);
s.execute("select.none", &json!({})).unwrap();
Scene { section, left, right, in_left, in_right }
}
fn ev(kind: PointerKind, p: (f64, f64), cmd: bool) -> PointerEvent {
PointerEvent { cmd, ..PointerEvent::at(kind, p.0, p.1, 1.0) }
}
fn drag(s: &mut Session, a: (f64, f64), b: (f64, f64), cmd: bool) -> Vec<NodeId> {
s.pointer(&ev(PointerKind::Down, a, cmd)).unwrap();
s.pointer(&ev(PointerKind::Move, b, cmd)).unwrap();
s.pointer(&ev(PointerKind::Up, b, cmd)).unwrap();
let mut sel = s.selection();
sel.sort();
sel
}
fn x_of(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().world_bounds(id).unwrap().x0
}
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
#[test]
fn a_drag_on_an_artboards_background_in_a_section_selects_what_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (60.0, 60.0), (110.0, 110.0), false), vec![k.in_left[0]]);
assert_eq!(drag(&mut s, (340.0, 340.0), (60.0, 60.0), false), sorted(k.in_left.to_vec()));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
}
#[test]
fn a_drag_on_a_sections_background_selects_the_artboards_layers_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), false), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!(drag(&mut s, (20.0, 20.0), (720.0, 380.0), false), sorted(vec![k.left, k.right]), "artboards it encloses go whole");
assert_eq!(x_of(&s, k.section), 0.0, "the section stays put");
}
#[test]
fn a_selected_section_still_drags_and_a_click_on_its_background_steps_out_to_it() {
let mut s = Session::new();
let k = scene(&mut s);
s.execute("select.set", &json!({"ids": [k.section]})).unwrap();
drag(&mut s, (20.0, 400.0), (120.0, 400.0), false);
assert_eq!(x_of(&s, k.section), 100.0);
s.execute("select.set", &json!({"ids": [k.in_right]})).unwrap();
assert_eq!(drag(&mut s, (900.0, 500.0), (900.0, 500.0), false), vec![k.section]);
}
#[test]
fn cmd_drag_from_a_background_marks_out_nested_layers_and_cmd_click_still_picks_the_frame() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (60.0, 60.0), (110.0, 110.0), true), vec![k.in_left[0]]);
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), true), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
assert_eq!(drag(&mut s, (300.0, 300.0), (300.0, 300.0), true), vec![k.left]);
assert_eq!(drag(&mut s, (900.0, 500.0), (900.0, 500.0), true), vec![k.section]);
}
#[test]
fn cmd_drag_inside_a_selected_artboard_or_section_marks_out_nested_layers_instead_of_moving_it() {
let mut s = Session::new();
let k = scene(&mut s);
s.execute("select.set", &json!({"ids": [k.left]})).unwrap();
assert_eq!(drag(&mut s, (130.0, 75.0), (90.0, 90.0), true), vec![k.in_left[0]]);
s.execute("select.set", &json!({"ids": [k.section]})).unwrap();
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), true), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
s.execute("select.set", &json!({"ids": [k.left]})).unwrap();
assert_eq!(drag(&mut s, (300.0, 300.0), (300.0, 300.0), true), vec![k.left], "a Cmd click keeps the artboard");
assert_eq!(drag(&mut s, (80.0, 80.0), (80.0, 80.0), true), vec![k.in_left[0]], "a Cmd click on a layer in it picks the layer");
let mut s = Session::new();
let board = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 400}));
let inner = [rect(&mut s, 20.0, 20.0, board), rect(&mut s, 200.0, 200.0, board)];
s.execute("select.set", &json!({"ids": [board]})).unwrap();
assert_eq!(drag(&mut s, (330.0, 30.0), (10.0, 300.0), true), sorted(inner.to_vec()), "a top-level artboard too");
assert_eq!(x_of(&s, board), 0.0);
}
@@ -0,0 +1,116 @@
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind};
use figcraft_doc::NodeId;
fn ex(s: &mut Session, cmd: &str, p: Value) -> NodeId {
id_of(&s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))["id"]).unwrap()
}
struct Board {
frame: NodeId,
inner: NodeId,
rect: NodeId,
}
fn board(s: &mut Session, x: f64) -> Board {
let frame = ex(s, "frame.create", json!({"x": x, "y": 0, "width": 300, "height": 300}));
let rect = ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": frame}));
let other = ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": frame}));
let inner = ex(s, "object.group", json!({"ids": [rect, other]}));
let extra = ex(s, "shape.rectangle", json!({"x": 250, "y": 20, "width": 20, "height": 20, "parent": frame}));
ex(s, "object.group", json!({"ids": [inner, extra]}));
Board { frame, inner, rect }
}
fn send(s: &mut Session, kind: PointerKind, x: f64, y: f64, shift: bool) {
s.pointer(&PointerEvent { shift, ..PointerEvent::at(kind, x, y, 1.0) }).unwrap();
}
fn double_click(s: &mut Session, x: f64, y: f64, shift: bool) -> Vec<NodeId> {
send(s, PointerKind::Down, x, y, shift);
send(s, PointerKind::Up, x, y, shift);
send(s, PointerKind::Down, x, y, shift);
send(s, PointerKind::DoubleClick, x, y, shift);
send(s, PointerKind::Up, x, y, shift);
send(s, PointerKind::Move, x + 1.0, y, shift);
let mut sel = s.selection();
sel.sort();
sel
}
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
#[test]
fn shift_double_clicks_go_deeper_in_a_neighbouring_artboard_and_keep_the_rest() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.none", &json!({})).unwrap();
assert_eq!(double_click(&mut s, 100.0, 100.0, false), vec![a.inner], "a plain double-click enters the artboard");
assert_eq!(double_click(&mut s, 500.0, 100.0, true), sorted(vec![a.inner, b.inner]), "Shift: the neighbour's layer joins");
assert_eq!(double_click(&mut s, 500.0, 100.0, true), sorted(vec![a.inner, b.rect]), "Shift again: a level deeper there");
assert_eq!(double_click(&mut s, 100.0, 100.0, true), sorted(vec![a.rect, b.rect]), "and in the first artboard too");
assert!(s.ds().unwrap().vector_edit.is_none());
assert_eq!(s.doc().unwrap().node(a.frame).unwrap().children.len(), 1, "nothing moved out of place");
}
#[test]
fn a_shift_double_click_on_a_neighbouring_row_adds_its_layer_at_the_selected_depth() {
let mut s = Session::new();
let section = ex(&mut s, "node.create", json!({"type": "section", "x": -100, "y": -100, "width": 1200, "height": 1000}));
let artboard = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 1000, "height": 800}));
s.execute("node.reparent", &json!({"ids": [artboard], "parent": section})).unwrap();
let content = ex(&mut s, "frame.create", json!({"x": 100, "y": 100, "width": 600, "height": 400, "parent": artboard}));
let specs = ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 600, "height": 200, "parent": content}));
let names: Vec<NodeId> = (0..3)
.map(|i| {
let row = ex(&mut s, "frame.create", json!({"x": 30, "y": i * 30, "width": 560, "height": 22, "parent": specs}));
let name = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 120, "height": 22, "parent": row}));
ex(&mut s, "text.create", json!({"text": "Client:", "x": 0, "y": 0, "parent": name}));
name
})
.collect();
s.execute("select.set", &json!({"ids": [names[0]]})).unwrap();
assert_eq!(double_click(&mut s, 135.0, 238.0, true), sorted(vec![names[0], names[1]]), "the next row's name joins the selected one");
assert_eq!(double_click(&mut s, 135.0, 268.0, true), sorted(names.clone()), "and the row after it");
}
#[test]
fn a_shift_double_click_with_the_hand_keeps_a_selection_made_after_earlier_presses() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.set", &json!({"ids": [a.inner]})).unwrap();
for _ in 0..2 {
send(&mut s, PointerKind::Down, 100.0, 100.0, false);
send(&mut s, PointerKind::Up, 100.0, 100.0, false);
}
s.execute("select.set", &json!({"ids": [b.inner]})).unwrap();
s.set_tool(crate::tools::ToolId::Hand);
assert_eq!(double_click(&mut s, 100.0, 100.0, true), sorted(vec![a.inner, b.inner]), "the Move presses' selection doesn't come back");
}
#[test]
fn a_shift_double_click_without_its_presses_keeps_the_current_selection() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.set", &json!({"ids": [a.inner]})).unwrap();
for _ in 0..2 {
send(&mut s, PointerKind::Down, 1000.0, 1000.0, false);
send(&mut s, PointerKind::Up, 1000.0, 1000.0, false);
}
s.execute("select.set", &json!({"ids": [b.inner]})).unwrap();
send(&mut s, PointerKind::DoubleClick, 100.0, 100.0, true);
assert_eq!(sorted(s.selection()), sorted(vec![a.inner, b.inner]), "a double-click alone works from the selection it finds");
}
+39
View File
@@ -960,3 +960,42 @@ fn setting_characters_as_a_command_never_renames_the_layer() {
s.execute("node.set", &json!({"id": t, "props": {"characters": "Site em 7 dias"}})).unwrap();
assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("Site em 7 dias", "Title"), "the field keeps its name");
}
fn top_middle(s: &Session, t: NodeId) -> (f64, f64) {
let doc = s.doc().unwrap();
let p = doc.world_transform(t) * figcraft_geom::kurbo::Point::new(doc.node(t).unwrap().width / 2.0, 0.0);
(p.x, p.y)
}
#[test]
fn centred_auto_width_text_grows_and_shrinks_both_ways() {
let font = test_mono_font();
for (src, rotation) in [("ANCHOR TEST\nabc", 0.0), ("abc", 0.0), ("abc", 90.0)] {
let mut s = Session::new();
let t = text(&mut s, src, json!({"fontSize": 40, "fontFamily": font, "textAlign": "center", "textAutoResize": "widthAndHeight"}));
s.execute("node.set", &json!({"id": t, "props": {"x": 200, "y": 50, "rotation": rotation}})).unwrap();
let anchor = top_middle(&s, t);
let w0 = size(&s, t).0;
begin(&mut s, t, Some(src.chars().count()), false).unwrap();
for c in "defghijklmnopqrstuvwxyz".chars() {
crate::textedit::insert(&mut s, &c.to_string()).unwrap();
assert_near(top_middle(&s, t), anchor, &format!("{src:?} at {rotation}°: typing {c}"));
}
assert!(size(&s, t).0 > w0 + 1e-6, "{src:?} at {rotation}°: typing grows the text");
for _ in 0..23 {
key(&mut s, "Backspace", false, false, false).unwrap();
assert_near(top_middle(&s, t), anchor, &format!("{src:?} at {rotation}°: deleting"));
}
assert!((size(&s, t).0 - w0).abs() < 1e-6, "back to the starting width");
}
}
#[test]
fn left_aligned_auto_width_text_still_grows_to_the_right() {
let font = test_mono_font();
let mut s = Session::new();
let t = text(&mut s, "abc", json!({"fontSize": 40, "fontFamily": font, "textAutoResize": "widthAndHeight"}));
let left = s.doc().unwrap().world_transform(t);
s.execute("node.set", &json!({"id": t, "props": {"characters": "abcdefghijklmnop"}})).unwrap();
assert_eq!(s.doc().unwrap().world_transform(t), left);
}
+113
View File
@@ -0,0 +1,113 @@
//! Tab and Shift+Tab while editing a text layer move editing to the next or previous text layer
//! of the same top-level frame, in reading order (rows top to bottom, each left to right), with
//! all of its text selected; hidden and locked text is passed over, and at either end the key
//! does nothing.
use figcraft_doc::NodeId;
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn text(s: &mut Session, chars: &str, x: f64, y: f64, parent: NodeId) -> NodeId {
id_of(&ex(s, "text.create", json!({"text": chars, "x": x, "y": y, "parent": parent}))["id"]).unwrap()
}
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 400, "height": 300}))["id"]).unwrap()
}
fn tab(s: &mut Session, shift: bool) {
ex(s, "text.edit.key", json!({"key": "Tab", "shift": shift}));
}
/// The text being edited and whether all of it is selected.
fn editing(s: &Session) -> (NodeId, bool) {
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
let n = s.doc().unwrap().node(te.id).unwrap().kind.text().unwrap().char_count();
(te.id, te.anchor.min(te.caret) == 0 && te.anchor.max(te.caret) == n)
}
fn chars(s: &Session, id: NodeId) -> String {
s.doc().unwrap().node(id).unwrap().kind.text().unwrap().characters.clone()
}
/// A frame with a row of three texts whose tops differ by a few pixels, out of order in the
/// layer list, and a second row below; a text in another frame beside it.
fn two_rows(s: &mut Session) -> Vec<NodeId> {
let f = frame(s, 0.0, 0.0);
let b = text(s, "B", 150.0, 12.0, f);
let a = text(s, "A", 10.0, 10.0, f);
let e = text(s, "E", 150.0, 100.0, f);
let c = text(s, "C", 290.0, 6.0, f);
let d = text(s, "D", 10.0, 101.0, f);
let other = frame(s, 500.0, 0.0);
text(s, "Elsewhere", 10.0, 10.0, other);
vec![a, b, c, d, e]
}
#[test]
fn tab_reads_a_row_left_to_right_then_the_next_row() {
let mut s = Session::new();
let order = two_rows(&mut s);
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
for want in &order[1..] {
tab(&mut s, false);
assert_eq!(editing(&s), (*want, true), "on to {} with all of it selected", chars(&s, *want));
}
assert!(order.iter().all(|t| !chars(&s, *t).contains('\t')), "no tab typed");
}
#[test]
fn shift_tab_goes_back() {
let mut s = Session::new();
let order = two_rows(&mut s);
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 0}));
for want in order[..4].iter().rev() {
tab(&mut s, true);
assert_eq!(editing(&s).0, *want, "back to {}", chars(&s, *want));
}
}
#[test]
fn tab_on_the_last_text_keeps_editing_it() {
let mut s = Session::new();
let order = two_rows(&mut s);
let undo = s.ds().unwrap().history.undo.len();
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 1}));
tab(&mut s, false);
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
assert_eq!((te.id, te.caret, te.anchor), (order[4], 1, 1), "the last one: nothing moves");
assert_eq!(chars(&s, order[4]), "E", "and nothing is typed");
// Shift+Tab on the first one does nothing either.
ex(&mut s, "text.edit.end", json!({}));
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
tab(&mut s, true);
assert_eq!(editing(&s).0, order[0]);
ex(&mut s, "text.edit.end", json!({}));
assert_eq!(s.ds().unwrap().history.undo.len(), undo, "no undo step for it");
}
#[test]
fn hidden_and_locked_text_is_skipped() {
let mut s = Session::new();
let f = frame(&mut s, 0.0, 0.0);
let first = text(&mut s, "First", 10.0, 10.0, f);
let hidden = text(&mut s, "Hidden", 10.0, 50.0, f);
ex(&mut s, "node.set", json!({"id": hidden, "props": {"visible": false}}));
let locked = text(&mut s, "Locked", 10.0, 90.0, f);
ex(&mut s, "node.set", json!({"id": locked, "props": {"locked": true}}));
let inner = id_of(&ex(&mut s, "frame.create", json!({"x": 10, "y": 130, "width": 200, "height": 60, "parent": f}))["id"]).unwrap();
text(&mut s, "In a locked frame", 0.0, 0.0, inner);
ex(&mut s, "node.set", json!({"id": inner, "props": {"locked": true}}));
let last = text(&mut s, "Last", 10.0, 220.0, f);
ex(&mut s, "text.edit.begin", json!({"id": first, "caret": 0}));
tab(&mut s, false);
assert_eq!(editing(&s).0, last, "past the hidden text, the locked one and the text in a locked frame");
tab(&mut s, true);
assert_eq!(editing(&s).0, first);
}
+3 -3
View File
@@ -221,11 +221,11 @@ fn list_keys_at_list_items() {
2,
"Tab",
false,
"a\n\tb",
"a\nb",
vec![(B, 0), (P, 1)],
"a plain paragraph at a level isn't an item: Tab types a tab",
"a plain paragraph at a level isn't an item: Tab leaves the list alone (and moves to the next text, none here)",
),
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb\t", vec![(P, 0), (P, 0)], "outside a list Tab types a tab"),
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb", vec![(P, 0), (P, 0)], "outside a list Tab types no tab"),
("a", vec![(B, 8)], 1, "Tab", false, "a", vec![(B, 8)], "silent: nesting stops at 8 levels"),
];
for (chars, before, caret, k, shift, after, want, why) in cases {
+194 -20
View File
@@ -360,43 +360,134 @@ fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
}
#[test]
fn command_resize_leaves_fills_when_text_or_auto_layout_recomputes_the_box() {
for case in ["text", "child", "frame"] {
fn command_resize_leaves_a_texts_fills() {
let mut s = session();
let image = image_layer(&mut s);
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
let layer = id(&ex(
&mut s,
"text.create",
json!({"text": "hello world hello world hello world", "props": {
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
}}),
));
ex(&mut s, "select.set", json!({"ids": [layer]}));
let doc = s.doc().unwrap();
let world = doc.world_transform(layer);
let n = doc.node(layer).unwrap();
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(10.0, n.height / 2.0));
drag(&mut s, from, to, CMD);
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "a text reflows: keep the existing resize behaviour");
}
fn image_units_per_layer_unit(s: &Session, layer: NodeId) -> (f64, f64, f64, f64) {
use figcraft_doc::color::PaintKind;
let doc = s.doc().unwrap();
let n = doc.node(layer).unwrap();
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
let data = doc.images.get(&img.image).unwrap();
let c = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
(c[0] / n.width, c[3] / n.height, c[4], c[5])
}
#[test]
fn command_resize_crops_in_auto_layout_against_the_box_layout_leaves() {
use figcraft_doc::color::{ImageScaleMode, PaintKind};
for case in ["child", "child with a minimum width", "auto layout frame"] {
let mut s = session();
let image = image_layer(&mut s);
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
let layer = match case {
"text" => id(&ex(
&mut s,
"text.create",
json!({"text": "hello world hello world hello world", "props": {
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
}}),
)),
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
let (layer, to_x, width) = match case {
"auto layout frame" => {
set(&mut s, &[frame], json!({"fills": fills}));
(frame, 10.0, 40.0)
}
_ => {
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
if case == "child" {
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
set(&mut s, &[image], json!({"minWidth": 150}));
image
(image, 150.0, 150.0)
} else {
set(&mut s, &[frame], json!({"fills": fills}));
frame
set(&mut s, &[image], json!({"minWidth": 150}));
(image, 10.0, 150.0)
}
}
};
ex(&mut s, "select.set", json!({"ids": [layer]}));
let before = image_units_per_layer_unit(&s, layer);
let doc = s.doc().unwrap();
let world = doc.world_transform(layer);
let n = doc.node(layer).unwrap();
let from = world * Point::new(n.width, n.height / 2.0);
let to = world * Point::new(10.0, n.height / 2.0);
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(to_x, n.height / 2.0));
drag(&mut s, from, to, CMD);
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "{case}: keep the existing resize behaviour");
let n = s.doc().unwrap().node(layer).unwrap().clone();
assert!(near(n.width, width), "{case}: {} wide, as auto layout leaves it", n.width);
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
assert_eq!(img.scale_mode, ImageScaleMode::Crop, "{case}: cropped");
let after = image_units_per_layer_unit(&s, layer);
assert!(near(after.0, before.0) && near(after.1, before.1), "{case}: the image keeps its scale, not stretched: {before:?} -> {after:?}");
assert!(near(after.2, before.2) && near(after.3, before.3), "{case}: its left edge stays where it was in the layer: {before:?} -> {after:?}");
}
}
/// A minimum width can give a layer back the width its left side was dragged in by: the crop then
/// slides back along the image instead of running past its right edge.
#[test]
fn command_crop_slides_back_onto_the_image_when_layout_widens_the_layer() {
use figcraft_doc::color::{ImagePaint, PaintKind};
let mut s = session();
let image = image_layer(&mut s);
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
set(&mut s, &[image], json!({"minWidth": 150}));
ex(&mut s, "select.set", json!({"ids": [image]}));
let before = image_units_per_layer_unit(&s, image);
let world = s.doc().unwrap().world_transform(image);
drag(&mut s, world * Point::new(0.0, 50.0), world * Point::new(190.0, 50.0), CMD);
let doc = s.doc().unwrap();
let n = doc.node(image).unwrap();
assert!(near(n.width, 150.0), "{} wide, as the minimum width leaves it", n.width);
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
let data = doc.images.get(&img.image).unwrap();
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
let (x0, _, x1, _) = ImagePaint::crop_rect(crop);
assert!(x0 <= 1e-9 && x1 >= 1.0 - 1e-9, "the image covers the layer: {x0}..{x1}");
let after = image_units_per_layer_unit(&s, image);
assert!(near(after.0, before.0) && near(after.1, before.1), "the image keeps its scale: {before:?} -> {after:?}");
}
/// Where the image's edge stops a crop, Shift still keeps the ratio (both axes stop together) and
/// Alt still keeps the box centred (both sides stop together).
#[test]
fn command_crop_stopped_by_the_image_keeps_the_ratio_with_shift_and_the_centre_with_alt() {
let mut s = session();
let layer = image_layer(&mut s);
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(200.0, 100.0), Point::new(150.0, 80.0), CMD);
assert_eq!(size(&s, layer), (150.0, 80.0));
drag(&mut s, Point::new(150.0, 80.0), Point::new(240.0, 128.0), Mods { shift: true, alt: false, cmd: true });
assert!(
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 187.5, 100.0)),
"the bottom stops at the image, the right side with it: {:?}",
bounds(&s, layer)
);
let mut s = session();
let layer = image_layer(&mut s);
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(0.0, 50.0), Point::new(20.0, 50.0), CMD);
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
assert!(near_rect(bounds(&s, layer), Rect::new(20.0, 0.0, 150.0, 100.0)), "{:?}", bounds(&s, layer));
drag(&mut s, Point::new(150.0, 50.0), Point::new(190.0, 50.0), Mods { shift: false, alt: true, cmd: true });
assert!(
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 170.0, 100.0)),
"the left side stops at the image, the right side as far: {:?}",
bounds(&s, layer)
);
}
/// A resize is an explicit edit of the size: a size bound to a variable lets go of it (#809), so
/// Cmd/Ctrl crops a bound layer's image as any other's; other bindings stay.
#[test]
@@ -913,6 +1004,73 @@ fn snapping_to_layers_wins_over_the_pixel_grid() {
assert_eq!(size(&s, b), (100.0, 151.0));
}
#[test]
fn frames_land_on_whole_pixels_whatever_they_snap_to() {
// Figma's help: frames, sections and components "always snap to the pixel grid, even if Snap
// to pixel grid is disabled". Other layers follow the setting.
let frame = |s: &mut Session, x: f64, y: f64| id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 100, "height": 100})));
let whole = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.fract() == 0.0);
let mut s = Session::new();
// A neighbour off the pixel grid, as a scaled or imported layer leaves one: its right edge at
// 100.4.
rect(&mut s, 0.4, 0.0, 100.0, 100.0, None);
let f = frame(&mut s, 300.0, 300.0);
let r = rect(&mut s, 300.0, 600.0, 100.0, 100.0, None);
// Moved next to it, a rectangle snaps onto 100.4 and the frame to the whole pixel there.
ex(&mut s, "select.set", json!({"ids": [r]}));
drag(&mut s, Point::new(350.0, 650.0), Point::new(151.5, 650.0), Mods::default());
assert!(near(bounds(&s, r).x0, 100.4), "{:?}", bounds(&s, r));
ex(&mut s, "select.set", json!({"ids": [f]}));
drag(&mut s, Point::new(350.0, 350.0), Point::new(151.5, 350.0), Mods::default());
assert_eq!(bounds(&s, f).origin(), Point::new(100.0, 300.0), "moved by the snap, onto the whole pixel");
// With Snap to pixel grid off, frames still move, resize and draw on whole pixels.
ex(&mut s, "view.snapPixel", json!({"on": false}));
ex(&mut s, "view.snapObjects", json!({"on": false}));
drag(&mut s, Point::new(150.0, 350.0), Point::new(160.3, 360.6), Mods::default());
assert_eq!(bounds(&s, f).origin(), Point::new(110.0, 311.0), "moved");
drag(&mut s, Point::new(210.0, 411.0), Point::new(250.4, 450.6), Mods::default());
assert_eq!(size(&s, f), (140.0, 140.0), "resized");
ex(&mut s, "tool.set", json!({"tool": "frame"}));
drag(&mut s, Point::new(500.3, 500.6), Point::new(560.6, 540.2), Mods::default());
let drawn = s.selection()[0];
assert!(whole(bounds(&s, drawn)), "drawn: {:?}", bounds(&s, drawn));
// A frame already off the pixel grid lands on it once moved.
ex(&mut s, "tool.set", json!({"tool": "move"}));
let off = frame(&mut s, 800.4, 800.7);
ex(&mut s, "select.set", json!({"ids": [off]}));
drag(&mut s, Point::new(850.0, 850.0), Point::new(860.0, 850.0), Mods::default());
assert!(whole(bounds(&s, off)), "{:?}", bounds(&s, off));
// A rectangle follows the pointer.
ex(&mut s, "select.set", json!({"ids": [r]}));
drag(&mut s, Point::new(150.0, 650.0), Point::new(160.3, 650.0), Mods::default());
assert!(near(bounds(&s, r).x0, 110.7), "{:?}", bounds(&s, r));
}
#[test]
fn frames_resized_together_each_land_on_whole_pixels() {
let mut s = session();
let frame = |s: &mut Session, x: f64| id(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 100, "height": 100})));
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
ex(&mut s, "select.set", json!({"ids": [a, b]}));
// 300 wide to 400: a third more, so each frame alone would be 133.33 wide.
drag(&mut s, Point::new(300.0, 100.0), Point::new(400.0, 100.0), Mods::default());
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 133.0, 100.0));
assert_eq!(bounds(&s, b), Rect::new(267.0, 0.0, 400.0, 100.0));
}
#[test]
fn a_frame_dropped_into_a_frame_off_the_pixel_grid_lands_on_its_whole_pixels() {
let mut s = session();
let target = id(&ex(&mut s, "frame.create", json!({"x": 300.5, "y": 0.5, "width": 300, "height": 300})));
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50})));
ex(&mut s, "select.set", json!({"ids": [f]}));
drag(&mut s, Point::new(25.0, 25.0), Point::new(425.0, 125.0), Mods::default());
let n = s.doc().unwrap().node(f).unwrap().clone();
assert_eq!(n.parent, Some(target));
let [.., x, y] = n.transform.as_coeffs();
assert_eq!((x.fract(), y.fract()), (0.0, 0.0), "at {x}, {y} in the frame");
}
#[test]
fn corner_cursors_stay_diagonal_whatever_the_proportions() {
let mut s = session();
@@ -974,3 +1132,19 @@ fn the_transform_box_and_its_handles() {
// At a larger zoom the same layer is big enough on screen for its handles inside it.
assert_eq!(handle_at(s.doc().unwrap(), &[tiny], Point::new(320.2, 10.2), 20.0), Some(Handle::Corner(0)));
}
#[test]
fn command_crop_changes_a_locked_ratio_and_stops_at_the_images_edges() {
let mut s = session();
let layer = image_layer(&mut s);
set(&mut s, &[layer], json!({"constrainProportions": true}));
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
assert_eq!(size(&s, layer), (150.0, 100.0), "a side changes the ratio, lock or not");
drag(&mut s, Point::new(150.0, 50.0), Point::new(260.0, 50.0), CMD);
assert_eq!(size(&s, layer), (200.0, 100.0), "the side stops at the image's edge");
drag(&mut s, Point::new(100.0, 0.0), Point::new(100.0, -40.0), CMD);
assert!(near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 200.0, 100.0)), "the top stops at the image's top: {:?}", bounds(&s, layer));
drag(&mut s, Point::new(200.0, 50.0), Point::new(100.0, 50.0), Mods { shift: true, alt: false, cmd: true });
assert_eq!(size(&s, layer), (100.0, 50.0), "Shift keeps the ratio");
}
@@ -700,6 +700,31 @@ fn deleting_points_vs_delete_and_heal() {
assert_eq!((n.vertices.len(), n.segments.len()), (4, 3), "deleting a segment leaves its points");
}
#[test]
fn deleting_a_point_selects_the_next_one_on_its_path() {
let mut s = Session::new();
let id = id_of(&ex(&mut s, "vector.create", json!({"path": "M0 0 L100 0 L200 0 L300 0"}))["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
let selected = |s: &Session| editing(s).unwrap().vertices.iter().map(|v| page_pos(s, id, *v)).collect::<Vec<_>>();
let second = point_at(&s, id, (100.0, 0.0));
ex(&mut s, "vector.edit.select", json!({"vertices": [second]}));
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(200.0, 0.0)], "the point after the deleted one");
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(300.0, 0.0)], "so Delete again walks along the path");
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(0.0, 0.0)], "past the path's end, the point before it");
let mut s = Session::new();
let id = square(&mut s, true);
let tr = point_at(&s, id, (100.0, 0.0));
ex(&mut s, "vector.edit.select", json!({"vertices": [tr]}));
key(&mut s, "Delete", false);
let after = selected(&s);
assert_eq!(after.len(), 1, "one point selected after a plain Delete: {after:?}");
assert!([Point::new(100.0, 100.0), Point::new(0.0, 0.0)].contains(&after[0]), "a neighbour of the deleted corner: {after:?}");
}
#[test]
fn handles_follow_their_mirroring() {
// A smooth middle point at (100, 0) on an open path; one handle is dragged to (+30, 10).
+53
View File
@@ -102,6 +102,8 @@ pub const TOOL_NAMES: &[&str] = &[
"get_node",
"design_context",
"export_assets",
"component_mappings",
"sync_mappings",
"select",
"export",
"screenshot",
@@ -126,6 +128,8 @@ const DOCUMENT_TOOLS: &[&str] = &[
"get_node",
"design_context",
"export_assets",
"component_mappings",
"sync_mappings",
"select",
"export",
"screenshot",
@@ -286,6 +290,33 @@ fn tools() -> Vec<Value> {
),
false,
),
tool(
"component_mappings",
"Component mappings",
"Which code component each design component is: its import, code name, source file, a ready snippet, its properties and variants, and which design values need translating. Check this before writing a component: reuse a mapped one, never recreate it. `unmapped` lists those with no code component yet.",
obj(
json!({
"ids": ids_schema("Layers: the components they are, use or hold (default every component in the file)"),
"unmapped": boolean("Only components without a mapping"),
"root": string("The code repository, to check each link's source file is there (default where this server runs)")
}),
&[],
),
true,
),
tool(
"sync_mappings",
"Sync mappings with a repository",
"Apply a code repository's figcraft.connect.json to the open design (`import`, one undo step), or write the design's mappings to it (`export`, keeping its other keys and the links of components this design doesn't have). Run `import` first when component_mappings shows less than the repository should have.",
obj(
json!({
"direction": {"type": "string", "enum": ["import", "export"], "description": "import: file to design. export: design to file"},
"path": string("The file (default figcraft.connect.json where this server runs)")
}),
&["direction"],
),
false,
),
tool(
"select",
"Select layers",
@@ -490,6 +521,26 @@ fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResu
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
}
/// `codeConnect.list`, checking source files against `root`, else where this server runs.
fn component_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
let mut params = a.clone();
let root = std::path::absolute(s_arg(a, "root")?.unwrap_or(".")).map_err(|e| format!("root: {e}"))?;
params.insert("root".into(), json!(root.to_string_lossy()));
exec(b, "codeConnect.list", Value::Object(params)).map(|v| ToolResult::json(&v))
}
/// `codeConnect.import` or `.export` with a code repository's connect file, made absolute here: an
/// attached app runs in another folder.
fn sync_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
let command = match s_arg(a, "direction")? {
Some("import") => "codeConnect.import",
Some("export") => "codeConnect.export",
_ => return Err("`direction`: import or export".into()),
};
let path = std::path::absolute(s_arg(a, "path")?.unwrap_or("figcraft.connect.json")).map_err(|e| format!("path: {e}"))?;
exec(b, command, json!({"path": path.to_string_lossy()})).map(|v| ToolResult::json(&v))
}
fn wait_for_changes(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
b.call("events.poll", Value::Object(a.clone())).map(|v| ToolResult::json(&v))
}
@@ -637,6 +688,8 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
"get_node" => get_node(b, &a),
"design_context" => design_context(b, &a),
"export_assets" => export_assets(b, &a),
"component_mappings" => component_mappings(b, &a),
"sync_mappings" => sync_mappings(b, &a),
"select" => select(b, &a),
"export" => export(b, &a),
"screenshot" => screenshot(b, &a),
+37
View File
@@ -0,0 +1,37 @@
//! `component_mappings` and `sync_mappings` against a code repository's connect file.
use serde_json::{Value, json};
use crate::common::Client;
fn repo(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("figcraft-mcp-connect-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::canonicalize(dir).unwrap()
}
#[test]
fn mappings_travel_through_a_repositorys_file() {
let dir = repo("travel");
let mut c = Client::new();
let frame = c.create(json!({"type": "frame", "name": "Tag", "width": 80, "height": 24}));
let main = c.run("component.create", json!({"ids": [frame]}))["id"].clone();
let file = dir.join("figcraft.connect.json");
std::fs::write(&file, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Tag","language":"react","importPath":"@/ui/tag","name":"Tag","template":"<Tag />","source":"src/tag.tsx"}]}"#).unwrap();
let before = c.ok("component_mappings", json!({"unmapped": true, "root": dir}));
assert_eq!(before["unmapped"], 1);
c.ok("sync_mappings", json!({"direction": "import", "path": file}));
let after = c.ok("component_mappings", json!({"ids": [main], "root": dir}));
let link = &after["components"][0]["links"][0];
assert_eq!(link["import"], r#"import { Tag } from "@/ui/tag";"#);
assert_eq!(link["sourceFound"], false, "src/tag.tsx isn't there yet");
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/tag.tsx"), "").unwrap();
assert_eq!(c.ok("component_mappings", json!({"ids": [main], "root": dir}))["components"][0]["links"][0]["sourceFound"], true);
c.ok("sync_mappings", json!({"direction": "export", "path": file}));
let written: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
assert_eq!(written["project"]["name"], "shop", "keys the export doesn't own stay");
assert_eq!(written["links"][0]["source"], "src/tag.tsx");
assert!(c.err("sync_mappings", json!({"direction": "sideways"})).contains("import or export"));
}
+2
View File
@@ -8,6 +8,8 @@ mod agent_tasks;
mod attached;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::disallowed_methods)]
mod automation_roots;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod code_connect;
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+2
View File
@@ -1515,6 +1515,8 @@ fn public_family(family: &str) -> Option<String> {
match hidden {
"SF Compact" | "SF Compact Rounded" => Some(hidden.to_string()),
"SF NS Rounded" => Some("SF Pro Rounded".into()),
// Apple's serif, also published as a download; macOS installs it as `.New York`.
"New York" => Some(hidden.to_string()),
_ => None,
}
}
+21
View File
@@ -461,10 +461,31 @@ fn hidden_apple_families_take_public_names() {
assert_eq!(public_family(".SF Compact").as_deref(), Some("SF Compact"));
assert_eq!(public_family(".SF Compact Rounded").as_deref(), Some("SF Compact Rounded"));
assert_eq!(public_family(".SF NS Rounded").as_deref(), Some("SF Pro Rounded"));
assert_eq!(public_family(".New York").as_deref(), Some("New York"));
assert_eq!(public_family(".Keyboard"), None);
assert_eq!(public_family("Inter").as_deref(), Some("Inter"));
}
#[test]
fn new_york_is_found_under_its_public_name() {
// macOS installs New York as `.New York` (a dot keeps it out of font menus): it used to be
// skipped, so "New York" was a missing font. Only on a Mac that has the files.
let dir = std::path::Path::new("/System/Library/Fonts");
if !dir.join("NewYork.ttf").is_file() || !dir.join("NewYorkItalic.ttf").is_file() {
return;
}
let mut pending = BTreeMap::new();
scan_dir(dir, 0, &mut pending);
let mut db = FontDb { pending, ..FontDb::default() };
let families = db.families();
assert!(families.iter().any(|f| f == "New York"), "{families:?}");
assert!(families.iter().all(|f| !f.starts_with('.')), "dot names stay out of the list: {families:?}");
for (style, italic) in [("Regular", false), ("Italic", true)] {
let face = db.find("New York", style).expect("New York loads");
assert_eq!((face.family.as_str(), face.italic), ("New York", italic), "{style}");
}
}
/// A named style keeps its own optical size whatever the text size (existing documents render as
/// before); a custom `opsz` value (what a `.sketch` import sets) wins. Needs a variable font with an
/// optical size axis and named instances: macOS's or Windows' system font.
+7
View File
@@ -102,6 +102,7 @@ name = "English"
"All comments" = "All comments"
"All components" = "All components"
"All fonts" = "All fonts"
"All libraries" = "All libraries"
"All objects" = "All objects"
"All supported properties" = "All supported properties"
"All the fonts this file uses are installed" = "All the fonts this file uses are installed"
@@ -392,6 +393,9 @@ name = "English"
"Ctrl+arrows" = "Ctrl+arrows"
"Ctrl+click" = "Ctrl+click"
"Ctrl+click a padding field" = "Ctrl+click a padding field"
"In code" = "In code"
"Source file" = "Source file"
"Variant value" = "Variant value"
"⌘ click a padding field" = "⌘ click a padding field"
"Ctrl+scroll" = "Ctrl+scroll"
"Current name" = "Current name"
@@ -1469,6 +1473,8 @@ name = "English"
"Small caps" = "Small caps"
"Smart animate" = "Smart animate"
"Snap to pixel grid" = "Snap to pixel grid"
"Snap to pixel grid off" = "Snap to pixel grid off"
"Snap to pixel grid on" = "Snap to pixel grid on"
"Social and slides" = "Social and slides"
"Social media" = "Social media"
"Social post sizes" = "Social post sizes"
@@ -1759,6 +1765,7 @@ name = "English"
"What it's for" = "What it's for"
"What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on." = "What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on."
"When marked ready" = "When marked ready"
"While editing text: next or previous text layer" = "While editing text: next or previous text layer"
"While hovering" = "While hovering"
"While pressing" = "While pressing"
"White" = "White"
File diff suppressed because it is too large. Load diff
+3
View File
@@ -99,6 +99,7 @@ name = "Русский"
"All comments" = "Все комментарии"
"All components" = "Все компоненты"
"All fonts" = "Все шрифты"
"All libraries" = "Все библиотеки"
"All objects" = "Все объекты"
"All supported properties" = "Все поддерживаемые свойства"
"All the fonts this file uses are installed" = "Все шрифты, которые использует этот файл, установлены"
@@ -1346,6 +1347,8 @@ name = "Русский"
"Small caps" = "Капитель"
"Smart animate" = "Smart animate"
"Snap to pixel grid" = "Привязка к пиксельной сетке"
"Snap to pixel grid off" = "Привязка к пиксельной сетке выключена"
"Snap to pixel grid on" = "Привязка к пиксельной сетке включена"
"Social and slides" = "Соцсети и слайды"
"Social media" = "Соцсети"
"Social post sizes" = "Размеры публикаций для соцсетей"
+15
View File
@@ -22,9 +22,23 @@ impl FigApp {
// `file.open`/`file.close`). Record that presentation before returning, so an in-flight
// screenshot admitted on the old file cannot accept pixels from the new one.
self.observe_presentation();
if let Ok(v) = &r {
self.note_snapping(id, v);
}
r.map_err(|e| self.failed(id, &e)).ok()
}
/// Snap to pixel grid turned on or off says which at the bottom, as in Figma: its shortcut
/// (Shift+Cmd/Ctrl+') changes nothing on the canvas until the next drag.
fn note_snapping(&mut self, id: &str, result: &Value) {
let msg = match (id, result.get("on").and_then(Value::as_bool)) {
("view.snapPixel", Some(true)) => crate::i18n::tr("Snap to pixel grid on"),
("view.snapPixel", Some(false)) => crate::i18n::tr("Snap to pixel grid off"),
_ => return,
};
self.toast(msg);
}
/// A programmatic command that changed the engine clipboard never wrote the system clipboard:
/// forget the old system mirror so a later user paste does not trust it as our own copy.
/// `before` is the layers generation captured before the command ran.
@@ -321,6 +335,7 @@ impl FigApp {
self.autosave_tick(ctx, now);
self.auto_save_tick(ctx, now);
updates_ui::tick(self, ctx);
crate::assets_panel::refresh_libraries(self, ctx);
self.logic_ticked = true;
}
}
+34 -6
View File
@@ -21,7 +21,7 @@ mod drag_sprite;
mod input;
pub(crate) use input::release_fields_for_press;
mod outline;
mod overlays;
pub(crate) mod overlays;
mod render;
mod rulers;
@@ -53,6 +53,7 @@ pub mod widget_bar;
pub struct CanvasState {
pub rect: Rect,
texture: Option<egui::TextureHandle>,
tex_pixels: Option<Arc<egui::ColorImage>>,
tex_view: Option<figcraft_render::View>,
/// The file ([`figcraft_engine::DocState::uid`]) and page the texture shows: it is drawn only
/// on them.
@@ -146,6 +147,7 @@ impl Default for CanvasState {
Self {
rect: Rect::NOTHING,
texture: None,
tex_pixels: None,
tex_view: None,
tex_of: None,
tex_coarse: false,
@@ -196,6 +198,7 @@ impl CanvasState {
fn switch_texture(&mut self, shown: Option<(u64, NodeId)>, open: impl Fn(u64) -> bool) {
if shown.is_some() && self.tex_of != shown {
let back = self.kept.iter().position(|k| Some(k.of) == shown).map(|i| self.kept.remove(i));
self.tex_pixels = None;
let (texture, view, of) = (self.texture.take(), self.tex_view.take(), self.tex_of.take());
// An image without the dragged layers isn't the page's complete one: not kept.
if let (Some(texture), Some(view), Some(of), false, false) = (texture, view, of, self.tex_coarse, self.tex_skipped) {
@@ -216,6 +219,23 @@ impl CanvasState {
pub(crate) fn drop_closed(&mut self, open: impl Fn(u64) -> bool) {
self.kept.retain(|k| open(k.of.0));
}
pub(crate) fn pixel_under(&self, p: Point, of: Option<(u64, NodeId)>, page: Color32) -> Option<Color32> {
let (image, v) = (self.tex_pixels.as_ref()?, self.tex_view.as_ref()?);
if of.is_none() || self.tex_of != of {
return None;
}
let x = ((p.x - v.origin.0) * v.scale).floor();
let y = ((p.y - v.origin.1) * v.scale).floor();
let [w, h] = image.size;
if !(x >= 0.0 && y >= 0.0 && x < w as f64 && y < h as f64) {
return None;
}
let c = *image.pixels.get(y as usize * w + x as usize)?;
let under = 255 - u16::from(c.a());
let over = |a: u8, b: u8| (u16::from(a) + (u16::from(b) * under + 127) / 255).min(255) as u8;
Some(Color32::from_rgb(over(c.r(), page.r()), over(c.g(), page.g()), over(c.b(), page.b())))
}
}
/// What the canvas shows while an IME composition is in progress: the document with the
@@ -280,8 +300,9 @@ fn pointer_event(app: &FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers
sy: f64::from(pos.y),
shift: m.shift,
alt: m.alt,
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does.
cmd: m.command || app.ui.crop.is_some(),
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does (not while its points
// are being edited, where Cmd/Ctrl bends a segment).
cmd: m.command || (app.ui.crop.is_some() && app.session.ds().is_ok_and(|d| d.vector_edit.is_none())),
ctrl: m.ctrl,
zoom,
pressure: app.canvas.pressure,
@@ -326,7 +347,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
// Otherwise keep the centre.
ds.view.vw = f64::from(rect.width());
ds.view.vh = f64::from(rect.height());
if first {
if first && ds.fit_when_sized {
ds.zoom_to_fit();
}
}
@@ -387,10 +408,12 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
} else {
egui::TextureOptions::LINEAR
};
let pixels = Arc::new(done.image);
match &mut app.canvas.texture {
Some(t) => t.set(done.image, filter),
None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)),
Some(t) => t.set(Arc::clone(&pixels), filter),
None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", Arc::clone(&pixels), filter)),
}
app.canvas.tex_pixels = Some(pixels);
let done_at = done.at;
let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0);
if done.coarse {
@@ -484,6 +507,11 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
let panning = app.canvas.space_pan || app.canvas.middle_pan.is_some();
let shown = crate::cursors::on_canvas(panning, ctx.input(|i| i.pointer.any_down()), app.canvas.zoom_tool, app.session.tool.overlay.cursor);
shown.show(&ctx, at);
if shown == crate::cursors::Shown::Drawn(crate::cursors::Glyph::Eyedropper)
&& let Some(c) = app.canvas.pixel_under(app.to_page(at), app.session.ds().ok().map(|ds| (ds.uid, ds.page)), bg)
{
crate::cursors::sampled_swatch(&ctx, at, c);
}
app.canvas.cursor = Some(shown);
}
}
+11
View File
@@ -130,6 +130,17 @@ impl Shown {
}
}
pub fn sampled_swatch(ctx: &egui::Context, at: Pos2, color: Color32) {
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("canvas_cursor_swatch")));
let centre = at + vec2(SWATCH_OFFSET, SWATCH_OFFSET);
painter.circle_filled(centre, SWATCH_RADIUS + 2.0, INK);
painter.circle_filled(centre, SWATCH_RADIUS + 1.0, EDGE);
painter.circle_filled(centre, SWATCH_RADIUS, color);
}
pub(crate) const SWATCH_OFFSET: f32 = 16.0;
pub(crate) const SWATCH_RADIUS: f32 = 8.0;
/// Dark lines over a light edge: readable on any page and artwork.
pub(crate) const INK: Color32 = Color32::from_rgb(0x1E, 0x1E, 0x1E);
const EDGE: Color32 = Color32::WHITE;
+6 -5
View File
@@ -529,9 +529,10 @@ fn draw_crop(app: &FigApp, painter: &egui::Painter, id: NodeId, img: &ImagePaint
/// Draw the handles.
pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
// Crop mode ends when a colour picker opens, or when its layer leaves the selection or its fill
// is no longer a Crop image (an undo).
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none()) {
// Crop mode ends when a colour picker opens, when its layer leaves the selection or its fill
// is no longer a Crop image (an undo), or when the layer's points are being edited.
let editing_points = app.session.ds().is_ok_and(|d| d.vector_edit.is_some());
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none() || editing_points) {
app.ui.crop = None;
}
let app = &*app;
@@ -821,13 +822,13 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) {
let (dx, dy) = (u.0 - start.0, u.1 - start.1);
(x0 + dx, y0 + dy, x1 + dx, y1 + dy)
} else {
// Scale about the opposite corner, keeping the image's aspect ratio unless Shift.
// Scale about the opposite corner, keeping the image's aspect ratio with Shift.
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)];
let (ax, ay) = corners.get((*which + 2) % 4).copied().unwrap_or((x0, y0));
let (cx, cy) = corners.get(*which).copied().unwrap_or((x1, y1));
let (ow, oh) = (cx - ax, cy - ay);
let (mut nw, mut nh) = (u.0 - ax, u.1 - ay);
if !modifiers.shift {
if modifiers.shift {
// Node aspect matters: the unit box is not square in pixels.
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
let k = ((nw * n.width).abs() / (ow * n.width).abs().max(1e-9)).max((nh * n.height).abs() / (oh * n.height).abs().max(1e-9));
+15
View File
@@ -321,6 +321,9 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
open_context_menu(app, pos, mods.command);
return true;
}
if crop_mode_multi_click(app, resp, pos, &mods) {
return true;
}
// A third quick click is counted as a triple, not a double (a click elsewhere in between still
// leaves its time in the sequence): it means the same here — edit, enter, open — unless a
// vector or text is being edited, where a triple already has its own meaning. A triple on
@@ -432,6 +435,18 @@ fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers)
}
}
/// A double- or triple-click in crop mode stays in crop mode (it would edit the points), and is
/// taken here. Its last press may have begun a resize on a side of the layer: its release ends that.
fn crop_mode_multi_click(app: &mut FigApp, resp: &egui::Response, pos: Pos2, mods: &egui::Modifiers) -> bool {
if app.ui.crop.is_none() || !(resp.double_clicked() || resp.triple_clicked()) {
return false;
}
if std::mem::take(&mut app.canvas.dragging) {
send(app, PointerKind::Up, pos, mods);
}
true
}
fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) {
let ev = pointer_event(app, kind, pos, m);
// A hover where nothing changed since the last one finds what that one found (the state is
+16 -1
View File
@@ -170,14 +170,29 @@ pub(super) fn outline_path(doc: &Document, n: &figcraft_doc::Node) -> Option<fig
figcraft_render::node_outline(doc, n).map(|(p, _)| p)
}
/// How far, in screen points, the flattened outline of a path with `curves` curved segments may
/// stray from it. Up to [`SMOOTH_CURVES`] curves it is 0.02, so the outline bends smoothly. Above
/// that it grows with the count, up to 0.5 at 25 times as many. The outline is flattened again each
/// frame the view moves or the layer is hovered, and egui tessellates every point each frame, so a
/// heavy vector keeps about as many points as at 0.5.
pub(super) fn outline_tolerance(curves: usize) -> f64 {
(0.02 * curves as f64 / SMOOTH_CURVES as f64).clamp(0.02, 0.5)
}
/// The most curved segments an outline flattens at the smooth 0.02 pt ([`outline_tolerance`]).
pub(super) const SMOOTH_CURVES: usize = 200;
/// [`outline_path`] on screen, flattened into polylines.
fn outline_shape(app: &FigApp, doc: &Document, id: NodeId) -> Option<Vec<Vec<Pos2>>> {
use figcraft_geom::kurbo::PathEl;
let n = doc.node(id)?;
let path = outline_path(doc, n)?;
let w = doc.world_transform(id);
let mut out = Vec::new();
let mut cur: Vec<Pos2> = Vec::new();
figcraft_geom::kurbo::flatten(path.iter(), 0.5 / app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0), |el| {
let curves = path.elements().iter().filter(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).count();
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0);
figcraft_geom::kurbo::flatten(path.iter(), outline_tolerance(curves) / zoom, |el| {
use figcraft_geom::kurbo::PathEl::*;
match el {
MoveTo(p) => {
@@ -46,3 +46,82 @@ fn square_corners_keep_the_box() {
let id = layer(&mut s, "rectangle", json!({"stroke": "#000000", "strokeWeight": 4, "strokeAlign": "outside"}));
assert!(path_of(s.doc().unwrap(), id).is_none());
}
/// How far, in screen points, layer `id`'s outline strays from its path: the largest distance from
/// the middle of one of its straight pieces to the path.
fn largest_stray(u: &crate::layers_drag_tests::Ui, id: NodeId) -> f64 {
use figcraft_geom::kurbo::ParamCurveNearest;
let doc = u.app.session.doc().unwrap().clone();
let path = path_of(&doc, id).unwrap();
let to_local = doc.world_transform(id).inverse();
let zoom = u.app.session.ds().unwrap().view.zoom;
let mut largest: f64 = 0.0;
for shape in super::outline::outline_shapes(&u.app, &doc, id, egui::Stroke::new(1.0, egui::Color32::WHITE)) {
let egui::Shape::Path(line) = shape else { panic!("a polyline outline") };
for piece in line.points.windows(2) {
let middle = to_local * u.app.to_page(piece[0] + (piece[1] - piece[0]) * 0.5);
let d = path.segments().map(|seg| seg.nearest(middle, 1e-9).distance_sq).fold(f64::MAX, f64::min).sqrt();
largest = largest.max(d * zoom);
}
}
largest
}
/// The outline is flattened to 0.02 pt on screen at any zoom, so its straight pieces don't show:
/// each stays well within 0.1 pt of the curve (0.5 pt left straight pieces visible on an ellipse).
#[test]
fn a_selected_ellipses_outline_stays_on_the_curve_at_any_zoom() {
let mut s = Session::new();
let ellipse =
NodeId(s.execute("node.create", &json!({"type": "ellipse", "x": 0, "y": 0, "width": 65, "height": 50})).unwrap()["id"].as_u64().unwrap());
let mut u = crate::layers_drag_tests::Ui::new(s);
for zoom in [1.0, 3.5, 16.0] {
u.app.session.execute("view.set", &json!({"zoom": zoom, "cx": 30, "cy": 25})).unwrap();
u.frame(vec![]);
let stray = largest_stray(&u, ellipse);
assert!(stray < 0.1, "at {zoom}x the outline strays {stray:.3} pt from the curve");
}
}
/// A vector of `rows` closed bands, each `waves` cubic waves 10 pt wide along its top.
fn waves(rows: usize, waves: usize) -> String {
let mut d = String::new();
for r in 0..rows {
let y = r as f64 * 10.0;
d += &format!("M0 {y} ");
for k in 0..waves {
let x = k as f64 * 10.0;
d += &format!("C{} {} {} {} {} {y} ", x + 3.3, y - 8.0, x + 6.6, y + 8.0, x + 10.0);
}
d += &format!("L{} {} L0 {} Z ", waves as f64 * 10.0, y + 6.0, y + 6.0);
}
d
}
/// Heavy vectors are flattened coarser, so hovering, panning and zooming them stays as cheap as
/// before: a vector of 5,000 curves keeps the points 0.5 pt gave it (0.02 pt gives about five times
/// as many), and one of 200 still bends as smoothly as an ellipse.
#[test]
fn a_heavy_vectors_outline_keeps_the_points_it_had() {
use super::outline::{SMOOTH_CURVES, outline_shapes, outline_tolerance};
let mut s = Session::new();
let vector = |s: &mut Session, d: String| {
NodeId(s.execute("node.create", &json!({"type": "vector", "path": d, "closed": true, "x": 0, "y": 0})).unwrap()["id"].as_u64().unwrap())
};
let heavy = vector(&mut s, waves(50, 100));
let light = vector(&mut s, waves(2, SMOOTH_CURVES / 2));
let u = crate::layers_drag_tests::Ui::new(s);
let doc = u.app.session.doc().unwrap().clone();
let points = |id: NodeId| -> usize {
outline_shapes(&u.app, &doc, id, egui::Stroke::new(1.0, egui::Color32::WHITE))
.iter()
.map(|shape| if let egui::Shape::Path(line) = shape { line.points.len() } else { 0 })
.sum()
};
let zoom = u.app.session.ds().unwrap().view.zoom;
let mut before = 0;
figcraft_geom::kurbo::flatten(path_of(&doc, heavy).unwrap().iter(), 0.5 / zoom, |_| before += 1);
assert!(points(heavy) <= before, "{} points, {before} at 0.5 pt", points(heavy));
assert_eq!(outline_tolerance(SMOOTH_CURVES), 0.02);
assert!(largest_stray(&u, light) < 0.1, "{SMOOTH_CURVES} curves bend smoothly");
}
+10 -5
View File
@@ -174,22 +174,27 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
labels
}
/// The pixel grid's lines: one screen pixel wide, a light grey at a fifth of its strength, so
/// they darken white and lighten a dark canvas or fill alike. Measured in Figma (2026-11-24):
/// 242 on white and 78 on a grey of 50, which this grey gives.
pub(crate) const PIXEL_GRID: Color32 = Color32::from_rgba_unmultiplied_const(190, 190, 190, 51);
/// Pixel grid at high zoom.
fn pixel_grid(app: &FigApp, painter: &egui::Painter) {
let r = app.canvas.rect;
let p0 = app.to_page(r.min);
let p1 = app.to_page(r.max);
let col = Color32::from_black_alpha(18);
let line = stroke(PIXEL_GRID, 1.0 / painter.pixels_per_point());
let mut x = p0.x.floor();
while x <= p1.x {
let s = app.to_screen(x, 0.0).x;
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], stroke(col, 1.0));
let s = painter.round_to_pixel_center(app.to_screen(x, 0.0).x);
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], line);
x += 1.0;
}
let mut y = p0.y.floor();
while y <= p1.y {
let s = app.to_screen(0.0, y).y;
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], stroke(col, 1.0));
let s = painter.round_to_pixel_center(app.to_screen(0.0, y).y);
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], line);
y += 1.0;
}
}
+87 -8
View File
@@ -235,6 +235,7 @@ pub struct Renders {
preview: Retained,
/// The last full render's document, page and scale.
last: Option<(u64, NodeId, f64)>,
last_shown: Option<(u64, NodeId, View)>,
/// How long the last render from scratch took.
full_ms: f64,
/// Previews come first only when renders from scratch take at least this long.
@@ -242,8 +243,13 @@ pub struct Renders {
/// A full render being drawn band by band (the browser): the job it was started for, the
/// font generation then, the bands and the time they took so far.
steps: Option<Stepping>,
#[cfg(test)]
refine_gate: Option<RefineGate>,
}
#[cfg(test)]
pub(crate) type RefineGate = Arc<dyn Fn(&Job, Option<Done>) -> Option<Done> + Send + Sync>;
/// A full render drawn in steps and what it is of: a newer job of the same file, page, zoom, size
/// and render options keeps it going (its image is then patched to the job, as a pan or an edit
/// is), any other drops it.
@@ -300,7 +306,48 @@ impl Default for Renders {
impl Renders {
/// Previews when renders from scratch take at least `ms` (tests: 0, always).
pub fn with_threshold(ms: f64) -> Self {
Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None }
Self {
full: Retained::default(),
preview: Retained::default(),
last: None,
last_shown: None,
full_ms: 0.0,
preview_after_ms: ms,
steps: None,
#[cfg(test)]
refine_gate: None,
}
}
#[cfg(test)]
pub(crate) fn with_refine_gate(self, gate: RefineGate) -> Self {
Self { refine_gate: Some(gate), ..self }
}
fn keep(&mut self, job: &Job, d: &Done) {
self.last = Some((job.uid, job.page, job.view.scale));
self.handed_over(d);
}
fn handed_over(&mut self, d: &Done) {
self.late_preview_stayed(d.uid, d.page, d.view.clone());
}
pub fn late_preview_stayed(&mut self, uid: u64, page: NodeId, view: View) {
self.last_shown = Some((uid, page, view));
}
fn kept_image_is_as_sharp_as_a_preview(&self, job: &Job) -> bool {
let Some((uid, page, kept)) = &self.last_shown else { return false };
let (outer, inner) = (kept.page_rect(), job.view.page_rect());
*uid == job.uid
&& *page == job.page
&& job.view.scale >= kept.scale
&& job.view.scale <= kept.scale * PREVIEW_FACTOR
&& outer.x0 <= inner.x0
&& outer.y0 <= inner.y0
&& outer.x1 >= inner.x1
&& outer.y1 >= inner.y1
}
/// Whether `job` is a render from scratch: the kept image is of another zoom, page or file, or
@@ -312,7 +359,11 @@ impl Renders {
/// Whether `job` gets a preview first: it renders from scratch and those have been slow on a
/// page already drawn (the first render has no measure).
fn wants_preview(&self, job: &Job) -> bool {
job.zoom_preview && self.last.is_some() && self.full_ms_so_far() >= self.preview_after_ms && self.starts_over(job)
job.zoom_preview
&& self.last.is_some()
&& self.full_ms_so_far() >= self.preview_after_ms
&& self.starts_over(job)
&& !self.kept_image_is_as_sharp_as_a_preview(job)
}
/// How long the last render from scratch took, or what the one being drawn in steps has taken
@@ -323,7 +374,7 @@ impl Renders {
/// Whether `job` should get a preview should its render run long: from scratch, with none first.
pub fn wants_late_preview(&self, job: &Job) -> bool {
job.zoom_preview && self.starts_over(job) && !self.wants_preview(job)
job.zoom_preview && self.starts_over(job) && !self.wants_preview(job) && !self.kept_image_is_as_sharp_as_a_preview(job)
}
/// The coarse preview of the whole of `job`'s view, when one should come first.
@@ -331,14 +382,23 @@ impl Renders {
if !self.wants_preview(job) {
return None;
}
preview_with(job, &mut self.preview)
let done = preview_with(job, &mut self.preview);
if let Some(d) = &done {
self.handed_over(d);
}
done
}
/// The image of `job`'s view, built on the kept one where it can be.
pub fn refine(&mut self, job: &Job) -> Option<Done> {
let done = guarded(&mut self.full, |r| run(job, &job.view, r, false));
#[cfg(test)]
let done = match &self.refine_gate {
Some(gate) => gate(job, done),
None => done,
};
if let Some(d) = &done {
self.last = Some((job.uid, job.page, job.view.scale));
self.keep(job, d);
if d.work == Work::Full {
self.full_ms = d.ms;
}
@@ -421,7 +481,10 @@ impl Renders {
// A pan or an edit at this zoom builds on this render: no preview for it.
self.last = Some((job.uid, job.page, job.view.scale));
self.steps = Some(Stepping { job: job.clone(), fonts: figcraft_text::layout_generation(), steps, spent: 0.0 });
drawn.map(Refined::Shown)
drawn.map(|d| {
self.handed_over(&d);
Refined::Shown(d)
})
}
Ok(Err(d)) => Some(Refined::Done(self.finished(job, *d))),
Err(_) => {
@@ -434,7 +497,7 @@ impl Renders {
/// Record a render done at once in [`Self::refine_for`].
fn finished(&mut self, job: &Job, d: Option<Done>) -> Option<Done> {
if let Some(d) = &d {
self.last = Some((job.uid, job.page, job.view.scale));
self.keep(job, d);
if d.work == Work::Full {
self.full_ms = d.ms;
}
@@ -501,6 +564,10 @@ pub struct Worker {
#[cfg(not(target_arch = "wasm32"))]
impl Worker {
pub fn new(ctx: egui::Context) -> Self {
Self::with_renders(ctx, Renders::default())
}
pub(crate) fn with_renders(ctx: egui::Context, mut renders: Renders) -> Self {
let (tx, jobs) = std::sync::mpsc::channel::<(u64, Job)>();
let (done_tx, rx) = std::sync::mpsc::channel::<Done>();
let finished = Arc::new(std::sync::atomic::AtomicU64::new(0));
@@ -514,6 +581,8 @@ impl Worker {
let refined_seen = refined.clone();
let previewing = Arc::new(std::sync::atomic::AtomicBool::new(false));
let busy = previewing.clone();
let watchdog_busy = previewing.clone();
let (late_tx, late_rx) = std::sync::mpsc::channel::<(u64, u64, NodeId, View)>();
let (preview_tx, preview_ctx) = (done_tx.clone(), ctx.clone());
let watchdog =
std::thread::Builder::new().name("figcraft-render-preview".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || {
@@ -538,6 +607,7 @@ impl Worker {
&& let Some(d) = preview_with(&job, &mut retained)
&& still_rendering()
{
let _ = late_tx.send((seq, d.uid, d.page, d.view.clone()));
sent = preview_tx.send(answering(d, seq)).is_ok();
preview_ctx.request_repaint_of(viewport);
}
@@ -578,7 +648,6 @@ impl Worker {
log::error!("render surround thread: {e}");
}
let spawned = std::thread::Builder::new().name("figcraft-render".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || {
let mut renders = Renders::default();
let mut next = None;
loop {
let Some((mut seq, mut job)) = next.take().or_else(|| jobs.recv().ok()) else { break };
@@ -612,6 +681,16 @@ impl Worker {
}
let done = renders.refine(&job);
refined.store(seq, std::sync::atomic::Ordering::SeqCst);
if done.is_none() {
while watchdog_busy.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
for (shown_for, uid, page, view) in late_rx.try_iter() {
if shown_for == seq && done.is_none() {
renders.late_preview_stayed(uid, page, view);
}
}
let refined_job = done.is_some();
if let Some(d) = done
&& done_tx.send(answering(d, seq)).is_err()
@@ -173,6 +173,47 @@ fn a_zoom_out_previews_the_whole_view_then_refines_to_a_fresh_render() {
assert!(same_pixels(&refined, &fresh), "the settled image is a render from scratch");
}
#[test]
fn a_zoom_in_shows_the_kept_image_until_a_preview_would_be_sharper() {
let (s, _) = document();
let ds = s.ds().unwrap();
let at = |scale: f64| job(&ds.doc, ds.page, ds.uid, view_at((300.0, 200.0), scale, 400, 300));
let mut r = Renders::with_threshold(0.0);
r.refine(&at(1.0)).unwrap();
for scale in [1.08, 2.0, PREVIEW_FACTOR] {
assert!(r.preview(&at(scale)).is_none(), "{scale}x: the kept image, enlarged, is as sharp as a preview");
assert!(!r.wants_late_preview(&at(scale)), "{scale}x: no preview beside the render either");
}
assert!(r.preview(&at(PREVIEW_FACTOR * 1.5)).is_some(), "enlarged past a preview's sharpness");
assert!(r.preview(&at(0.5)).is_some(), "a zoom out");
let mut aside = at(2.0);
aside.view.origin.0 += 10_000.0;
assert!(r.preview(&aside).is_some(), "a zoom in where the kept image isn't");
r.refine(&at(2.0)).unwrap();
assert!(r.preview(&at(2.0 * PREVIEW_FACTOR)).is_none(), "measured from the image refined last");
}
#[test]
fn a_zoom_in_after_an_unrefined_zoom_out_is_measured_from_the_preview_on_screen() {
let (s, _) = document();
let ds = s.ds().unwrap();
let at = |scale: f64| job(&ds.doc, ds.page, ds.uid, view_at((300.0, 200.0), scale, 400, 300));
let mut r = Renders::with_threshold(0.0);
r.refine(&at(1.0)).unwrap();
assert!(r.preview(&at(0.25)).is_some_and(|d| d.coarse), "a zoom out shows its preview");
assert!(r.preview(&at(2.0)).is_some(), "the preview on screen is coarser than this zoom's preview");
assert!(r.preview(&at(2.0)).is_none(), "the same zoom again: the preview on screen is as sharp as another");
let mut w = waiting(Duration::from_secs(3600));
w.submit(at(1.0));
assert!(refined(&mut w).is_some_and(|d| !d.coarse && d.view.scale == 1.0));
let now = Instant::now();
w.submit(at(0.25));
assert!(w.poll_at(now).is_some_and(|d| d.coarse), "the browser shows the zoom out's preview");
w.submit(at(2.0));
assert!(w.poll_at(now).is_some_and(|d| d.coarse && d.view.scale == 2.0 / PREVIEW_FACTOR), "and previews the zoom in that follows it");
}
/// Zoom, pan and edit with `r`; whether each step was previewed, and the pan's and the edit's
/// images.
fn zoom_pan_edit(r: &mut Renders) -> (Vec<bool>, Done, Done) {
@@ -241,7 +282,7 @@ fn previews_cover_the_view_for_any_zoom_and_density() {
let (s, _) = document();
let ds = s.ds().unwrap();
let mut r = Renders::with_threshold(0.0);
r.refine(&job(&ds.doc, ds.page, ds.uid, view_at((0.0, 0.0), 0.37, 64, 64))).unwrap();
let kept = job(&ds.doc, ds.page, ds.uid, view_at((0.0, 0.0), 0.37, 64, 64));
let mut n = 0;
// Zooms from 2% to 6400% at 1x, 1.5x and 2x displays, odd sizes, centres off the pixel grid.
for zoom in [0.02, 0.1, 0.333, 1.0, 2.5, 8.0, 64.0] {
@@ -250,6 +291,7 @@ fn previews_cover_the_view_for_any_zoom_and_density() {
let v = view_at((123.456, -78.9), zoom * ppp, w, h);
let c = coarse_view(&v);
assert!(covers(&c, &v), "coarse view of {v:?}");
r.refine(&kept).unwrap();
let p = r.preview(&job(&ds.doc, ds.page, ds.uid, v.clone())).expect("a preview");
assert!(covers(&p.view, &v), "preview of {v:?} shows {:?}", p.view);
n += 1;
@@ -343,7 +385,7 @@ fn renders_from_scratch_with_nothing_to_go_by_get_a_late_preview() {
let first = at(&doc, page, uid, 1.0);
assert!(r.wants_late_preview(&first) && r.preview(&first).is_none(), "the first render");
r.refine(&first).unwrap();
assert!(r.wants_late_preview(&at(&doc, page, uid, 4.0)), "a zoom after quick renders");
assert!(r.wants_late_preview(&at(&doc, page, uid, 0.25)), "a zoom after quick renders");
assert!(r.wants_late_preview(&at(&doc, page, uid + 1, 1.0)), "another file");
let mut panned = first.clone();
panned.view.origin.0 += 5.0;
@@ -357,7 +399,7 @@ fn renders_from_scratch_with_nothing_to_go_by_get_a_late_preview() {
// Renders that have been slow: the preview comes first instead.
let mut slow = Renders::with_threshold(0.0);
slow.refine(&first).unwrap();
let zoom = at(&doc, page, uid, 4.0);
let zoom = at(&doc, page, uid, 0.25);
assert!(!slow.wants_late_preview(&zoom) && slow.preview(&zoom).is_some());
}
@@ -729,3 +771,57 @@ fn a_render_dropped_while_drawing_leaves_its_time_as_the_measure() {
assert!(matches!(r.refine_for(&at(1.0), 0.0), Refined::More));
assert!(r.preview(&at(2.0)).is_some(), "the zoom gets a preview by the dropped render's measure");
}
fn until_late_preview_of(w: &mut Worker, seq: u64) -> Vec<(u64, bool)> {
let start = std::time::Instant::now();
let mut got = vec![];
while !got.contains(&(seq, true)) {
assert!(start.elapsed() < Duration::from_secs(30), "no late preview of request {seq}: {got:?}");
got.extend(w.poll().map(|d| (d.seq, d.coarse)));
std::thread::sleep(Duration::from_millis(1));
}
got
}
fn until_idle(w: &mut Worker) -> Vec<(u64, bool)> {
let start = std::time::Instant::now();
let mut got = vec![];
while w.in_flight() {
assert!(start.elapsed() < Duration::from_secs(60), "the render never finished");
got.extend(w.poll().map(|d| (d.seq, d.coarse)));
std::thread::sleep(Duration::from_millis(1));
}
got.extend(w.poll().map(|d| (d.seq, d.coarse)));
got
}
#[test]
fn a_zoom_in_after_a_late_preview_left_on_screen_is_measured_from_that_preview() {
let zoomed_out = view_at((300.0, 200.0), 0.5, 1200, 1200);
let zoomed_in = view_at((300.0, 200.0), 2.0, 200, 150);
let held = [zoomed_out.scale.to_bits(), zoomed_in.scale.to_bits()];
let (release, released) = std::sync::mpsc::channel::<()>();
let released = std::sync::Mutex::new(released);
let gate = Arc::new(move |job: &Job, done: Option<Done>| {
if !held.contains(&job.view.scale.to_bits()) {
return done;
}
let _ = released.lock().unwrap().recv_timeout(Duration::from_secs(60));
done.filter(|_| job.view.scale.to_bits() != held[0])
});
let (s, _) = document();
let ds = s.ds().unwrap();
let mut w = Worker::with_renders(egui::Context::default(), Renders::with_threshold(f64::INFINITY).with_refine_gate(gate));
w.submit(job(&ds.doc, ds.page, ds.uid, view_at((300.0, 200.0), 1.0, 120, 90)));
assert!(drain(&mut w).contains(&(1, false)), "a sharp image at 1x");
w.submit(job(&ds.doc, ds.page, ds.uid, zoomed_out));
let mut got = until_late_preview_of(&mut w, 2);
release.send(()).unwrap();
got.extend(until_idle(&mut w));
assert_eq!(got, [(2, true)], "the watchdog's preview, and no refined image after it");
w.submit(job(&ds.doc, ds.page, ds.uid, zoomed_in));
let mut got = until_late_preview_of(&mut w, 3);
release.send(()).unwrap();
got.extend(until_idle(&mut w));
assert_eq!(got, [(3, true), (3, false)], "the 1x image is gone from the screen: the zoom in gets its late preview");
}
+14
View File
@@ -131,6 +131,11 @@ fn shows(code: &str, web: bool) -> bool {
// Arabic; keep the catalog out until an embedded Arabic fallback is supplied.
return figcraft_text::face_with_char('ع', &["Noto Sans Arabic"]).is_some();
}
if code.split(['-', '_']).next().is_some_and(|b| b.eq_ignore_ascii_case("he") || b.eq_ignore_ascii_case("iw")) {
// Desktop draws Hebrew with a system face (or bundled craft-fonts); the web leaves it out
// unless Noto Sans Hebrew is embedded (FIGCRAFT_EMBED_SCRIPTS=Hebr).
return figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
}
if code.split('-').next() == Some("ta") {
// Desktop draws Tamil with a system face (#2018); the web has none until craft-fonts
// carries Noto Sans Tamil.
@@ -233,6 +238,15 @@ mod tests {
assert_eq!(shows("ar-SA", true), face);
}
#[test]
fn the_web_offers_hebrew_only_with_its_face() {
assert!(shows("he", false), "desktop always lists Hebrew");
let face = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
assert_eq!(shows("he", true), face);
assert_eq!(shows("he-IL", true), face);
assert_eq!(shows("iw-IL", true), face);
}
#[test]
fn the_web_offers_tamil_only_with_its_face() {
assert!(shows("ta", false), "desktop always lists Tamil");
@@ -88,3 +88,49 @@ fn closing_the_picker_drops_its_eyedropper() {
assert_eq!(u.app.session.tool.tool, ToolId::Move);
assert_eq!(u.app.session.tool.picked, None, "a colour sampled for a closed picker is dropped");
}
#[test]
fn the_pick_color_key_with_a_picker_open_colours_the_pickers_paint() {
let mut s = Session::new();
s.execute("page.setBackground", &json!({"color": "#FFFFFF"})).unwrap();
rect(&mut s, 0.0, json!({"fill": "#FF0000"}));
let b = rect(&mut s, 200.0, json!({"fill": "#00FF00", "stroke": "#0000FF"}));
s.execute("select.set", &json!({"ids": [b]})).unwrap();
let target = PickerTarget::Paint { fills: false, index: 0, ids: vec![b] };
let mut u = Ui::new(s);
u.app.ui.picker = Some(target.clone());
u.frame(vec![]);
let key = |pressed| Event::Key { key: egui::Key::I, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
u.frame(vec![key(true), key(false)]);
assert_eq!((u.app.session.tool.tool, u.app.session.tool.pick_only), (ToolId::Eyedropper, true));
let on_red = u.app.to_screen(30.0, 30.0);
click(&mut u, on_red);
let n = u.app.session.doc().unwrap().node(b).unwrap().clone();
let hex = |p: &figcraft_color::Paint| p.solid_color().map(|c| c.to_hex()).unwrap_or_default();
assert_eq!((hex(&n.strokes[0]), hex(&n.fills[0])), ("FF0000".to_string(), "00FF00".to_string()));
assert_eq!(u.app.ui.picker, Some(target), "the picker stays open on its paint");
}
#[test]
fn the_eyedropper_shows_the_colour_under_it_from_the_canvas_image() {
let mut s = Session::new();
s.execute("page.setBackground", &json!({"color": "#FFFFFF"})).unwrap();
rect(&mut s, 0.0, json!({"fill": "#FF0000"}));
let mut u = Ui::new(s);
u.app.session.execute("edit.pickColor", &json!({})).unwrap();
let of = u.app.session.ds().ok().map(|ds| (ds.uid, ds.page));
let under = |u: &Ui, x: f64| u.app.canvas.pixel_under(figcraft_geom::Point::new(x, 30.0), of, egui::Color32::WHITE);
let mut seen = None;
for _ in 0..500 {
let p = u.app.to_screen(30.0, 30.0);
u.frame(vec![Event::PointerMoved(p)]);
seen = under(&u, 30.0);
if seen.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(4));
}
assert_eq!(seen, Some(egui::Color32::from_rgb(255, 0, 0)));
assert_eq!(under(&u, 130.0), Some(egui::Color32::WHITE), "the page around it");
assert_eq!(u.app.canvas.cursor.map(|c| c.name()).as_deref(), Some("eyedropper"));
}
+129
View File
@@ -300,3 +300,132 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
assert_eq!(image_at(&u, vector, true, Some(1)).scale_mode, ImageScaleMode::Crop);
assert_eq!(u.app.session.doc().unwrap().node(vector).unwrap().fills, layer_fills, "the layer's fills are untouched");
}
#[test]
fn in_crop_mode_the_edges_of_an_image_in_auto_layout_crop_it_too() {
let (mut u, layer, _) = setup();
let column = id(&u.app.session.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap());
u.app.run("node.reparent", json!({"ids": [layer], "parent": column}));
u.app.run("node.set", json!({"ids": [column], "props": {"layout": "vertical", "sizingV": "hug"}}));
u.app.run("select.set", json!({"ids": [layer]}));
u.app.run("image.crop", json!({}));
u.frame(vec![]);
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
let (from, to) = (u.app.to_screen(100.0, 100.0), u.app.to_screen(100.0, 60.0));
u.drag_to(from, to);
u.button(to, false);
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
assert!((n.height - 60.0).abs() < 1e-6 && (n.width - 200.0).abs() < 1e-6, "the bottom edge moved up: {} x {}", n.width, n.height);
let (m, Some(after)) = mode(&u, layer) else { panic!("a crop") };
assert_eq!(m, ImageScaleMode::Crop);
assert!((after[3] - before[3] * 0.6).abs() < 1e-9 && (after[0] - before[0]).abs() < 1e-9, "cropped, not squashed: {before:?} -> {after:?}");
assert!((after[5] - before[5]).abs() < 1e-9, "the top stays: {before:?} -> {after:?}");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
}
#[test]
fn a_double_click_in_crop_mode_keeps_cropping_and_vector_edit_ends_crop_mode() {
let (mut u, layer, _) = setup();
u.app.run("image.crop", json!({}));
u.frame(vec![]);
let at = u.app.to_screen(100.0, 50.0);
for _ in 0..2 {
u.button(at, true);
u.button(at, false);
}
u.frame(vec![]);
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "a double-click while cropping doesn't edit the points");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
u.drag_to(from, to);
u.button(to, false);
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
assert!((n.width - 150.0).abs() < 1e-6 && matches!(n.kind, figcraft_doc::NodeKind::Rectangle), "the side crops; the layer stays a rectangle");
u.app.run("vector.edit.begin", json!({"id": layer}));
u.frame(vec![]);
assert_eq!(u.app.ui.crop, None, "editing the points ends crop mode");
u.app.run("image.crop", json!({}));
u.frame(vec![]);
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "cropping ends editing the points");
assert_eq!(u.app.ui.crop, Some((layer, 0)));
}
/// The second press of a double-click on a side of the layer begins a resize; its release, which
/// is the double-click, ends it, and crop mode stays.
#[test]
fn a_double_click_on_a_side_in_crop_mode_leaves_no_resize_open() {
let (mut u, layer, _) = setup();
u.app.run("image.crop", json!({}));
u.frame(vec![]);
let at = u.app.to_screen(200.0, 50.0);
for _ in 0..2 {
u.button(at, true);
u.button(at, false);
}
u.frame(vec![]);
assert!(u.app.session.ds().unwrap().interaction.is_none(), "the resize the second press began is over");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
}
#[test]
fn in_crop_mode_the_images_corners_scale_freely_and_with_shift_in_proportion() {
let image_size = |u: &Ui, layer: NodeId| {
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
let (_, Some(c)) = mode(u, layer) else { panic!("a crop") };
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
((x1 - x0) * n.width, (y1 - y0) * n.height)
};
for shift in [false, true] {
let (mut u, layer, _) = setup();
u.app.run("image.crop", json!({}));
u.frame(vec![]);
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
u.drag_to(from, to);
u.button(to, false);
let (w0, h0) = image_size(&u, layer);
let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE };
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(260.0, 110.0));
u.frame_with(
vec![Event::PointerMoved(from), Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }],
modifiers,
);
for k in 1..=10 {
u.frame_with(vec![Event::PointerMoved(from + (to - from) * (k as f32 / 10.0))], modifiers);
}
u.frame_with(vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }], modifiers);
let (w1, h1) = image_size(&u, layer);
let kept = (w1 / h1 - w0 / h0).abs() < 1e-6;
assert!(w1 > w0, "the corner scaled the image: {w0}x{h0} -> {w1}x{h1}");
assert_eq!(kept, shift, "Shift {shift}: {w0}x{h0} -> {w1}x{h1}");
}
}
#[test]
fn in_auto_layout_a_side_dragged_past_the_image_leaves_no_empty_strip() {
let mut s = Session::new();
let image = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x % 255) as u8, (y % 255) as u8, 120, 255]));
let mut png = std::io::Cursor::new(Vec::new());
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
let data = base64::engine::general_purpose::STANDARD.encode(png.into_inner());
let content = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 1092, "height": 1400})).unwrap());
id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 300, "height": 160, "parent": content})).unwrap());
let layer = id(&s.execute("image.place", &json!({"data": data, "x": 0, "y": 300, "width": 804, "height": 969})).unwrap());
s.execute("node.reparent", &json!({"ids": [layer], "parent": content})).unwrap();
s.execute("node.set", &json!({"ids": [content], "props": {"layout": "vertical", "sizingV": "hug", "padding": [112, 0, 100, 0]}})).unwrap();
s.execute("node.set", &json!({"ids": [layer], "props": {"constrainProportions": true}})).unwrap();
s.execute("select.set", &json!({"ids": [layer]})).unwrap();
let mut u = Ui::new(s);
u.app.run("view.set", json!({"zoom": 0.5, "cx": 546, "cy": 700}));
u.app.run("image.crop", json!({}));
u.frame(vec![]);
let b = u.app.session.doc().unwrap().world_bounds(layer).unwrap();
let (from, to) = (u.app.to_screen(400.0, b.y0), u.app.to_screen(400.0, b.y0 - 120.0));
u.drag_to(from, to);
u.button(to, false);
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
let (_, Some(c)) = mode(&u, layer) else { panic!("a crop") };
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
assert!(x0 <= 1e-9 && y0 <= 1e-9 && x1 >= 1.0 - 1e-9 && y1 >= 1.0 - 1e-9, "the image covers the layer: {:?}", (x0, y0, x1, y1));
assert!(n.width >= 1.0 && n.height >= 1.0, "{} x {}", n.width, n.height);
assert!(u.app.session.ds().unwrap().vector_edit.is_none());
}
@@ -683,6 +683,7 @@ fn create_collection(app: &mut FigApp, vars: &Variables, st: &mut Editor) {
{
st.library = None;
st.collection = Some(id.clone());
st.group = None;
start_rename(st, Rename::Collection(id));
}
}
@@ -896,7 +897,11 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va
// An inherited variable is named (and deleted) in the collection it extends.
let inherited = v.extends.is_some();
if editable && st.rename.as_ref() == Some(&target) {
if let Some(name) = rename_field(ui, st, &target, &v.name, name_r, regular(11.0)) {
// The row shows the name's last part: the field edits that and keeps the group. A name of
// slashes and spaces alone is ignored, as the group would swallow it and drop the variable.
let (group, short) = v.name.rsplit_once('/').unwrap_or(("", &v.name));
if let Some(typed) = rename_field(ui, st, &target, short, name_r, regular(11.0)).filter(|n| n.split('/').any(|p| !p.trim().is_empty())) {
let name = if group.is_empty() { typed } else { format!("{group}/{typed}") };
app.run("variable.update", json!({"variable": v.id, "name": name}));
}
} else {
@@ -1160,7 +1165,9 @@ fn create_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
VariableType::Boolean => tr_noop("Boolean"),
};
if menu_item(ui, tr(label), "") {
let name = unique(label, |n| view.in_collection(&coll.id).any(|v| v.name == n));
// Made in the group shown, so the table showing it lists it.
let base = st.group.as_ref().map_or_else(|| label.to_string(), |g| format!("{g}/{label}"));
let name = unique(&base, |n| view.in_collection(&coll.id).any(|v| v.name == n));
let params = json!({"collection": coll.id, "name": name, "type": kind.id()});
if let Some(id) = app.run("variable.create", params).and_then(|r| r["id"].as_str().map(str::to_string)) {
st.query.clear();
+53 -24
View File
@@ -102,9 +102,6 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
if resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
}
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
let (name_font, detail_font) = (regular(12.0), regular(row.detail_size));
let width = |s: &str, font: &egui::FontId| ui.painter().layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE).size().x;
let room = (r.width() - 40.0).max(0.0);
@@ -120,8 +117,19 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
widgets::elide_start_font(ui, row.detail, detail_room, detail_font.clone())
};
let cut = name != row.name || detail != row.detail;
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
if crate::i18n::right_to_left() {
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 24.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
ui.painter().text(pos2(r.max.x - 32.0, r.center().y), Align2::RIGHT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, detail, detail_font, row.detail_ink);
} else {
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
}
cut
}
@@ -144,30 +152,40 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
dropped(app, ui.ctx());
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.panel)).show(ui, |ui| {
let rect = ui.max_rect();
let left = Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()));
ui.painter().line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.border));
sidebar(app, ui, &t, left);
let rtl = crate::i18n::right_to_left();
let side = if rtl {
Rect::from_min_size(pos2(rect.max.x - SIDEBAR, rect.min.y), vec2(SIDEBAR, rect.height()))
} else {
Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()))
};
let border_x = if rtl { side.left() } else { side.right() };
ui.painter().line_segment([pos2(border_x, side.top()), pos2(border_x, side.bottom())], Stroke::new(1.0, t.border));
sidebar(app, ui, &t, side);
let main =
if rtl { Rect::from_min_max(rect.min, pos2(side.min.x, rect.max.y)) } else { Rect::from_min_max(pos2(side.max.x, rect.min.y), rect.max) };
if app.ui.home_view.file_query.trim().is_empty() && app.ui.home_view.section == Section::Online {
// Your online files lay themselves out in the area (and scroll their own list).
let area = Rect::from_min_max(pos2(left.max.x + 40.0, rect.min.y + 24.0), rect.max - vec2(40.0, 24.0));
let area = main.shrink2(vec2(40.0, 24.0));
crate::online::section(app, ui, area, &t);
opened_join(app);
return;
}
let main = Rect::from_min_max(pos2(left.max.x, rect.min.y), rect.max);
ui.scope_builder(egui::UiBuilder::new().max_rect(main), |ui| {
egui::ScrollArea::vertical().id_salt("home").auto_shrink([false, false]).show(ui, |ui| {
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(40, 24)).show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
if app.ui.home_view.file_query.trim().is_empty() {
match app.ui.home_view.section {
Section::Templates => templates(app, ui, &t),
_ => recents(app, ui, &t),
let align = if rtl { egui::Align::Max } else { egui::Align::Min };
ui.with_layout(egui::Layout::top_down(align), |ui| {
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
if app.ui.home_view.file_query.trim().is_empty() {
match app.ui.home_view.section {
Section::Templates => templates(app, ui, &t),
_ => recents(app, ui, &t),
}
} else {
search_results(app, ui, &t);
opened_join(app);
}
} else {
search_results(app, ui, &t);
opened_join(app);
}
});
});
});
});
@@ -221,8 +239,13 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
}
focus_ring(ui, t, r, &resp, 5);
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
if crate::i18n::right_to_left() {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr(label), regular(12.0), t.text);
} else {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
}
if resp.clicked() {
app.ui.home_view.section = section;
app.ui.home_view.file_query.clear();
@@ -241,10 +264,16 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
}
focus_ring(ui, t, r, &resp, 5);
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
let key_label = figcraft_engine::keymap::display("Cmd+,", crate::shortcuts::platform());
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
if crate::i18n::right_to_left() {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr("Preferences"), regular(12.0), t.text);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, &key_label, regular(11.0), t.text_secondary);
} else {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
}
resp = resp.on_hover_text(format!("{} ({})", tr("Preferences"), key_label));
if resp.clicked() {
app.ui.preferences = !app.ui.preferences;
+3 -1
View File
@@ -95,7 +95,9 @@ const LATIN_AMERICA: &[&str] =
/// language the UI can't draw (CJK on the web without CJK faces built in) doesn't count.
fn resolve_one(want: &str) -> Option<usize> {
let tag = want.trim().split(['.', '@']).next().unwrap_or("").replace('_', "-");
let base = tag.split('-').next().unwrap_or("");
let raw_base = tag.split('-').next().unwrap_or("");
// Map the obsolete ISO 639-1 tag `iw` (still emitted by older Java/Android locales) to `he`.
let base = if raw_base.eq_ignore_ascii_case("iw") { "he" } else { raw_base };
let has = |subtags: &[&str]| tag.split('-').skip(1).any(|t| subtags.iter().any(|s| s.eq_ignore_ascii_case(t)));
let zh = |code: &str| {
LANGS.iter().position(|l| l.code.eq_ignore_ascii_case(code)).filter(|i| LANGS.get(*i).is_some_and(|l| crate::cjk::can_show(l.code)))
+41 -1
View File
@@ -584,11 +584,51 @@ fn right_to_left_languages_mirror_the_window() {
for code in ["en", "", "es-419", "zh-Hans", "tr", "ru", "arn", "hey"] {
assert!(!writes_right_to_left(code), "{code}");
}
// Every catalog that mirrors is one of them, and the Arabic one does.
// Every catalog that mirrors is one of them, and the Arabic and Hebrew ones do.
assert!(LANGS.iter().any(|l| l.code == "ar" && writes_right_to_left(l.code)));
assert!(LANGS.iter().any(|l| l.code == "he" && writes_right_to_left(l.code)));
assert!(!writes_right_to_left(LANGS[0].code), "English reads left to right");
}
#[test]
fn hebrew_tags_and_plurals() {
let he = LANGS.iter().position(|l| l.code == "he").expect("locales/he.toml is baked in");
assert_eq!(LANGS[he].name, "עברית");
for tag in ["he", "he-IL", "he_IL.UTF-8", "iw", "iw-IL", "iw_IL.UTF-8"] {
assert_eq!(resolve(tag, None), he, "{tag}");
assert_eq!(resolve("system", Some(tag)), he, "{tag}");
}
assert!(!plural_one(he, 0) && plural_one(he, 1) && !plural_one(he, 2) && !plural_one(he, 5));
let singular = fill(counted(he, "{n} layers", 1), &[("n", &1)]);
let dual = fill(counted(he, "{n} layers", 2), &[("n", &2)]);
assert_eq!(singular, "1 שכבה");
assert_eq!(dual, "2 שכבות");
}
#[test]
fn the_built_in_hebrew_face_draws_the_hebrew_catalog() {
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Hebrew" && f.style == "Regular") {
eprintln!("built without craft-fonts' Noto Sans Hebrew; skipping");
return;
}
let Some(face) = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]) else {
panic!("the supplied Noto Sans Hebrew face must draw Hebrew");
};
let he = &LANGS[LANGS.iter().position(|l| l.code == "he").unwrap()];
let letters: BTreeSet<char> = he
.ui
.iter()
.chain(he.commands)
.chain(he.menu)
.flat_map(|(_, t)| forms(t))
.flat_map(str::chars)
.filter(|c| matches!(u32::from(*c), 0x05D0..=0x05EA))
.collect();
assert!(letters.len() >= 27);
let missing: String = letters.iter().filter(|c| !face.has_char(**c)).collect();
assert!(missing.is_empty(), "Hebrew catalog glyphs missing from the embedded face: {missing:?}");
}
#[test]
fn the_built_in_arabic_face_draws_the_arabic_catalog() {
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Arabic" && f.style == "Regular") {
@@ -0,0 +1,77 @@
use egui::accesskit::{Node, Role};
use figcraft_doc::{NodeId, NodeKind};
use figcraft_engine::Session;
use serde_json::json;
use crate::component_swap_default_tests::{centre, click, tree};
use crate::layers_drag_tests::Ui;
fn id(v: serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn combos(nodes: &[Node]) -> Vec<String> {
nodes.iter().filter(|n| n.role() == Role::ComboBox).filter_map(|n| n.value().map(str::to_string)).collect()
}
fn small_and_large_instances_selected(with_a_rectangle: bool) -> (Ui, Vec<(String, NodeId)>, Vec<NodeId>) {
let mut s = Session::new();
let mut variants = Vec::new();
for (k, name) in ["Size=S, State=Default", "Size=L, State=Default", "Size=S, State=Hover", "Size=L, State=Hover"].iter().enumerate() {
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 20 + k * 44, "width": 80, "height": 30, "name": name})).unwrap());
variants.push((name.to_string(), id(s.execute("component.create", &json!({"ids": [f]})).unwrap())));
}
s.execute("component.combineVariants", &json!({"ids": variants.iter().map(|v| v.1).collect::<Vec<_>>()})).unwrap();
let small = id(s.execute("instance.create", &json!({"component": variants[0].1, "x": 300, "y": 20})).unwrap());
let large = id(s.execute("instance.create", &json!({"component": variants[1].1, "x": 300, "y": 80})).unwrap());
let mut selected = vec![small, large];
if with_a_rectangle {
selected.push(id(s.execute("shape.rectangle", &json!({"x": 500, "y": 20, "width": 20, "height": 20})).unwrap()));
}
s.execute("select.set", &json!({"ids": selected})).unwrap();
let u = Ui::new(s);
u.ctx.enable_accesskit();
(u, variants, vec![small, large])
}
fn main_of(u: &Ui, instance: NodeId) -> NodeId {
match &u.app.session.doc().unwrap().node(instance).unwrap().kind {
NodeKind::Instance { component, .. } => *component,
_ => panic!("not an instance"),
}
}
fn pick(u: &mut Ui, shown: &str, value: &str) {
let nodes = tree(u);
let dropdown = nodes.iter().find(|n| n.role() == Role::ComboBox && n.value() == Some(shown)).unwrap_or_else(|| panic!("a {shown} dropdown"));
click(u, centre(dropdown));
let nodes = tree(u);
let item = nodes
.iter()
.find(|n| n.label() == Some(value) && !matches!(n.role(), Role::ComboBox | Role::TextInput) && n.bounds().is_some())
.unwrap_or_else(|| panic!("{value} in the menu"));
click(u, centre(item));
}
#[test]
fn two_selected_instances_show_their_shared_variant_properties_and_set_them_together() {
let (mut u, variants, instances) = small_and_large_instances_selected(false);
let variant = |name: &str| variants.iter().find(|v| v.0 == name).unwrap().1;
let shown = combos(&tree(&mut u));
assert!(shown.contains(&"Mixed".to_string()), "Size differs between them: {shown:?}");
assert!(shown.contains(&"Default".to_string()), "State is the same: {shown:?}");
pick(&mut u, "Mixed", "L");
assert_eq!(instances.iter().map(|i| main_of(&u, *i)).collect::<Vec<_>>(), [variant("Size=L, State=Default"); 2]);
pick(&mut u, "Default", "Hover");
assert_eq!(instances.iter().map(|i| main_of(&u, *i)).collect::<Vec<_>>(), [variant("Size=L, State=Hover"); 2]);
}
#[test]
fn instances_selected_with_a_plain_layer_show_no_instance_properties() {
let (mut u, _, _) = small_and_large_instances_selected(true);
let shown = combos(&tree(&mut u));
assert!(!shown.iter().any(|v| v == "Mixed" || v == "Default"), "no property rows: {shown:?}");
}
+51 -13
View File
@@ -1,6 +1,7 @@
//! Arrow keys in the layers panel once a row has been clicked: up/down through the rows (Shift
//! extends), left/right to collapse, expand, and go to the parent or first child; a press on the
//! canvas gives arrows back to nudging. Delete after a click in the Pages list deletes the page.
//! Arrow keys in the layers panel once F6 has put the keyboard on its rows: up/down through the
//! rows (Shift extends), left/right to collapse, expand, and go to the parent or first child. After
//! a click on a row the arrows nudge the layer, as on the canvas. Delete after a click in the Pages
//! list deletes the page.
use egui::{Event, Key, Modifiers, Pos2, pos2, vec2};
use figcraft_doc::NodeId;
@@ -46,10 +47,29 @@ fn click_row(u: &mut Ui, id: NodeId) {
assert_eq!(sel(u), vec![id]);
}
/// Presses F6 until the keyboard is on the layers panel, as a keyboard user gets there.
fn keyboard_into_the_layers(u: &mut Ui) {
for _ in 0..crate::a11y::Region::ALL.len() {
key(u, Key::F6, false);
u.frame(vec![]);
if u.app.ui.nav.region == crate::a11y::Region::Layers {
return;
}
}
panic!("F6 never reached the layers panel");
}
/// Selects `id` and moves the keyboard onto its row with F6.
fn keyboard_to_the_row(u: &mut Ui, id: NodeId) {
u.app.run("select.set", json!({"ids": [id]}));
u.frame(vec![]);
keyboard_into_the_layers(u);
}
#[test]
fn up_and_down_walk_the_rows_and_shift_extends() {
let (mut u, a, frame, _, c) = setup();
click_row(&mut u, c);
keyboard_to_the_row(&mut u, c);
key(&mut u, Key::ArrowDown, false);
assert_eq!(sel(&u), vec![frame]);
key(&mut u, Key::ArrowDown, false);
@@ -103,6 +123,7 @@ fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() {
let mut want = vec![rect4, frame1];
want.sort();
assert_eq!(got, want, "the pointer range keeps the frame");
keyboard_into_the_layers(&mut u);
// Rows: Frame 2, Rect 4, Frame 1, Rect 3, Rect 2. Shift+Down runs from Rect 2 (the anchor).
key(&mut u, Key::ArrowDown, true);
let mut got = sel(&u);
@@ -115,7 +136,7 @@ fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() {
#[test]
fn left_and_right_open_close_and_move_between_levels() {
let (mut u, _, frame, child, _) = setup();
click_row(&mut u, frame);
keyboard_to_the_row(&mut u, frame);
key(&mut u, Key::ArrowRight, false);
assert!(u.app.ui.expanded.contains(&frame), "Right opens a closed row");
assert_eq!(sel(&u), vec![frame]);
@@ -129,21 +150,38 @@ fn left_and_right_open_close_and_move_between_levels() {
}
#[test]
fn a_canvas_press_gives_arrows_back_to_nudging() {
fn a_clicked_row_leaves_the_arrows_to_the_canvas() {
let (mut u, _, _, _, c) = setup();
click_row(&mut u, c);
assert!(u.app.ui.layers_focus);
// Press on empty canvas (deselects), then select c from the canvas side and nudge it.
let p = pos2(900.0, 700.0);
u.button(p, true);
u.button(p, false);
assert!(!u.app.ui.layers_focus);
u.app.run("select.set", json!({"ids": [c]}));
key(&mut u, Key::ArrowRight, false);
assert_eq!(sel(&u), vec![c]);
let doc = u.app.session.doc().unwrap();
assert_eq!(doc.node(c).unwrap().transform.translation().x, 201.0);
}
#[test]
fn down_on_a_clicked_row_moves_it_one_place_in_a_vertical_auto_layout() {
let mut s = Session::new();
let column = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 200, "name": "Column"})).unwrap());
let rows: Vec<NodeId> = (0..3)
.map(|i| id(s.execute("shape.rectangle", &json!({"x": 0, "y": i * 30, "width": 80, "height": 20, "parent": column})).unwrap()))
.collect();
s.execute("layout.add", &json!({"ids": [column], "direction": "vertical"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let mut u = Ui::new(s);
u.app.ui.expanded.insert(column);
u.frame(vec![]);
click_row(&mut u, rows[1]);
key(&mut u, Key::ArrowDown, false);
let order = u.app.session.doc().unwrap().node(column).unwrap().children.clone();
assert_eq!(order, [rows[0], rows[2], rows[1]]);
assert_eq!(sel(&u), vec![rows[1]]);
key(&mut u, Key::ArrowUp, false);
key(&mut u, Key::ArrowUp, false);
let order = u.app.session.doc().unwrap().node(column).unwrap().children.clone();
assert_eq!(order, [rows[1], rows[0], rows[2]]);
}
/// The middle of `page`'s row in the Pages list, found by clicking down the list until it opens;
/// then back to `back`.
fn page_row(u: &mut Ui, page: NodeId, back: NodeId) -> Pos2 {
+148 -2
View File
@@ -122,10 +122,13 @@ fn a_wide_name_among_many_long_narrow_ones_is_still_measured() {
for _ in 0..50 {
named(&mut s, &"i".repeat(100), None);
}
named(&mut s, &"W".repeat(70), None);
named(&mut s, &"W".repeat(25), None);
let mut u = Ui::new(s);
let (elided, ..) = painted(&mut u, "WWWW");
let (elided, _, size) = painted(&mut u, "WWWW");
assert!(!elided, "the wide name reads in full");
// Wider than the panel leaves a name, so it reads in full only if it was measured, and well
// under the cap, with or without craft-fonts.
assert!(size.x > 200.0 && size.x < crate::layers::NAME_ROOM - 100.0, "the test's name is {} pt wide", size.x);
}
/// Review: a name is laid out as it is painted, on one line, so line breaks in it don't make it
@@ -159,3 +162,146 @@ fn a_drag_released_over_the_canvas_drops_nowhere() {
}
assert_eq!(u.app.session.doc().unwrap().node(page).unwrap().children, order, "no reorder");
}
fn hidden_layer_eye(name: &str, mirrored: bool) -> (Ui, NodeId, egui::Rect) {
let mut s = Session::new();
let layer =
id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20, "props": {"name": name, "visible": false}})).unwrap());
let mut u = Ui::new(s);
u.app.ui.mirrored = mirrored;
u.ctx.enable_accesskit();
for _ in 0..3 {
u.frame(vec![]);
}
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let eye = nodes
.iter()
.find(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == Some("Hidden"))
.and_then(|(_, n)| n.bounds())
.expect("the eye of the hidden layer");
(u, layer, egui::Rect::from_min_max(Pos2::new(eye.x0 as f32, eye.y0 as f32), Pos2::new(eye.x1 as f32, eye.y1 as f32)))
}
#[test]
fn the_eye_of_a_long_named_layer_sits_at_the_panels_edge_and_is_clickable() {
for mirrored in [false, true] {
let (_, _, short) = hidden_layer_eye("Short", mirrored);
let (mut u, layer, long) = hidden_layer_eye(LONG, mirrored);
let (a, b) = if mirrored { (long.min.x, short.min.x) } else { (long.max.x, short.max.x) };
assert!((a - b).abs() < 1.0, "mirrored {mirrored}: the eye at the panel's edge, not past it: {a} vs {b}");
u.button(long.center(), true);
u.button(long.center(), false);
assert!(u.app.session.doc().unwrap().node(layer).unwrap().visible, "mirrored {mirrored}: the eye shows the layer");
}
}
#[test]
fn a_paragraph_named_text_layer_widens_the_list_no_more_than_the_name_cap() {
let mut s = Session::new();
named(&mut s, &"After the Chicago World's Fair, Tiffany built Laurelton Hall on Long Island. ".repeat(4), None);
let mut u = Ui::new(s);
let (elided, p, size) = painted(&mut u, "After the Chicago");
assert!(elided, "a paragraph elides at the cap");
assert!(p.x + size.x <= p.x + 400.0 + 1.0, "the name takes at most 400 pt: {}", size.x);
}
/// The bounds of the buttons named `label` (AccessKit), from left to right.
fn buttons(u: &mut Ui, label: &str) -> Vec<egui::Rect> {
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let mut rects: Vec<egui::Rect> = nodes
.iter()
.filter(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == Some(label))
.filter_map(|(_, n)| n.bounds())
.map(|b| egui::Rect::from_min_max(Pos2::new(b.x0 as f32, b.y0 as f32), Pos2::new(b.x1 as f32, b.y1 as f32)))
.collect();
rects.sort_by(|a, b| a.min.x.total_cmp(&b.min.x));
rects
}
/// Review: an ordinary row as wide as the view keeps its eye where it was before the eye and padlock
/// were held in view (measured on `main`: 262 to 282 pt, mirrored 1158 to 1178 pt), with a vertical
/// scrollbar or without.
#[test]
fn the_eye_of_an_ordinary_row_stays_where_it_was() {
for count in [1, 60] {
for mirrored in [false, true] {
let mut s = Session::new();
for i in 0..count {
let props = json!({"name": format!("Rect {i}"), "visible": i + 1 != count});
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20, "props": props})).unwrap();
}
let mut u = Ui::new(s);
u.app.ui.mirrored = mirrored;
u.ctx.enable_accesskit();
for _ in 0..3 {
u.frame(vec![]);
}
let eye = buttons(&mut u, "Hidden");
let x = if mirrored { 1158.0 } else { 262.0 };
assert_eq!(eye.iter().map(|r| (r.min.x, r.max.x)).collect::<Vec<_>>(), [(x, x + 20.0)], "{count} rows, mirrored {mirrored}");
}
}
}
/// Review: while a sweep across the eyes is held, a long-named row it took in shows its eye, so its
/// name stays clipped before the eye after the pointer has moved past it.
#[test]
fn a_swept_long_named_row_keeps_its_name_clipped_before_the_eye() {
let mut s = Session::new();
let long = named(&mut s, LONG, None);
let short = named(&mut s, "Short", None);
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
let at = u.row_at(short);
u.frame(vec![Event::PointerMoved(at)]);
let eye = *buttons(&mut u, "Hidden").first().expect("the hovered row's eye");
let below = u.row_at(long) + vec2(0.0, 40.0);
u.frame(vec![Event::PointerMoved(eye.center())]);
u.drag_to(eye.center(), Pos2::new(eye.center().x, below.y));
let out = u.frame_output(vec![]);
let clip = out
.shapes
.iter()
.find_map(|c| match &c.shape {
Shape::Text(t) if t.galley.text().starts_with("Size=small") => Some(c.clip_rect),
_ => None,
})
.expect("the long name");
u.button(Pos2::new(eye.center().x, below.y), false);
let doc = u.app.session.doc().unwrap();
assert!(!doc.node(long).unwrap().visible && !doc.node(short).unwrap().visible, "the sweep hid both");
assert!(clip.max.x <= eye.min.x - 20.0, "the name ends before the padlock and eye: {} vs eye at {}", clip.max.x, eye.min.x);
}
/// Review: on a row nested so deep that its disclosure triangle sits where the eye and padlock
/// would be at the view's edge, they stay at the row's end, so the triangle still opens and closes
/// the layer.
#[test]
fn the_disclosure_triangle_of_a_deeply_nested_row_is_not_under_the_padlock() {
let mut s = Session::new();
let mut parent = None;
let mut deepest = None;
for i in 0..13 {
let f = id(s
.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "parent": parent, "props": {"name": format!("F{i}")}}))
.unwrap());
parent = Some(f);
deepest = Some(f);
}
let deepest = deepest.unwrap();
let leaf = named(&mut s, "Leaf", parent);
s.execute("select.set", &json!({"ids": [leaf]})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
let tri = *buttons(&mut u, "Collapse").last().expect("the deepest frame's triangle");
u.frame(vec![Event::PointerMoved(tri.center())]);
u.frame(vec![Event::PointerMoved(tri.center())]);
u.button(tri.center(), true);
u.button(tri.center(), false);
u.frame(vec![]);
assert!(!u.app.ui.expanded.contains(&deepest), "the triangle closed the frame");
let n = u.app.session.doc().unwrap().node(deepest).unwrap();
assert!(n.visible && !n.locked, "neither the eye nor the padlock took the click");
}
+17 -2
View File
@@ -157,6 +157,8 @@ mod import_report_tests;
#[cfg(test)]
mod inspect_fields_tests;
#[cfg(test)]
mod instances_shared_props_tests;
#[cfg(test)]
mod layers_behaviour_tests;
#[cfg(test)]
mod layers_component_rows_tests;
@@ -203,6 +205,8 @@ mod menu_input_tests;
#[cfg(test)]
mod menu_overflow_tests;
#[cfg(test)]
mod menu_scroll_tests;
#[cfg(test)]
mod mirror_tests;
#[cfg(test)]
mod missing_fonts_tests;
@@ -232,6 +236,8 @@ mod pen_mode_tests;
#[cfg(test)]
mod perf_tests;
#[cfg(test)]
mod pixel_grid_tests;
#[cfg(test)]
mod plugin_panel_tests;
#[cfg(test)]
mod plugin_save_ui_tests;
@@ -293,6 +299,8 @@ mod text_link_tests;
#[cfg(test)]
mod text_mixed_fill_tests;
#[cfg(test)]
mod text_paste_style_tests;
#[cfg(test)]
mod tidy_tests;
#[cfg(test)]
mod titlebar_tests;
@@ -307,6 +315,8 @@ mod variable_picker_tests;
#[cfg(test)]
mod variables_export_ui_tests;
#[cfg(test)]
mod variables_group_create_tests;
#[cfg(test)]
mod variables_rename_tests;
#[cfg(test)]
mod variables_select_tests;
@@ -560,8 +570,9 @@ pub struct UiState {
pub layer_search: bool,
pub layer_filter: String,
pub layer_anchor: Option<NodeId>,
/// The layers panel has the keyboard: arrow keys move through its rows instead of nudging
/// (set by a click on a row, cleared by a press on the canvas).
/// A layer row was clicked last: Shift+F10 opens the context menu at its row (set by a click on
/// a row, cleared by a press on the canvas). Arrow keys still nudge; they move through the rows
/// only once F6 has put the keyboard on the layers panel.
pub layers_focus: bool,
/// The file (its `uid`) whose pages list has the keyboard: Delete with no layers selected deletes
/// its current page (set by a click on a page row or the add-page button, cleared by a click on a
@@ -638,6 +649,9 @@ pub struct UiState {
/// copy changes the engine clipboard without writing the OS clipboard; the generation then
/// no longer matches, so the stale mirror is not mistaken for the user's own copy.
pub last_copy_generation: u64,
/// The formatting of the characters last copied as text: a paste into a text edit of those
/// same characters keeps it.
pub text_copy: Option<figcraft_engine::textedit::RichText>,
/// The fill, stroke or effect row highlighted in the Design panel: Cmd/Ctrl+C copies it.
pub property_row: Option<property_rows::Highlight>,
/// A paint or effect copied from its row: Cmd/Ctrl+V pastes it while it's the last copy.
@@ -786,6 +800,7 @@ impl Default for UiState {
last_copy: None,
last_copy_generation: 0,
text_copy: None,
property_row: None,
property_copy: None,
after_field: None,
+114
View File
@@ -0,0 +1,114 @@
//! A panel menu taller than the window scrolls, so its last rows can be reached and picked: the
//! page's variable mode menu of a collection with more modes than fit.
use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, Pos2, TouchPhase, vec2};
use figcraft_engine::Session;
use serde_json::json;
use crate::layers_drag_tests::Ui;
use crate::live_tests::{flat, text_center, texts};
/// A click at `p`, and the frames that follow; what the last frame drew.
fn click(u: &mut Ui, p: Pos2) -> Vec<egui::Shape> {
for _ in 0..5 {
u.frame(vec![Event::PointerMoved(p)]);
}
let mut shapes = Vec::new();
for pressed in [Some(true), Some(false)].into_iter().chain(std::iter::repeat_n(None, 20)) {
let events = pressed.map(|pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
shapes = flat(&u.frame_output(events.into_iter().collect()).shapes);
}
shapes
}
/// Where `label` is drawn, if it is.
fn at(shapes: &[egui::Shape], label: &str) -> Option<Pos2> {
texts(shapes).into_iter().find(|(t, ..)| t == label).map(|(_, p, size)| p + size / 2.0)
}
#[test]
fn a_menu_taller_than_the_window_scrolls_to_its_last_row() {
let modes: Vec<String> = (0..60).map(|k| format!("Mode {k}")).collect();
let mut s = Session::new();
s.execute("variable.createCollection", &json!({"name": "Theme", "modes": modes})).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
let mut u = Ui::new(s);
let shapes = flat(&u.frame_output(vec![]).shapes);
let menu = click(&mut u, text_center(&shapes, "Auto (Mode 0)"));
let first = at(&menu, " Mode 0").expect("the menu is open");
assert!(at(&menu, " Mode 59").is_none_or(|p| p.y > 900.0), "the last row starts below the window");
let wheel = Event::MouseWheel {
unit: MouseWheelUnit::Point,
source: egui::MouseWheelSource::Unknown,
delta: vec2(0.0, -5000.0),
phase: TouchPhase::Move,
modifiers: Modifiers::NONE,
};
u.frame(vec![Event::PointerMoved(first), wheel]);
for _ in 0..30 {
u.frame(vec![]);
}
let shapes = flat(&u.frame_output(vec![]).shapes);
let last = at(&shapes, " Mode 59").expect("scrolled to the last row");
assert!(last.y < 900.0, "inside the window: {last:?}");
click(&mut u, last);
let page = u.app.session.page().unwrap();
let doc = u.app.session.doc().unwrap();
let coll = &doc.variables.collections[0];
let picked = coll.modes.iter().find(|m| m.name == "Mode 59").unwrap().id.clone();
assert_eq!(doc.node(page).unwrap().var_modes.get(&coll.id), Some(&picked), "the last mode is picked");
}
/// The page's variable mode menu of a collection with `n` modes, opened; what it drew.
fn mode_menu(n: usize) -> (Ui, Vec<egui::Shape>) {
let modes: Vec<String> = (0..n).map(|k| format!("Mode {k}")).collect();
let mut s = Session::new();
s.execute("variable.createCollection", &json!({"name": "Theme", "modes": modes})).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
let mut u = Ui::new(s);
let shapes = flat(&u.frame_output(vec![]).shapes);
let menu = click(&mut u, text_center(&shapes, "Auto (Mode 0)"));
(u, menu)
}
/// A press and release of `key`, and a frame after it.
fn key(u: &mut Ui, key: egui::Key) {
for pressed in [true, false] {
u.frame(vec![Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
}
u.frame(vec![]);
}
#[test]
fn a_click_on_the_scroll_bar_track_keeps_the_menu_open() {
let (mut u, menu) = mode_menu(60);
let first = at(&menu, " Mode 0").expect("the menu is open");
u.ctx.enable_accesskit();
let out = u.frame_output(vec![Event::PointerMoved(first)]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
let bar = nodes
.iter()
.filter(|(_, n)| n.role() == egui::accesskit::Role::ScrollBar)
.filter_map(|(_, n)| n.bounds())
.find(|b| b.x0 as f32 > first.x && (b.y0..b.y1).contains(&f64::from(first.y)))
.expect("the menu's scroll bar");
let shapes = click(&mut u, Pos2::new(((bar.x0 + bar.x1) / 2.0) as f32, (bar.y1 - 10.0) as f32));
assert!(texts(&shapes).iter().any(|(t, ..)| t.starts_with(" Mode ")), "the menu is still open");
assert!(at(&shapes, " Mode 0").is_none_or(|p| p.y < first.y), "the click on the track scrolled the rows");
}
#[test]
fn the_keyboard_stays_on_its_row_when_the_window_shrinks_until_the_menu_scrolls_and_grows_back() {
let (mut u, _) = mode_menu(25);
for _ in 0..3 {
key(&mut u, egui::Key::ArrowDown);
}
let row = u.ctx.memory(|m| m.focused()).expect("a row has the keyboard");
for height in [400.0, 900.0] {
u.screen = vec2(1440.0, height);
for _ in 0..10 {
u.frame(vec![]);
}
assert_eq!(u.ctx.memory(|m| m.focused()), Some(row), "the same row has the keyboard at a window {height} pt tall");
}
}
+2
View File
@@ -209,6 +209,7 @@ pub fn invoke(app: &mut FigApp, id: &str) {
.ok()
.and_then(|d| d.vector_edit.as_ref())
.is_some_and(|ve| ve.parts().iter().any(|p| !p.vertices.is_empty() || !p.segments.is_empty()));
let rich = doc.filter(|_| !partial).and_then(|d| figcraft_engine::textedit::layers_rich_text(d, &ids));
let mirror = doc.filter(|_| !partial).and_then(|d| text_layers_text(d, &ids).or_else(|| figcraft_svg_export(d, &ids)));
let ran = app.run(id, json!({}));
// A partial copy put temporary layers on the engine clipboard; mirror their SVG.
@@ -223,6 +224,7 @@ pub fn invoke(app: &mut FigApp, id: &str) {
app.clipboard_set_text(&text);
app.ui.last_copy = Some(text);
app.ui.last_copy_generation = app.session.clipboard.layers_generation;
app.ui.text_copy = rich;
}
}
"edit.paste" => paste(app, None, None),
+26 -14
View File
@@ -37,9 +37,9 @@ const MAX_THUMBS: usize = 600;
const THUMBS_PER_FRAME: usize = 8;
/// Layers compared per component when checking whether its thumbnail is stale.
const MAX_COMPARED: usize = 20_000;
/// Look for changed library files this often (seconds) while the panel shows.
/// Look for changed library files this often (seconds).
const LIBRARY_REFRESH: f64 = 2.0;
/// Ask team libraries' servers for newer versions this often (seconds) while the panel shows.
/// Ask team libraries' servers for newer versions this often (seconds).
// shortcut: polled (a few bytes when nothing changed); a server push needs a connection per
// library, worth it once libraries are used beyond the Assets panel.
const SERVER_REFRESH: f64 = 30.0;
@@ -278,33 +278,42 @@ fn build_listing(app: &FigApp, doc: &Document, q: &str, key: (u64, String, u64))
Listing { key, local: foldered("", local), local_styles, libraries, updates }
}
/// Re-read enabled library files that changed on disk (throttled).
fn refresh_libraries(app: &mut FigApp, ui: &Ui) {
/// Re-read enabled library files that changed on disk (throttled), every logic tick whether or not
/// the Assets panel shows, so the style pickers list library styles too. A library this file
/// hasn't tried to read yet (just opened or added) is read at once.
pub(crate) fn refresh_libraries(app: &mut FigApp, ctx: &egui::Context) {
let Ok(doc) = app.session.doc() else { return };
if doc.libraries.enabled.is_empty() {
return;
}
let paths: Vec<String> = doc.libraries.enabled.iter().map(|l| l.path.clone()).collect();
let id = Id::unique("asset_libraries_checked");
let now = ui.input(|i| i.time);
let last: Option<f64> = ui.data(|d| d.get_temp(id));
if last.is_none_or(|l| now - l >= LIBRARY_REFRESH) {
// The paths the last read tried: one that was refused (too large, not on this computer) is
// never cached, and would otherwise be tried again every frame.
let tried_id = Id::unique("asset_libraries_tried");
let now = ctx.input(|i| i.time);
let last: Option<f64> = ctx.data(|d| d.get_temp(id));
let tried: Vec<String> = ctx.data(|d| d.get_temp(tried_id)).unwrap_or_default();
let unread_here = paths.iter().any(|p| !is_server_link(p) && app.session.libraries.cached(p).is_none() && !tried.contains(p));
if unread_here || last.is_none_or(|l| now - l >= LIBRARY_REFRESH) {
for p in &paths {
let _ = app.session.libraries.load(p);
}
ui.data_mut(|d| d.insert_temp(id, now));
ctx.data_mut(|d| {
d.insert_temp(id, now);
d.insert_temp(tried_id, paths.clone());
});
// Team libraries: in the background, at once for one not fetched yet.
let sid = Id::unique("asset_server_libraries_checked");
let fetched: Option<f64> = ui.data(|d| d.get_temp(sid));
let fetched: Option<f64> = ctx.data(|d| d.get_temp(sid));
// Only the ones you added or checked: a file can't make the app contact a server (#1097).
let team: Vec<&String> = paths.iter().filter(|p| is_server_link(p) && app.session.library_allowed(p)).collect();
let unread = team.iter().any(|p| app.session.libraries.cached(p).is_none());
if !team.is_empty() && (unread || fetched.is_none_or(|l| now - l >= SERVER_REFRESH)) {
app.session.refresh_server_libraries();
ui.data_mut(|d| d.insert_temp(sid, now));
ctx.data_mut(|d| d.insert_temp(sid, now));
}
}
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(LIBRARY_REFRESH));
}
/// The search field with the libraries button; returns the lowercase query.
@@ -577,12 +586,15 @@ fn render_thumbs(ui: &Ui, w: f32, thumbs: &mut Thumbs, wanted: &[(Source, NodeId
}
}
/// Draw the Assets panel: refresh libraries, switch to the libraries view when asked,
/// otherwise cache a listing keyed by revision, query and library state, render local and
/// Draw the Assets panel: repaint every `LIBRARY_REFRESH` while the file has libraries (so a
/// library changed on disk shows; the app's tick reads it), switch to the libraries view when
/// asked, otherwise cache a listing keyed by revision, query and library state, render local and
/// enabled-library assets with reused thumbnails, and dispatch place, style, hide, toggle
/// and drag actions.
pub fn show(app: &mut FigApp, ui: &mut Ui) {
refresh_libraries(app, ui);
if app.session.doc().is_ok_and(|d| !d.libraries.enabled.is_empty()) {
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(LIBRARY_REFRESH));
}
if app.ui.libraries {
libraries_view(app, ui);
return;
+132 -41
View File
@@ -31,6 +31,7 @@ use crate::widgets;
pub fn instance_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
let [id] = sel else {
combine_ui(app, ui, doc, sel);
instances_ui(app, ui, doc, sel);
return;
};
let Some(n) = doc.node(*id) else { return };
@@ -712,7 +713,7 @@ fn instance_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node) {
}
});
}
instance_props(app, ui, doc, n, &comps);
instance_props(app, ui, doc, &[n.id], &comps);
// Exposed nested instances: their properties, under their names.
if !nested {
for c in figcraft_engine::components::exposed_copies(doc, id) {
@@ -722,7 +723,7 @@ fn instance_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node) {
icons::paint(ui.painter(), r, Icon::Instance, crate::theme::COMPONENT);
ui.label(egui::RichText::new(&cn.name).font(semibold(11.0)).color(t.text));
});
instance_props(app, ui, doc, cn, &comps);
instance_props(app, ui, doc, &[cn.id], &comps);
}
}
}
@@ -732,38 +733,120 @@ fn nested_in_main(doc: &Document, id: NodeId) -> bool {
!inside_instance(doc, id) && figcraft_engine::components::owning_component(doc, id).is_some_and(|c| c != id)
}
/// Variant and component property controls for instance `n`.
fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps: &[(NodeId, String)]) {
let NodeKind::Instance { component, props } = &n.kind else { return };
let id = n.id;
let set = variant_set(doc, *component);
let slots = slots_of(doc, id);
/// The Instance section for a selection of two or more instances: the properties they share. A
/// selection with any other layer shows nothing.
fn instances_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
if sel.len() < 2 || !sel.iter().all(|id| matches!(doc.node(*id).map(|n| &n.kind), Some(NodeKind::Instance { .. }))) {
return;
}
let t = Tokens::get(ui.ctx());
let comps = local_components(app, ui, doc);
widgets::separator(ui);
row(ui, 36.0, |ui| {
ui.label(egui::RichText::new(tr("Instance")).font(semibold(11.0)).color(t.text));
});
instance_props(app, ui, doc, sel, &comps);
}
/// A variant property the selected instances share: the values every one of their sets has, and
/// the current value, None when it differs between them (Mixed).
struct SharedVariantProp {
name: String,
values: Vec<String>,
current: Option<String>,
}
/// A boolean, text, instance-swap or slot property the selected instances share, by name and type:
/// its definition (the first instance's) and the value, None when it differs between them (Mixed).
struct SharedProp {
name: String,
def: PropDef,
value: Option<Value>,
}
/// The variant and other properties of instance `id` with its own values (a property it doesn't
/// set has its default). None when `id` isn't an instance.
fn own_props(doc: &Document, id: NodeId) -> Option<(Vec<SharedVariantProp>, Vec<SharedProp>)> {
let Some(NodeKind::Instance { component, props }) = doc.node(id).map(|n| &n.kind) else { return None };
let current = doc.node(*component).map(|c| variant_props(&c.name)).unwrap_or_default();
let variants = variant_set(doc, *component)
.map(|set| variant_options(doc, set))
.unwrap_or_default()
.into_iter()
.map(|(name, values)| SharedVariantProp { current: Some(current.get(&name).cloned().unwrap_or_default()), name, values })
.collect();
let others = instance_prop_list(doc, *component)
.into_iter()
.map(|(name, def)| {
let value = props.get(&name).cloned().unwrap_or_else(|| figcraft_engine::components::prop_default_value(&def));
SharedProp { name, def, value: Some(value) }
})
.collect();
Some((variants, others))
}
/// The properties every instance in `ids` has, in the first one's order, with the values they share;
/// nothing when any of `ids` isn't an instance.
fn shared_props(doc: &Document, ids: &[NodeId]) -> (Vec<SharedVariantProp>, Vec<SharedProp>) {
let Some((first, rest)) = ids.split_first() else { return Default::default() };
let Some((mut variants, mut others)) = own_props(doc, *first) else { return Default::default() };
for id in rest {
let Some((own_variants, own_others)) = own_props(doc, *id) else { return Default::default() };
variants.retain_mut(|shared| {
let Some(own) = own_variants.iter().find(|o| o.name == shared.name) else { return false };
shared.values.retain(|v| own.values.contains(v));
if shared.current != own.current {
shared.current = None;
}
true
});
others.retain_mut(|shared| {
let Some(own) =
own_others.iter().find(|o| o.name == shared.name && std::mem::discriminant(&o.def) == std::mem::discriminant(&shared.def))
else {
return false;
};
if shared.value != own.value {
shared.value = None;
}
true
});
}
(variants, others)
}
/// Variant and component property controls for instances `ids`: the properties they share, set on
/// all of them at once. Slots show only for a single instance.
fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, ids: &[NodeId], comps: &[(NodeId, String)]) {
let (variants, others) = shared_props(doc, ids);
let slots = match ids {
[id] => slots_of(doc, *id),
_ => Vec::new(),
};
// Variant properties.
if let Some(set) = set {
let current = doc.node(*component).map(|c| variant_props(&c.name)).unwrap_or_default();
for (k, vals) in variant_options(doc, set) {
let cur = current.get(&k).cloned().unwrap_or_default();
row(ui, 32.0, |ui| {
prop_label(ui, &k, Icon::ComponentSet);
let w = ui.available_width().max(60.0);
// A string variable naming one of the values can choose it.
crate::variable_ui::bindable(app, ui, &[id], &format!("{PROP_BINDING}{k}"), VariableType::String, w, |app, ui| {
let resp = widgets::dropdown(ui, &cur, w, None);
menu_popup(&resp).show(|ui| {
for v in &vals {
if menu_item(ui, v, "") {
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): v}}));
ui.close();
}
for SharedVariantProp { name: k, values: vals, current } in variants {
row(ui, 32.0, |ui| {
prop_label(ui, &k, Icon::ComponentSet);
let w = ui.available_width().max(60.0);
// A string variable naming one of the values can choose it.
crate::variable_ui::bindable(app, ui, ids, &format!("{PROP_BINDING}{k}"), VariableType::String, w, |app, ui| {
let resp = widgets::dropdown(ui, current.as_deref().unwrap_or(tr("Mixed")), w, None);
menu_popup(&resp).show(|ui| {
for v in &vals {
if menu_item(ui, v, "") {
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): v}}));
ui.close();
}
});
}
});
});
}
});
}
// Boolean, text and instance-swap properties.
for (k, d) in instance_prop_list(doc, *component) {
let v = props.get(&k).cloned().unwrap_or_else(|| figcraft_engine::components::prop_default_value(&d));
for SharedProp { name: k, def: d, value } in others {
if matches!(d, PropDef::Slot { .. }) && !slots.iter().any(|(_, name)| *name == k) {
continue;
}
row(ui, 32.0, |ui| {
prop_label(ui, &k, type_icon(&d));
let w = ui.available_width().max(60.0);
@@ -771,26 +854,28 @@ fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps
let bind_field = format!("{PROP_BINDING}{k}");
match d {
PropDef::Boolean { .. } => {
crate::variable_ui::bindable(app, ui, &[id], &bind_field, VariableType::Boolean, w, |app, ui| {
let on = v.as_bool().unwrap_or(false);
if widgets::checkbox(ui, on, "") {
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): !on}}));
crate::variable_ui::bindable(app, ui, ids, &bind_field, VariableType::Boolean, w, |app, ui| {
let state = value.as_ref().map(|v| v.as_bool().unwrap_or(false));
if widgets::checkbox_tri(ui, state, "") {
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): !state.unwrap_or(false)}}));
}
});
}
PropDef::Text { .. } => {
crate::variable_ui::bindable(app, ui, &[id], &bind_field, VariableType::String, w, |app, ui| {
let cur = v.as_str().unwrap_or_default().to_string();
if let Some(ns) = widgets::text_field(ui, Id::unique(("iprop", id, k.as_str())), &cur, w, "")
crate::variable_ui::bindable(app, ui, ids, &bind_field, VariableType::String, w, |app, ui| {
let cur = value.as_ref().and_then(Value::as_str).unwrap_or_default().to_string();
let placeholder = if value.is_some() { "" } else { tr("Mixed") };
if let Some(ns) = widgets::text_field(ui, Id::unique(("iprop", ids, k.as_str())), &cur, w, placeholder)
&& ns != cur
{
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): ns}}));
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): ns}}));
}
});
}
PropDef::InstanceSwap { preferred, .. } => {
if let Some(c) = swap_dropdown(ui, doc, figcraft_engine::params::id_of(&v), &preferred, comps, w, &k).1 {
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): c.0}}));
let cur = value.as_ref().and_then(figcraft_engine::params::id_of);
if let Some(c) = swap_dropdown(ui, doc, cur, value.is_none(), &preferred, comps, w, &k).1 {
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): c.0}}));
}
}
PropDef::Variant { .. } => {}
@@ -806,18 +891,24 @@ fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps
/// The dropdown of an instance-swap property showing component `cur`: its menu lists the
/// property's preferred components first (when it has any), then every component in the file. The
/// dropdown, and the component picked (picking the current one picks nothing). `name` labels it for
/// assistive technology.
/// dropdown, and the component picked (picking the current one picks nothing). Without `cur` it reads
/// "Mixed" when `mixed` (the selected instances swap in different components), else "None". `name`
/// labels it for assistive technology.
pub(crate) fn swap_dropdown(
ui: &mut Ui,
doc: &Document,
cur: Option<NodeId>,
mixed: bool,
preferred: &[NodeId],
comps: &[(NodeId, String)],
w: f32,
name: &str,
) -> (egui::Response, Option<NodeId>) {
let label = cur.and_then(|c| doc.node(c)).map(|c| c.name.clone()).unwrap_or_else(|| tr("None").into());
let label = match cur.and_then(|c| doc.node(c)) {
Some(c) => c.name.clone(),
None if mixed => tr("Mixed").into(),
None => tr("None").into(),
};
let resp = widgets::dropdown(ui, &label, w, Some(Icon::Instance));
if !name.is_empty() {
crate::a11y::combo(&resp, name, &label, crate::a11y::menu_open(&resp));
+50 -1
View File
@@ -404,7 +404,8 @@ pub fn playground_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod
widgets::label(ui, name, t.text_secondary);
let preferred: Vec<NodeId> = p["preferred"].as_array().into_iter().flatten().filter_map(figcraft_engine::params::id_of).collect();
let w = ui.available_width().max(60.0);
if let Some(c) = crate::component_panel::swap_dropdown(ui, doc, figcraft_engine::params::id_of(value), &preferred, &comps, w, name).1
if let Some(c) =
crate::component_panel::swap_dropdown(ui, doc, figcraft_engine::params::id_of(value), false, &preferred, &comps, w, name).1
{
set = Some((name.to_string(), json!(c.0)));
}
@@ -481,11 +482,21 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
edit = Some(("name", v));
}
});
widgets::sublabels(ui, tr("Source file"), None);
row(ui, 32.0, |ui| {
let width = ui.available_width() - 2.0 * PAD;
if let Some(v) =
widgets::text_field(ui, Id::unique(("code_connect_source", owner, lang.id())), &link.source, width, "src/components/button.tsx")
{
edit = Some(("source", v));
}
});
widgets::sublabels(ui, tr("Template"), None);
if let Some(v) = widgets::multiline_field(ui, template_id(owner, lang), &link.template, "<Button size={size}>{label}</Button>", 3) {
edit = Some(("template", v));
}
widgets::note(ui, tr("{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written."), t.text_secondary);
variant_values(app, ui, doc, owner, lang, &link);
if let Some((key, value)) = edit {
let mut params = params;
params[key] = json!(value);
@@ -499,6 +510,44 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
ui.add_space(4.0);
}
/// The variant values of a connected component and what code calls them: a value left empty
/// stays as the design names it.
fn variant_values(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, lang: CodeLang, link: &CodeLink) {
let properties = code_connect::variants(doc, owner);
if properties.is_empty() {
return;
}
let mut change: Option<(String, String, String)> = None;
widgets::sublabels(ui, tr("Variant value"), Some(tr("In code")));
let col = widgets::col_width(ui.available_width());
for (property, options) in &properties {
for option in options {
let current = link.values.get(property).and_then(|m| m.get(option)).map_or("", String::as_str);
row(ui, 32.0, |ui| {
ui.spacing_mut().item_spacing.x = 8.0;
ui.allocate_ui_with_layout(vec2(col, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.set_min_width(col);
ui.add(egui::Label::new(format!("{property}: {option}")).truncate());
});
if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_value", owner, lang.id(), property, option)), current, col, option)
{
change = Some((property.clone(), option.clone(), v));
}
});
}
}
let Some((property, option, value)) = change else { return };
let mut values = link.values.clone();
let mapped = values.entry(property).or_default();
if value.trim().is_empty() {
mapped.remove(&option);
} else {
mapped.insert(option, value.trim().to_string());
}
values.retain(|_, m| !m.is_empty());
app.run("codeConnect.set", json!({"id": owner, "language": lang.id(), "values": values}));
}
/// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab.
pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) {
let runnable: Vec<(String, String, String)> = app
+56 -20
View File
@@ -556,8 +556,9 @@ pub(crate) fn list_width(ui: &Ui) -> f32 {
}
/// A name's room on a row stops growing here: a name of thousands of characters (#1650) elides
/// past it instead of making the list that wide.
pub(crate) const NAME_ROOM: f32 = 1200.0;
/// past it instead of making the list that wide. 400 pt still holds a long variant name
/// (`Size=small, Type=primary, State=default, Icon=leading, Width=full`) in full.
pub(crate) const NAME_ROOM: f32 = 400.0;
/// A row's name: the layer's, or its kind's label when it has none.
fn row_name(n: &figcraft_doc::Node) -> &str {
@@ -1018,20 +1019,34 @@ fn drop_layers(app: &mut FigApp, doc: &Document, rows: &[Row], moving: &[NodeId]
app.run("layers.reparent", json!({"ids": ids, "parent": parent.id, "index": index}));
}
/// The eye and padlock of a row: painted when hovered (`over`, false in Dev Mode) or set, and, outside
/// Dev Mode, clickable; a drag over them starts a sweep. Returns the layers whose eye / padlock was clicked.
fn eye_lock(
ui: &mut Ui,
t: &Tokens,
rects: [Rect; 2],
row: &Row,
n: &figcraft_doc::Node,
over: bool,
dev: bool,
sweep: &mut Option<Sweep>,
) -> (Option<NodeId>, Option<NodeId>) {
let [r, rr] = rects;
let (mut vis, mut lock) = (None, None);
/// The eye and padlock's span on a row (`rr`, the row inset 8 pt from each side) wider than the view:
/// its end stops 8 pt inside the view's edge, where it is on a row as wide as the view, but never so
/// far in that the buttons cover the row's disclosure triangle, icon or name start (`name_x`,
/// unmirrored). Returns that row span (what [`eye_lock`] places them at the end of) and the
/// buttons' 48 pt: the eye and padlock are 20 pt each, 4 pt from the end and 2 pt apart.
fn row_buttons(rr: Rect, view: Rect, name_x: f32, rtl: bool) -> (Rect, Rect) {
if rtl {
let name_start = rr.min.x + rr.max.x - name_x;
let end = Rect::from_min_max(pos2(rr.min.x.max((view.min.x + 8.0).min(name_start - 48.0)), rr.min.y), rr.max);
return (end, Rect::from_x_y_ranges(end.min.x..=(end.min.x + 48.0), rr.y_range()));
}
let end = Rect::from_min_max(rr.min, pos2(rr.max.x.min((view.max.x - 8.0).max(name_x + 48.0)), rr.max.y));
(end, Rect::from_x_y_ranges((end.max.x - 48.0)..=end.max.x, rr.y_range()))
}
/// Where a row's name is drawn: the view, less the eye and padlock's `buttons` while they show, so
/// a long name is clipped before them instead of drawn under them.
fn name_clip(view: Rect, buttons: Rect, buttons_shown: bool, rtl: bool) -> Rect {
match (buttons_shown, rtl) {
(false, _) => view,
(true, false) => Rect::from_x_y_ranges(view.min.x..=view.max.x.min(buttons.min.x), view.y_range()),
(true, true) => Rect::from_x_y_ranges(view.min.x.max(buttons.max.x)..=view.max.x, view.y_range()),
}
}
/// Whether row `r`'s layer shows as hidden and as locked: what a sweep in progress sets for the rows
/// it took in, else the layer's own state. The row joins the sweep when the pointer is on it.
fn swept_state(ui: &Ui, r: Rect, row: &Row, n: &figcraft_doc::Node, sweep: &mut Option<Sweep>) -> (bool, bool) {
// A sweep across the eyes or padlocks takes in the rows the pointer passes.
if let Some(sw) = sweep.as_mut()
&& !sw.ids.contains(&row.id)
@@ -1042,9 +1057,26 @@ fn eye_lock(
sw.ids.push(row.id);
}
let swept = |lock: bool| sweep.as_ref().filter(|sw| sw.lock == lock && sw.ids.contains(&row.id)).map(|sw| sw.on);
(swept(false).unwrap_or(!n.visible), swept(true).unwrap_or(n.locked))
}
/// The eye and padlock of a row, shown `hidden` and `locked` ([`swept_state`]): painted when hovered
/// (`over`, false in Dev Mode) or set, and, outside Dev Mode, clickable; a drag over them starts a
/// sweep. Returns the layers whose eye / padlock was clicked.
fn eye_lock(
ui: &mut Ui,
t: &Tokens,
rects: [Rect; 2],
row: &Row,
n: &figcraft_doc::Node,
(hidden, locked): (bool, bool),
over: bool,
dev: bool,
sweep: &mut Option<Sweep>,
) -> (Option<NodeId>, Option<NodeId>) {
let [r, rr] = rects;
let (mut vis, mut lock) = (None, None);
// Lock / eye on hover (or when set); a layer in a locked one shows a faint padlock.
let hidden = swept(false).unwrap_or(!n.visible);
let locked = swept(true).unwrap_or(n.locked);
// In Dev Mode they only show what is set.
let show_lock = over || locked || row.locked_above;
let show_eye = over || hidden;
@@ -1315,6 +1347,8 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
let icon_rect = Rect::from_center_size(pos2(fx(x0 + 22.0), r.center().y), vec2(14.0, 14.0));
icons::paint(ui.painter(), icon_rect, icon, icon_col);
let name_x = x0 + 36.0;
let (buttons_end, buttons) = row_buttons(rr, ui.clip_rect(), name_x, rtl);
let toggles = swept_state(ui, r, row, n, &mut sweep);
if app.ui.rename.is_some_and(|rn| rn.id == row.id) {
if let Some(new) = rename_field(app, ui, row.id, row.depth, &n.name, r) {
rename_done = Some((row.id, new));
@@ -1326,9 +1360,11 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
// Room before the lock and eye buttons (the row is wide enough for the whole
// name, up to `NAME_ROOM`: a row widened by a deeper name gives no more).
let max_w = (rr.max.x - 56.0 - name_x).clamp(20.0, NAME_ROOM);
crate::bidi::paint_name_from(ui.painter(), pos2(fx(name_x), r.center().y), rtl, &name, font, col, max_w);
let buttons_shown = (over && !dev) || toggles.0 || toggles.1 || row.locked_above;
let clip = name_clip(ui.clip_rect(), buttons, buttons_shown, rtl);
crate::bidi::paint_name_from(&ui.painter().with_clip_rect(clip), pos2(fx(name_x), r.center().y), rtl, &name, font, col, max_w);
}
let (v, l) = eye_lock(ui, &t, [r, rr], row, n, over && !dev, dev, &mut sweep);
let (v, l) = eye_lock(ui, &t, [r, buttons_end], row, n, toggles, over && !dev, dev, &mut sweep);
vis = v.or(vis);
lock = l.or(lock);
if resp.clicked() {
+132 -13
View File
@@ -44,22 +44,92 @@ pub(crate) fn preview_blend(app: &mut FigApp, ctx: &egui::Context, ids: &[NodeId
/// (else its 600 px default area width) and keeps the size measured; rows ([`menu_row`]) take the
/// larger of that width and their content, so the menu fits its content. Chain `.width(w)` for a
/// menu at least `w` wide.
pub fn menu_popup(anchor: &egui::Response) -> egui::Popup<'static> {
egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style)
pub fn menu_popup(anchor: &egui::Response) -> Menu {
Menu(egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style))
}
/// A context menu (secondary click on `resp`) sized like [`menu_popup`].
pub fn context_popup(resp: &egui::Response) -> egui::Popup<'static> {
egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style)
pub fn context_popup(resp: &egui::Response) -> Menu {
Menu(egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style))
}
/// A context menu for a property row: a secondary click anywhere over `rect` opens it, even over
/// the row's fields (which would otherwise take the click), like the incumbent's row menus.
pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> egui::Popup<'static> {
pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> Menu {
let resp = ui.interact(rect, id, Sense::hover());
let open = ui.rect_contains_pointer(rect) && ui.input(|i| i.pointer.secondary_clicked());
let at_pointer = egui::Popup::menu(&resp).width(MENU_MIN_W).style(menu_style).at_pointer_fixed();
at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true)))
Menu(at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true))))
}
/// The gap a menu taller than the window keeps from the window's top and bottom edges.
const MENU_WINDOW_GAP: f32 = 8.0;
/// A popup menu ([`menu_popup`], [`context_popup`]) whose rows scroll when it would be taller
/// than the window. egui keeps a popup inside the window by moving it, but one taller than the
/// window runs off its edge, and rows past it can't be reached.
#[must_use]
pub struct Menu(egui::Popup<'static>);
impl Menu {
/// At least `width` wide.
pub fn width(self, width: f32) -> Self {
Self(self.0.width(width))
}
/// Open and closed under `id` instead of the anchor's.
pub fn id(self, id: Id) -> Self {
Self(self.0.id(id))
}
pub fn close_behavior(self, behavior: egui::PopupCloseBehavior) -> Self {
Self(self.0.close_behavior(behavior))
}
/// Where the menu may go when its first placement doesn't fit, in order.
pub fn align_alternatives(self, alternatives: &'static [egui::RectAlign]) -> Self {
Self(self.0.align_alternatives(alternatives))
}
/// Show the menu while it is open. Its rows `content` scroll with the wheel or the scroll bar
/// once they were taller than the window last frame, as the main menu's do (#2217); a menu
/// that fits is laid out as it is, so it still grows with its rows (a scroll area in a popup
/// would keep the popup's last height). A click on the scroll bar scrolls and leaves the menu
/// open. The rows have the same ids scrolling or not, so the row the keyboard is on keeps it
/// when the window's height changes which of the two the menu does.
pub fn show<R>(self, content: impl FnOnce(&mut Ui) -> R) -> Option<egui::InnerResponse<R>> {
let rows = self.0.get_id().with("menu_rows");
let bar_key = rows.with("scroll_bar");
let ctx = self.0.ctx().clone();
let bar_clicked = ctx.data(|d| d.get_temp::<Id>(bar_key)).is_some_and(|bar| ctx.interaction_snapshot(|i| i.clicked == Some(bar)));
let popup = if bar_clicked { self.0.close_behavior(egui::PopupCloseBehavior::IgnoreClicks) } else { self.0 };
let rows_ui = egui::UiBuilder::new().scope_id(rows);
popup.show(|ui| {
let window = ui.ctx().content_rect().height();
let max_height = (window - ui.style().spacing.menu_margin.sum().y - 2.0 * MENU_WINDOW_GAP).max(0.0);
let rows_height = ui.scope_id().with("menu_rows_height");
let last = ui.data(|d| d.get_temp::<f32>(rows_height)).unwrap_or(0.0);
let (inner, height) = if last > max_height {
let out = egui::ScrollArea::vertical()
.id_salt("menu_rows")
.max_height(max_height)
.scroll_source(egui::scroll_area::ScrollSource::MOUSE_WHEEL | egui::scroll_area::ScrollSource::SCROLL_BAR)
.show(ui, |ui| ui.scope_builder(rows_ui, content).inner);
// egui's id for a scroll area's vertical bar (a test in `menu_scroll_tests` clicks it).
ui.data_mut(|d| d.insert_temp(bar_key, out.id.with(1_usize)));
(out.inner, out.content_size.y)
} else {
let inner = ui.scope_builder(rows_ui, content).inner;
let height = ui.min_rect().height();
if height > max_height {
ui.ctx().request_repaint();
}
(inner, height)
};
ui.data_mut(|d| d.insert_temp(rows_height, height));
inner
})
}
}
pub fn menu_item(ui: &mut Ui, label: &str, shortcut: &str) -> bool {
@@ -116,12 +186,23 @@ fn lit_row(
// These menus sit on the theme's popup fill (white in the light theme), not on the dark
// `t.menu` of the menu bar: the theme's text, white only on the green highlight (#972).
let col = if hovered { t.menu_text } else { t.text };
ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col);
if let Some(k) = keys {
let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0);
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
let rtl = crate::widgets::rtl(ui);
if rtl {
ui.painter().galley(pos2(r.max.x - MENU_PAD - lead - text.size().x, r.center().y - text.size().y / 2.0), text, col);
if let Some(k) = keys {
let at = pos2(r.min.x + MENU_PAD, r.center().y - k.size().y / 2.0);
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
}
} else {
ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col);
if let Some(k) = keys {
let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0);
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
}
}
art(ui.painter(), r, col);
// In RTL, anchor right-aligned trailing artwork near the reading end (left) so it stays opposite the label.
let art_r = if rtl && art_w > 0.0 { Rect::from_min_max(r.min, pos2((r.min.x + art_w + MENU_PAD).min(r.max.x), r.max.y)) } else { r };
art(ui.painter(), art_r, col);
resp
}
@@ -196,16 +277,54 @@ const CHECK_COL: f32 = 14.0;
/// `Some(true)`) is drawn in its own column ahead of the icon, so a checked entry's label does
/// not move against the unchecked ones.
pub fn menu_icon_item(ui: &mut Ui, icon: Option<crate::icons::Icon>, on: Option<bool>, label: &str, shortcut: &str) -> bool {
let rtl = crate::widgets::rtl(ui);
let paint = |p: &egui::Painter, r: Rect, col: Color32| {
if on == Some(true) {
let mark = p.layout_no_wrap("✓".to_owned(), regular(11.5), col);
p.galley(pos2(r.min.x + MENU_PAD, r.center().y - mark.size().y / 2.0), mark, col);
let x = if rtl { r.max.x - MENU_PAD - mark.size().x } else { r.min.x + MENU_PAD };
p.galley(pos2(x, r.center().y - mark.size().y / 2.0), mark, col);
}
if let Some(icon) = icon {
crate::icons::paint(p, Rect::from_min_size(pos2(r.min.x + MENU_PAD + CHECK_COL, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col);
let x = if rtl { r.max.x - MENU_PAD - CHECK_COL - 16.0 } else { r.min.x + MENU_PAD + CHECK_COL };
crate::icons::paint(p, Rect::from_min_size(pos2(x, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col);
}
};
let resp = lit_row(ui, label, shortcut, 0.0, CHECK_COL + 22.0, paint, false);
a11y::menu_item(&resp, label, shortcut, on);
resp.clicked()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rtl_lit_row_places_art_opposite_label() {
let ctx = egui::Context::default();
ctx.all_styles_mut(|s| s.right_to_left = true);
let mut art_rect = None;
ctx.run_ui(Default::default(), |ui| {
egui::Area::new(egui::Id::unique("menu-rtl-test")).fixed_pos(pos2(0.0, 0.0)).show(ui.ctx(), |ui| {
ui.set_width(220.0);
let _ = lit_row(
ui,
"קצוות עגולים",
"",
64.0,
0.0,
|_pt, r, _| {
art_rect = Some(r);
},
false,
);
});
})
.textures_delta
.clear();
let art_r = art_rect.expect("art invoked");
// Artwork paints relative to art_r.max.x in [art_r.max.x - 64.0, art_r.max.x],
// so its right edge stays on the left side while the RTL label sits at r.max.x - MENU_PAD.
assert!((art_r.max.x - (art_r.min.x + 64.0 + MENU_PAD)).abs() < 0.01, "art_r={art_r:?}");
assert!(art_r.max.x < 100.0, "expected trailing left placement, got {art_r:?}");
}
}
+1 -1
View File
@@ -116,10 +116,10 @@ fn report(layers: usize) {
let open: Vec<NodeId> = b.app.session.doc().unwrap().nodes().filter(|n| !n.children.is_empty()).map(|n| n.id).collect();
b.app.ui.expanded.extend(open);
rows.push(("first frame, every layer expanded", b.frame(vec![])));
b.app.ui.layers_focus = true;
let top = b.app.session.doc().ok().and_then(|d| d.node(page)?.children.last().copied());
b.app.session.set_selection(top.into_iter().collect());
b.frame(vec![]);
b.frame(key(Key::F6, Modifiers::SHIFT));
rows.push(("arrow key down the expanded layers", b.mean(30, |_| key(Key::ArrowDown, Modifiers::NONE))));
b.app.ui.expanded.clear();
b.frame(vec![]);
+66
View File
@@ -0,0 +1,66 @@
//! The pixel grid, drawn headless: from 400% its lines are one screen pixel wide and a grey that
//! shows on a white frame and on the dark canvas alike, as in Figma.
use egui::{Color32, RawInput, Shape, ViewportId, ViewportInfo};
use figcraft_engine::Session;
use serde_json::json;
use crate::canvas::overlays::PIXEL_GRID;
use crate::layers_drag_tests::Ui;
use crate::live_tests::flat;
/// Each grid line drawn in a frame on a screen of `native` pixels per point (the last of a few,
/// for a new scale to take effect): its width and the coordinate it runs along, its x if
/// vertical and its y if horizontal.
fn grid_lines(u: &mut Ui, native: f32) -> Vec<(f32, f32)> {
let mut out = None;
for _ in 0..4 {
let mut raw = RawInput::default();
raw.viewports.insert(ViewportId::ROOT, ViewportInfo { native_pixels_per_point: Some(native), ..Default::default() });
out = Some(u.frame_raw(raw));
}
let shapes = flat(&out.map(|o| o.shapes).unwrap_or_default());
shapes
.iter()
.filter_map(|s| match s {
Shape::LineSegment { points: [a, b], stroke } if stroke.color == PIXEL_GRID => Some((stroke.width, if a.x == b.x { a.x } else { a.y })),
_ => None,
})
.collect()
}
/// Whether every line in `lines` sits on the middle of a row or column of pixels of a screen of
/// `native` pixels per point, so it covers that one pixel and no half of two.
fn on_pixel_centres(lines: &[(f32, f32)], native: f32) -> bool {
lines.iter().all(|(_, at)| ((at * native - 0.5) - (at * native - 0.5).round()).abs() < 1e-3)
}
/// `c` drawn over a grey of `bg`, as the canvas blends it.
fn over(c: Color32, bg: u8) -> f32 {
let [r, _, _, a] = c.to_srgba_unmultiplied();
let a = f32::from(a) / 255.0;
f32::from(bg) * (1.0 - a) + f32::from(r) * a
}
#[test]
fn the_pixel_grid_shows_on_white_and_on_dark_one_screen_pixel_wide() {
let mut s = Session::new();
s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
let mut u = Ui::new(s);
let view = &mut u.app.session.ds_mut().unwrap().view;
view.zoom = 8.0;
// A view between whole points, so the page's pixels fall between the screen's.
(view.cx, view.cy) = (50.03, 50.07);
let lines = grid_lines(&mut u, 1.0);
assert!(!lines.is_empty(), "the grid draws at 800%");
assert!(lines.iter().all(|(w, _)| *w == 1.0), "one screen pixel: {lines:?}");
assert!(on_pixel_centres(&lines, 1.0), "on the screen's pixels: {lines:?}");
// Measured in Figma (2026-11-24): a grid line is 242 on white and 78 on a grey of 50.
assert_eq!((over(PIXEL_GRID, 255).round(), over(PIXEL_GRID, 50).round()), (242.0, 78.0));
// On a 2x screen the lines stay one of its pixels wide.
let lines = grid_lines(&mut u, 2.0);
assert!(!lines.is_empty() && lines.iter().all(|(w, _)| *w == 0.5), "{lines:?}");
assert!(on_pixel_centres(&lines, 2.0), "on the 2x screen's pixels: {lines:?}");
u.app.session.ds_mut().unwrap().view.zoom = 3.0;
assert!(grid_lines(&mut u, 2.0).is_empty(), "no grid below 400%");
}
+13 -4
View File
@@ -73,7 +73,12 @@ fn toast(app: &FigApp) -> &str {
}
fn expected_picker() -> Vec<(String, String, Vec<String>)> {
vec![("Save as".into(), "Prototype.figcraft".into(), vec!["figcraft".into(), "fig".into()])]
picker_named("Prototype")
}
/// The Save as picker suggesting `name` with the native extension.
fn picker_named(name: &str) -> Vec<(String, String, Vec<String>)> {
vec![("Save as".into(), format!("{name}.figcraft"), vec!["figcraft".into(), "fig".into()])]
}
#[test]
@@ -124,7 +129,8 @@ fn native_paths_and_an_extensionless_default_save_native_files_and_show_the_writ
let mut reopened = Session::empty();
reopened.execute("file.open", &json!({"path": path})).unwrap();
assert_eq!(reopened.doc().unwrap().nodes().count(), app.session.doc().unwrap().nodes().count());
assert_eq!(reopened.doc().unwrap().name, "Prototype");
let stem = std::path::Path::new(written).file_stem().unwrap().to_str().unwrap();
assert_eq!(reopened.doc().unwrap().name, stem, "named after the file it was saved as");
}
}
@@ -261,16 +267,19 @@ fn saving_legacy_fig_paths_keeps_the_success_toast_and_original_source_bytes() {
let legacy_bytes = std::fs::read(&legacy).unwrap();
app.save();
app.poll_dialog(&egui::Context::default());
assert_eq!(*picks.lock().unwrap(), expected_picker());
assert_eq!(*picks.lock().unwrap(), picker_named("original"), "named after the file it was saved as first");
assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes);
assert!(target.is_file());
assert!(app.ui.last_error.is_none());
assert_eq!(app.session.doc().unwrap(), &before);
if destination == "corrected.figcraft" {
let mut renamed = before.clone();
renamed.name = "corrected".into();
assert_eq!(app.session.doc().unwrap(), &renamed, "saved to another file: named after it");
assert_eq!(toast(&app), "Saved corrected.figcraft");
assert_eq!(app.session.ds().unwrap().path.as_deref(), target.to_str());
assert!(!app.session.ds().unwrap().is_dirty());
} else {
assert_eq!(app.session.doc().unwrap(), &before, "an export leaves the document alone");
assert_eq!(toast(&app), "Exported copy.fig");
assert_eq!(app.session.ds().unwrap().path.as_deref(), Some(legacy_path.as_str()));
assert!(app.session.ds().unwrap().is_dirty());
+15 -2
View File
@@ -2,8 +2,8 @@
//! headless: arrows pan with nothing selected, the keyboard box selection key and Cmd/Ctrl+arrows
//! drawing it out, list indentation while editing text, symbols another keyboard layout types with
//! Shift, the presentation keys (Space and N forward, C comments, F full screen), Alt+R for the
//! rotation origin, Enter placing a shape with its tool chosen and Cmd/Ctrl+= and - zooming the
//! canvas, not the interface.
//! rotation origin, Enter placing a shape with its tool chosen, Cmd/Ctrl+= and - zooming the
//! canvas, not the interface, and Shift+Cmd/Ctrl+' saying whether it snaps to the pixel grid.
use egui::{Event, Key, Modifiers, ViewportCommand, ViewportId};
use figcraft_doc::NodeId;
@@ -299,3 +299,16 @@ fn cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift() {
assert!((rot(&u) - rot_before).abs() < 1e-6, "no turn while editing points");
u.app.run("vector.edit.end", json!({}));
}
#[test]
fn shift_cmd_quote_says_whether_snapping_to_the_pixel_grid_is_on() {
let mut u = Ui::new(Session::new());
let toast = |u: &Ui| u.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default();
let snap = |u: &Ui| u.app.session.ds().unwrap().view.snap_pixel;
press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT);
assert!(!snap(&u));
assert_eq!(toast(&u), "Snap to pixel grid off");
press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT);
assert!(snap(&u));
assert_eq!(toast(&u), "Snap to pixel grid on");
}
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more