mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-09 03:48:56 +00:00
Merge upstream/main into fix/scrub-speed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+4
-1
File diff suppressed because one or more lines are too long
@@ -68,7 +68,9 @@ impl Backend for Store {
|
||||
Err(err) => log::error!("file {file}: a change couldn't be logged: {err}"),
|
||||
}
|
||||
}
|
||||
log.entries += journal.len();
|
||||
// A refusal changes nothing in the document: it counts toward the log's size (bytes), but
|
||||
// not toward the entries that make a snapshot rewrite worthwhile.
|
||||
log.entries += journal.iter().filter(|j| !matches!(j, figcraft_collab::Journal::Refused { .. })).count();
|
||||
log.dirty = true;
|
||||
e.meta.updated = now();
|
||||
if log.entries >= after || log.bytes + log.pending.len() as u64 >= max_bytes {
|
||||
|
||||
@@ -155,6 +155,24 @@ fn read_only_sessions_keep_client_ids_without_rewriting_the_snapshot() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_viewers_refused_batches_do_not_rewrite_the_snapshot() {
|
||||
let dir = TempDir::new("refusals");
|
||||
let c = StoreConfig { compact_after: 3, ..cfg(dir.path()) };
|
||||
let mut store = Store::open(dir.path(), c).unwrap();
|
||||
let (id, _, _) = publish(&mut store, "Busy");
|
||||
let mut server = store.open(&id).unwrap();
|
||||
let mut v = join(&mut server, Access::View);
|
||||
store.changed(&id, &mut server);
|
||||
let generation = || disk::check_snapshot(&fs::read(dir.path().join(FILES).join(&id).join(SNAPSHOT)).unwrap()).unwrap();
|
||||
assert_eq!(generation(), 1);
|
||||
for i in 0..10 {
|
||||
rename(&mut server, &mut v, &format!("P{i}"));
|
||||
store.changed(&id, &mut server);
|
||||
}
|
||||
assert_eq!(generation(), 1, "refusals are logged, not compacted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_log_is_compacted_while_open() {
|
||||
let dir = TempDir::new("compact");
|
||||
|
||||
@@ -217,7 +217,8 @@ impl Recovery {
|
||||
return false;
|
||||
}
|
||||
let _ = match online {
|
||||
Some(text) => std::fs::write(¬e, text),
|
||||
// The note holds the secret the client resumes with: owner-only, as the copy.
|
||||
Some(text) => write_private(¬e, text.as_bytes()),
|
||||
None => std::fs::remove_file(¬e),
|
||||
};
|
||||
true
|
||||
@@ -326,24 +327,29 @@ fn rejoin_online(file: &Path, s: &mut Session) -> Option<u64> {
|
||||
fn write_atomic(path: &Path, doc: &figcraft_engine::doc::Document, versions: &[Version], branches: &[Branch]) -> bool {
|
||||
let Ok(bytes) = figcraft_format::save_bytes_with_history(doc, None, versions, branches) else { return false };
|
||||
let tmp = path.with_extension("tmp");
|
||||
if write_private(&tmp, &bytes).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return false;
|
||||
}
|
||||
std::fs::rename(&tmp, path).is_ok()
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path`, created (or cut back) readable by its owner only on Unix.
|
||||
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create(true).truncate(true).mode(0o600);
|
||||
let Ok(mut f) = opts.open(&tmp) else { return false };
|
||||
if std::io::Write::write_all(&mut f, &bytes).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return false;
|
||||
}
|
||||
let mut f = opts.open(path)?;
|
||||
// `mode` applies to a new file only: one that was there keeps its mode unless set.
|
||||
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
|
||||
std::io::Write::write_all(&mut f, bytes)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
if std::fs::write(&tmp, bytes).is_err() {
|
||||
return false;
|
||||
}
|
||||
std::fs::write(path, bytes)
|
||||
}
|
||||
std::fs::rename(&tmp, path).is_ok()
|
||||
}
|
||||
|
||||
/// [`recover_all`], for a start that keeps nothing waiting: how many documents came back as
|
||||
|
||||
@@ -206,7 +206,17 @@ fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> {
|
||||
|
||||
/// The next answer `pick` takes, or why there is none.
|
||||
fn reply<T>(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option<T>) -> Result<T, String> {
|
||||
// One deadline for the whole answer: pings, pongs and a message trickling in each renew the
|
||||
// read timeout, so without it a server could keep a request (and the refresh permit the
|
||||
// caller holds) waiting for as long as it liked.
|
||||
// The request-reply bound, not the session idle one: a publish uploads a whole file and can
|
||||
// legitimately take minutes to be answered (see `connect`).
|
||||
let until = std::time::Instant::now() + limits.request_reply_timeout;
|
||||
ws.get_mut().read_until(Some(until));
|
||||
loop {
|
||||
if std::time::Instant::now() >= until {
|
||||
return Err("no answer from the server (it took too long)".into());
|
||||
}
|
||||
return match ws.read() {
|
||||
Ok(Message::Binary(b)) => match message::decode::<ServerMsg>(&b, limits.max_server_message) {
|
||||
Ok(ServerMsg::Refused { reason }) => Err(format!("{REFUSED}{reason}")),
|
||||
@@ -251,6 +261,27 @@ mod tests {
|
||||
rx.recv_timeout(Duration::from_secs(3)).is_ok()
|
||||
}
|
||||
|
||||
/// A server that keeps pinging and never answers ends the wait at the request-reply bound.
|
||||
#[test]
|
||||
fn reply_gives_up_at_the_request_reply_deadline_against_a_pinging_server() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
if let Ok(mut ws) = tungstenite::accept(s) {
|
||||
while ws.send(Message::Ping(Bytes::new())).is_ok() {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
});
|
||||
let limits = NetLimits { request_reply_timeout: Duration::from_millis(400), ..NetLimits::default() };
|
||||
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
|
||||
let mut ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
assert!(reply::<()>(&mut ws, &limits, |_| None).is_err());
|
||||
assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// A server that keeps pinging and never answers the close must not pin `close` forever.
|
||||
#[test]
|
||||
fn close_returns_against_a_server_that_keeps_pinging() {
|
||||
|
||||
@@ -28,6 +28,11 @@ pub fn openable(url: &str) -> bool {
|
||||
if url.is_empty() || url.chars().any(char::is_control) {
|
||||
return false;
|
||||
}
|
||||
// Never valid in a URL unencoded, and read as syntax by the shells some openers go through
|
||||
// (webbrowser on WSL hands the address to `cmd.exe /c start`, escaping only `&` and `^`).
|
||||
if url.chars().any(|c| c.is_whitespace() || matches!(c, '|' | '<' | '>' | '"' | '`' | '\\' | '^')) {
|
||||
return false;
|
||||
}
|
||||
let Some((scheme, rest)) = url.split_once(':') else { return false };
|
||||
// An RFC 3986 scheme, so a stray colon in text cannot look like one.
|
||||
let mut chars = scheme.chars();
|
||||
@@ -44,5 +49,11 @@ pub fn openable(url: &str) -> bool {
|
||||
// `http` and `https` name a host, so the authority is required: `http:x` is not a web link,
|
||||
// and `http:///p` has no host.
|
||||
let Some(after) = rest.strip_prefix("//") else { return false };
|
||||
!after.is_empty() && !after.starts_with('/')
|
||||
if after.is_empty() || after.starts_with('/') {
|
||||
return false;
|
||||
}
|
||||
// The authority is made of host characters only (an opener that can't parse the address may
|
||||
// fall back to treating it as a file path).
|
||||
let authority = after.split(['/', '?', '#']).next().unwrap_or_default();
|
||||
authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
|
||||
}
|
||||
|
||||
@@ -277,6 +277,14 @@ pub fn read_capped(path: impl AsRef<Path>, max: u64) -> Result<Vec<u8>> {
|
||||
return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max))));
|
||||
}
|
||||
let f = std::fs::File::open(p).map_err(io(path))?;
|
||||
// What was opened, not what was looked at: the path could have been swapped in between.
|
||||
let meta = f.metadata().map_err(io(path))?;
|
||||
if !meta.is_file() {
|
||||
return Err(refuse("isn't a regular file (a device or a pipe?), so it isn't read".into()));
|
||||
}
|
||||
if meta.len() > max {
|
||||
return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max))));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
|
||||
f.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(io(path))?;
|
||||
// It grew after it was looked at.
|
||||
|
||||
@@ -104,3 +104,31 @@ fn the_next_sticky_shortcut_joins_the_next_shape_and_leaves_stickies_as_they_wer
|
||||
assert!(r.get("connector").is_none(), "{r}");
|
||||
assert!(matches!(node(&s, id(&r, "id")).board, Some(BoardItem::Sticky { .. })));
|
||||
}
|
||||
|
||||
/// `at` (#1919; "drag the preview to any location on your board", Build faster with quick create):
|
||||
/// the next one is centred on that point, wherever it is, and the connector takes the sides facing
|
||||
/// each other; `at` must be two finite numbers.
|
||||
#[test]
|
||||
fn the_next_one_goes_where_it_is_dropped() {
|
||||
let mut s = board();
|
||||
let a = id(&s.execute("board.shape", &json!({"shape": "diamond", "x": 0, "y": 0, "width": 200, "height": 120})).unwrap(), "id");
|
||||
let r = s.execute("board.addConnected", &json!({"id": a, "side": "below", "at": [700, 60]})).unwrap();
|
||||
let (b, c) = (id(&r, "id"), id(&r, "connector"));
|
||||
assert_eq!(at(&s, b), (600.0, 0.0), "centred on the point");
|
||||
let k = connector(&s, c);
|
||||
assert_eq!(
|
||||
(k.from, k.to),
|
||||
(End::Node { node: a, side: Side::Bottom, at: None }, End::Node { node: b, side: Side::Auto, at: None }),
|
||||
"leaves by the handle's side"
|
||||
);
|
||||
// Inside a frame at (1000, 500): the page point lands in the frame's coordinates.
|
||||
let f = id(&s.execute("frame.create", &json!({"x": 1000, "y": 500, "width": 800, "height": 600})).unwrap(), "id");
|
||||
let inner = id(&s.execute("board.shape", &json!({"shape": "ellipse", "x": 0, "y": 0, "width": 200, "height": 120, "parent": f})).unwrap(), "id");
|
||||
let r = s.execute("board.addConnected", &json!({"id": inner, "at": [1300, 700]})).unwrap();
|
||||
let placed = id(&r, "id");
|
||||
assert_eq!(node(&s, placed).parent, Some(f), "beside it, in the frame");
|
||||
assert_eq!(at(&s, placed), (200.0, 140.0), "centred on the page point, in the frame's coordinates");
|
||||
for wrong in [json!([1]), json!("x"), json!([0, "y"]), json!({"x": 1, "y": 2})] {
|
||||
assert!(s.execute("board.addConnected", &json!({"id": a, "at": wrong})).is_err(), "{wrong}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,36 @@ pub use connectors::{END_HANDLE_PX, selected_connector_ends};
|
||||
use connectors::{connector_cmd, reattach};
|
||||
pub use derived::route;
|
||||
pub(crate) use derived::{settle_routes, settle_stamps, settle_text, stamp_target};
|
||||
|
||||
/// The topmost sticky or shape at `p` on `page`, other than `except`, sections and frames looked
|
||||
/// into: what a "+" handle dragged onto it joins (#1919).
|
||||
pub fn sticky_or_shape_at(doc: &Document, page: NodeId, p: Point, except: Option<NodeId>) -> Option<NodeId> {
|
||||
fn find(doc: &Document, id: NodeId, p: Point, except: Option<NodeId>, depth: usize) -> Option<NodeId> {
|
||||
let n = doc.node(id)?;
|
||||
for c in n.children.iter().rev() {
|
||||
let Some(k) = doc.node(*c) else { continue };
|
||||
if !k.visible {
|
||||
continue;
|
||||
}
|
||||
match k.board {
|
||||
Some(BoardItem::Sticky { .. } | BoardItem::Shape { .. }) => {
|
||||
if Some(*c) != except && doc.world_bounds(*c).is_some_and(|b| b.contains(p)) {
|
||||
return Some(*c);
|
||||
}
|
||||
}
|
||||
// Not a board object of its own (a section, a frame): what is inside it may be.
|
||||
None if depth < 32 => {
|
||||
if let Some(hit) = find(doc, *c, p, except, depth + 1) {
|
||||
return Some(hit);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(doc, page, p, except, 0)
|
||||
}
|
||||
pub use edit::label_of;
|
||||
pub(crate) use edit::{copied_items, copy_map, rejoin};
|
||||
use edit::{label_cmd, set_color, set_style};
|
||||
@@ -114,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"board.addConnected",
|
||||
"Add connected shape",
|
||||
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector",
|
||||
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), at? ([x, y] on the page: the next one's centre, anywhere, instead of its place on that side; the connector then leaves by `side` and arrives by the side facing it), edit? (start typing in it; default false)} → {id, text, connector} the next one of the same kind, size and colour on that side, joined by a connector",
|
||||
true,
|
||||
add_connected
|
||||
),
|
||||
|
||||
@@ -223,6 +223,19 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let color = color.unwrap_or(s.tool.board.sticky);
|
||||
let (to_at, from_side, to_side) = connected_place((at.x, at.y), (n.width, n.height), next, &side)
|
||||
.ok_or_else(|| bad(cmd, format!("`side` is right, below, left or above, not `{side}`")))?;
|
||||
// Dropped somewhere by hand ("drag the preview to any location on your board", #1919): the
|
||||
// next one is centred on that point of the page (placed in the parent's coordinates), and the
|
||||
// connector leaves by the handle's side and arrives by the side facing it.
|
||||
let (to_at, from_side, to_side) = match drop_point(cmd, p)? {
|
||||
Some((x, y)) => {
|
||||
let local = doc.world_transform(parent).inverse() * figcraft_geom::Point::new(x, y);
|
||||
if !(local.x.is_finite() && local.y.is_finite()) {
|
||||
return Err(bad(cmd, "`at` can't be placed in that parent"));
|
||||
}
|
||||
((local.x - next.0 / 2.0, local.y - next.1 / 2.0), from_side, Side::Auto)
|
||||
}
|
||||
None => (to_at, from_side, to_side),
|
||||
};
|
||||
let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?);
|
||||
if editing.is_some() {
|
||||
textedit::end(s)?;
|
||||
@@ -246,6 +259,16 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"id": id, "text": text, "connector": line}))
|
||||
}
|
||||
|
||||
/// `at?` of `board.addConnected`: a point on the page, `[x, y]`, or none.
|
||||
fn drop_point(cmd: &str, p: &Value) -> Result<Option<(f64, f64)>> {
|
||||
let Some(v) = get(p, "at") else { return Ok(None) };
|
||||
let pair = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)));
|
||||
match pair {
|
||||
Some((x, y)) if x.is_finite() && y.is_finite() => Ok(Some((x, y))),
|
||||
_ => Err(bad(cmd, "`at` is [x, y] on the page, two finite numbers")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape with text's layers: the frame, its outline and its text.
|
||||
fn make_shape(
|
||||
doc: &mut Document,
|
||||
|
||||
@@ -193,6 +193,7 @@ impl Session {
|
||||
}
|
||||
// New text at the click (Figma puts the baseline-ish top-left there).
|
||||
let parent = frame_at(&doc, page, ev.p(), &[]).unwrap_or(page);
|
||||
let defaults = self.default_props.text.clone();
|
||||
let ds = self.ds_mut()?;
|
||||
let d = ds.doc_mut();
|
||||
let id = d.alloc_id();
|
||||
@@ -204,12 +205,18 @@ impl Session {
|
||||
if let Some(fills) = readable_text_fills(d, parent) {
|
||||
n.fills = fills;
|
||||
}
|
||||
if let Some((w, h)) = figcraft_text::auto_size(&n) {
|
||||
n.width = w.max(1.0);
|
||||
n.height = h;
|
||||
}
|
||||
let line = n.height;
|
||||
d.insert(n, parent, None)?;
|
||||
// Edit ▸ Set default properties from a text layer: its fills and font (best effort).
|
||||
if let Some(defaults) = &defaults {
|
||||
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", d, id, defaults);
|
||||
}
|
||||
let line = d.node_mut(id).map_or(14.0, |n| {
|
||||
if let Some((w, h)) = figcraft_text::auto_size(n) {
|
||||
n.width = w.max(1.0);
|
||||
n.height = h;
|
||||
}
|
||||
n.height
|
||||
});
|
||||
ds.selection = vec![id];
|
||||
textedit::begin(self, id, Some(0), true)?;
|
||||
self.tool.gesture = Gesture::TextBox { id, start: ev.p(), line };
|
||||
|
||||
@@ -42,6 +42,13 @@ impl Session {
|
||||
}
|
||||
let mut created = id;
|
||||
let page = self.page()?;
|
||||
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
|
||||
// or arrows, which keep their own look).
|
||||
let defaults = if matches!(tool, ToolId::Rectangle | ToolId::Ellipse | ToolId::Polygon | ToolId::Star) {
|
||||
self.default_props.shape.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.preview(|doc, sel| {
|
||||
let (mut a, b) = (start, p);
|
||||
if pixel {
|
||||
@@ -92,6 +99,10 @@ impl Session {
|
||||
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
|
||||
}
|
||||
doc.insert(n, parent, None)?;
|
||||
if let Some(d) = &defaults {
|
||||
// Best effort: a default the shape can't take leaves it as drawn.
|
||||
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
|
||||
}
|
||||
*sel = vec![nid];
|
||||
created = Some(nid);
|
||||
let _ = page;
|
||||
|
||||
@@ -17,6 +17,7 @@ mod clipboard;
|
||||
mod props;
|
||||
mod select;
|
||||
|
||||
pub(crate) use clipboard::apply_copied_props;
|
||||
pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into};
|
||||
use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace};
|
||||
use props::{
|
||||
@@ -142,12 +143,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
true,
|
||||
find_replace
|
||||
),
|
||||
spec!("edit.setDefaultProperties", "Set default properties", "{id?}", false, |s, p| {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?;
|
||||
let v = copy_props_of(s.doc()?, id);
|
||||
s.clipboard.props = Some(v);
|
||||
ok()
|
||||
}),
|
||||
spec!(
|
||||
"edit.setDefaultProperties",
|
||||
"Set default properties",
|
||||
"{id?} the layer's fills, strokes, effects, opacity and corners (a text layer's: also its font) become what new rectangles, ellipses, polygons and stars (or, from a text layer, new text) drawn with the tools take → {for: shapes|text, properties}",
|
||||
false,
|
||||
|s, p| {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.setDefaultProperties", "select a layer"))?;
|
||||
let doc = s.doc()?;
|
||||
let text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
|
||||
let v = copy_props_of(doc, id);
|
||||
let kind = if text {
|
||||
s.default_props.text = Some(v.clone());
|
||||
"text"
|
||||
} else {
|
||||
s.default_props.shape = Some(v.clone());
|
||||
"shapes"
|
||||
};
|
||||
Ok(json!({"for": kind, "properties": v}))
|
||||
}
|
||||
),
|
||||
spec!("select.set", "Select", "{ids: [..]} (replace the selection)", false, |s, p| {
|
||||
let ids = match get(p, "ids") {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(id_of).collect(),
|
||||
|
||||
@@ -357,21 +357,27 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
|
||||
/// properties only to text, the corners only to a layer with corners.
|
||||
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
|
||||
let mut m = props.as_object().cloned().unwrap_or_default();
|
||||
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
|
||||
if !is_text {
|
||||
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
|
||||
}
|
||||
if !doc.get(id)?.kind.has_corner_radius() {
|
||||
m.remove("cornerRadius");
|
||||
m.remove("cornerSmoothing");
|
||||
}
|
||||
crate::cmd::props::apply(cmd, doc, id, &m)
|
||||
}
|
||||
|
||||
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
|
||||
let ids = req_targets("edit.pasteProperties", s, p)?;
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let mut m = props.as_object().cloned().unwrap_or_default();
|
||||
let is_text = matches!(doc.get(i)?.kind, NodeKind::Text(_));
|
||||
if !is_text {
|
||||
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
|
||||
}
|
||||
if !doc.get(i)?.kind.has_corner_radius() {
|
||||
m.remove("cornerRadius");
|
||||
m.remove("cornerSmoothing");
|
||||
}
|
||||
crate::cmd::props::apply("edit.pasteProperties", doc, i, &m)?;
|
||||
apply_copied_props("edit.pasteProperties", doc, i, &props)?;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -267,6 +267,18 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
// A removal that names no paint among the rows shown changes nothing, the characters' own
|
||||
// fills included; characters coloured differently show no rows at all ("Click + to
|
||||
// replace mixed content").
|
||||
if !add {
|
||||
let shown = if fills { crate::cmd::lists::character_fills(n).map_or(0, |f| f.len()) } else { n.strokes.len() };
|
||||
if index.unwrap_or(shown.saturating_sub(1)) >= shown {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
let frameish = n.kind.is_frame_like();
|
||||
let list = if fills { &mut n.fills } else { &mut n.strokes };
|
||||
if add {
|
||||
@@ -298,6 +310,9 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
let list = if fills { &mut n.fills } else { &mut n.strokes };
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
if list.is_empty() {
|
||||
@@ -344,7 +359,8 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result<Valu
|
||||
let (paint, stroke) = {
|
||||
let doc = s.doc()?;
|
||||
let n = doc.get(id)?;
|
||||
let list = if fills { &n.fills } else { &n.strokes };
|
||||
// A text's fills are what its characters show (the list the Design panel's rows are).
|
||||
let list = if fills { crate::cmd::lists::character_fills(n).unwrap_or_default() } else { n.strokes.clone() };
|
||||
let at = at.unwrap_or(list.len().saturating_sub(1));
|
||||
let paint = list.get(at).cloned().ok_or_else(|| bad(cmd, format!("no {} at index {at}", if fills { "fill" } else { "stroke" })))?;
|
||||
(paint, (!fills).then(|| n.stroke.clone()))
|
||||
|
||||
@@ -184,9 +184,10 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"image": image, "width": width, "height": height, "changed": changed}))
|
||||
}
|
||||
|
||||
/// The index of a layer's top visible image fill (fills paint bottom to top).
|
||||
/// The index of a layer's top visible image fill among the fills it shows (fills paint bottom to
|
||||
/// top): a text's characters' shared list, so none while they are coloured differently.
|
||||
pub fn top_image_fill(n: &Node) -> Option<usize> {
|
||||
n.fills.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_)))
|
||||
crate::cmd::lists::character_fills(n)?.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_)))
|
||||
}
|
||||
|
||||
fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -197,11 +198,15 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) };
|
||||
let doc = s.doc()?;
|
||||
let n = doc.get(id)?;
|
||||
// A text's fills are its characters' (the Design panel's rows): the crop edits that list, and
|
||||
// characters coloured differently have no row to crop ("Click + to replace mixed content").
|
||||
let shown =
|
||||
crate::cmd::lists::character_fills(n).ok_or_else(|| refuse("the characters have different fills, so there is no one fill to crop"))?;
|
||||
let index = match get(p, "index") {
|
||||
None | Some(Value::Null) => top_image_fill(n).ok_or_else(|| refuse("the layer has no image fill to crop"))?,
|
||||
Some(_) => req_index(cmd, p, "index")?,
|
||||
};
|
||||
let mut paint = n.fills.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?;
|
||||
let mut paint = shown.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?;
|
||||
let PaintKind::Image(img) = &mut paint.kind else { return Err(bad(cmd, "that fill is not an image")) };
|
||||
// An image already in Crop mode only enters crop mode: no edit, no undo step.
|
||||
if img.scale_mode != ImageScaleMode::Crop {
|
||||
@@ -209,6 +214,8 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
img.crop = Some(img.placement_crop(f64::from(data.width), f64::from(data.height), n.width, n.height));
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
let n = s.doc_mut()?.get_mut(id)?;
|
||||
// The characters' shared list becomes the layer's, so the crop shows on every one of them.
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
if let Some(f) = n.fills.get_mut(index) {
|
||||
*f = paint;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! Every list is stored bottom first: index 0 paints (or applies) first, the last one is on top;
|
||||
//! the Design panel shows them in reverse, the topmost row first.
|
||||
|
||||
use figcraft_doc::{Document, LayoutGrid, Node, NodeId};
|
||||
use figcraft_doc::{Document, LayoutGrid, Node, NodeId, NodeKind};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{CommandSpec, ok};
|
||||
@@ -189,6 +189,52 @@ fn paint_field_kept(old: &figcraft_color::Paint, new: &figcraft_color::Paint, fi
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills a text's characters show when every character shows the same list: the layer's
|
||||
/// fills, or the one list that styling all of them while editing left on them. None when the
|
||||
/// characters differ, as the layer's fill is then mixed ("Text nodes can have multiple sets of
|
||||
/// fills if some characters are colored differently than others", the developer documentation's
|
||||
/// `fills`). Any other layer: its fills.
|
||||
pub fn character_fills(n: &Node) -> Option<Vec<figcraft_color::Paint>> {
|
||||
let NodeKind::Text(t) = &n.kind else { return Some(n.fills.clone()) };
|
||||
let mut spans = t.spans().into_iter().map(|(_, _, st)| st.fills.as_ref().unwrap_or(&n.fills));
|
||||
let first = spans.next().unwrap_or(&n.fills).clone();
|
||||
spans.all(|f| *f == first).then_some(first)
|
||||
}
|
||||
|
||||
/// Whether any character of a text carries fills of its own (on its base style or a run).
|
||||
pub(crate) fn has_character_fills(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => t.style.fills.is_some() || t.runs.iter().any(|r| r.style.fills.is_some()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a layer-level edit of a text's fills (the Fill section, `fill.*`, `node.set`): the
|
||||
/// characters' own fills go, so the edit shows on every one of them. One list they all shared
|
||||
/// becomes the layer's first, so the edit starts from what the characters showed; characters
|
||||
/// that differed fall back to the layer's fills, which the edit then replaces ("Click + to
|
||||
/// replace mixed content"). Not a text, or no character with fills of its own: nothing changes.
|
||||
pub(crate) fn take_character_fills(n: &mut Node) {
|
||||
if !has_character_fills(n) {
|
||||
return;
|
||||
}
|
||||
if let Some(shared) = character_fills(n)
|
||||
&& shared != n.fills
|
||||
{
|
||||
let old = std::mem::replace(&mut n.fills, shared);
|
||||
for (i, p) in old.iter().enumerate() {
|
||||
rebind_edited_paint(n, true, i, p);
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
t.style.fills = None;
|
||||
for r in &mut t.runs {
|
||||
r.style.fills = None;
|
||||
}
|
||||
t.normalize();
|
||||
}
|
||||
}
|
||||
|
||||
/// Where item `k` lands when the item at `from` moves to `to`.
|
||||
pub fn moved_index(k: usize, from: usize, to: usize) -> usize {
|
||||
if k == from {
|
||||
@@ -250,11 +296,19 @@ fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result<V
|
||||
let from = req_index(cmd, p, "from")?;
|
||||
let to = req_index(cmd, p, "to")?;
|
||||
for id in req_targets(cmd, s, p)? {
|
||||
let len = s.doc()?.node(id).map(|n| list.len(n)).unwrap_or(0);
|
||||
// A text's characters' shared fills are the list the Design panel shows and reorders.
|
||||
let len = s
|
||||
.doc()?
|
||||
.node(id)
|
||||
.map(|n| if list == BoundList::Fills { character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { list.len(n) })
|
||||
.unwrap_or(0);
|
||||
if from >= len || to >= len || from == to {
|
||||
continue;
|
||||
}
|
||||
let n = s.doc_mut()?.get_mut(id)?;
|
||||
if list == BoundList::Fills {
|
||||
take_character_fills(n);
|
||||
}
|
||||
let moved = match list {
|
||||
BoundList::Fills => reorder(&mut n.fills, from, to),
|
||||
BoundList::Strokes => reorder(&mut n.strokes, from, to),
|
||||
|
||||
@@ -109,10 +109,18 @@ pub fn effect_from(cmd: &str, p: &Value, key: &str) -> Result<Option<Effect>> {
|
||||
Ok(Some(effect))
|
||||
}
|
||||
|
||||
/// Most keys an effect object may carry (the widest effect takes about a dozen).
|
||||
const MAX_EFFECT_KEYS: usize = 32;
|
||||
|
||||
/// Refuse the keys of effect `given` that `parse` ignores, naming the keys the effect takes. Set to
|
||||
/// null, a key it reads fails to parse or changes the effect; a key it ignores changes nothing.
|
||||
fn refuse_ignored_effect_keys(cmd: &str, at: &str, given: &Value, parse: impl Fn(&Value) -> Option<Effect>) -> Result<()> {
|
||||
let Some(fields) = given.as_object() else { return Ok(()) };
|
||||
// Each key is probed by reparsing the whole object without it: bounded, or a long list of
|
||||
// unknown keys costs its length squared before it is refused.
|
||||
if fields.len() > MAX_EFFECT_KEYS {
|
||||
return Err(bad(cmd, format!("{at}: more than {MAX_EFFECT_KEYS} properties")));
|
||||
}
|
||||
let parsed = parse(given);
|
||||
let ignored: Vec<&str> = fields
|
||||
.iter()
|
||||
@@ -405,6 +413,9 @@ fn layout_mut<'a>(cmd: &str, k: &str, n: &'a mut Node) -> Result<&'a mut AutoLay
|
||||
/// Replace a node's fills (or strokes). Bindings on the paints whose bound values the new list
|
||||
/// changed let go, as an explicit edit does (see `lists::rebind_edited_paint`).
|
||||
fn set_paints(n: &mut Node, fills: bool, paints: Vec<Paint>) {
|
||||
if fills {
|
||||
super::lists::take_character_fills(n);
|
||||
}
|
||||
let old = std::mem::replace(if fills { &mut n.fills } else { &mut n.strokes }, paints);
|
||||
for (i, p) in old.iter().enumerate() {
|
||||
super::lists::rebind_edited_paint(n, fills, i, p);
|
||||
|
||||
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"proto.settings",
|
||||
"Prototype settings",
|
||||
"{device? (a device name, \"Custom size\" or \"None\"), background?, rotation? portrait|landscape (or 0|90; phones and tablets turn), color? (one of the device's colours by name), width?, height? (the custom size's screen, 1–10000 points; picks \"Custom size\"), responsive? bool (frames resize to the screen and their constraints and auto layout respond)}",
|
||||
"{device? (a device name, \"Custom size\" or \"None\"; any case; another name is refused with the list), background?, rotation? portrait|landscape (or 0|90; phones and tablets turn), color? (one of the device's colours by name), width?, height? (the custom size's screen, 1–10000 points; picks \"Custom size\"), responsive? bool (frames resize to the screen and their constraints and auto layout respond)} → the page's settings after the call (none given: reads them)",
|
||||
true,
|
||||
settings
|
||||
),
|
||||
@@ -173,12 +173,51 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// `proto.settings`: everything is checked before anything changes.
|
||||
/// The device setting `name` stands for, as the device picker names it: "None", "Custom size" or a
|
||||
/// model of [`PrototypeSettings::DEVICES`], whatever its case and the spaces around it.
|
||||
fn known_device(name: &str) -> Option<&'static str> {
|
||||
let name = name.trim();
|
||||
["None", PrototypeSettings::CUSTOM_DEVICE]
|
||||
.into_iter()
|
||||
.chain(PrototypeSettings::DEVICES.iter().map(|d| d.name))
|
||||
.find(|d| d.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// What `proto.settings` answers: the page's prototype settings (the device as the picker names it,
|
||||
/// the colour shown, the screen as presented, `null` without a device).
|
||||
fn settings_json(ps: &PrototypeSettings) -> Value {
|
||||
let screen = ps.device().map(|d| json!({"width": d.width, "height": d.height}));
|
||||
json!({
|
||||
"ok": true,
|
||||
"device": ps.device,
|
||||
"background": format!("#{}", ps.background.to_hex()),
|
||||
"rotation": ps.rotation,
|
||||
"color": ps.device_color().map(|c| c.name),
|
||||
"screen": screen,
|
||||
"customSize": {"width": ps.custom_size[0], "height": ps.custom_size[1]},
|
||||
"responsive": ps.responsive,
|
||||
})
|
||||
}
|
||||
|
||||
/// `proto.settings`: everything is checked before anything changes; an unknown device is refused
|
||||
/// with the devices to pick from, as an unknown colour is. Answers the settings as they are after
|
||||
/// the call, so a call without parameters reads them.
|
||||
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "proto.settings";
|
||||
let page = s.page()?;
|
||||
let bg = color(p, "background");
|
||||
let dev = string(p, "device");
|
||||
let dev = match p.get("device") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let name = v.as_str().unwrap_or_default();
|
||||
let found = known_device(name).ok_or_else(|| {
|
||||
let names: Vec<&str> =
|
||||
["None", PrototypeSettings::CUSTOM_DEVICE].into_iter().chain(PrototypeSettings::DEVICES.iter().map(|d| d.name)).collect();
|
||||
bad(cmd, format!("unknown device {}: device is one of {}", figcraft_format::clip(&v.to_string(), 60), names.join("|")))
|
||||
})?;
|
||||
Some(found.to_string())
|
||||
}
|
||||
};
|
||||
let rot = match p.get("rotation") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(rotation_of(v).ok_or_else(|| bad(cmd, "rotation: portrait|landscape"))?),
|
||||
@@ -231,12 +270,13 @@ fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None if !colors.iter().any(|x| x.name == next.color) => next.color.clear(),
|
||||
None => {}
|
||||
}
|
||||
let answer = settings_json(&next);
|
||||
if next != *prototype
|
||||
&& let NodeKind::Page { prototype, .. } = &mut s.doc_mut()?.get_mut(page)?.kind
|
||||
{
|
||||
*prototype = next;
|
||||
}
|
||||
ok()
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// Resize top-level `frame` to a screen of `(w, h)` as a responsive prototype does: its children
|
||||
|
||||
@@ -260,6 +260,9 @@ fn vue_links_are_a_default_import_with_quoted_bindings() {
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Title": "Say \"hi\""}}));
|
||||
ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": "<Card title=\"{title} {title}\" />"}));
|
||||
assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n<Card title=\"Say "hi" Say "hi"\" />\n");
|
||||
// Literal text before the first placeholder keeps it inside the attribute value.
|
||||
ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": "<Card title=\"Say: {title}\" />"}));
|
||||
assert_eq!(code(&mut s, i, "vue"), "import Card from \"./Card.vue\";\n\n<Card title=\"Say: Say "hi"\" />\n");
|
||||
// Text after a completed tag is text, even when it contains `=`.
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Title": "Buy"}}));
|
||||
ex(&mut s, "codeConnect.set", json!({"id": i, "language": "vue", "template": "<p>Total = {title}</p>"}));
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Edit ▸ Set default properties (#2028): new rectangles, ellipses, polygons and stars drawn with
|
||||
//! the tools take the properties of the layer it was set from, and new text takes a text layer's;
|
||||
//! it no longer only copied them for Paste properties.
|
||||
|
||||
use figcraft_color::Color;
|
||||
use figcraft_doc::{Node, NodeId, NodeKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
use crate::tools::{PointerEvent, PointerKind, ToolId};
|
||||
|
||||
/// Run `cmd`, failing the test on an error.
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// The layer `id` as it is now.
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Draw with `tool` from `a` to `b` (a click when they're equal); the new layer.
|
||||
fn draw(s: &mut Session, tool: ToolId, a: (f64, f64), b: (f64, f64)) -> NodeId {
|
||||
s.set_tool(tool);
|
||||
s.pointer(&PointerEvent::at(PointerKind::Down, a.0, a.1, 1.0)).unwrap();
|
||||
if a != b {
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, (a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, b.0, b.1, 1.0)).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, b.0, b.1, 1.0)).unwrap();
|
||||
*s.selection().first().unwrap()
|
||||
}
|
||||
|
||||
/// The first solid fill's colour of layer `n`.
|
||||
fn fill(n: &Node) -> Option<Color> {
|
||||
n.fills.first().and_then(|p| p.solid_color())
|
||||
}
|
||||
|
||||
/// A red, half-transparent rectangle with a 4 pt blue stroke and 12 pt corners.
|
||||
fn styled(s: &mut Session) -> NodeId {
|
||||
let id = id_of(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
|
||||
ex(s, "node.set", json!({"id": id, "props": {"fill": "#FF0000", "stroke": "#0000FF", "strokeWeight": 4, "opacity": 0.5, "cornerRadius": 12}}));
|
||||
id
|
||||
}
|
||||
|
||||
/// Rectangles, ellipses, polygons and stars drawn or clicked with their tools take the shape
|
||||
/// defaults (corners only where a shape has them, its own drawn size); frames, lines and layers made
|
||||
/// by commands keep their own look; undo takes a drawn shape away whole.
|
||||
#[test]
|
||||
fn new_shapes_drawn_with_the_tools_take_the_default_properties() {
|
||||
let mut s = Session::new();
|
||||
let source = styled(&mut s);
|
||||
let set = ex(&mut s, "edit.setDefaultProperties", json!({"id": source}));
|
||||
assert_eq!(set["for"], "shapes");
|
||||
let red = Some(Color::from_hex("#FF0000").unwrap());
|
||||
// Dragged and clicked (a click places a 100×100 shape) alike.
|
||||
for (tool, a, b) in
|
||||
[(ToolId::Rectangle, (200.0, 0.0), (300.0, 80.0)), (ToolId::Ellipse, (400.0, 0.0), (400.0, 0.0)), (ToolId::Star, (600.0, 0.0), (660.0, 60.0))]
|
||||
{
|
||||
let id = draw(&mut s, tool, a, b);
|
||||
let n = node(&s, id);
|
||||
assert_eq!(fill(&n), red, "{tool:?}");
|
||||
assert_eq!((n.stroke.weight, n.opacity), (4.0, 0.5), "{tool:?}");
|
||||
assert_eq!(n.strokes.first().and_then(|p| p.solid_color()), Some(Color::from_hex("#0000FF").unwrap()), "{tool:?}");
|
||||
}
|
||||
let rect = draw(&mut s, ToolId::Rectangle, (0.0, 200.0), (80.0, 260.0));
|
||||
assert_eq!(node(&s, rect).corners.radii, [12.0; 4], "corners go to layers with corners");
|
||||
assert_eq!((node(&s, rect).width, node(&s, rect).height), (80.0, 60.0), "the drawn size, not the source's");
|
||||
// Frames and lines keep their own look; a shape made by a command too.
|
||||
let frame = draw(&mut s, ToolId::Frame, (0.0, 400.0), (100.0, 500.0));
|
||||
assert_ne!(fill(&node(&s, frame)), red);
|
||||
let line = draw(&mut s, ToolId::Line, (0.0, 600.0), (100.0, 600.0));
|
||||
assert_ne!(node(&s, line).stroke.weight, 4.0);
|
||||
let made = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 700, "width": 10, "height": 10}))["id"]).unwrap();
|
||||
assert_ne!(fill(&node(&s, made)), red);
|
||||
// Undo takes a drawn shape away whole, defaults included.
|
||||
let drawn = draw(&mut s, ToolId::Polygon, (800.0, 0.0), (860.0, 60.0));
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
assert!(s.doc().unwrap().node(drawn).is_none());
|
||||
}
|
||||
|
||||
/// Setting defaults no longer overwrites what Copy properties copied.
|
||||
#[test]
|
||||
fn setting_defaults_leaves_the_copied_properties_alone() {
|
||||
let mut s = Session::new();
|
||||
let copied = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
|
||||
ex(&mut s, "node.set", json!({"id": copied, "props": {"fill": "#00FF00"}}));
|
||||
ex(&mut s, "edit.copyProperties", json!({"id": copied}));
|
||||
let source = styled(&mut s);
|
||||
ex(&mut s, "edit.setDefaultProperties", json!({"id": source}));
|
||||
let target = id_of(&ex(&mut s, "shape.ellipse", json!({"x": 0, "y": 100, "width": 50, "height": 50}))["id"]).unwrap();
|
||||
ex(&mut s, "edit.pasteProperties", json!({"ids": [target]}));
|
||||
assert_eq!(fill(&node(&s, target)), Some(Color::from_hex("#00FF00").unwrap()), "Paste properties pastes what was copied");
|
||||
}
|
||||
|
||||
/// A text layer sets the defaults of new text (its font and fills, laid out at that size), and the
|
||||
/// shapes' defaults stay as they were.
|
||||
#[test]
|
||||
fn new_text_takes_a_text_layers_defaults_and_shapes_keep_theirs() {
|
||||
let mut s = Session::new();
|
||||
let shape = styled(&mut s);
|
||||
ex(&mut s, "edit.setDefaultProperties", json!({"id": shape}));
|
||||
let text = id_of(&ex(&mut s, "text.create", json!({"text": "Title", "x": 0, "y": 200}))["id"]).unwrap();
|
||||
ex(&mut s, "node.set", json!({"id": text, "props": {"fontSize": 32, "fill": "#008000"}}));
|
||||
let set = ex(&mut s, "edit.setDefaultProperties", json!({"id": text}));
|
||||
assert_eq!(set["for"], "text");
|
||||
let id = draw(&mut s, ToolId::Text, (300.0, 300.0), (300.0, 300.0));
|
||||
let n = node(&s, id);
|
||||
let NodeKind::Text(t) = &n.kind else { panic!("a text layer") };
|
||||
assert_eq!(t.style.font_size, 32.0);
|
||||
assert_eq!(fill(&n), Some(Color::from_hex("#008000").unwrap()));
|
||||
assert!(n.height > 30.0, "laid out at the default size: {}", n.height);
|
||||
// The shapes' defaults are still the rectangle's.
|
||||
let rect = draw(&mut s, ToolId::Rectangle, (0.0, 500.0), (80.0, 560.0));
|
||||
assert_eq!(fill(&node(&s, rect)), Some(Color::from_hex("#FF0000").unwrap()));
|
||||
}
|
||||
@@ -288,41 +288,45 @@ fn pieces(t: &str) -> Vec<Piece<'_>> {
|
||||
checkable.then(|| parse(t).ok()).flatten().unwrap_or_else(|| vec![Piece::Text(t)])
|
||||
}
|
||||
|
||||
/// Whether `s` ends inside an unclosed opening tag (no `>` outside quotes since the last `<`).
|
||||
fn inside_open_tag(s: &str) -> bool {
|
||||
/// Whether `s` ends inside an unclosed opening tag (no `>` outside quotes since the last `<`), and
|
||||
/// the quote (with its byte offset) still open there.
|
||||
fn tag_state(s: &str) -> (bool, Option<(char, usize)>) {
|
||||
let mut in_tag = false;
|
||||
let mut quote = None;
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
let mut chars = s.char_indices().peekable();
|
||||
while let Some((i, c)) = chars.next() {
|
||||
match quote {
|
||||
Some(q) => {
|
||||
Some((q, _)) => {
|
||||
if c == q {
|
||||
quote = None;
|
||||
}
|
||||
}
|
||||
None => match c {
|
||||
'<' if !in_tag && chars.peek().is_some_and(|ch| ch.is_ascii_alphabetic() || matches!(*ch, '/' | '!' | '?')) => {
|
||||
'<' if !in_tag && chars.peek().is_some_and(|(_, ch)| ch.is_ascii_alphabetic() || matches!(*ch, '/' | '!' | '?')) => {
|
||||
in_tag = true;
|
||||
}
|
||||
'>' if in_tag => in_tag = false,
|
||||
'"' | '\'' if in_tag => quote = Some(c),
|
||||
'"' | '\'' if in_tag => quote = Some((c, i)),
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
in_tag
|
||||
(in_tag, quote)
|
||||
}
|
||||
|
||||
/// Where a placeholder sits in a Vue template: whether the attribute is bound, and the quote the
|
||||
/// template already opened (if any). `None` when it isn't in an attribute at all.
|
||||
fn vue_attribute(out: &str) -> Option<(bool, Option<char>)> {
|
||||
let end = out.trim_end();
|
||||
if !inside_open_tag(end) {
|
||||
let (in_tag, open) = tag_state(out);
|
||||
if !in_tag {
|
||||
return None;
|
||||
}
|
||||
let (after, quote) = match end.chars().last() {
|
||||
Some(q @ ('"' | '\'')) => (&end[..end.len() - q.len_utf8()], Some(q)),
|
||||
_ => (end, None),
|
||||
// A quote still open, with literal text after it (`title="Buy {x}"`), puts the placeholder in
|
||||
// that attribute's value as much as one directly after the quote does.
|
||||
let (after, quote) = match open {
|
||||
Some((q, at)) => (&out[..at], Some(q)),
|
||||
None => (end, None),
|
||||
};
|
||||
let after = after.trim_end();
|
||||
let eq = after.rfind('=')?;
|
||||
|
||||
@@ -85,3 +85,25 @@ fn a_scheme_is_required_and_control_characters_are_refused() {
|
||||
assert!(!openable(url), "{url:?} must be refused");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_syntax_and_malformed_authorities_are_refused() {
|
||||
for url in [
|
||||
// Never valid unencoded, and command syntax to the `cmd.exe /c start` an opener may use.
|
||||
"https://example.com/?a=b|calc",
|
||||
"https://example.com/<x>",
|
||||
"https://example.com/\"x\"",
|
||||
"https://example.com/a b",
|
||||
"https://example.com/`x`",
|
||||
"https://example.com/x^y",
|
||||
"https://example.com\\x",
|
||||
// An authority an opener can't parse may be reopened as a file path.
|
||||
"http://exam ple.com/",
|
||||
"http://a{b}/",
|
||||
] {
|
||||
assert!(!openable(url), "{url:?} must be refused");
|
||||
}
|
||||
for url in ["https://example.com/?a=b&c=d%20e", "https://[::1]:8080/x", "https://bücher.example/", "https://a.b-c_d.example:443/"] {
|
||||
assert!(openable(url), "{url:?} should open");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if manifest.id != entry.id || manifest.version != entry.version {
|
||||
return Err(fail("its manifest doesn't match the directory's entry"));
|
||||
}
|
||||
// What was shown and approved is the entry's access and commands: a bundle whose manifest
|
||||
// asks for more is refused, since the manifest is what the plugin then runs under.
|
||||
if manifest.permissions.access == figcraft_plugin::manifest::Access::Write && !entry.access.trim().eq_ignore_ascii_case("write") {
|
||||
return Err(fail("its manifest asks to write the document, but the directory showed it as read-only"));
|
||||
}
|
||||
if !entry.commands.is_empty()
|
||||
&& (manifest.permissions.commands.is_empty() || manifest.permissions.commands.iter().any(|c| !entry.commands.contains(c)))
|
||||
{
|
||||
return Err(fail("its manifest asks for commands the directory didn't show"));
|
||||
}
|
||||
let source = address(&server);
|
||||
let path = save(s, &mut manifest, &bundle).map_err(|e| fail(&e))?;
|
||||
let out = json!({
|
||||
|
||||
@@ -110,7 +110,7 @@ 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 prefs::{Clipboard, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale};
|
||||
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;
|
||||
|
||||
@@ -119,6 +119,8 @@ pub struct Session {
|
||||
pub docs: Vec<DocState>,
|
||||
pub active: usize,
|
||||
pub clipboard: Clipboard,
|
||||
/// Edit ▸ Set default properties: what new shapes and text drawn with the tools take.
|
||||
pub default_props: DefaultProps,
|
||||
pub prefs: Prefs,
|
||||
/// A command changed a preference that is kept at once (not only when the app quits): the app
|
||||
/// saves the preferences and clears this.
|
||||
@@ -275,6 +277,8 @@ mod dash_cap_tests;
|
||||
#[cfg(test)]
|
||||
mod datafill_tests;
|
||||
#[cfg(test)]
|
||||
mod default_props_tests;
|
||||
#[cfg(test)]
|
||||
mod design_paste_tests;
|
||||
#[cfg(test)]
|
||||
mod dev_measurements_tests;
|
||||
|
||||
@@ -252,3 +252,29 @@ fn publishing_sends_a_checked_folder() {
|
||||
assert_eq!(r["id"], ID);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bundle_asking_for_more_than_the_directory_showed_is_not_installed() {
|
||||
let (mut s, d) = session();
|
||||
// Shown as read-only with one command; the bundle's manifest asks to write, any command.
|
||||
let text =
|
||||
json!({"id": ID, "name": "Tiny", "version": "1.0.0", "author": "Ada", "main": "tiny.wasm", "permissions": {"access": "write"}}).to_string();
|
||||
let b = Bundle { manifest: text, wasm: wasm(), assets: vec![] }.encode();
|
||||
let mut e = entry(ID, "1.0.0", &b);
|
||||
e.commands = vec!["node.get".into()];
|
||||
d.lock().unwrap().plugins.push((e, b));
|
||||
s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap();
|
||||
let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("write"), "{err}");
|
||||
assert!(s.prefs.plugins.is_empty(), "nothing was installed");
|
||||
// Read-only as shown, but more commands than shown.
|
||||
let text = json!({"id": ID, "name": "Tiny", "version": "1.0.1", "author": "Ada", "main": "tiny.wasm", "permissions": {"access": "read", "commands": ["node.get", "node.set"]}}).to_string();
|
||||
let b = Bundle { manifest: text, wasm: wasm(), assets: vec![] }.encode();
|
||||
let mut e = entry(ID, "1.0.1", &b);
|
||||
e.commands = vec!["node.get".into()];
|
||||
d.lock().unwrap().plugins.clear();
|
||||
d.lock().unwrap().plugins.push((e, b));
|
||||
s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap();
|
||||
let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("commands"), "{err}");
|
||||
}
|
||||
|
||||
@@ -173,6 +173,18 @@ pub struct UiRequest {
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
/// What Edit ▸ Set default properties keeps: the properties new layers drawn with the tools take,
|
||||
/// as Copy properties copies them (fills, strokes and their settings, effects, opacity, blend,
|
||||
/// corners; for text also the font, size, line height and letter spacing). One set for shapes
|
||||
/// (rectangles, ellipses, polygons and stars), set from any layer but text, and one for text.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct DefaultProps {
|
||||
/// For new rectangles, ellipses, polygons and stars.
|
||||
pub shape: Option<Value>,
|
||||
/// For new text.
|
||||
pub text: Option<Value>,
|
||||
}
|
||||
|
||||
/// Clipboard contents (internal; the UI mirrors to the system clipboard).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Clipboard {
|
||||
|
||||
@@ -97,3 +97,31 @@ fn explicit_variable_modes_go_back_to_auto() {
|
||||
assert!(s.execute("variable.setMode", &json!({"ids": [f], "collection": "Tokens", "mode": "Dusk"})).is_err());
|
||||
assert!(s.execute("variable.setMode", &json!({"ids": [f], "collection": "Tokens"})).is_err(), "a mode, or null for Auto");
|
||||
}
|
||||
|
||||
/// #2027: an unknown device is refused with the devices to pick from, as an unknown colour is, and
|
||||
/// nothing changes; a known one is taken whatever its case and stored as the picker names it; the
|
||||
/// settings read back from `proto.settings` without parameters.
|
||||
#[test]
|
||||
fn unknown_devices_are_refused_and_settings_read_back() {
|
||||
let mut s = Session::new();
|
||||
let before = settings(&s);
|
||||
for junk in [json!("Pixel Nonexistent"), json!(""), json!(42), json!(["iPhone 16"])] {
|
||||
let err = s.execute("proto.settings", &json!({"device": junk, "responsive": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("unknown device") && err.contains("iPhone 17|") && err.contains("Custom size"), "{junk}: {err}");
|
||||
assert_eq!(settings(&s), before, "{junk}: nothing changes");
|
||||
}
|
||||
let set = s.execute("proto.settings", &json!({"device": " iphone 16 ", "color": "black"})).unwrap();
|
||||
assert_eq!(settings(&s).device, "iPhone 16", "stored as the picker names it");
|
||||
assert_eq!((&set["device"], &set["color"]), (&json!("iPhone 16"), &json!("Black")));
|
||||
let read = s.execute("proto.settings", &json!({})).unwrap();
|
||||
assert_eq!(read, set, "a call without parameters reads the settings");
|
||||
assert_eq!((&read["ok"], &read["rotation"], &read["responsive"]), (&json!(true), &json!("portrait"), &json!(false)));
|
||||
assert_eq!(read["screen"], json!({"width": 393.0, "height": 852.0}));
|
||||
assert!(read["background"].as_str().is_some_and(|c| c.starts_with('#')), "{read}");
|
||||
// "None" and "Custom size" in any case; no device has no screen or colour.
|
||||
s.execute("proto.settings", &json!({"device": "custom SIZE", "width": 800, "height": 600})).unwrap();
|
||||
assert_eq!(settings(&s).device, PrototypeSettings::CUSTOM_DEVICE);
|
||||
let none = s.execute("proto.settings", &json!({"device": "none"})).unwrap();
|
||||
assert_eq!((&none["device"], &none["screen"], &none["color"]), (&json!("None"), &json!(null), &json!(null)));
|
||||
assert_eq!(none["customSize"], json!({"width": 800.0, "height": 600.0}));
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ impl Session {
|
||||
docs: Vec::new(),
|
||||
active: 0,
|
||||
clipboard: Clipboard::default(),
|
||||
default_props: Default::default(),
|
||||
prefs: Prefs::default(),
|
||||
prefs_unsaved: false,
|
||||
tool: tools::ToolState::default(),
|
||||
|
||||
@@ -73,8 +73,15 @@ fn bundle() -> Vec<u8> {
|
||||
|
||||
fn directory(req: PluginReq) -> PluginReply {
|
||||
let bytes = bundle();
|
||||
let entry =
|
||||
PluginEntry { id: ID.into(), name: "Tiny tool".into(), version: "1.0.0".into(), sha256: sha256_hex(&bytes), ..PluginEntry::default() };
|
||||
let entry = PluginEntry {
|
||||
id: ID.into(),
|
||||
name: "Tiny tool".into(),
|
||||
version: "1.0.0".into(),
|
||||
access: "write".into(),
|
||||
commands: vec!["shape.rectangle".into()],
|
||||
sha256: sha256_hex(&bytes),
|
||||
..PluginEntry::default()
|
||||
};
|
||||
match req {
|
||||
PluginReq::List { .. } => PluginReply::List(vec![entry]),
|
||||
PluginReq::Fetch { .. } => PluginReply::Bundle { entry, bundle: bytes },
|
||||
|
||||
@@ -1,10 +1,94 @@
|
||||
//! Range fills on text: set on a range, cleared back to the layer's fill.
|
||||
//! Range fills on text: set on a range, cleared back to the layer's fill; a layer-level fill edit
|
||||
//! reaches every character.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::cmd::lists::character_fills;
|
||||
use crate::params::id_of;
|
||||
|
||||
/// The fill each character of `t` shows, as hex.
|
||||
fn fills_shown(s: &Session, t: figcraft_doc::NodeId) -> Vec<String> {
|
||||
let n = s.doc().unwrap().node(t).unwrap().clone();
|
||||
let tx = n.kind.text().unwrap().clone();
|
||||
(0..tx.char_count())
|
||||
.map(|i| {
|
||||
tx.style_at(i)
|
||||
.fills
|
||||
.clone()
|
||||
.unwrap_or_else(|| n.fills.clone())
|
||||
.iter()
|
||||
.map(|p| p.solid_color().unwrap().to_hex())
|
||||
.collect::<Vec<_>>()
|
||||
.join("+")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A text styled on a range, or on all of its characters, keeps those fills until the layer's
|
||||
/// fill is edited: then every character takes the layer's fills, in one undo step (#1856).
|
||||
#[test]
|
||||
fn a_layer_fill_edit_reaches_every_character() {
|
||||
let mut s = Session::new();
|
||||
let t = id_of(&s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"]).unwrap();
|
||||
s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().node(t).unwrap().clone();
|
||||
assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list");
|
||||
// "ello" yellow: the characters differ, the layer's fill is mixed, the canvas keeps both.
|
||||
s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"]);
|
||||
assert_eq!(character_fills(&node(&s)), None, "mixed");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "reselecting changes nothing");
|
||||
// The layer's fill set: every character takes it, their own fills are gone.
|
||||
let steps = s.ds().unwrap().history.undo.len();
|
||||
s.execute("fill.set", &json!({"ids": [t], "color": "#0000FF"})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["0000FF"; 5]);
|
||||
assert!(node(&s).kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own");
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "undo puts the characters' fills back");
|
||||
s.redo().unwrap();
|
||||
// All of the characters styled while editing: they share a list the layer doesn't have yet.
|
||||
// A fill added at the layer goes on top of that list, not the layer's old one.
|
||||
s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["00FF00"; 5]);
|
||||
assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list, the characters'");
|
||||
assert_eq!(node(&s).fills[0].solid_color().unwrap().to_hex(), "0000FF", "the layer's own list is older");
|
||||
s.execute("fill.add", &json!({"ids": [t], "color": "#FF00FF"})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["00FF00+FF00FF"; 5]);
|
||||
assert!(node(&s).kind.text().unwrap().runs.is_empty());
|
||||
assert_eq!(node(&s).fills.len(), 2, "the layer's list is the characters' now");
|
||||
// `node.set` with a fill, and a mixed text again: both reach every character.
|
||||
s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap();
|
||||
s.execute("node.set", &json!({"id": t, "props": {"fill": "#123456"}})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["123456"; 5]);
|
||||
// A removal that names no paint leaves the characters' own fills alone; a copy takes the fill
|
||||
// the characters show, the list the Design panel's rows are.
|
||||
s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap();
|
||||
s.execute("fill.remove", &json!({"ids": [t], "index": 7})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "nothing removed, nothing taken");
|
||||
// Characters coloured differently show no fill rows at all: a removal with or without an
|
||||
// index leaves the layer's hidden fill and the characters' own alone, and there is no row to
|
||||
// crop (the command is unavailable, as the menu has it).
|
||||
s.execute("fill.remove", &json!({"ids": [t], "index": 0})).unwrap();
|
||||
s.execute("fill.remove", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "mixed: nothing to remove");
|
||||
assert_eq!(node(&s).fills.len(), 1, "the layer's own fill stays");
|
||||
assert!(matches!(s.execute("image.crop", &json!({"ids": [t]})), Err(crate::EngineError::Disabled(..))), "mixed: nothing to crop");
|
||||
assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "and nothing taken");
|
||||
assert_eq!(crate::cmd::image::top_image_fill(&node(&s)), None, "the menu finds no image to crop either");
|
||||
s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap();
|
||||
s.execute("fill.copy", &json!({"id": t})).unwrap();
|
||||
let copied = s.clipboard.paint.clone().and_then(|(_, p)| p.solid_color()).map(|c| c.to_hex());
|
||||
assert_eq!(copied.as_deref(), Some("00FF00"), "the characters' fill is copied, not the layer's older one");
|
||||
// A rectangle is left alone by all of this.
|
||||
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"]).unwrap();
|
||||
s.execute("fill.set", &json!({"ids": [r], "color": "#ABCDEF"})).unwrap();
|
||||
assert_eq!(character_fills(s.doc().unwrap().node(r).unwrap()).map(|f| f.len()), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_fill_sets_and_clears() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -707,9 +707,16 @@ impl Unpacked {
|
||||
if self.exceeded(z, name) && z.by_name(name).is_ok_and(|f| f.size() <= limit) {
|
||||
return Err(FormatError::Corrupt(format!("{name}: {}", self.passed())));
|
||||
}
|
||||
let data = read_member(z, name, limit.min(self.left))?;
|
||||
self.left = self.left.saturating_sub(data.len() as u64);
|
||||
Ok(data)
|
||||
let cap = limit.min(self.left);
|
||||
let size = z.by_name(name).map_or(0, |f| f.size());
|
||||
let data = read_member(z, name, cap);
|
||||
// A read that failed part way (a bad checksum at the end, say) did its unpacking all the
|
||||
// same: it is charged in full, so an index naming that member again can't repeat it. One
|
||||
// refused for its recorded size before any unpacking costs nothing.
|
||||
if size <= cap {
|
||||
self.left = self.left.saturating_sub(data.as_ref().map_or(size, |d| d.len() as u64));
|
||||
}
|
||||
data
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -282,9 +282,11 @@ fn capped_member(
|
||||
if size > allowed {
|
||||
return Err(corrupt(format!("{name} is too large")));
|
||||
}
|
||||
let data = crate::read_member(z, name, allowed)?;
|
||||
*total += data.len() as u64;
|
||||
Ok(data)
|
||||
let data = crate::read_member(z, name, allowed);
|
||||
// A failed read (a bad checksum at the end, say) unpacked all the same: charged in full, so
|
||||
// a page list naming the member again can't repeat it within the budget.
|
||||
*total += data.as_ref().map_or(size, |d| d.len() as u64);
|
||||
data
|
||||
}
|
||||
|
||||
/// JSON member `name`, read by [`capped_member`] within the file's [`MAX_JSON_TOTAL`].
|
||||
|
||||
@@ -93,3 +93,26 @@ fn the_total_leaves_room_for_the_largest_real_files() {
|
||||
// Below what the per-area caps added up to (about 10 GB).
|
||||
const { assert!(MAX_UNPACKED < 10 * 1024 * 1024 * 1024) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_that_fails_part_way_still_spends_the_total() {
|
||||
// A member whose compressed bytes are damaged near the end unpacks almost all of itself
|
||||
// before failing: that work is charged, so an index naming it again can't repeat it for free.
|
||||
let body: Vec<u8> = (0..200_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
|
||||
// Stored, so a byte flipped in the middle is read through and fails only on the checksum.
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
let mut w = zip::ZipWriter::new(&mut buf);
|
||||
w.start_file("snapshots/v1.json", zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap();
|
||||
w.write_all(&body).unwrap();
|
||||
w.finish().unwrap();
|
||||
let mut bytes = buf.into_inner();
|
||||
let at = 30 + "snapshots/v1.json".len() + body.len() / 2;
|
||||
bytes[at] ^= 0xff;
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let size = z.by_name("snapshots/v1.json").unwrap().size();
|
||||
assert_eq!(size, body.len() as u64);
|
||||
let mut total = crate::Unpacked::new(size + size / 2);
|
||||
assert!(total.read(&mut z, "snapshots/v1.json", 1 << 20).is_err(), "the damaged member fails");
|
||||
let again = total.read(&mut z, "snapshots/v1.json", 1 << 20).unwrap_err().to_string();
|
||||
assert!(again.contains("together pass"), "the second read is refused for the total, not read again: {again}");
|
||||
}
|
||||
|
||||
@@ -459,6 +459,8 @@ fn path_end(path: &BezPath, at_end: bool) -> Option<(Point, Vec2)> {
|
||||
|
||||
/// The filled arrowhead shape for `cap` at one end of an open path.
|
||||
pub fn arrowhead(path: &BezPath, cap: StrokeCap, weight: f64, at_end: bool) -> Option<BezPath> {
|
||||
// Capped like a stroke's width: the circle below is flattened at a fixed tolerance.
|
||||
let weight = weight.min(MAX_STROKE_WIDTH);
|
||||
let (tip, dir) = path_end(path, at_end)?;
|
||||
let n = Vec2::new(-dir.y, dir.x);
|
||||
let s = (weight * 3.0).max(6.0);
|
||||
@@ -760,6 +762,15 @@ mod tests {
|
||||
assert!((b.x0 + 5.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absurd_arrow_weight_is_capped() {
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((100.0, 0.0));
|
||||
let head = arrowhead(&line, StrokeCap::CircleFilled, 1e300, true).unwrap();
|
||||
assert!(head.elements().len() < 10_000, "{}", head.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_on_open_paths() {
|
||||
let mut line = BezPath::new();
|
||||
|
||||
+83
-26
@@ -3,25 +3,31 @@
|
||||
//! `CRAFT_FONTS` is empty and native apps use system fonts. Required web releases enforce Inter
|
||||
//! Regular/SemiBold and Noto Sans Georgian Regular after filtering. Recipe: craft-fonts `docs/integration.md`.
|
||||
//! Noto Sans CJK only with `FIGCRAFT_EMBED_CJK` set (the web build's only way to show CJK UI text).
|
||||
//! The other scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari…) stay out of web builds unless
|
||||
//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Arab,Hebr,Thai,Deva`: one tag per script wanted,
|
||||
//! as the manifest's scripts column lists them; #1902).
|
||||
//! `FIGCRAFT_WEB_FONTS` (comma-separated families) adds manifest families to the web build.
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Font build script: emit `craft_fonts.rs` from `input_fonts`, passing the
|
||||
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target, `FIGCRAFT_EMBED_CJK` and `FIGCRAFT_WEB_FONTS` inputs;
|
||||
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target, `FIGCRAFT_EMBED_CJK`, `FIGCRAFT_EMBED_SCRIPTS` and
|
||||
/// `FIGCRAFT_WEB_FONTS` inputs;
|
||||
/// report generation and write failures with `cargo::error`.
|
||||
fn main() {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_SCRIPTS");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from);
|
||||
let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let embed_cjk = std::env::var_os("FIGCRAFT_EMBED_CJK").is_some();
|
||||
let embed_scripts = scripts_from(std::env::var("FIGCRAFT_EMBED_SCRIPTS").ok().as_deref());
|
||||
let web_fonts = web_fonts(&std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default());
|
||||
match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &web_fonts) {
|
||||
match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts) {
|
||||
Ok(entries) => src.push_str(&entries),
|
||||
Err(e) => println!("cargo::error={e}"),
|
||||
}
|
||||
@@ -32,6 +38,12 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The script tags `FIGCRAFT_EMBED_SCRIPTS` names (comma- or space-separated), trimmed; none when
|
||||
/// it is unset.
|
||||
fn scripts_from(var: Option<&str>) -> Vec<String> {
|
||||
var.unwrap_or_default().split([',', ' ']).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// The families `FIGCRAFT_WEB_FONTS` names: comma-separated, trimmed, empty names dropped.
|
||||
fn web_fonts(list: &str) -> Vec<String> {
|
||||
list.split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_owned).collect()
|
||||
@@ -43,8 +55,16 @@ fn not_embedded<'a>(web_fonts: &'a [String], faces: &[(String, String)]) -> Vec<
|
||||
}
|
||||
|
||||
/// Collect the effective catalog and enforce the required web release faces after filtering.
|
||||
/// Families named in `web_fonts` that nothing embedded get a warning (most likely misspelt).
|
||||
fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<String, String> {
|
||||
/// `embed_scripts`: script tags whose faces a web build keeps as well. Families named in `web_fonts`
|
||||
/// that nothing embedded get a warning (most likely misspelt).
|
||||
fn input_fonts(
|
||||
dir: Option<&std::path::Path>,
|
||||
wasm: bool,
|
||||
required: bool,
|
||||
embed_cjk: bool,
|
||||
embed_scripts: &[String],
|
||||
web_fonts: &[String],
|
||||
) -> Result<String, String> {
|
||||
let Some(dir) = dir else {
|
||||
for family in web_fonts {
|
||||
println!("cargo::warning=FIGCRAFT_WEB_FONTS: {family:?} isn't embedded: this build has no craft-fonts");
|
||||
@@ -60,7 +80,7 @@ fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_
|
||||
watch(&path);
|
||||
continue;
|
||||
}
|
||||
match craft_fonts(dir, manifest, wasm, embed_cjk, web_fonts) {
|
||||
match craft_fonts(dir, manifest, wasm, embed_cjk, embed_scripts, web_fonts) {
|
||||
Ok(catalog) => {
|
||||
loaded = true;
|
||||
out.push_str(&catalog.entries);
|
||||
@@ -106,9 +126,16 @@ struct Catalog {
|
||||
|
||||
/// Parse a font manifest of `family | style | file | scripts` rows into `CraftFont`
|
||||
/// entries: skip Adobe-authored families, skip CJK unless requested, keep the web catalog
|
||||
/// to its budgeted families and the ones `web_fonts` adds, canonicalize and watch each face, and
|
||||
/// emit `include_bytes!` items.
|
||||
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<Catalog, String> {
|
||||
/// to its budgeted families (plus the faces of the scripts in `embed_scripts` and the families `web_fonts`
|
||||
/// adds), canonicalize and watch each face, and emit `include_bytes!` items.
|
||||
fn craft_fonts(
|
||||
dir: &std::path::Path,
|
||||
manifest_rel: &str,
|
||||
wasm: bool,
|
||||
embed_cjk: bool,
|
||||
embed_scripts: &[String],
|
||||
web_fonts: &[String],
|
||||
) -> Result<Catalog, String> {
|
||||
let manifest = dir.join(manifest_rel);
|
||||
watch(&manifest);
|
||||
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
|
||||
@@ -129,11 +156,14 @@ fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk:
|
||||
continue;
|
||||
}
|
||||
// Web builds have a size budget: Inter, Noto Sans Georgian (small, for the Georgian UI), only the
|
||||
// SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK UI text), and the
|
||||
// SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK UI text), the faces
|
||||
// of the scripts `FIGCRAFT_EMBED_SCRIPTS` names (an Arabic or Persian document needs Noto Sans
|
||||
// Arabic, +0.8 MB; the browser has no system fonts to fall back on, #1902), and the
|
||||
// families a distribution names in `FIGCRAFT_WEB_FONTS` (a Thai face for Thai text, say).
|
||||
let wordmark = *family == "Archivo" && *style == "SemiBold";
|
||||
let asked = scripts.split(',').map(str::trim).any(|s| embed_scripts.iter().any(|e| e.eq_ignore_ascii_case(s)));
|
||||
let added = web_fonts.iter().any(|f| f == family);
|
||||
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !added {
|
||||
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !asked && !added {
|
||||
continue;
|
||||
}
|
||||
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
|
||||
@@ -187,9 +217,9 @@ mod tests {
|
||||
fn restored_latin_catalog_preserves_permitted_native_faces_and_web_budget() {
|
||||
let f = Fixture::new();
|
||||
std::fs::write(f.0.join("fonts/latin-manifest.txt"), include_str!("tests/fixtures/latin-families.txt")).unwrap();
|
||||
let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false, &[]).unwrap();
|
||||
let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false, &[], &[]).unwrap();
|
||||
assert_eq!(native.faces.len(), 43, "all prior permitted presentation faces remain available");
|
||||
let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false, &[]).unwrap();
|
||||
let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false, &[], &[]).unwrap();
|
||||
assert_eq!(web.faces.len(), 4, "the web catalog keeps only the four Inter faces");
|
||||
for catalog in [&native, &web] {
|
||||
assert!(!catalog.entries.contains("Source Sans 3"));
|
||||
@@ -197,16 +227,16 @@ mod tests {
|
||||
}
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Carlito"));
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Liberation Serif"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).is_ok());
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).is_ok());
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a catalog missing Inter Regular or Inter SemiBold.
|
||||
#[test]
|
||||
fn required_web_rejects_core_only_and_partial_latin_catalogs() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Inter Regular"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Inter Regular"));
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Unrelated", "SemiBold")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Inter SemiBold"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Inter SemiBold"));
|
||||
}
|
||||
|
||||
/// Asserts required web input embeds the Inter and Georgian catalogs (three entries) and
|
||||
@@ -215,12 +245,12 @@ mod tests {
|
||||
fn required_web_embeds_both_catalogs_and_requires_georgian() {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
let entries = input_fonts(Some(&f.0), true, true, false, &[]).unwrap();
|
||||
let entries = input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap();
|
||||
assert_eq!(entries.matches("CraftFont {").count(), 3);
|
||||
assert!(entries.contains("family: \"Inter\""));
|
||||
assert!(entries.contains("family: \"Noto Sans Georgian\""));
|
||||
f.manifest("manifest.txt", &[("Other", "Regular")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Noto Sans Georgian Regular"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Noto Sans Georgian Regular"));
|
||||
}
|
||||
|
||||
/// Asserts absent font input is empty when optional and an error when required, while present
|
||||
@@ -228,10 +258,10 @@ mod tests {
|
||||
#[test]
|
||||
fn optional_and_native_inputs_keep_their_existing_policy() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(None, true, false, false, &[]).unwrap().is_empty());
|
||||
assert!(input_fonts(None, true, true, false, &[]).unwrap_err().contains("CRAFT_FONTS_DIR is missing"));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(Some(&f.0), false, true, false, &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(None, true, false, false, &[], &[]).unwrap().is_empty());
|
||||
assert!(input_fonts(None, true, true, false, &[], &[]).unwrap_err().contains("CRAFT_FONTS_DIR is missing"));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &[], &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(Some(&f.0), false, true, false, &[], &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a manifest whose face file is missing, even when every
|
||||
@@ -241,7 +271,34 @@ mod tests {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
std::fs::remove_file(f.0.join("fonts/face.ttf")).unwrap();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("fonts/face.ttf"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("fonts/face.ttf"));
|
||||
}
|
||||
|
||||
/// #1902: a web build leaves the other scripts' faces out (an Arabic or Persian document shows
|
||||
/// missing-glyph boxes) unless `FIGCRAFT_EMBED_SCRIPTS` names their script tags; native builds
|
||||
/// keep every face, as before.
|
||||
#[test]
|
||||
fn web_embeds_other_scripts_faces_only_when_asked() {
|
||||
let f = Fixture::new();
|
||||
std::fs::write(
|
||||
f.0.join("fonts/manifest.txt"),
|
||||
"Noto Sans Georgian | Regular | fonts/face.ttf | Geor\nNoto Sans Arabic | Regular | fonts/face.ttf | Arab\nNoto Sans Hebrew | Regular | fonts/face.ttf | Hebr\nNoto Sans Symbols | Regular | fonts/face.ttf | Zsym,Latn\n",
|
||||
)
|
||||
.unwrap();
|
||||
let families = |c: &Catalog| c.faces.iter().map(|(f, _)| f.clone()).collect::<Vec<String>>();
|
||||
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[]).unwrap();
|
||||
assert_eq!(families(&web), ["Noto Sans Georgian"], "the web budget: Georgian only");
|
||||
let arabic = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &["Arab".to_string()], &[]).unwrap();
|
||||
assert_eq!(families(&arabic), ["Noto Sans Georgian", "Noto Sans Arabic"]);
|
||||
// Several tags, any case, spaces, and a tag among a face's several scripts.
|
||||
let more = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &scripts_from(Some(" hebr, LATN ")), &[]).unwrap();
|
||||
assert_eq!(families(&more), ["Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Symbols"]);
|
||||
// Native builds keep every face whatever the variable says.
|
||||
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[]).unwrap().faces.len(), 4);
|
||||
// The variable reaches the catalog through `input_fonts`.
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &["Arab".into()], &[]).unwrap().contains("Noto Sans Arabic"));
|
||||
assert!(!input_fonts(Some(&f.0), true, false, false, &[], &[]).unwrap().contains("Noto Sans Arabic"));
|
||||
assert!(scripts_from(None).is_empty());
|
||||
}
|
||||
|
||||
/// Asserts `FIGCRAFT_WEB_FONTS` (split on commas, trimmed) adds the families it names to the web
|
||||
@@ -254,11 +311,11 @@ mod tests {
|
||||
let named = web_fonts(" Noto Sans Thai, ,Noto Sans Thia ");
|
||||
assert_eq!(named, ["Noto Sans Thai", "Noto Sans Thia"]);
|
||||
let families = |c: &Catalog| c.faces.iter().map(|(family, _)| family.clone()).collect::<Vec<_>>();
|
||||
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &named).unwrap();
|
||||
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &named).unwrap();
|
||||
assert_eq!(families(&web), ["Noto Sans Georgian", "Noto Sans Thai"], "the named family joins; the others stay out");
|
||||
assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before");
|
||||
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[]).unwrap().faces.len(), 3, "native builds embed every family");
|
||||
assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before");
|
||||
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[]).unwrap().faces.len(), 3, "native builds embed every family");
|
||||
assert_eq!(not_embedded(&named, &web.faces), ["Noto Sans Thia"], "a misspelt family is reported");
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &named).unwrap().contains("family: \"Noto Sans Thai\""));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &[], &named).unwrap().contains("family: \"Noto Sans Thai\""));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,10 +544,13 @@ fn names(f: &skrifa::FontRef) -> (Option<String>, Option<String>) {
|
||||
(family, style)
|
||||
}
|
||||
|
||||
/// Families tried, in order, for characters a text's own font lacks. The symbol fonts come last:
|
||||
/// Apple Symbols (macOS), Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for
|
||||
/// signs such as ⌖ and ⤒ that no text face has.
|
||||
const FALLBACK_FAMILIES: [&str; 29] = [
|
||||
/// Families tried, in order, for characters a text's own font lacks. Every script face craft-fonts
|
||||
/// can embed (Noto Sans Arabic, Thai, Hebrew, Devanagari, Georgian) is here after the Latin faces,
|
||||
/// so a web build that embeds one (`FIGCRAFT_EMBED_SCRIPTS`, #1902) draws that script in an Inter
|
||||
/// document: the browser has no other fonts. The symbol fonts come last: Apple Symbols (macOS),
|
||||
/// Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for signs such as ⌖ and ⤒
|
||||
/// that no text face has.
|
||||
const FALLBACK_FAMILIES: [&str; 32] = [
|
||||
"Inter",
|
||||
"Helvetica Neue",
|
||||
"Arial",
|
||||
@@ -571,6 +574,9 @@ const FALLBACK_FAMILIES: [&str; 29] = [
|
||||
"Leelawadee UI",
|
||||
"Thonburi",
|
||||
"Tahoma",
|
||||
"Noto Sans Hebrew",
|
||||
"Noto Sans Devanagari",
|
||||
"Noto Sans Georgian",
|
||||
"Apple Symbols",
|
||||
"Segoe UI Symbol",
|
||||
"Noto Sans Symbols",
|
||||
@@ -640,6 +646,9 @@ struct FallbackLists {
|
||||
|
||||
/// The most styles whose fallback faces are kept (a file naming more starts the list again).
|
||||
const MAX_FALLBACK_STYLES: usize = 64;
|
||||
/// Most faces loaded from one font collection given as bytes (the largest real collections,
|
||||
/// the CJK ones, hold a few dozen).
|
||||
const MAX_COLLECTION_FACES: u32 = 64;
|
||||
|
||||
/// [`FontDb::key`]'s and [`FontDb::resolve`]'s answers for the families known in one generation.
|
||||
#[derive(Default)]
|
||||
@@ -711,7 +720,10 @@ impl FontDb {
|
||||
pub fn add_bytes(&mut self, bytes: Vec<u8>) -> Vec<Arc<Face>> {
|
||||
let shared = Arc::new(bytes);
|
||||
let count = match FileRef::new(shared.as_slice()) {
|
||||
Ok(FileRef::Collection(c)) => c.len(),
|
||||
// A collection's header may name any number of faces, each a few bytes pointing at
|
||||
// the same tables, and every face keeps its own character map: at most
|
||||
// [`MAX_COLLECTION_FACES`] of them are loaded.
|
||||
Ok(FileRef::Collection(c)) => c.len().min(MAX_COLLECTION_FACES),
|
||||
Ok(FileRef::Font(_)) => 1,
|
||||
Err(_) => 0,
|
||||
};
|
||||
|
||||
@@ -541,6 +541,31 @@ fn every_platform_has_a_thai_font_in_the_fallbacks() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #1902: a web build has no system fonts, so a document's missing characters can only come from
|
||||
/// the embedded faces. Every script face craft-fonts can embed (`FIGCRAFT_EMBED_SCRIPTS`) is a
|
||||
/// document fallback after the Latin faces; else Hebrew or Devanagari typed into an Inter layer
|
||||
/// would stay missing glyphs with its face embedded.
|
||||
#[test]
|
||||
fn every_embeddable_script_face_is_a_document_fallback() {
|
||||
let at = |family: &str| FALLBACK_FAMILIES.iter().position(|f| *f == family);
|
||||
let latin = at("Segoe UI").unwrap();
|
||||
for face in [
|
||||
"Noto Sans Arabic",
|
||||
"Noto Sans Thai",
|
||||
"Noto Sans Hebrew",
|
||||
"Noto Sans Devanagari",
|
||||
"Noto Sans Georgian",
|
||||
"Noto Sans Symbols",
|
||||
"Noto Sans Symbols 2",
|
||||
] {
|
||||
assert!(at(face).is_some_and(|i| i > latin), "{face} is a fallback after the Latin faces");
|
||||
}
|
||||
// And whatever script face this build embeds (CI builds have craft-fonts; CJK by request).
|
||||
for f in CRAFT_FONTS.iter().filter(|f| f.family.starts_with("Noto Sans") && !f.family.contains("CJK")) {
|
||||
assert!(FALLBACK_FAMILIES.contains(&f.family), "embedded {} is a document fallback", f.family);
|
||||
}
|
||||
}
|
||||
|
||||
// The paths are Unix absolute paths (font managers are a macOS thing): on Windows they aren't absolute.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -598,3 +623,15 @@ fn system_font_dirs_are_walked_once_each() {
|
||||
let unique: std::collections::HashSet<_> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len(), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_collection_header_naming_billions_of_faces_loads_a_bounded_few() {
|
||||
// Four bytes per face offset: a header can name far more faces than the data holds, and each
|
||||
// one would be parsed (and keep a character map) in turn.
|
||||
let mut bytes = synthetic_font_collection(32);
|
||||
bytes[8..12].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
let start = std::time::Instant::now();
|
||||
let faces = FontDb::default().add_bytes(bytes);
|
||||
assert!(faces.len() <= 64, "{}", faces.len());
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
}
|
||||
|
||||
@@ -413,6 +413,12 @@ name = "English"
|
||||
"Scrubbing at 1x" = "Scrubbing at 1x"
|
||||
"Scrubbing at 1/2" = "Scrubbing at 1/2"
|
||||
"Scrubbing at 1/4" = "Scrubbing at 1/4"
|
||||
"Delete {n} variables" = { one = "Delete {n} variable", other = "Delete {n} variables" }
|
||||
"Move out of any group" = "Move out of any group"
|
||||
"Move to group {group}" = "Move to group {group}"
|
||||
"Scope: all supported properties" = "Scope: all supported properties"
|
||||
"Scope: hidden from pickers" = "Scope: hidden from pickers"
|
||||
"Scope: only {scope}" = "Scope: only {scope}"
|
||||
"Wrap style" = "Wrap style"
|
||||
"Text direction" = "Text direction"
|
||||
"Auto: by the first letter with a direction" = "Auto: by the first letter with a direction"
|
||||
|
||||
@@ -385,6 +385,12 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
|
||||
"Decoration style" = "გაფორმების სტილი"
|
||||
"Decoration" = "გაფორმება"
|
||||
"Deep select" = "ღრმა მონიშვნა"
|
||||
"Wrap style" = "გადატანის სტილი"
|
||||
"Balance" = "დაბალანსებული"
|
||||
"Pretty" = "მოწესრიგებული"
|
||||
"Auto: as many words as fit on each line" = "ავტომატური: თითო სტრიქონში იმდენი სიტყვა, რამდენიც ეტევა"
|
||||
"Balance: every line close to the same length" = "დაბალანსებული: ყველა სტრიქონი დაახლოებით ერთი სიგრძისაა"
|
||||
"Pretty: full lines, no one word alone on the last" = "მოწესრიგებული: სავსე სტრიქონები, ბოლო სტრიქონზე ერთი სიტყვა მარტო არ რჩება"
|
||||
"Default" = "ნაგულისხმევი"
|
||||
"Default content" = "ნაგულისხმევი შიგთავსი"
|
||||
"Default value (the top-left variant)" = "ნაგულისხმევი მნიშვნელობა (ზედა მარცხენა ვარიანტი)"
|
||||
|
||||
@@ -34,6 +34,12 @@ fn handle(u: &Ui, side: &str) -> Option<Rect> {
|
||||
u.ctx.memory(|m| m.areas().visible_last_frame(&layer)).then(|| u.ctx.memory(|m| m.area_rect(layer.id))).flatten()
|
||||
}
|
||||
|
||||
/// Where the bar above the selection shows, if it does.
|
||||
fn bar(u: &Ui) -> Option<Rect> {
|
||||
let layer = LayerId::new(Order::Middle, Id::unique("board_bar"));
|
||||
u.ctx.memory(|m| m.areas().visible_last_frame(&layer)).then(|| u.ctx.memory(|m| m.area_rect(layer.id))).flatten()
|
||||
}
|
||||
|
||||
fn click(u: &mut Ui, p: Pos2) {
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
|
||||
@@ -140,3 +146,166 @@ fn the_object_a_stamp_will_stick_to_is_highlighted() {
|
||||
u.button(off, false);
|
||||
assert_eq!((target(&u), on(&u)), (None, None), "let go off the shape: on nothing, and no outline");
|
||||
}
|
||||
|
||||
/// Dragging a "+" carries the preview ("Click to select and create the next shape in that
|
||||
/// direction, or drag the preview to any location on your board", Build faster with quick create;
|
||||
/// #1919): let go on empty board and the next shape is made there, centred on the pointer, joined
|
||||
/// by a connector, with typing started; one undo takes both away.
|
||||
#[test]
|
||||
fn dragging_a_handle_drops_the_next_shape_where_it_is_let_go() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let before = u.app.session.doc().unwrap().ids().count();
|
||||
let from = handle(&u, "below").expect("a handle below").center();
|
||||
let to = from + egui::vec2(260.0, 180.0);
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let next = doc.ids().find(|i| *i != a && matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).expect("a new shape");
|
||||
let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector");
|
||||
let centre = screen_box(&u, next).center();
|
||||
assert!((centre - to).length() < 1.0, "centred where it was let go: {centre:?}, not {to:?}");
|
||||
assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(next)));
|
||||
assert!(u.app.session.ds().unwrap().text_edit.is_some(), "typing in the new shape");
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
u.app.session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "undo takes the shape and its connector away");
|
||||
}
|
||||
|
||||
/// A "+" dragged onto another sticky or shape joins the two with a connector instead of making a
|
||||
/// new shape (#1919).
|
||||
#[test]
|
||||
fn dropping_a_handle_on_another_shape_joins_them() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
let b = id(&u.app.session.execute("board.shape", &json!({"shape": "ellipse", "x": 400, "y": 300, "width": 160, "height": 100})).unwrap());
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let shapes = |u: &Ui| {
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
doc.ids().filter(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).count()
|
||||
};
|
||||
assert_eq!(shapes(&u), 2);
|
||||
let from = handle(&u, "right").expect("a handle right").center();
|
||||
let to = screen_box(&u, b).center();
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(shapes(&u), 2, "no new shape");
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector");
|
||||
assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(b)));
|
||||
}
|
||||
|
||||
/// A sticky or shape inside a section or frame takes the drop too (review): the connector joins it.
|
||||
#[test]
|
||||
fn dropping_a_handle_on_a_shape_inside_a_frame_joins_it() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
let f = id(&u.app.session.execute("frame.create", &json!({"x": 300, "y": 200, "width": 500, "height": 400})).unwrap());
|
||||
let b = id(&u
|
||||
.app
|
||||
.session
|
||||
.execute("board.shape", &json!({"shape": "ellipse", "x": 100, "y": 100, "width": 160, "height": 100, "parent": f}))
|
||||
.unwrap());
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let from = handle(&u, "right").expect("a handle right").center();
|
||||
let to = screen_box(&u, b).center();
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector");
|
||||
assert!(
|
||||
matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(b)),
|
||||
"joined to the shape in the frame, not the frame"
|
||||
);
|
||||
}
|
||||
|
||||
/// A handle let go off the canvas, over a panel, makes nothing (review).
|
||||
#[test]
|
||||
fn letting_a_handle_go_over_a_panel_makes_nothing() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let before = u.app.session.doc().unwrap().ids().count();
|
||||
let from = handle(&u, "left").expect("a handle left").center();
|
||||
// The left sidebar.
|
||||
let to = Pos2::new(u.app.canvas.rect.min.x - 60.0, from.y);
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "nothing made");
|
||||
}
|
||||
|
||||
/// A handle let go over the floating toolbar at the bottom of the canvas makes nothing either
|
||||
/// (review): the toolbar lies inside the canvas rectangle.
|
||||
#[test]
|
||||
fn letting_a_handle_go_over_the_toolbar_makes_nothing() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let before = u.app.session.doc().unwrap().ids().count();
|
||||
let from = handle(&u, "below").expect("a handle below").center();
|
||||
let to = crate::toolbar::pill_rect(u.app.canvas.rect, crate::toolbar::bar_width(&u.app)).center();
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "nothing made behind the toolbar");
|
||||
}
|
||||
|
||||
/// The selection moving to another shape under a drag ends the drag (review): letting go later,
|
||||
/// even with the first shape selected again, makes nothing.
|
||||
#[test]
|
||||
fn a_drag_ends_when_the_selection_moves_to_another_shape() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
let b = id(&u.app.session.execute("board.shape", &json!({"shape": "ellipse", "x": 600, "y": 0, "width": 160, "height": 100})).unwrap());
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let before = u.app.session.doc().unwrap().ids().count();
|
||||
let from = handle(&u, "below").expect("a handle below").center();
|
||||
let to = from + egui::vec2(0.0, 160.0);
|
||||
u.drag_to(from, to);
|
||||
u.app.session.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
u.frame(vec![Event::PointerMoved(to)]);
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![Event::PointerMoved(to)]);
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.session.doc().unwrap().ids().count(), before, "the drag was over");
|
||||
}
|
||||
|
||||
/// The bar above the selection stays away while a handle is dragged, as for any drag (review):
|
||||
/// letting go where it was makes the next one there, not behind it, and the bar is back after.
|
||||
#[test]
|
||||
fn the_bar_stays_away_while_a_handle_is_dragged() {
|
||||
let (mut u, a) = board_with_shape();
|
||||
u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
let r = bar(&u).expect("the bar shows");
|
||||
let from = handle(&u, "above").expect("a handle above").center();
|
||||
let to = r.center();
|
||||
u.drag_to(from, to);
|
||||
assert!(bar(&u).is_none(), "no bar while a handle is dragged");
|
||||
u.button(to, false);
|
||||
u.frame(vec![]);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let next = doc.ids().find(|i| *i != a && matches!(doc.node(*i).unwrap().board, Some(BoardItem::Shape { .. }))).expect("a new shape");
|
||||
let line = doc.ids().find(|i| matches!(doc.node(*i).unwrap().board, Some(BoardItem::Connector(_)))).expect("a connector");
|
||||
let centre = screen_box(&u, next).center();
|
||||
assert!((centre - to).length() < 1.0, "centred where the bar was: {centre:?}, not {to:?}");
|
||||
assert!(matches!(&doc.node(line).unwrap().board, Some(BoardItem::Connector(c)) if c.from.node() == Some(a) && c.to.node() == Some(next)));
|
||||
// Typing in the new one keeps the bar away, as before; done typing, it is back.
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
assert!(bar(&u).is_some(), "the bar is back for the new selection");
|
||||
}
|
||||
|
||||
@@ -191,10 +191,11 @@ pub(crate) fn place(sel: Rect, size: egui::Vec2, canvas: Rect) -> Pos2 {
|
||||
pos2(cx - w / 2.0, y)
|
||||
}
|
||||
|
||||
/// The bar above a board's selection, while nothing is being dragged and the file can be edited.
|
||||
/// The bar above a board's selection, while nothing is being dragged (a "+" handle included) and
|
||||
/// the file can be edited.
|
||||
pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let editable = app.session.active_read_only().is_none();
|
||||
if app.session.tool.busy() || !editable || !app.session.doc().is_ok_and(figcraft_engine::board::is_board) {
|
||||
if app.session.tool.busy() || !editable || !app.session.doc().is_ok_and(figcraft_engine::board::is_board) || crate::board_connect::dragging(ctx) {
|
||||
return;
|
||||
}
|
||||
let Some(h) = has(app) else { return };
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! Boards: a "+" beside each side of the one selected sticky or shape (#1597). Hovering one shows
|
||||
//! where the next one goes; clicking it makes the next of the same kind there, joined by a
|
||||
//! connector, and starts typing in it (`board.addConnected`).
|
||||
//! connector, and starts typing in it (`board.addConnected`). Dragging one carries the preview
|
||||
//! ("drag the preview to any location on your board", #1919): let go on empty board and the next
|
||||
//! one is made there, joined by a connector leaving by the handle's side; let go on another sticky
|
||||
//! or shape (inside a section too) and a connector joins the two; let go off the canvas or over the
|
||||
//! toolbar, nothing. The bar above the selection stays away while a "+" is dragged, as for any drag.
|
||||
|
||||
use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, pos2, vec2};
|
||||
use egui::{Area, Color32, CornerRadius, Id, LayerId, Order, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, pos2, vec2};
|
||||
use figcraft_doc::{BoardItem, NodeId};
|
||||
use figcraft_engine::ToolId;
|
||||
use figcraft_engine::board::{STICKY, connected_place};
|
||||
use figcraft_engine::board::{STICKY, connected_place, sticky_or_shape_at};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::FigApp;
|
||||
@@ -18,6 +22,17 @@ pub(crate) const REACH: f32 = 36.0;
|
||||
const RADIUS: f32 = 9.0;
|
||||
const SIDES: [&str; 4] = ["above", "right", "below", "left"];
|
||||
|
||||
/// A drag from a "+": the object and the side it started from, kept while the button is down.
|
||||
#[derive(Clone)]
|
||||
struct Drag {
|
||||
from: NodeId,
|
||||
side: &'static str,
|
||||
}
|
||||
|
||||
fn drag_id() -> Id {
|
||||
Id::unique("board_connect_drag")
|
||||
}
|
||||
|
||||
/// The sticky or shape the handles are for: its id, its box on the page and the next one's size.
|
||||
fn target(app: &FigApp) -> Option<(NodeId, figcraft_geom::Rect, (f64, f64))> {
|
||||
let editable = app.session.active_read_only().is_none();
|
||||
@@ -41,6 +56,12 @@ pub(crate) fn shown(app: &FigApp) -> bool {
|
||||
target(app).is_some()
|
||||
}
|
||||
|
||||
/// A "+" is being dragged: the bar above the selection stays away meanwhile, as for any drag, so
|
||||
/// nothing is made behind it.
|
||||
pub(crate) fn dragging(ctx: &egui::Context) -> bool {
|
||||
ctx.data(|d| d.get_temp::<Drag>(drag_id())).is_some()
|
||||
}
|
||||
|
||||
/// The centre of the "+" for `side` of the object's screen box `r`.
|
||||
fn handle_at(r: Rect, side: &str) -> Pos2 {
|
||||
match side {
|
||||
@@ -51,8 +72,35 @@ fn handle_at(r: Rect, side: &str) -> Pos2 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The middle of `side` of the object's screen box `r`, where its connector leaves.
|
||||
fn side_middle(r: Rect, side: &str) -> Pos2 {
|
||||
match side {
|
||||
"above" => r.center_top(),
|
||||
"right" => r.right_center(),
|
||||
"below" => r.center_bottom(),
|
||||
_ => r.left_center(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A "+" side as `board.connector` names it.
|
||||
fn connector_side(side: &str) -> &'static str {
|
||||
match side {
|
||||
"above" => "top",
|
||||
"below" => "bottom",
|
||||
"left" => "left",
|
||||
_ => "right",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let Some((id, b, next)) = target(app) else { return };
|
||||
let drag: Option<Drag> = ctx.data(|d| d.get_temp(drag_id()));
|
||||
let Some((id, b, next)) = target(app) else {
|
||||
// The selection or the tool changed under a drag: it is over.
|
||||
if drag.is_some() {
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let r = Rect::from_two_pos(app.to_screen(b.x0, b.y0), app.to_screen(b.x1, b.y1));
|
||||
// Too small on screen to tell the handles from the object.
|
||||
if r.width() < 2.0 * RADIUS || r.height() < 2.0 * RADIUS {
|
||||
@@ -63,16 +111,18 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
// Not over the toolbar at the bottom of the canvas.
|
||||
let toolbar = crate::toolbar::pill_rect(app.canvas.rect, crate::toolbar::bar_width(app)).expand(RADIUS);
|
||||
let mut picked = None;
|
||||
let mut started = None;
|
||||
let mut let_go = false;
|
||||
for side in SIDES {
|
||||
let c = handle_at(r, side);
|
||||
if !app.canvas.rect.shrink(RADIUS).contains(c) || toolbar.contains(c) {
|
||||
continue;
|
||||
}
|
||||
let area = Area::new(Id::unique(("board_connect", side))).fixed_pos(c - vec2(RADIUS, RADIUS)).order(Order::Middle);
|
||||
let clicked = area
|
||||
let (clicked, drag_started, drag_stopped) = area
|
||||
.show(ctx, |ui| {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(2.0 * RADIUS, 2.0 * RADIUS), Sense::click());
|
||||
let hot = resp.hovered();
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(2.0 * RADIUS, 2.0 * RADIUS), Sense::click_and_drag());
|
||||
let hot = resp.hovered() || resp.dragged();
|
||||
let p = ui.painter();
|
||||
p.circle_filled(rect.center(), RADIUS, if hot { accent } else { t.panel });
|
||||
p.circle_stroke(rect.center(), RADIUS, Stroke::new(1.0, if hot { accent } else { t.border }));
|
||||
@@ -80,19 +130,72 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let arm = RADIUS * 0.45;
|
||||
p.line_segment([rect.center() - vec2(arm, 0.0), rect.center() + vec2(arm, 0.0)], ink);
|
||||
p.line_segment([rect.center() - vec2(0.0, arm), rect.center() + vec2(0.0, arm)], ink);
|
||||
if hot {
|
||||
// Where a click puts the next one; a drag shows its own preview.
|
||||
if hot && drag.is_none() && !resp.dragged() {
|
||||
preview(app, ctx, b, next, side, accent);
|
||||
}
|
||||
resp.on_hover_text(tr("Add a connected shape")).clicked()
|
||||
let resp = resp.on_hover_text(tr("Add a connected shape"));
|
||||
(resp.clicked(), resp.drag_started(), resp.drag_stopped())
|
||||
})
|
||||
.inner;
|
||||
if clicked {
|
||||
picked = Some(side);
|
||||
}
|
||||
if drag_started {
|
||||
started = Some(side);
|
||||
}
|
||||
let_go |= drag_stopped;
|
||||
}
|
||||
if let Some(side) = picked {
|
||||
app.run("board.addConnected", json!({"id": id, "side": side, "edit": true}));
|
||||
}
|
||||
if let Some(side) = started {
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag { from: id, side }));
|
||||
}
|
||||
// A drag carries the preview: the next one centred on the pointer, or the object under it,
|
||||
// which the connector joins instead.
|
||||
let Some(Drag { from, side }) = drag else { return };
|
||||
// The selection moved to another sticky or shape under the drag: it is over too.
|
||||
if from != id {
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
return;
|
||||
}
|
||||
let Some(pointer) = ctx.input(|i| i.pointer.latest_pos()) else { return };
|
||||
let over = object_under(app, from, pointer);
|
||||
// Off the canvas (over a panel) or over the floating toolbar there is nothing to show and
|
||||
// nothing to make.
|
||||
let on_canvas = app.canvas.rect.contains(pointer) && !toolbar.contains(pointer);
|
||||
if on_canvas {
|
||||
drag_preview(app, ctx, (b, next, side), pointer, over);
|
||||
}
|
||||
if let_go {
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
if !on_canvas {
|
||||
return;
|
||||
}
|
||||
match over {
|
||||
Some(to) => {
|
||||
app.run("board.connector", json!({"from": from, "to": to, "fromSide": connector_side(side)}));
|
||||
}
|
||||
None => {
|
||||
let q = app.to_page(pointer);
|
||||
app.run("board.addConnected", json!({"id": from, "side": side, "at": [q.x, q.y], "edit": true}));
|
||||
}
|
||||
}
|
||||
} else if !ctx.input(|i| i.pointer.any_down()) {
|
||||
// The button came up without the handle hearing of it (the pointer left the window).
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The sticky or shape under the screen point `p` on the canvas (inside a section or frame too),
|
||||
/// other than `except`.
|
||||
fn object_under(app: &FigApp, except: NodeId, p: Pos2) -> Option<NodeId> {
|
||||
if !app.canvas.rect.contains(p) {
|
||||
return None;
|
||||
}
|
||||
let ds = app.session.ds().ok()?;
|
||||
sticky_or_shape_at(&ds.doc, ds.page, app.to_page(p), Some(except))
|
||||
}
|
||||
|
||||
/// Where the next one goes for `side`, faintly: its box and the connector's line to it.
|
||||
@@ -107,9 +210,46 @@ fn preview(app: &FigApp, ctx: &egui::Context, b: figcraft_geom::Rect, next: (f64
|
||||
_ => (from.left_center(), ghost.right_center()),
|
||||
};
|
||||
let p = ctx.layer_painter(LayerId::new(Order::Middle, Id::unique("board_connect_preview")));
|
||||
let faint = Stroke::new(1.5, accent.gamma_multiply(0.6));
|
||||
ghost_box(&p, ghost, accent);
|
||||
p.line_segment([a, z], faint);
|
||||
}
|
||||
|
||||
/// The next one's box, faintly: a tint and a dashed outline.
|
||||
fn ghost_box(p: &egui::Painter, ghost: Rect, accent: Color32) {
|
||||
let faint = Stroke::new(1.5, accent.gamma_multiply(0.6));
|
||||
p.rect_filled(ghost, CornerRadius::same(8), accent.gamma_multiply(0.08));
|
||||
let corners = [ghost.left_top(), ghost.right_top(), ghost.right_bottom(), ghost.left_bottom(), ghost.left_top()];
|
||||
p.extend(Shape::dashed_line(&corners, faint, 6.0, 4.0));
|
||||
p.line_segment([a, z], faint);
|
||||
}
|
||||
|
||||
/// The dragged preview: the next one centred on `pointer` and the connector's line to it from
|
||||
/// `side` of the object's box `b`, or, over another object, that object outlined and the line to
|
||||
/// it; the line arrives at the side of the box facing the object.
|
||||
fn drag_preview(app: &FigApp, ctx: &egui::Context, (b, next, side): (figcraft_geom::Rect, (f64, f64), &str), pointer: Pos2, over: Option<NodeId>) {
|
||||
let accent = crate::theme::canvas_accent(ctx);
|
||||
let from = Rect::from_two_pos(app.to_screen(b.x0, b.y0), app.to_screen(b.x1, b.y1));
|
||||
let p = ctx.layer_painter(LayerId::new(Order::Middle, Id::unique("board_connect_preview")));
|
||||
let to_box = match over.and_then(|o| app.session.doc().ok()?.world_bounds(o)) {
|
||||
Some(ob) => {
|
||||
let r = Rect::from_two_pos(app.to_screen(ob.x0, ob.y0), app.to_screen(ob.x1, ob.y1));
|
||||
p.rect_stroke(r, CornerRadius::same(4), Stroke::new(1.5, accent), StrokeKind::Outside);
|
||||
r
|
||||
}
|
||||
None => {
|
||||
let size = app.to_screen(next.0, next.1) - app.to_screen(0.0, 0.0);
|
||||
let ghost = Rect::from_center_size(pointer, size);
|
||||
ghost_box(&p, ghost, accent);
|
||||
ghost
|
||||
}
|
||||
};
|
||||
let d = to_box.center() - from.center();
|
||||
let z = if d.x.abs() >= d.y.abs() {
|
||||
if d.x >= 0.0 { to_box.left_center() } else { to_box.right_center() }
|
||||
} else if d.y >= 0.0 {
|
||||
to_box.center_top()
|
||||
} else {
|
||||
to_box.center_bottom()
|
||||
};
|
||||
p.line_segment([side_middle(from, side), z], Stroke::new(1.5, accent.gamma_multiply(0.6)));
|
||||
}
|
||||
|
||||
@@ -40,6 +40,15 @@ enum Drag {
|
||||
/// The Crop-mode image being edited: (node, fills, index, paint, image rect in the unit box).
|
||||
type UnitRect = (f64, f64, f64, f64);
|
||||
|
||||
/// The paint list a picker paint at an index belongs to on layer `n`, as the Fill section and the
|
||||
/// colour picker list it: for fills, a text's characters' shared fills (`character_fills`: the
|
||||
/// layer's own when the characters have none), else the layer's strokes. None when a text's
|
||||
/// characters have different fills. Writes go through `fill.set`, which moves the characters'
|
||||
/// list to the layer first, so the handles read and write the same paint (#1856).
|
||||
fn edited_list(n: &figcraft_doc::Node, fills: bool) -> Option<Vec<Paint>> {
|
||||
if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }
|
||||
}
|
||||
|
||||
/// The paint open in the colour picker, else the image fill in crop mode (while its layer is the
|
||||
/// selection).
|
||||
fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRect)> {
|
||||
@@ -53,7 +62,7 @@ fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRec
|
||||
};
|
||||
let doc = app.session.doc().ok()?;
|
||||
let n = doc.node(id)?;
|
||||
let list = if fills { &n.fills } else { &n.strokes };
|
||||
let list = edited_list(n, fills)?;
|
||||
let PaintKind::Image(img) = &list.get(index)?.kind else { return None };
|
||||
if img.scale_mode != ImageScaleMode::Crop {
|
||||
return None;
|
||||
@@ -220,7 +229,7 @@ fn gradient_target(app: &FigApp) -> Option<(NodeId, bool, usize, figcraft_color:
|
||||
return None;
|
||||
}
|
||||
let n = app.session.doc().ok()?.node(id)?;
|
||||
let list = if *fills { &n.fills } else { &n.strokes };
|
||||
let list = edited_list(n, *fills)?;
|
||||
match &list.get(*index)?.kind {
|
||||
PaintKind::Gradient(g) => Some((id, *fills, *index, g.clone())),
|
||||
_ => None,
|
||||
@@ -260,7 +269,7 @@ fn line_param(a: Pos2, b: Pos2, p: Pos2) -> Option<(f64, f32)> {
|
||||
|
||||
fn set_gradient(app: &mut FigApp, id: NodeId, fills: bool, index: usize, g: figcraft_color::Gradient) {
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(id)).cloned() else { return };
|
||||
let list = if fills { &n.fills } else { &n.strokes };
|
||||
let Some(list) = edited_list(&n, fills) else { return };
|
||||
let Some(mut paint) = list.get(index).cloned() else { return };
|
||||
paint.kind = PaintKind::Gradient(g);
|
||||
let cmd = if fills { "fill.set" } else { "stroke.set" };
|
||||
@@ -684,7 +693,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
Drag::Gradient { id, fills, index, which } => {
|
||||
let Some(u) = screen_to_unit(app, *id, pos) else { return };
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let list = if *fills { &n.fills } else { &n.strokes };
|
||||
let Some(list) = edited_list(&n, *fills) else { return };
|
||||
let Some(mut paint) = list.get(*index).cloned() else { return };
|
||||
if let PaintKind::Gradient(g) = &mut paint.kind {
|
||||
match which {
|
||||
@@ -759,7 +768,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
(ax.min(ax + nw), ay.min(ay + nh), ax.max(ax + nw), ay.max(ay + nh))
|
||||
};
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let list = if *fills { &n.fills } else { &n.strokes };
|
||||
let Some(list) = edited_list(&n, *fills) else { return };
|
||||
let Some(mut paint) = list.get(*index).cloned() else { return };
|
||||
if let PaintKind::Image(img) = &mut paint.kind {
|
||||
img.crop = Some(ImagePaint::crop_from_rect(r.0, r.1, r.2, r.3));
|
||||
@@ -781,3 +790,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod character_fill_tests;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The canvas crop handles on a text whose characters share an image fill the layer doesn't have
|
||||
//! (#1856): they show and edit the characters' image, the one the Fill section and the colour
|
||||
//! picker show, not the layer's own fill at that index.
|
||||
|
||||
use base64::Engine as _;
|
||||
use figcraft_color::{Color, ImageScaleMode, Paint, PaintKind};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use super::crop_target;
|
||||
use crate::colorpicker::PickerTarget;
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::present_tests::id;
|
||||
|
||||
#[test]
|
||||
fn the_crop_handles_follow_the_characters_shared_image_in_crop_mode() {
|
||||
let mut s = Session::new();
|
||||
let t = id(&s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap());
|
||||
s.execute("fill.set", &json!({"ids": [t.0], "color": "#00FF00"})).unwrap();
|
||||
let image = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 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());
|
||||
s.execute("image.place", &json!({"data": data, "target": t.0, "mode": "fill"})).unwrap();
|
||||
s.execute("image.crop", &json!({"ids": [t.0], "index": 1})).unwrap();
|
||||
// The cropped image goes to the characters; the layer keeps only its green.
|
||||
let cropped = s.doc().unwrap().node(t).unwrap().fills[1].clone();
|
||||
s.execute("text.style", &json!({"id": t.0, "start": 0, "end": 5, "textFills": [cropped]})).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(t).unwrap().fills = vec![Paint::solid(Color::from_hex("#00FF00").unwrap())];
|
||||
let mut u = Ui::new(s);
|
||||
// The picker on the Fill section's row: the characters' image, already in Crop mode.
|
||||
u.app.ui.picker = Some(PickerTarget::Paint { fills: true, index: 0, ids: vec![t] });
|
||||
let (at, fills, index, img, _) = crop_target(&u.app).expect("the handles show the characters' image");
|
||||
assert_eq!((at, fills, index), (t, true, 0));
|
||||
assert_eq!(img.scale_mode, ImageScaleMode::Crop);
|
||||
assert!(
|
||||
matches!(u.app.session.doc().unwrap().node(t).unwrap().fills[0].kind, PaintKind::Solid { .. }),
|
||||
"the layer's own fill is not what they show"
|
||||
);
|
||||
}
|
||||
@@ -53,6 +53,113 @@ pub struct Editor {
|
||||
details: Option<String>,
|
||||
/// The group the table shows ("space" or "color/brand"); None = every variable.
|
||||
group: Option<String>,
|
||||
/// The selected variables' ids (this file's), kept to the rows the table shows.
|
||||
pub(crate) selected: Vec<String>,
|
||||
/// The row a Shift+click extends from.
|
||||
pub(crate) anchor: Option<String>,
|
||||
/// The variable ids the table shows now, in row order (the range a Shift+click covers).
|
||||
pub(crate) order: Vec<String>,
|
||||
}
|
||||
|
||||
/// A click on row `id`: plain selects only it, Shift extends from the anchor to it through the
|
||||
/// rows shown (added to the selection with Cmd/Ctrl), Cmd/Ctrl (or Shift without an anchor) toggles it.
|
||||
pub(crate) fn select_clicked(st: &mut Editor, id: &str, m: egui::Modifiers) {
|
||||
let pos = |x: &str| st.order.iter().position(|o| o == x);
|
||||
let anchor = st.anchor.as_deref().filter(|a| st.selected.iter().any(|s| s == a)).and_then(pos);
|
||||
if m.shift
|
||||
&& let (Some(ai), Some(bi)) = (anchor, pos(id))
|
||||
{
|
||||
let (lo, hi) = (ai.min(bi), ai.max(bi));
|
||||
let mut s: Vec<String> = if m.command { st.selected.clone() } else { vec![] };
|
||||
for x in st.order.get(lo..=hi).unwrap_or_default() {
|
||||
if !s.contains(x) {
|
||||
s.push(x.clone());
|
||||
}
|
||||
}
|
||||
st.selected = s;
|
||||
} else if m.shift || m.command {
|
||||
match st.selected.iter().position(|x| x == id) {
|
||||
Some(i) => {
|
||||
st.selected.remove(i);
|
||||
}
|
||||
None => st.selected.push(id.to_string()),
|
||||
}
|
||||
st.anchor = Some(id.to_string());
|
||||
} else {
|
||||
st.selected = vec![id.to_string()];
|
||||
st.anchor = Some(id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// The variables a row's menu acts on: the whole selection when the row is part of a selection of
|
||||
/// several (in table order, leaving out inherited ones, which are changed in their own collection),
|
||||
/// else None.
|
||||
fn bulk_ids<'a>(view: &View<'a>, st: &Editor, v: &Variable) -> Option<Vec<&'a Variable>> {
|
||||
if !view.editable() || st.selected.len() < 2 || !st.selected.contains(&v.id) {
|
||||
return None;
|
||||
}
|
||||
let list: Vec<&Variable> =
|
||||
st.order.iter().filter(|id| st.selected.contains(id)).filter_map(|id| view.vars.get_by_id(id)).filter(|x| x.extends.is_none()).collect();
|
||||
(list.len() > 1).then_some(list)
|
||||
}
|
||||
|
||||
/// Run one `variable.*` command per variable as a single undo step.
|
||||
fn bulk_run(app: &mut FigApp, label: &str, vars: &[&Variable], step: impl Fn(&Variable) -> Option<(&'static str, Value)>) {
|
||||
let steps: Vec<Value> = vars.iter().filter_map(|v| step(v)).map(|(command, params)| json!({"command": command, "params": params})).collect();
|
||||
if !steps.is_empty() {
|
||||
app.run("command.batch", json!({"label": label, "commands": steps}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The context menu of a row that is part of a selection of several: delete, move to a group and
|
||||
/// scope act on all of them.
|
||||
fn bulk_menu(app: &mut FigApp, ui: &mut Ui, coll_groups: &[String], vars: &[&Variable]) {
|
||||
let n = vars.len();
|
||||
if menu_item(ui, &trn("Delete {n} variables", n, &[]), "") {
|
||||
bulk_run(app, "Delete variables", vars, |v| Some(("variable.delete", json!({"variable": v.id}))));
|
||||
ui.close();
|
||||
}
|
||||
// Many groups make the menu taller than the window: the rows after Delete scroll.
|
||||
let max_h = ui.ctx().content_rect().height() * 0.6;
|
||||
egui::ScrollArea::vertical().id_salt("variables_bulk_menu_scroll").max_height(max_h).show(ui, |ui| {
|
||||
let moves = std::iter::once(None).chain(coll_groups.iter().map(|g| Some(g.as_str())));
|
||||
for g in moves {
|
||||
let label = g.map_or_else(|| tr("Move out of any group").to_string(), |g| trf("Move to group {group}", &[("group", &g)]));
|
||||
if menu_item(ui, &label, "") {
|
||||
bulk_run(app, "Move variables", vars, |v| {
|
||||
let short = v.name.rsplit('/').next().unwrap_or(&v.name);
|
||||
let name = g.map_or_else(|| short.to_string(), |g| format!("{g}/{short}"));
|
||||
(name != v.name).then(|| ("variable.update", json!({"variable": v.id, "name": name})))
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
let mut scopes: Vec<(&'static str, &'static str)> = Vec::new();
|
||||
for v in vars {
|
||||
for s in scopes_for(v.kind) {
|
||||
if !scopes.contains(s) {
|
||||
scopes.push(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
let set = |app: &mut FigApp, label: &str, value: Option<&'static str>, ui: &mut Ui| {
|
||||
if menu_item(ui, label, "") {
|
||||
bulk_run(app, "Change scope", vars, |v| match value {
|
||||
None => Some(("variable.update", json!({"variable": v.id, "scopes": Value::Null}))),
|
||||
Some("") => Some(("variable.update", json!({"variable": v.id, "scopes": []}))),
|
||||
Some(s) => {
|
||||
scopes_for(v.kind).iter().any(|(id, _)| *id == s).then(|| ("variable.update", json!({"variable": v.id, "scopes": [s]})))
|
||||
}
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
};
|
||||
set(app, tr("Scope: all supported properties"), None, ui);
|
||||
set(app, tr("Scope: hidden from pickers"), Some(""), ui);
|
||||
for (id, label) in scopes {
|
||||
set(app, &trf("Scope: only {scope}", &[("scope", &tr(label))]), Some(id), ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
@@ -575,6 +682,17 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) {
|
||||
let mut list: Vec<&Variable> =
|
||||
view.in_collection(&coll.id).filter(|v| in_group(v) && (q.is_empty() || v.name.to_lowercase().contains(&q))).collect();
|
||||
list.sort_by(|a, b| group_of(&a.name).cmp(group_of(&b.name)));
|
||||
st.order = list.iter().map(|v| v.id.clone()).collect();
|
||||
let order = st.order.clone();
|
||||
st.selected.retain(|id| order.contains(id));
|
||||
// Escape clears the selection (unless a field has the keyboard).
|
||||
if !st.selected.is_empty()
|
||||
&& st.rename.is_none()
|
||||
&& !ui.ctx().egui_wants_keyboard_input()
|
||||
&& ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
|
||||
{
|
||||
st.selected.clear();
|
||||
}
|
||||
let width = (NAME_W + coll.modes.len() as f32 * MODE_W + 40.0).max(ui.available_width());
|
||||
egui::ScrollArea::both().id_salt("vars_table").auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
|
||||
@@ -597,6 +715,11 @@ fn table(app: &mut FigApp, ui: &mut Ui, view: &View, st: &mut Editor) {
|
||||
}
|
||||
if view.editable() {
|
||||
create_row(app, ui, view, coll, st);
|
||||
// A click on the empty space below the rows clears the selection.
|
||||
let (_, empty) = ui.allocate_exact_size(vec2(width, ui.available_height().max(24.0)), Sense::click());
|
||||
if empty.clicked() {
|
||||
st.selected.clear();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -686,7 +809,10 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let editable = view.editable();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::click());
|
||||
if resp.hovered() || (editable && st.details.as_deref() == Some(v.id.as_str())) {
|
||||
let selected = editable && st.selected.contains(&v.id);
|
||||
if selected {
|
||||
ui.painter().rect_filled(r, CornerRadius::ZERO, t.selected_row);
|
||||
} else if resp.hovered() || (editable && st.details.as_deref() == Some(v.id.as_str())) {
|
||||
ui.painter().rect_filled(r, CornerRadius::ZERO, t.hover);
|
||||
}
|
||||
kind_glyph(ui, view.vars, v, coll, Rect::from_center_size(pos2(r.min.x + 24.0, r.center().y), vec2(14.0, 14.0)));
|
||||
@@ -709,10 +835,19 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va
|
||||
value_cell(app, ui, view, v, coll, &m.id, cell);
|
||||
}
|
||||
if editable {
|
||||
if resp.clicked() {
|
||||
let m = ui.input(|i| i.modifiers);
|
||||
select_clicked(st, &v.id, m);
|
||||
}
|
||||
if !inherited && resp.double_clicked() && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < name_r.max.x) {
|
||||
start_rename(st, target.clone());
|
||||
}
|
||||
crate::right::context_popup(&resp).show(|ui| {
|
||||
if let Some(vars) = bulk_ids(view, st, v) {
|
||||
let coll_groups = groups(view.in_collection(&coll.id).map(|x| x.name.as_str()));
|
||||
bulk_menu(app, ui, &coll_groups, &vars);
|
||||
return;
|
||||
}
|
||||
if menu_item(ui, tr("Edit variable"), "") {
|
||||
st.details = Some(v.id.clone());
|
||||
ui.close();
|
||||
|
||||
@@ -1294,3 +1294,59 @@ fn sidebar_field_text_stays_in_place_on_focus() {
|
||||
assert!((before.center().y - after.center().y).abs() <= 0.5, "numeric={numeric}: before={before:?}, after={after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option
|
||||
/// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what
|
||||
/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without
|
||||
/// Alt a drag on the field is no click, so it neither edits nor moves anything.
|
||||
#[test]
|
||||
fn alt_held_over_a_field_scrubs_it() {
|
||||
let (mut u, a, _) = setup();
|
||||
let (at, _) = field(&mut u, "X");
|
||||
let steps = undo_steps(&u);
|
||||
// Alt is held as the pointer arrives over the field, a frame before the press (the field takes
|
||||
// a drag only once it has seen Alt; egui assigns a press by the frame before it).
|
||||
let alt = Modifiers { alt: true, ..Modifiers::NONE };
|
||||
u.frame_with(vec![Event::PointerMoved(at)], alt);
|
||||
drag(&mut u, at, 25.0, alt);
|
||||
assert_eq!(geom(&u, a).0, 35.0, "a step a point: X from 10");
|
||||
assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub");
|
||||
assert_eq!(field(&mut u, "X").1, "35", "the field shows it and isn't editing");
|
||||
let (at, _) = field(&mut u, "X");
|
||||
drag(&mut u, at, 25.0, Modifiers::NONE);
|
||||
assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub");
|
||||
assert_eq!(undo_steps(&u), steps + 1);
|
||||
// Alt let go before the button still ends the scrub with its undo step.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
let press = |pressed: bool, m: Modifiers, p: Pos2| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m };
|
||||
u.frame_with(vec![Event::PointerMoved(at)], alt);
|
||||
u.frame_with(vec![press(true, alt, at)], alt);
|
||||
for k in 1..=10 {
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 2.0 * k as f32, at.y))], alt);
|
||||
}
|
||||
let to = pos2(at.x + 20.0, at.y);
|
||||
u.frame_with(vec![Event::PointerMoved(to), press(false, Modifiers::NONE, to)], Modifiers::NONE);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 55.0, "twenty more");
|
||||
assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt");
|
||||
// Without Alt the field doesn't take the drag at all (a touch swipe over it is the panel's to
|
||||
// scroll): the press is a click of the field's, not a drag.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
let field_id = Id::unique("pos_x").with("field");
|
||||
u.frame_with(vec![Event::PointerMoved(at)], Modifiers::NONE);
|
||||
u.frame_with(vec![press(true, Modifiers::NONE, at)], Modifiers::NONE);
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], Modifiers::NONE);
|
||||
assert!(!u.ctx.is_being_dragged(field_id), "a plain press on the field isn't a drag of the field's");
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, Modifiers::NONE, pos2(at.x + 10.0, at.y))], Modifiers::NONE);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 55.0, "nothing scrubbed");
|
||||
// With Alt held over it, the field does take the drag.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
u.frame_with(vec![Event::PointerMoved(at)], alt);
|
||||
u.frame_with(vec![press(true, alt, at)], alt);
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], alt);
|
||||
assert!(u.ctx.is_being_dragged(field_id), "with Alt the drag is the field's");
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, alt, pos2(at.x + 10.0, at.y))], alt);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 65.0, "ten more");
|
||||
}
|
||||
|
||||
@@ -13,11 +13,13 @@ pub(crate) struct Ui {
|
||||
pub(crate) ctx: egui::Context,
|
||||
pub(crate) app: FigApp,
|
||||
time: f64,
|
||||
/// The test screen's size (1440 x 900 unless a test shrinks it).
|
||||
pub(crate) screen: egui::Vec2,
|
||||
}
|
||||
|
||||
impl Ui {
|
||||
pub(crate) fn new(s: Session) -> Self {
|
||||
let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0 };
|
||||
let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0, screen: vec2(1440.0, 900.0) };
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
@@ -44,7 +46,7 @@ impl Ui {
|
||||
pub(crate) fn frame_raw(&mut self, raw: RawInput) -> egui::FullOutput {
|
||||
self.time += 1.0 / 60.0;
|
||||
self.app.clock.set_test_now(Some(self.time));
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), ..raw };
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, self.screen)), time: Some(self.time), ..raw };
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| app.ui(ui));
|
||||
out.textures_delta.clear();
|
||||
|
||||
@@ -249,6 +249,8 @@ mod text_enter_tests;
|
||||
#[cfg(test)]
|
||||
mod text_link_tests;
|
||||
#[cfg(test)]
|
||||
mod text_mixed_fill_tests;
|
||||
#[cfg(test)]
|
||||
mod titlebar_tests;
|
||||
#[cfg(test)]
|
||||
mod ui_params_tests;
|
||||
@@ -261,6 +263,8 @@ mod variables_export_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_rename_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_select_tests;
|
||||
#[cfg(test)]
|
||||
mod variants_discovery_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_keys_tests;
|
||||
|
||||
@@ -293,7 +293,8 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ids = sel.to_vec();
|
||||
let list = common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() });
|
||||
// A text's fills are what its characters show: one list they share, or mixed (#1856).
|
||||
let list = common(doc, sel, |n| if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }).flatten();
|
||||
let title = if fills { tr("Fill") } else { tr("Stroke") };
|
||||
let empty = list.as_ref().is_none_or(|l| l.is_empty());
|
||||
let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke };
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(super) fn spacing_input(ui: &mut Ui, field: &SpacingField, value: &str, widt
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
let numeric = value.trim_end_matches('%').parse::<f64>().ok();
|
||||
match widgets::scrub(ui, field.id, &response, numeric, 1.0) {
|
||||
match widgets::scrub(ui, field.id, &response, numeric, 1.0, true) {
|
||||
Some(FieldEdit::Scrub(v, done)) => Some(SpacingEdit::Scrub(v, done)),
|
||||
_ => typed.map(SpacingEdit::Typed),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! The Fill section on a text whose characters were coloured while editing (#1856), driven
|
||||
//! through egui headless: characters with different fills show as mixed content and + replaces
|
||||
//! them on every character; characters that all share fills the layer doesn't have show those.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Pos2, pos2};
|
||||
use figcraft_doc::NodeId;
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
const NOTE: &str = "Click + to replace mixed content";
|
||||
|
||||
/// A red "Hello" with its characters from `from` on coloured yellow while editing, selected.
|
||||
fn ui(from: usize) -> (Ui, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let t = NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap();
|
||||
s.execute("text.style", &json!({"id": t, "start": from, "end": 5, "textFills": ["#FFFF00"]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.ctx.enable_accesskit();
|
||||
u.frame(vec![]);
|
||||
(u, t)
|
||||
}
|
||||
|
||||
/// The accessible controls after a frame: role, label, value and centre.
|
||||
fn controls(u: &mut Ui) -> Vec<(Role, String, String, Pos2)> {
|
||||
u.frame(vec![]);
|
||||
let out = u.frame_output(vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
nodes
|
||||
.iter()
|
||||
.map(|(_, n)| {
|
||||
let at = n.bounds().map_or(pos2(0.0, 0.0), |b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32));
|
||||
(n.role(), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string(), at)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the Fill section shows: its hex rows top first, whether the mixed-content note is there
|
||||
/// (only a paint section shows it, and the strokes here are never mixed), and its + button. The
|
||||
/// section's rows lie between its + and the Stroke section's; Selection colors is further down.
|
||||
fn fill_section(c: &[(Role, String, String, Pos2)]) -> (Vec<String>, bool, Pos2) {
|
||||
let button = |name: &str| {
|
||||
c.iter().find(|(r, l, _, _)| *r == Role::Button && l == name).map(|(_, _, _, p)| *p).unwrap_or_else(|| panic!("no {name} button: {c:?}"))
|
||||
};
|
||||
let (top, bottom) = (button("Add fill"), button("Add stroke"));
|
||||
let mut rows: Vec<(f32, String)> =
|
||||
c.iter().filter(|(r, _, _, p)| *r == Role::TextInput && p.y > top.y && p.y < bottom.y).map(|(_, _, v, p)| (p.y, v.clone())).collect();
|
||||
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let note = c.iter().any(|(_, l, v, _)| l == NOTE || v == NOTE);
|
||||
(rows.into_iter().map(|(_, v)| v).collect(), note, top)
|
||||
}
|
||||
|
||||
fn fills_shown(u: &Ui, t: NodeId) -> Vec<String> {
|
||||
let n = u.app.session.doc().unwrap().node(t).unwrap().clone();
|
||||
let tx = n.kind.text().unwrap().clone();
|
||||
(0..tx.char_count())
|
||||
.map(|i| {
|
||||
tx.style_at(i)
|
||||
.fills
|
||||
.clone()
|
||||
.unwrap_or_else(|| n.fills.clone())
|
||||
.iter()
|
||||
.map(|p| p.solid_color().unwrap().to_hex())
|
||||
.collect::<Vec<_>>()
|
||||
.join("+")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differently_coloured_characters_show_as_mixed_content_and_plus_replaces_them() {
|
||||
let (mut u, t) = ui(1);
|
||||
let c = controls(&mut u);
|
||||
let (rows, note, plus) = fill_section(&c);
|
||||
assert!(note, "the Fill section shows the note: {c:?}");
|
||||
assert!(rows.is_empty(), "no row for the layer's own red: {rows:?}");
|
||||
// + adds a fill on top of the layer's: every character shows the layer's fills now.
|
||||
let steps = u.app.session.ds().unwrap().history.undo.len();
|
||||
u.button(plus, true);
|
||||
u.button(plus, false);
|
||||
u.frame(vec![]);
|
||||
let n = u.app.session.doc().unwrap().node(t).unwrap().clone();
|
||||
assert_eq!(n.fills.len(), 2, "the new fill on the layer's: {:?}", n.fills);
|
||||
assert!(n.kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own");
|
||||
assert!(fills_shown(&u, t).iter().all(|f| f == "FF0000+D9D9D9"), "{:?}", fills_shown(&u, t));
|
||||
assert_eq!(u.app.session.ds().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
let c = controls(&mut u);
|
||||
let (rows, note, _) = fill_section(&c);
|
||||
assert!(!note, "no note once the characters agree: {c:?}");
|
||||
assert_eq!(rows, ["D9D9D9", "FF0000"], "the new fill above the layer's red: {c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn characters_sharing_fills_the_layer_lacks_show_theirs() {
|
||||
let (mut u, t) = ui(0);
|
||||
let n = u.app.session.doc().unwrap().node(t).unwrap().clone();
|
||||
assert_eq!(n.fills[0].solid_color().unwrap().to_hex(), "FF0000", "the layer still has its old fill");
|
||||
assert_eq!(fills_shown(&u, t), ["FFFF00"; 5]);
|
||||
let c = controls(&mut u);
|
||||
let (rows, note, _) = fill_section(&c);
|
||||
assert_eq!(rows, ["FFFF00"], "the characters' yellow is the row, not the layer's red: {c:?}");
|
||||
assert!(!note, "{c:?}");
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! Selecting several variables in the Local variables window (#2002): a click selects one row,
|
||||
//! Shift+click the range from the anchor, Ctrl/Cmd+click toggles a row, Escape and a click on the
|
||||
//! empty space clear; delete, move to a group and scope then act on the whole selection in one
|
||||
//! undo step.
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::{flat, has_text, text_center};
|
||||
|
||||
const NAMES: [&str; 5] = ["alpha", "bravo", "charlie", "delta", "echo"];
|
||||
|
||||
/// The window open on a collection of five number variables.
|
||||
fn window() -> Ui {
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
for n in NAMES {
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
fn row(u: &mut Ui, name: &str) -> Pos2 {
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
// The name column, left of the value cells.
|
||||
let p = text_center(&shapes, name);
|
||||
Pos2::new(p.x, p.y)
|
||||
}
|
||||
|
||||
fn click(u: &mut Ui, p: Pos2, button: PointerButton, m: Modifiers) {
|
||||
u.frame_with(vec![Event::PointerMoved(p)], m);
|
||||
for pressed in [true, false] {
|
||||
u.frame_with(vec![Event::PointerButton { pos: p, button, pressed, modifiers: m }], m);
|
||||
}
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
fn click_row(u: &mut Ui, name: &str, m: Modifiers) {
|
||||
let p = row(u, name);
|
||||
click(u, p, PointerButton::Primary, m);
|
||||
}
|
||||
|
||||
fn selected(u: &Ui) -> Vec<String> {
|
||||
let st = u.app.ui.variables.as_ref().unwrap();
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let mut names: Vec<String> = st.selected.iter().filter_map(|id| doc.variables.get_by_id(id)).map(|v| v.name.clone()).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
fn names(u: &Ui) -> Vec<String> {
|
||||
u.app.session.doc().unwrap().variables.variables.iter().map(|v| v.name.clone()).collect()
|
||||
}
|
||||
|
||||
const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE };
|
||||
const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
|
||||
|
||||
#[test]
|
||||
fn a_click_selects_one_variable_and_replaces_the_selection() {
|
||||
let mut u = window();
|
||||
click_row(&mut u, "bravo", Modifiers::NONE);
|
||||
assert_eq!(selected(&u), ["bravo"]);
|
||||
click_row(&mut u, "delta", Modifiers::NONE);
|
||||
assert_eq!(selected(&u), ["delta"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_click_selects_the_range_from_the_anchor() {
|
||||
let mut u = window();
|
||||
click_row(&mut u, "bravo", Modifiers::NONE);
|
||||
click_row(&mut u, "delta", SHIFT);
|
||||
assert_eq!(selected(&u), ["bravo", "charlie", "delta"]);
|
||||
// A range upward from the same anchor.
|
||||
click_row(&mut u, "alpha", SHIFT);
|
||||
assert_eq!(selected(&u), ["alpha", "bravo"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_click_toggles_one_variable() {
|
||||
let mut u = window();
|
||||
click_row(&mut u, "alpha", Modifiers::NONE);
|
||||
click_row(&mut u, "charlie", CTRL);
|
||||
assert_eq!(selected(&u), ["alpha", "charlie"]);
|
||||
click_row(&mut u, "alpha", CTRL);
|
||||
assert_eq!(selected(&u), ["charlie"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_clears_the_selection() {
|
||||
let mut u = window();
|
||||
click_row(&mut u, "alpha", Modifiers::NONE);
|
||||
click_row(&mut u, "bravo", SHIFT);
|
||||
assert_eq!(selected(&u).len(), 2);
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::Key { key: Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
assert!(selected(&u).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_rows_are_painted_with_the_selected_row_colour() {
|
||||
let mut u = window();
|
||||
let colour = crate::theme::Tokens::get(&u.ctx).selected_row;
|
||||
let count = |u: &mut Ui| flat(&u.frame_output(vec![]).shapes).iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == colour)).count();
|
||||
let none = count(&mut u);
|
||||
click_row(&mut u, "alpha", Modifiers::NONE);
|
||||
let one = count(&mut u);
|
||||
click_row(&mut u, "charlie", SHIFT);
|
||||
let three = count(&mut u);
|
||||
assert!(one > none, "the selected row is highlighted");
|
||||
assert_eq!(three - one, 2, "two more rows highlighted by the range");
|
||||
}
|
||||
|
||||
/// Select bravo..delta, then right-click delta.
|
||||
fn select_three_and_open_menu(u: &mut Ui) -> Vec<egui::Shape> {
|
||||
click_row(u, "bravo", Modifiers::NONE);
|
||||
click_row(u, "delta", SHIFT);
|
||||
assert_eq!(selected(u), ["bravo", "charlie", "delta"]);
|
||||
let p = row(u, "delta");
|
||||
click(u, p, PointerButton::Secondary, Modifiers::NONE);
|
||||
flat(&u.frame_output(vec![]).shapes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_delete_removes_exactly_the_selected_variables_in_one_undo_step() {
|
||||
let mut u = window();
|
||||
let menu = select_three_and_open_menu(&mut u);
|
||||
assert!(has_text(&menu, "Delete 3 variables"));
|
||||
let before = u.app.session.undo_labels(100).len();
|
||||
click(&mut u, text_center(&menu, "Delete 3 variables"), PointerButton::Primary, Modifiers::NONE);
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
assert_eq!(names(&u), ["alpha", "echo"]);
|
||||
assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step");
|
||||
u.app.session.undo().unwrap();
|
||||
assert_eq!(names(&u), NAMES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_move_to_a_group_renames_every_selected_variable_in_one_step() {
|
||||
let mut u = window();
|
||||
u.app.session.execute("variable.create", &json!({"collection": "Theme", "name": "space/zero", "type": "number", "value": 0})).unwrap();
|
||||
let menu = select_three_and_open_menu(&mut u);
|
||||
let before = u.app.session.undo_labels(100).len();
|
||||
click(&mut u, text_center(&menu, "Move to group space"), PointerButton::Primary, Modifiers::NONE);
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
let mut now = names(&u);
|
||||
now.sort();
|
||||
assert_eq!(now, ["alpha", "echo", "space/bravo", "space/charlie", "space/delta", "space/zero"]);
|
||||
assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step");
|
||||
u.app.session.undo().unwrap();
|
||||
assert!(names(&u).contains(&"bravo".to_string()) && names(&u).contains(&"delta".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_scope_change_reaches_every_selected_variable_in_one_step() {
|
||||
let mut u = window();
|
||||
let menu = select_three_and_open_menu(&mut u);
|
||||
let before = u.app.session.undo_labels(100).len();
|
||||
click(&mut u, text_center(&menu, "Scope: only Corner radius"), PointerButton::Primary, Modifiers::NONE);
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
let scoped: Vec<String> = u
|
||||
.app
|
||||
.session
|
||||
.doc()
|
||||
.unwrap()
|
||||
.variables
|
||||
.variables
|
||||
.iter()
|
||||
.filter(|v| v.scopes.as_deref() == Some(&["CORNER_RADIUS".to_string()][..]))
|
||||
.map(|v| v.name.clone())
|
||||
.collect();
|
||||
assert_eq!(scoped, ["bravo", "charlie", "delta"]);
|
||||
assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_outside_the_selection_keeps_the_single_variable_menu() {
|
||||
let mut u = window();
|
||||
click_row(&mut u, "alpha", Modifiers::NONE);
|
||||
click_row(&mut u, "bravo", SHIFT);
|
||||
let p = row(&mut u, "echo");
|
||||
click(&mut u, p, PointerButton::Secondary, Modifiers::NONE);
|
||||
let menu = flat(&u.frame_output(vec![]).shapes);
|
||||
assert!(has_text(&menu, "Delete variable") && !has_text(&menu, "Delete 2 variables"));
|
||||
}
|
||||
|
||||
/// The bounding rect of every popup layer (the menu's area).
|
||||
fn popup_rect(u: &Ui) -> egui::Rect {
|
||||
u.ctx.memory(|m| {
|
||||
let rects: Vec<egui::Rect> =
|
||||
m.areas().visible_layer_ids().into_iter().filter(|l| l.order == egui::Order::Foreground).filter_map(|l| m.area_rect(l.id)).collect();
|
||||
assert!(!rects.is_empty(), "no popup open");
|
||||
rects.into_iter().reduce(|a, b| a.union(b)).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bulk_menu_scrolls_when_forty_groups_make_it_taller_than_the_window() {
|
||||
let mut u = window();
|
||||
for g in 0..40 {
|
||||
u.app
|
||||
.session
|
||||
.execute("variable.create", &json!({"collection": "Theme", "name": format!("g{g:02}/leaf"), "type": "number", "value": 0}))
|
||||
.unwrap();
|
||||
}
|
||||
u.screen = egui::vec2(1000.0, 500.0);
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
click_row(&mut u, "bravo", Modifiers::NONE);
|
||||
click_row(&mut u, "charlie", SHIFT);
|
||||
let p = row(&mut u, "charlie");
|
||||
click(&mut u, p, PointerButton::Secondary, Modifiers::NONE);
|
||||
let menu = flat(&u.frame_output(vec![]).shapes);
|
||||
assert!(has_text(&menu, "Delete 2 variables"));
|
||||
let screen = egui::Rect::from_min_size(Pos2::ZERO, u.screen);
|
||||
let area = popup_rect(&u);
|
||||
assert!(screen.contains_rect(area), "the menu area {area:?} runs past the screen {screen:?}");
|
||||
let last = "Move to group g39";
|
||||
let screen_h = u.screen.y;
|
||||
let visible = |shapes: &[egui::Shape]| crate::live_tests::texts(shapes).iter().any(|(t, p, s)| t == last && p.y + s.y <= screen_h);
|
||||
assert!(!visible(&menu), "the last group row should start out of view");
|
||||
let at = Pos2::new(area.center().x, area.center().y);
|
||||
let mut shapes = menu;
|
||||
for _ in 0..30 {
|
||||
u.frame(vec![
|
||||
Event::PointerMoved(at),
|
||||
Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
phase: egui::TouchPhase::Move,
|
||||
delta: egui::vec2(0.0, -400.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
]);
|
||||
shapes = flat(&u.frame_output(vec![Event::PointerMoved(at)]).shapes);
|
||||
if visible(&shapes) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(visible(&shapes), "scrolling the menu never brought {last:?} into view");
|
||||
assert!(screen.contains_rect(popup_rect(&u)));
|
||||
}
|
||||
@@ -160,8 +160,9 @@ pub fn scrubbed(from: f64, amount: f64, quantum: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The shared label-scrub gesture, including changing modifier rates and raw edge motion.
|
||||
/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`.
|
||||
pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option<f64>, step: f64) -> Option<FieldEdit> {
|
||||
/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`. `fine_on_alt`:
|
||||
/// Alt gives tenths (off where Alt is what makes the drag a scrub at all).
|
||||
pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option<f64>, step: f64, fine_on_alt: bool) -> Option<FieldEdit> {
|
||||
let v = value?;
|
||||
// Where the scrub began and how far it has taken the value (the modifiers can change on
|
||||
// the way: each stretch counts at its own rate).
|
||||
@@ -183,7 +184,7 @@ pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option<f64>, st
|
||||
// from the window this frame, the pointer's last position still counts (a move and
|
||||
// the leaving in one frame); None once egui has no position for it.
|
||||
let rise = p.hover_pos().or(p.interact_pos()).zip(p.press_origin()).map(|(at, from)| f64::from(from.y - at.y));
|
||||
(f64::from(if at_edge { raw } else { moved }), rise, i.modifiers.shift, i.modifiers.alt)
|
||||
(f64::from(if at_edge { raw } else { moved }), rise, i.modifiers.shift, i.modifiers.alt && fine_on_alt)
|
||||
});
|
||||
// Gone from the window (egui says so, the button still down), the pointer keeps the speed
|
||||
// it had rather than falling back to the usual one.
|
||||
@@ -306,7 +307,20 @@ fn number_field_impl(
|
||||
let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max);
|
||||
let editing_id = id.with("editing");
|
||||
let mut editing: Option<String> = ui.data(|d| d.get_temp(editing_id));
|
||||
let field_resp = ui.interact(edit_rect, id.with("field"), Sense::click());
|
||||
// Alt held over the field scrubs it too, as the label always does: "hover the input field
|
||||
// itself and hold down the modifier key" (Adjust alignment, rotation, position, and
|
||||
// dimensions). The field senses drags only while Alt is held, or while a scrub begun that way
|
||||
// goes on (Alt released or not), so a plain press or a touch swipe on it stays the scroll
|
||||
// area's; egui assigns a press by the frame before it, so Alt is held over the field before
|
||||
// the press, as a hand does. Alt as the drag begins is what makes it a scrub.
|
||||
let field_id = id.with("field");
|
||||
let alt_now = ui.input(|i| i.modifiers.alt);
|
||||
let scrubbing_id = id.with("altscrub");
|
||||
let scrubbing = ui.data(|d| d.get_temp::<bool>(scrubbing_id)).unwrap_or(false);
|
||||
let field_sense = if editing.is_none() && (alt_now || scrubbing) { Sense::click_and_drag() } else { Sense::click() };
|
||||
let field_resp = ui.interact(edit_rect, field_id, field_sense);
|
||||
let alt_scrub = editing.is_none() && if field_resp.drag_started() { alt_now } else { scrubbing };
|
||||
ui.data_mut(|d| d.insert_temp(scrubbing_id, alt_scrub && field_resp.dragged() && !field_resp.drag_stopped()));
|
||||
a11y::number(&field_resp, lead.name(), value, suffix, empty.text());
|
||||
a11y::ring_around(ui, rect, &field_resp);
|
||||
// The label scrubs with the pointer; the keyboard stops at the value only.
|
||||
@@ -332,10 +346,13 @@ fn number_field_impl(
|
||||
}
|
||||
Lead::None | Lead::Named(_) => {}
|
||||
}
|
||||
if lead_resp.hovered() || lead_resp.dragged() {
|
||||
if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
if let Some(edit) = scrub(ui, id, &lead_resp, value, step) {
|
||||
// On the field, Alt is what makes the drag a scrub, so it is not the fine rate there.
|
||||
if let Some(edit) =
|
||||
scrub(ui, id, &lead_resp, value, step, true).or_else(|| alt_scrub.then(|| scrub(ui, id, &field_resp, value, step, false)).flatten())
|
||||
{
|
||||
out = Some(Edit::All(edit));
|
||||
}
|
||||
let (key_step, key_big) = key_steps(ui.ctx(), suffix, step);
|
||||
@@ -381,7 +398,7 @@ fn number_field_impl(
|
||||
}
|
||||
// Typing on a field the keyboard reached (Tab) edits it: the editor takes the typed text.
|
||||
let typed_now = editing.is_none() && on_field && ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_))));
|
||||
let started = editing.is_none() && (field_resp.clicked() || typed_now);
|
||||
let started = editing.is_none() && ((field_resp.clicked() && !alt_now) || typed_now);
|
||||
// The text the field would commit to no effect: what it showed when the edit began, or the
|
||||
// value the arrows last stepped it to.
|
||||
let kept_id = id.with("kept");
|
||||
|
||||
@@ -92,7 +92,8 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option<Paint> {
|
||||
},
|
||||
PickerTarget::Paint { fills, index, ids } => {
|
||||
let n = doc.node(*ids.first()?)?;
|
||||
let list = if *fills { &n.fills } else { &n.strokes };
|
||||
// A text's fills are its characters' (none to pick while they differ).
|
||||
let list = if *fills { figcraft_engine::cmd::lists::character_fills(n)? } else { n.strokes.clone() };
|
||||
list.get(*index).cloned()
|
||||
}
|
||||
PickerTarget::Effect { ids, index, secondary } => doc.node(*ids.first()?)?.effects.get(*index)?.color(*secondary).map(Paint::solid),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Boards parity
|
||||
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
|
||||
|
||||
**Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind
|
||||
(`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that
|
||||
@@ -37,14 +37,16 @@ all end with the same geometry.
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was |
|
||||
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile (`board_connect_tests`, #1919) |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before |
|
||||
| Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) |
|
||||
| A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side |
|
||||
| Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. Dragging a run moves it, and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none |
|
||||
| Quick-create handles (drag out a connected copy) | missing | |
|
||||
| Quick-create handles (drag out a connected copy) | done | a "+" dragged carries the preview: the next one is made where it is let go, joined; or a connector joins the sticky or shape it is let go on (#1919) |
|
||||
| Connector waypoints placed by hand | missing | routes are computed from the ends; no bend points of your own |
|
||||
| Quick-create handles | partial | a "+" beside each side of the one selected sticky or shape makes the next one there, joined by a connector (`board.addConnected`, also Shift+Cmd/Ctrl+Enter); no dragging a handle out to place it |
|
||||
| Quick-create handles | done | a "+" beside each side of the one selected sticky or shape makes the next one there, joined by a connector (`board.addConnected`, also Shift+Cmd/Ctrl+Enter); dragged, it places the next one where it is let go, or joins the sticky or shape it is let go on (#1919) |
|
||||
| Marker and highlighter | done | the Pencil's stroke fitting with board presets: marker opaque, highlighter wide, see-through and multiplying |
|
||||
| Eraser | done | drag over marker and highlighter strokes to remove them, one undo step |
|
||||
| Pen colours and widths in the toolbar | partial | `tool.marker {color}`, `tool.highlighter {color}`; colour changes on a selected stroke from the contextual bar |
|
||||
@@ -70,6 +72,7 @@ all end with the same geometry.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. |
|
||||
| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. |
|
||||
| 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged |
|
||||
| 2026-10-31 | patch | M12, #1708: a connector end dropped on the outer half of a shape takes the side it is towards, instead of only within 10 px of a side's middle, so a drop anywhere along an edge chooses that edge (dragging a selected connector's end and with the connector tool, ring included); a drop in the middle of a shape still takes the facing side. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Components, variants, styles and variables parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
|
||||
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
|
||||
@@ -64,7 +64,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
| Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only |
|
||||
| Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) |
|
||||
| Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style, size, line height and letter spacing, the rest through the command |
|
||||
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only |
|
||||
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once |
|
||||
| Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay |
|
||||
| Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show |
|
||||
| Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values |
|
||||
@@ -79,6 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged |
|
||||
| 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. |
|
||||
| 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. |
|
||||
| 2026-11-06 | patch | M3: a layer's effect binding (`variable.bind`, `effects/<i>/<field>`) takes only a field its effect has, as an effect style's does: `effects/0/refraction` on a drop shadow, or a binding on an effect the layer doesn't have, is refused instead of being kept and doing nothing (a binding an older file has there still does nothing, and unbinds). Tests: `binding_lists_tests::a_layer_binds_only_fields_its_effects_have`. Grade unchanged. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Localization parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (; documents: a paragraph's base direction can be forced with Text ▸ Text direction, as Add right-to-left text says (#1830); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (`FIGCRAFT_EMBED_SCRIPTS` embeds other scripts' craft-fonts faces in a web build, so Arabic and Persian documents draw there (#1902); ; documents: a paragraph's base direction can be forced with Text ▸ Text direction, as Add right-to-left text says (#1830); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed
|
||||
by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian
|
||||
@@ -86,7 +86,10 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v
|
||||
nothing (startup and memory measured unchanged); no CJK font installed means tofu, never a
|
||||
crash. The web build has no system fonts: built with craft-fonts and `FIGCRAFT_EMBED_CJK=1` it
|
||||
embeds Noto Sans CJK SC (+16 MB) and offers Japanese, Korean and Simplified Chinese; otherwise the language picker and
|
||||
System leave them out. No font file is in this repo.
|
||||
System leave them out. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as
|
||||
the craft-fonts manifest lists them) embeds those scripts' faces as well, so an Arabic or Persian
|
||||
document draws in Noto Sans Arabic (+0.8 MB) instead of missing-glyph boxes (#1902), and with `Arab`
|
||||
the picker offers the Arabic UI catalog too, as on the desktop. No font file is in this repo.
|
||||
|
||||
## Languages
|
||||
|
||||
@@ -95,6 +98,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v
|
||||
| English | en | 2,352 / 2,352 (100%, source) | yes | Latin | yes (source) | full | 0 |
|
||||
| Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build); no Traditional Chinese catalog (zh-TW, zh-HK read English) | no | draft | 1–2 (after native review) |
|
||||
| Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 |
|
||||
| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) |
|
||||
| French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) |
|
||||
@@ -130,6 +135,7 @@ Hindi and Arabic. Traditional Chinese is not planned (no catalog; its users see
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. |
|
||||
| 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). |
|
||||
| 2026-11-05 | minor | Documents: a paragraph's base direction can be forced left to right or right to left (Text ▸ Text direction, `text.direction`, `node.set textDirection`, the Type settings control, the `.fig` lines' `sourceDirectionality`), as Add right-to-left text says (#1830); detection stays the default. Four new UI strings (English only; other catalogs fall back). |
|
||||
| 2026-10-30 | minor | Bosnian (`bs`, Bosanski) draft catalog: every UI string (1,906), command label (629) and menu wording (31), machine-drafted in Latin script with ijekavian forms and marked as a draft awaiting native review. Bosnian plurals: one for 1, 21, 31… (not 11), few for 2–4, 22–24… (not 12–14), other for the rest. Grade and hours unchanged (Bosnian is not one of the twelve key languages) |
|
||||
|
||||
+6
-2
@@ -854,11 +854,15 @@ removes the whole conditional). Every one is an undo step and applies to all `id
|
||||
with the same interactions). Flows `proto.flow.add` / `rename` / `remove`,
|
||||
and the device, its rotation and the background `proto.settings {device?, background?,
|
||||
rotation?, color?, width?, height?, responsive?}` (`None`, `iPhone 16`, `iPhone 16 Pro Max`,
|
||||
`Android Compact`, `iPad mini`, `MacBook Air`, `Desktop` or `Custom size`; `rotation` `portrait` or
|
||||
`Android Compact`, `iPad mini`, `MacBook Air`, `Desktop` or `Custom size`, in any case; another
|
||||
name is an error that lists the devices, and nothing changes; `rotation` `portrait` or
|
||||
`landscape`, which turns phones and tablets; `color` one of the device's colours by name, e.g.
|
||||
`Black`, `White`, `Pink`, `Teal`, `Blue` for the iPhone 16 (an error lists them), `""` for the
|
||||
default; `width` / `height` set the custom size's screen, 1–10000 points, and pick `Custom size`,
|
||||
which is a bare screen without a body). On a device the presented frame is sized to the device's
|
||||
which is a bare screen without a body). Every call answers the page's settings as they are after
|
||||
it, so `proto.settings {}` reads them: `{device, background, rotation, color (the colour shown, null
|
||||
without a body), screen ({width, height} as presented, null without a device), customSize,
|
||||
responsive}`. On a device the presented frame is sized to the device's
|
||||
screen: a frame bigger than the screen scrolls through its whole size whatever its `overflow`, content
|
||||
past the frame's own edges scrolls only as its `overflow` allows (else it's clipped), and `fixed`
|
||||
layers stay on screen (pinned to the edges their constraints name). With `responsive: true` (saved
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Prototyping parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** patch (`proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
**Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except
|
||||
media control, every transition and easing exist; key/gamepad triggers take controller buttons,
|
||||
@@ -107,6 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` |
|
||||
| 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. |
|
||||
| 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. |
|
||||
| 2026-10-30 | patch | A manual overlay can be placed on the canvas (#405): while the interaction editor has an Open overlay action with Manual position open, the overlay frame shows dimmed, outlined, where it opens from the top-left of the layer that opens it (right below that layer without an offset), and dragging it moves it there. The X and Y fields follow while dragging, and the drag is one undo step (`crates/ui-egui/src/canvas/proto_canvas/overlay_ghost.rs`). Numbers unchanged |
|
||||
|
||||
+4
-1
@@ -78,7 +78,10 @@ CJK and Thai text need their own fonts, which egui and Inter lack: the desktop a
|
||||
one when something on screen needs it, so layer and page names in those scripts show whatever the
|
||||
UI language (see `crates/ui-egui/src/cjk.rs`). The web build has no system fonts,
|
||||
so Japanese, Korean and Chinese appear there only in a build with craft-fonts and
|
||||
`FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. A
|
||||
`FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. The other
|
||||
scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari) join a web build only with
|
||||
`FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as the manifest lists them), for
|
||||
documents in those scripts; with `Arab` embedded the picker offers Arabic too (#1902). A
|
||||
Chinese UI puts its Chinese face first so Han takes Simplified Chinese shapes. Georgian is drawn in
|
||||
craft-fonts' Noto Sans Georgian, one of the built-in faces in `theme::install_fonts`, or else in an
|
||||
installed font on the desktop. Web builds keep it only when the craft-fonts they're built with has
|
||||
|
||||
+7
-2
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user