mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-07 12:13:14 +00:00
Merge main into #1854
This commit is contained in:
+2
-1
File diff suppressed because one or more lines are too long
@@ -51,6 +51,12 @@ fn health_check(stream: &mut TcpStream, until: Instant) -> bool {
|
||||
let mut req = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 << 10 {
|
||||
// The same deadline as the request line: a peer dripping header bytes would otherwise
|
||||
// hold this thread and its connection slot for as long as it liked.
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() {
|
||||
break;
|
||||
}
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => req.extend_from_slice(chunk.get(..n).unwrap_or_default()),
|
||||
@@ -409,3 +415,31 @@ fn linger(ws: &mut WebSocket<Duplex>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod health_check_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_health_check_dripping_headers_ends_at_the_deadline() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.write_all(b"GET /healthz HTTP/1.1\r\n").unwrap();
|
||||
// One header byte every 20 ms, far past the deadline, until the server hangs up.
|
||||
for _ in 0..200 {
|
||||
if c.write_all(b"X").is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let start = Instant::now();
|
||||
assert!(health_check(&mut stream, start + Duration::from_millis(300)));
|
||||
assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed());
|
||||
drop(stream);
|
||||
client.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,12 @@ pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option<Side>, Option<Sid
|
||||
(attach(from, to.centre()).1, attach(to, from.centre()).1)
|
||||
}
|
||||
|
||||
/// Where a connector's ends attach, as routed now: the points [`ConnectorPath::Runs`] is measured
|
||||
/// from the middle of.
|
||||
pub fn attach_points(from: RouteEnd, to: RouteEnd) -> (Point, Point) {
|
||||
(attach(from, to.centre()).0, attach(to, from.centre()).0)
|
||||
}
|
||||
|
||||
/// The route's path handles: one for each run of an elbow and one for a curve, with the portion
|
||||
/// of the path each moves and where it sits.
|
||||
pub fn path_handles(pts: &[Point], routing: Routing) -> Vec<(usize, Point)> {
|
||||
@@ -96,8 +102,9 @@ pub fn reshaped(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&Co
|
||||
}
|
||||
}
|
||||
|
||||
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another.
|
||||
const MAX_RUNS: usize = 64;
|
||||
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another, and an
|
||||
/// importer leaves a saved one to the router.
|
||||
pub const MAX_RUNS: usize = 64;
|
||||
|
||||
/// The runs of the right-angled route `pts` with run `portion` moved to `p`.
|
||||
fn reshaped_runs(pts: &[Point], portion: usize, p: Point) -> Option<ConnectorPath> {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub mod vector_faces;
|
||||
pub mod vector_regions;
|
||||
|
||||
pub use board::*;
|
||||
pub use board_route::{END_GAP, RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use colors::*;
|
||||
pub use comments::*;
|
||||
pub use facilitation::*;
|
||||
|
||||
+17
-5
@@ -948,7 +948,7 @@ impl Node {
|
||||
if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w };
|
||||
// Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown
|
||||
// box; an arc's corners don't.
|
||||
let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
|
||||
let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
|
||||
base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter
|
||||
} else {
|
||||
0.0
|
||||
@@ -964,9 +964,10 @@ impl Node {
|
||||
!(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke()))
|
||||
}
|
||||
|
||||
/// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc
|
||||
/// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides.
|
||||
fn grows_by_exactly_its_spread(&self) -> bool {
|
||||
/// Whether this node's outline has no sharp corners (right-angled ones aside), so mitres along
|
||||
/// it end on its box grown by as much: a box or a whole ellipse. An arc (an ellipse that doesn't
|
||||
/// go all the way round) has corners where its ends meet its sides.
|
||||
fn outline_mitres_end_on_its_box(&self) -> bool {
|
||||
match self.kind {
|
||||
NodeKind::Rectangle | NodeKind::Section { .. } => true,
|
||||
NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep),
|
||||
@@ -974,9 +975,20 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a spread grows this node by exactly the spread: its outline mitres end on its box
|
||||
/// (see [`Node::outline_mitres_end_on_its_box`]), and so does its stroke. A dashed stroke is
|
||||
/// cut into dashes with corners wherever they fall round the outline, and a width profile or a
|
||||
/// brush can give the stroke corners of its own, which the spread mitres out.
|
||||
fn grows_by_exactly_its_spread(&self) -> bool {
|
||||
let s = &self.stroke;
|
||||
let cornered = self.has_visible_stroke() && (!s.dashes.is_empty() || s.profile().is_some() || s.brush.is_some());
|
||||
!cornered && self.outline_mitres_end_on_its_box()
|
||||
}
|
||||
|
||||
/// How much further than its spread a drop shadow can reach at the outline's sharp corners:
|
||||
/// spread moves the edges out in parallel and they meet in a mitre (see
|
||||
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread.
|
||||
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread,
|
||||
/// unless their stroke has corners (see [`Node::grows_by_exactly_its_spread`]).
|
||||
fn spread_miter_reach(&self) -> f64 {
|
||||
if self.grows_by_exactly_its_spread() {
|
||||
return 0.0;
|
||||
|
||||
@@ -223,6 +223,7 @@ fn text_case() {
|
||||
assert_eq!(style_weight("Semi Bold Italic"), 600);
|
||||
assert_eq!(style_weight("Black"), 900);
|
||||
assert_eq!(style_weight("Regular"), 400);
|
||||
assert_eq!(style_weight("Hairline"), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -439,8 +439,9 @@ pub fn style_weight(style: &str) -> u16 {
|
||||
{
|
||||
return n;
|
||||
}
|
||||
let table: [(&str, u16); 10] = [
|
||||
let table: [(&str, u16); 11] = [
|
||||
("thin", 100),
|
||||
("hairline", 100),
|
||||
("extralight", 200),
|
||||
("ultralight", 200),
|
||||
("light", 300),
|
||||
|
||||
@@ -10,6 +10,8 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::edit::{roots, z_sorted};
|
||||
use super::{CommandSpec, ok};
|
||||
|
||||
mod suggest;
|
||||
use crate::params::{f64_of, get, id_of, num_or, req_id, req_index, req_num, req_targets, string, targets};
|
||||
use crate::{EngineError, Result, Session, bad, spec};
|
||||
|
||||
@@ -109,7 +111,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Ok(json!({"removed": removed}))
|
||||
}
|
||||
),
|
||||
spec!("layout.suggest", "Suggest auto layout", "{ids?, direction? (horizontal|vertical|grid)}", true, layout_add),
|
||||
spec!(
|
||||
"layout.suggest",
|
||||
"Suggest auto layout",
|
||||
"{ids?, direction? (horizontal|vertical|grid)} splits each frame's layers into rows or columns by the gaps between them, wraps every band of several layers in a frame without fill that hugs it and does the same inside, so the layers keep their place where the gaps are even and the bands start at the same offset across the flow; the frame keeps its size, and the result carries `warnings` for gaps that differ, bands that start at different offsets (they line up at the smallest and some move) and layers that overlap. Instances and the layers inside them are refused. `direction` sets the top level's direction (nested frames follow the gaps); grid lays the layers out in one grid. A group is converted to a frame and several layers are wrapped in one, as Add auto layout does",
|
||||
true,
|
||||
suggest::layout_suggest
|
||||
),
|
||||
spec!("object.moveToPage", "Move to page", "{ids?, page}", true, move_to_page),
|
||||
spec!("object.setThumbnail", "Set as thumbnail", "{id?}", true, |s, p| {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("object.setThumbnail", "select a frame"))?;
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Suggest auto layout (#1823): split a frame's layers into rows or columns by the gaps between
|
||||
//! them, wrap each band that holds several layers in a frame of its own and do the same inside
|
||||
//! it, so the design gets as many auto layout frames as it needs and keeps its placement.
|
||||
|
||||
use figcraft_doc::{AutoLayout, Document, LayoutMode, NodeId, NodeKind, Sizing};
|
||||
use figcraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{Wrap, convert, infer_layout, sort_layout_children, wrap};
|
||||
use crate::params::{id_of, req_targets, string};
|
||||
use crate::{EngineError, Result, Session, bad};
|
||||
|
||||
/// How deep nested band frames go before a frame is laid out as a single list.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most layers analysed in one frame; past this the frame is laid out as a single list.
|
||||
const MAX_CHILDREN: usize = 1000;
|
||||
/// Gaps that differ by more than this are reported.
|
||||
const GAP_TOLERANCE: f64 = 0.5;
|
||||
/// Edges closer than this count as touching.
|
||||
const EDGE_EPS: f64 = 1e-6;
|
||||
|
||||
/// One row or column: the layers in it and the span it covers along both axes.
|
||||
struct Band {
|
||||
members: Vec<(NodeId, Rect)>,
|
||||
/// Start and end along the split axis.
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
/// Start and end along the other axis.
|
||||
cross_lo: f64,
|
||||
cross_hi: f64,
|
||||
}
|
||||
|
||||
fn span(r: &Rect, vertical: bool) -> (f64, f64, f64, f64) {
|
||||
if vertical { (r.y0, r.y1, r.x0, r.x1) } else { (r.x0, r.x1, r.y0, r.y1) }
|
||||
}
|
||||
|
||||
/// Split the layers into bands along one axis: sorted by their start, a layer joins the current
|
||||
/// band while it starts before the band ends, and opens a new band when there is a gap or it
|
||||
/// only touches. Layers starting together always share a band.
|
||||
fn bands(boxes: &[(NodeId, Rect)], vertical: bool) -> Vec<Band> {
|
||||
let mut sorted = boxes.to_vec();
|
||||
sorted.sort_by(|a, b| span(&a.1, vertical).0.total_cmp(&span(&b.1, vertical).0));
|
||||
let mut out: Vec<Band> = Vec::new();
|
||||
for item in sorted {
|
||||
let (lo, hi, cross_lo, cross_hi) = span(&item.1, vertical);
|
||||
match out.last_mut() {
|
||||
Some(b) if lo < b.hi - EDGE_EPS || lo - b.lo < EDGE_EPS => {
|
||||
b.hi = b.hi.max(hi);
|
||||
b.cross_lo = b.cross_lo.min(cross_lo);
|
||||
b.cross_hi = b.cross_hi.max(cross_hi);
|
||||
b.members.push(item);
|
||||
}
|
||||
_ => out.push(Band { members: vec![item], lo, hi, cross_lo, cross_hi }),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The layers a frame lays out, with their boxes in the frame's own space. `None` when a box
|
||||
/// isn't a finite number.
|
||||
fn flow_boxes(doc: &Document, frame: NodeId) -> Option<Vec<(NodeId, Rect)>> {
|
||||
let mut out = Vec::new();
|
||||
for c in figcraft_layout::flow_children(doc, frame) {
|
||||
let n = doc.node(c)?;
|
||||
let r = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect());
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
out.push((c, r));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn finite_or_zero(v: f64) -> f64 {
|
||||
if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 }
|
||||
}
|
||||
|
||||
fn mode_from(direction: &str) -> LayoutMode {
|
||||
match direction.to_ascii_lowercase().as_str() {
|
||||
"vertical" | "column" => LayoutMode::Vertical,
|
||||
"grid" => LayoutMode::Grid,
|
||||
_ => LayoutMode::Horizontal,
|
||||
}
|
||||
}
|
||||
|
||||
/// The auto layout that places `bands` where they are: the gap between them, the room before the
|
||||
/// first and after the last, and on the other axis the smallest offset from each edge.
|
||||
fn layout_for(bands: &[Band], vertical: bool, frame_w: f64, frame_h: f64, name: &str, warnings: &mut Vec<String>) -> AutoLayout {
|
||||
let gaps: Vec<f64> = bands.windows(2).filter_map(|w| Some((w.get(1)?.lo - w.first()?.hi).max(0.0))).collect();
|
||||
let smallest = gaps.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let largest = gaps.iter().copied().fold(0.0, f64::max);
|
||||
if largest - smallest > GAP_TOLERANCE {
|
||||
let what = if vertical { "rows" } else { "columns" };
|
||||
warnings.push(format!(
|
||||
"\"{name}\": the gaps between the {what} differ ({} to {}), so the smallest is used and later {what} move",
|
||||
finite_or_zero(smallest),
|
||||
finite_or_zero(largest)
|
||||
));
|
||||
}
|
||||
let (main_size, cross_size) = if vertical { (frame_h, frame_w) } else { (frame_w, frame_h) };
|
||||
let main_start = bands.first().map_or(0.0, |b| b.lo).max(0.0);
|
||||
let main_end = (main_size - bands.last().map_or(0.0, |b| b.hi)).max(0.0);
|
||||
let cross_start = bands.iter().map(|b| b.cross_lo).fold(f64::INFINITY, f64::min).max(0.0);
|
||||
let cross_end = bands.iter().map(|b| cross_size - b.cross_hi).fold(f64::INFINITY, f64::min).max(0.0);
|
||||
// Every band is lined up at the start across the flow, so one that starts further in (a
|
||||
// centred title above a card) moves to the smallest offset.
|
||||
let widest_start = bands.iter().map(|b| b.cross_lo).fold(f64::NEG_INFINITY, f64::max);
|
||||
let smallest_start = bands.iter().map(|b| b.cross_lo).fold(f64::INFINITY, f64::min);
|
||||
if widest_start - smallest_start > GAP_TOLERANCE {
|
||||
let what = if vertical { "rows" } else { "columns" };
|
||||
warnings.push(format!(
|
||||
"\"{name}\": the {what} start at different offsets ({} to {}), so they are lined up at the smallest and some move",
|
||||
finite_or_zero(smallest_start),
|
||||
finite_or_zero(widest_start)
|
||||
));
|
||||
}
|
||||
let [ms, me, cs, ce] = [main_start, main_end, cross_start, cross_end].map(finite_or_zero);
|
||||
AutoLayout {
|
||||
mode: if vertical { LayoutMode::Vertical } else { LayoutMode::Horizontal },
|
||||
gap: finite_or_zero(smallest),
|
||||
// Top, right, bottom, left.
|
||||
padding: if vertical { [ms, ce, me, cs] } else { [cs, me, ce, ms] },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay a frame out as one list the way "Add auto layout" does: the direction is inferred, or
|
||||
/// `direction` forces it.
|
||||
fn flat_layout(s: &mut Session, frame: NodeId, direction: Option<&str>) -> Result<()> {
|
||||
let doc = s.doc_mut()?;
|
||||
let mut al = infer_layout(doc, frame);
|
||||
if let Some(d) = direction {
|
||||
al.mode = mode_from(d);
|
||||
}
|
||||
let mut kids = doc.get(frame)?.children.clone();
|
||||
sort_layout_children(doc, &mut kids, al.mode == LayoutMode::Vertical);
|
||||
let n = doc.get_mut(frame)?;
|
||||
n.children = kids;
|
||||
n.layout = Some(al);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn the frame's layers into bands and give the frame, and every band frame made on the way,
|
||||
/// the auto layout that keeps them where they are. Returns whether the frame got auto layout.
|
||||
fn split(s: &mut Session, frame: NodeId, depth: usize, direction: Option<&str>, warnings: &mut Vec<String>) -> Result<bool> {
|
||||
let doc = s.doc()?;
|
||||
let name = doc.get(frame)?.name.clone();
|
||||
let (frame_w, frame_h) = (doc.get(frame)?.width, doc.get(frame)?.height);
|
||||
let any_mask = doc.get(frame)?.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.is_mask);
|
||||
let Some(boxes) = flow_boxes(doc, frame) else {
|
||||
warnings.push(format!("\"{name}\": a layer has no usable position, so no auto layout was added"));
|
||||
return Ok(false);
|
||||
};
|
||||
if boxes.len() < 2 {
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
if depth >= MAX_DEPTH || boxes.len() > MAX_CHILDREN || any_mask {
|
||||
let why = if any_mask {
|
||||
"it has a mask"
|
||||
} else if depth >= MAX_DEPTH {
|
||||
"the frames are nested too deep"
|
||||
} else {
|
||||
"it has too many layers to analyse"
|
||||
};
|
||||
warnings.push(format!("\"{name}\": {why}, so its layers are laid out in one list"));
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
// The direction asked for decides the axis of the top level; nested frames follow the gaps.
|
||||
let forced = direction.map(mode_from);
|
||||
let (vertical, found) = match forced {
|
||||
Some(LayoutMode::Vertical) => (true, bands(&boxes, true)),
|
||||
Some(LayoutMode::Horizontal) => (false, bands(&boxes, false)),
|
||||
Some(_) => (true, Vec::new()),
|
||||
None => {
|
||||
let rows = bands(&boxes, true);
|
||||
if rows.len() >= 2 { (true, rows) } else { (false, bands(&boxes, false)) }
|
||||
}
|
||||
};
|
||||
if found.len() < 2 {
|
||||
if forced.is_some() {
|
||||
if forced != Some(LayoutMode::Grid) {
|
||||
warnings.push(format!("\"{name}\": its layers don't separate along the direction asked for, so they are laid out in one list"));
|
||||
}
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
warnings.push(format!("\"{name}\": its layers overlap along both axes, so no auto layout was added"));
|
||||
return Ok(false);
|
||||
}
|
||||
let al = layout_for(&found, vertical, frame_w, frame_h, &name, warnings);
|
||||
// Band frames first, while the layers are still where they were.
|
||||
let mut made = Vec::new();
|
||||
for band in &found {
|
||||
if band.members.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let ids: Vec<NodeId> = band.members.iter().map(|(id, _)| *id).collect();
|
||||
let r = wrap(s, &json!({"ids": ids}), "layout.suggest", Wrap::Frame)?;
|
||||
let fid = id_of(&r["id"]).ok_or_else(|| EngineError::Other("wrap failed".into()))?;
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.fills.clear();
|
||||
f.clip = false;
|
||||
made.push(fid);
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
let mut kids = doc.get(frame)?.children.clone();
|
||||
sort_layout_children(doc, &mut kids, vertical);
|
||||
let n = doc.get_mut(frame)?;
|
||||
n.children = kids;
|
||||
n.layout = Some(al);
|
||||
for fid in made {
|
||||
if split(s, fid, depth + 1, None, warnings)? {
|
||||
// A band frame that got auto layout is as big as what is in it (one that did not stays Fixed).
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.child_layout.sizing_h = Sizing::Hug;
|
||||
f.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Add auto layout to the frames, group or layers asked for the way "Add auto layout" finds its
|
||||
/// targets, then split each into nested rows and columns by the gaps between its layers.
|
||||
pub(super) fn layout_suggest(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("layout.suggest", s, p)?;
|
||||
let direction = string(p, "direction");
|
||||
let doc = s.doc()?;
|
||||
// An instance's layers come from its main component: nothing is added to them. Checked
|
||||
// before anything changes, with the words Convert to group uses.
|
||||
for i in &ids {
|
||||
let n = doc.get(*i)?;
|
||||
if matches!(n.kind, NodeKind::Instance { .. }) {
|
||||
return Err(bad("layout.suggest", format!("\"{}\" is an instance: its layers come from its main component (detach it first)", n.name)));
|
||||
}
|
||||
if crate::components::owning_instance(doc, *i).is_some() {
|
||||
return Err(bad("layout.suggest", format!("\"{}\" is inside an instance: edit its main component, or detach the instance", n.name)));
|
||||
}
|
||||
}
|
||||
let all_frames = ids.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like() && n.layout.is_none()));
|
||||
let single_group = ids.len() == 1 && ids.first().and_then(|i| doc.node(*i)).is_some_and(|n| matches!(n.kind, NodeKind::Group));
|
||||
// A frame with auto layout already is wrapped, like a layer, and so are several layers.
|
||||
let (targets, own_size) = if all_frames {
|
||||
(ids, true)
|
||||
} else if single_group {
|
||||
// The group's layers are laid out directly, not inside a wrapper.
|
||||
convert(s, &json!({"ids": ids}), "layout.suggest", true)?;
|
||||
(ids, false)
|
||||
} else {
|
||||
let r = wrap(s, &json!({"ids": ids}), "layout.suggest", Wrap::Frame)?;
|
||||
let fid = id_of(&r["id"]).ok_or_else(|| EngineError::Other("wrap failed".into()))?;
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.fills.clear();
|
||||
f.clip = false;
|
||||
(vec![fid], false)
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
for f in &targets {
|
||||
// A frame keeps its size; a wrapper or a converted group has none of its own and hugs.
|
||||
let got_layout = split(s, *f, 0, direction.as_deref(), &mut warnings)?;
|
||||
if got_layout && !own_size {
|
||||
let n = s.doc_mut()?.get_mut(*f)?;
|
||||
if !single_group || n.child_layout.sizing_h != Sizing::Fill {
|
||||
n.child_layout.sizing_h = Sizing::Hug;
|
||||
}
|
||||
if !single_group || n.child_layout.sizing_v != Sizing::Fill {
|
||||
n.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.set_selection(targets.clone());
|
||||
let mut out = json!({"ids": targets});
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -129,11 +129,138 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Hiragino's weight names: "W3" is 300.
|
||||
fn w_number(word: &str) -> Option<u16> {
|
||||
let n = word.strip_prefix('w')?.parse::<u16>().ok()?;
|
||||
(1..=9).contains(&n).then_some(n * 100)
|
||||
}
|
||||
|
||||
/// A weight number as some families name styles ("Condensed 600"). Below 100 it is something else
|
||||
/// (a width grade, an optical size: "Condensed 2", "Caption 12").
|
||||
fn number_weight(word: &str) -> Option<u16> {
|
||||
let n = word.parse::<u16>().ok().filter(|_| word.bytes().all(|b| b.is_ascii_digit()))?;
|
||||
(100..=1000).contains(&n).then_some(n)
|
||||
}
|
||||
|
||||
/// Style-name words that give a weight or a slant.
|
||||
const WEIGHT_WORDS: [&str; 25] = [
|
||||
"thin",
|
||||
"hairline",
|
||||
"extralight",
|
||||
"ultralight",
|
||||
"light",
|
||||
"semilight",
|
||||
"demilight",
|
||||
"regular",
|
||||
"normal",
|
||||
"roman",
|
||||
"book",
|
||||
"medium",
|
||||
"semibold",
|
||||
"demibold",
|
||||
"bold",
|
||||
"extrabold",
|
||||
"ultrabold",
|
||||
"black",
|
||||
"extrablack",
|
||||
"ultrablack",
|
||||
"heavy",
|
||||
"italic",
|
||||
"oblique",
|
||||
"plain",
|
||||
"standard",
|
||||
];
|
||||
|
||||
/// Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed").
|
||||
const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"];
|
||||
|
||||
/// The width a Univers number leading a style name gives, as Univers, Frutiger and Helvetica Neue
|
||||
/// LT name styles ("45 Light", "55 Roman", "57 Condensed", "67 Bold Condensed"): the first digit
|
||||
/// grades the weight, the second the width (3 or 4 extended, 5 or 6 normal, 7 or 8 condensed, 9
|
||||
/// ultra condensed; even is italic, which the name says too). Only before weight, slant and width
|
||||
/// words, so another leading number ("12 Regular", "55 Rounded") stays part of the width.
|
||||
fn univers_width(words: &[&str]) -> Option<u8> {
|
||||
const WIDTHS: [&str; 6] = ["condensed", "compressed", "narrow", "extended", "expanded", "wide"];
|
||||
let (code, rest) = words.split_first()?;
|
||||
let &[b'1'..=b'9', d @ b'3'..=b'9'] = code.as_bytes() else { return None };
|
||||
let known = |w: &&str| WEIGHT_WORDS.contains(w) || GRADES.contains(w) || WIDTHS.contains(w);
|
||||
(!rest.is_empty() && rest.iter().all(known)).then_some((d - b'1') / 2)
|
||||
}
|
||||
|
||||
/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow",
|
||||
/// "Extra Condensed Bold" → "extra condensed", "67 Bold Condensed" → its Univers width and "condensed").
|
||||
fn style_rest(style: &str) -> String {
|
||||
let s = style.to_ascii_lowercase().replace('-', " ");
|
||||
let words: Vec<&str> = s.split_whitespace().collect();
|
||||
let weight = |w: &str| WEIGHT_WORDS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some();
|
||||
let rest = words.iter().enumerate().filter(|(i, w)| {
|
||||
let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique"));
|
||||
!weight(w) && !graded
|
||||
});
|
||||
let univers = univers_width(&words).map(|d| format!("univers width {d}"));
|
||||
// The Univers number (the first word kept) gives way to its width.
|
||||
let rest = rest.map(|(_, w)| *w).skip(usize::from(univers.is_some()));
|
||||
univers.as_deref().into_iter().chain(rest).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A style name that slants: italic, or oblique as some families name it.
|
||||
fn slanted(style: &str) -> bool {
|
||||
let s = style.to_ascii_lowercase();
|
||||
s.contains("italic") || s.contains("oblique")
|
||||
}
|
||||
|
||||
/// The weight a style name says ("W3", "W6 Italic", "Condensed W7", "Condensed 600" and "45 Light" too).
|
||||
pub(crate) fn name_weight(style: &str) -> u16 {
|
||||
let s = style.to_ascii_lowercase().replace('-', " ");
|
||||
let words: Vec<&str> = s.split_whitespace().collect();
|
||||
// A Univers number's weight digit has no fixed CSS weight ("65" is Medium in Helvetica Neue,
|
||||
// Bold in Univers): the words after it say it.
|
||||
if let Some((_, rest)) = words.split_first().filter(|_| univers_width(&words).is_some()) {
|
||||
return figcraft_doc::style_weight(&rest.join(" "));
|
||||
}
|
||||
words.iter().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style))
|
||||
}
|
||||
|
||||
/// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed
|
||||
/// by, lightest first, as the style menu lists them) after the chars' style, with the same slant
|
||||
/// and width. The chars' style is found in the list by name and its neighbour taken; a style the
|
||||
/// family doesn't have, or a custom weight axis value, goes to the listed style of nearest weight
|
||||
/// that way. None when the family has nothing further.
|
||||
pub(crate) fn next_style(styles: &[(String, u16)], st: &TextStyle, up: bool) -> Option<String> {
|
||||
let italic = st.italic() || slanted(&st.font_style);
|
||||
let rest = style_rest(&st.font_style);
|
||||
let mut same: Vec<&(String, u16)> = styles.iter().filter(|(x, _)| slanted(x) == italic && style_rest(x) == rest).collect();
|
||||
let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], "");
|
||||
let here = same.iter().position(|(x, _)| norm(x) == norm(&st.font_style));
|
||||
let axis = st.variations.contains_key("wght");
|
||||
if let Some(i) = here.filter(|_| !axis) {
|
||||
let next = if up { i.checked_add(1) } else { i.checked_sub(1) };
|
||||
return next.and_then(|n| same.get(n)).map(|(x, _)| x.clone());
|
||||
}
|
||||
let w = i32::from(if axis { st.weight() } else { name_weight(&st.font_style) });
|
||||
// Of equal weights, the one nearest in the family's order: the first going up, the last going down.
|
||||
if !up {
|
||||
same.reverse();
|
||||
}
|
||||
same.into_iter()
|
||||
.map(|(x, xw)| (i32::from(*xw) - w, x))
|
||||
.filter(|(d, _)| if up { *d > 0 } else { *d < 0 })
|
||||
.min_by_key(|(d, _)| d.abs())
|
||||
.map(|(_, x)| x.clone())
|
||||
}
|
||||
|
||||
/// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family.
|
||||
fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
style(s, p, |st| {
|
||||
let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16;
|
||||
let italic = st.italic();
|
||||
st.set_font_style(styled_name(weight_name(w), italic));
|
||||
let styles = figcraft_text::family_style_weights(&st.font_family);
|
||||
if styles.is_empty() {
|
||||
// A family that isn't installed: step the weight by 100 under its canonical name.
|
||||
let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16;
|
||||
let italic = st.italic();
|
||||
st.set_font_style(styled_name(weight_name(w), italic));
|
||||
} else if let Some(next) = next_style(&styles, st, up) {
|
||||
st.set_font_style(next);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -46,3 +46,37 @@ fn a_plugin_gets_names_but_no_paths() {
|
||||
assert!(out.contains("Front"), "{out}");
|
||||
assert!(!out.contains(SECRET) && !out.contains("path"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_gets_library_names_but_not_their_links() {
|
||||
const LINK: &str = "ws://tracker.example:9/?file=f&token=per-file-secret";
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink {
|
||||
id: "lib".into(),
|
||||
name: "Kit".into(),
|
||||
path: LINK.into(),
|
||||
version: 3,
|
||||
});
|
||||
let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))";
|
||||
install(&mut s, manifest("org.test.libs", "read", &[]), &script(&[("library.list", json!({}))], OnRefusal::Fail, tail));
|
||||
let out = ex(&mut s, "plugin.run", json!({"id": "org.test.libs"}))["output"].to_string();
|
||||
assert!(out.contains("Kit"), "{out}");
|
||||
assert!(!out.contains("per-file-secret") && !out.contains("\\\"path\\\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_gets_a_fixed_message_for_library_update_failures() {
|
||||
const LINK: &str = "/home/someone/private/kits/kit.figcraft";
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink {
|
||||
id: "lib".into(),
|
||||
name: "Kit".into(),
|
||||
path: LINK.into(),
|
||||
version: 3,
|
||||
});
|
||||
let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))";
|
||||
install(&mut s, manifest("org.test.upd", "read", &[]), &script(&[("library.updates", json!({}))], OnRefusal::Fail, tail));
|
||||
let out = ex(&mut s, "plugin.run", json!({"id": "org.test.upd"}))["output"].to_string();
|
||||
assert!(out.contains("could not be read"), "{out}");
|
||||
assert!(!out.contains("someone") && !out.contains("private"), "{out}");
|
||||
}
|
||||
|
||||
@@ -180,12 +180,21 @@ fn refusal(m: &Manifest, command: &str, params: &Value) -> Option<String> {
|
||||
if command == "variable.import" && get(params, "variables").and_then(Value::as_str).is_some_and(|t| !t.trim_start().starts_with('{')) {
|
||||
return Some("plugins can't read files: pass the variables JSON itself".into());
|
||||
}
|
||||
// A saved version is the file's history, which plugins can't read (`version.` is denied).
|
||||
if command == "dev.compare" && get(params, "version").is_some_and(|v| !v.is_null()) {
|
||||
return Some("plugins can't read saved versions: leave out `version`".into());
|
||||
}
|
||||
if !m.permissions.allows(command) {
|
||||
return Some(format!("`{command}` isn't in the commands {} asked permission for", m.name));
|
||||
}
|
||||
if m.permissions.access == Access::Read && find_command(command).is_some_and(|c| c.history) {
|
||||
return Some(format!("`{command}` edits the document, and {} may only read it", m.name));
|
||||
}
|
||||
// Branches live beside the document (not in its undo history or its `Arc`), so the write
|
||||
// checks below don't see them change.
|
||||
if m.permissions.access == Access::Read && matches!(command, "branch.create" | "branch.updateFromMain" | "branch.merge" | "branch.archive") {
|
||||
return Some(format!("`{command}` changes the file's branches, and {} may only read it", m.name));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -263,10 +272,23 @@ impl figcraft_plugin::Host for EngineHost<'_> {
|
||||
Ok(v)
|
||||
});
|
||||
r.map(|mut v| {
|
||||
// A plugin gets the open files' names, not where they are on disk (#1117).
|
||||
if command == "doc.list" {
|
||||
for e in v.as_array_mut().into_iter().flatten().filter_map(Value::as_object_mut) {
|
||||
// A plugin gets the open files' and libraries' names, not where they are on disk or
|
||||
// the share links (with their tokens) that reach them (#1117).
|
||||
if matches!(command, "doc.list" | "library.list" | "library.updates") {
|
||||
// `doc.list` is a list; `library.list` keeps its list under `libraries`, and
|
||||
// `library.updates` its failures under `errors`.
|
||||
let list = match command {
|
||||
"library.list" => v.get_mut("libraries"),
|
||||
"library.updates" => v.get_mut("errors"),
|
||||
_ => Some(&mut v),
|
||||
};
|
||||
for e in list.and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) {
|
||||
e.remove("path");
|
||||
// A failure's text may quote the path, a token or another form of it: the
|
||||
// plugin gets a fixed message.
|
||||
if let Some(err) = e.get_mut("error").filter(|v| v.is_string()) {
|
||||
*err = json!("the library could not be read");
|
||||
}
|
||||
}
|
||||
}
|
||||
v.to_string()
|
||||
@@ -708,6 +730,23 @@ mod refusal_tests {
|
||||
let r = refusal(&m, "library.publishToServer", &json!({}));
|
||||
assert!(r.is_some(), "library.publishToServer uploads the document and must be refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_plugin_cannot_change_branches() {
|
||||
let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm"}"#).unwrap();
|
||||
for cmd in ["branch.archive", "branch.updateFromMain", "branch.merge", "branch.create"] {
|
||||
assert!(refusal(&m, cmd, &json!({})).is_some(), "{cmd} changes persisted branch state");
|
||||
}
|
||||
assert!(refusal(&m, "branch.list", &json!({})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_cannot_compare_against_a_saved_version() {
|
||||
let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm","permissions":{"access":"write"}}"#).unwrap();
|
||||
assert!(refusal(&m, "dev.compare", &json!({"version": "v1"})).is_some());
|
||||
assert!(refusal(&m, "dev.compare", &json!({"version": null})).is_none());
|
||||
assert!(refusal(&m, "dev.compare", &json!({})).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Suggest auto layout (#1823): a frame's layers are split into rows or columns by the gaps between
|
||||
//! them, each band of several layers gets a frame of its own, and the design keeps its placement.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
use figcraft_doc::{LayoutMode, NodeId, NodeKind, Sizing};
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
id_of(&v["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": w, "height": h})))
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, parent: NodeId, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id(&ex(s, "shape.rectangle", json!({"parent": parent, "x": x, "y": y, "width": w, "height": h})))
|
||||
}
|
||||
|
||||
/// A layer's box on the page: `[x0, y0, x1, y1]`, rounded.
|
||||
fn page_box(s: &Session, n: NodeId) -> [f64; 4] {
|
||||
let b = s.doc().unwrap().world_bounds(n).unwrap();
|
||||
[b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1000.0).round() / 1000.0)
|
||||
}
|
||||
|
||||
fn boxes(s: &Session, ns: &[NodeId]) -> Vec<[f64; 4]> {
|
||||
ns.iter().map(|n| page_box(s, *n)).collect()
|
||||
}
|
||||
|
||||
fn kids(s: &Session, n: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().node(n).unwrap().children.clone()
|
||||
}
|
||||
|
||||
fn mode(s: &Session, n: NodeId) -> Option<LayoutMode> {
|
||||
s.doc().unwrap().node(n).unwrap().layout.as_ref().map(|l| l.mode)
|
||||
}
|
||||
|
||||
/// A frame made by Suggest auto layout: no fill, no clipping, hugging what is in it.
|
||||
fn assert_band(s: &Session, n: NodeId, m: LayoutMode) {
|
||||
let node = s.doc().unwrap().node(n).unwrap();
|
||||
assert!(matches!(node.kind, NodeKind::Frame), "a band is a frame");
|
||||
assert!(node.fills.is_empty() && !node.clip, "a band has no fill and does not clip");
|
||||
assert_eq!(mode(s, n), Some(m));
|
||||
assert_eq!((node.child_layout.sizing_h, node.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
}
|
||||
|
||||
fn warnings(r: &Value) -> Vec<String> {
|
||||
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(String::from)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The issue's design: four 50 x 50 squares in a 200 x 200 frame, two rows of two.
|
||||
fn squares() -> (Session, NodeId, [NodeId; 4]) {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 100.0, 50.0, 200.0, 200.0);
|
||||
let sq = [(0.0, 0.0), (60.0, 0.0), (0.0, 60.0), (60.0, 60.0)].map(|(x, y)| rect(&mut s, f, x, y, 50.0, 50.0));
|
||||
(s, f, sq)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let before_frame = page_box(&s, f);
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(result["ids"], json!([f]));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let rows = kids(&s, f);
|
||||
assert_eq!(rows.len(), 2, "two rows");
|
||||
for (row, pair) in rows.iter().zip([[sq[0], sq[1]], [sq[2], sq[3]]]) {
|
||||
assert_band(&s, *row, LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, *row), pair);
|
||||
}
|
||||
let node = s.doc().unwrap().node(f).unwrap();
|
||||
assert_eq!(node.child_layout.sizing_h, Sizing::Fixed, "the frame keeps its size");
|
||||
assert_eq!(node.child_layout.sizing_v, Sizing::Fixed);
|
||||
assert_eq!(page_box(&s, f), before_frame);
|
||||
assert_eq!(boxes(&s, &sq), before, "every square stays where it was");
|
||||
assert_eq!(s.selection(), vec![f]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggesting_auto_layout_is_one_undo_step() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let rows_before = kids(&s, f);
|
||||
let steps = s.ds().unwrap().history.undo.len();
|
||||
ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1);
|
||||
let rows = kids(&s, f);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(kids(&s, f), rows_before);
|
||||
assert_eq!(mode(&s, f), None);
|
||||
assert!(rows.iter().all(|r| s.doc().unwrap().node(*r).is_none()), "the band frames are gone");
|
||||
assert_eq!(
|
||||
boxes(&s, &sq),
|
||||
[[100.0, 50.0, 150.0, 100.0], [160.0, 50.0, 210.0, 100.0], [100.0, 110.0, 150.0, 160.0], [160.0, 110.0, 210.0, 160.0]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_squares_in_a_row_get_one_horizontal_layout_without_nesting() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 20.0, 30.0, 200.0, 100.0);
|
||||
let sq = [0.0, 70.0, 140.0].map(|x| rect(&mut s, f, x, 25.0, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
assert_eq!(kids(&s, f), sq, "the squares are the frame's own layers");
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_squares_in_a_column_get_one_vertical_layout_without_nesting() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 20.0, 30.0, 100.0, 200.0);
|
||||
let sq = [0.0, 70.0, 140.0].map(|y| rect(&mut s, f, 25.0, y, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, f), sq);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_above_two_columns_of_squares_gives_a_row_per_line() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let header = rect(&mut s, f, 0.0, 0.0, 200.0, 50.0);
|
||||
let sq = [(0.0, 60.0), (0.0, 120.0), (110.0, 60.0), (110.0, 120.0)].map(|(x, y)| rect(&mut s, f, x, y, 50.0, 50.0));
|
||||
let all = [vec![header], sq.to_vec()].concat();
|
||||
let before = boxes(&s, &all);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
// The squares line up in two rows, so the gaps between rows win over the gap between columns.
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let top = kids(&s, f);
|
||||
assert_eq!(top.len(), 3);
|
||||
assert_eq!(top.first(), Some(&header));
|
||||
assert_band(&s, top[1], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, top[1]), vec![sq[0], sq[2]]);
|
||||
assert_band(&s, top[2], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, top[2]), vec![sq[1], sq[3]]);
|
||||
assert_eq!(boxes(&s, &all), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_above_a_tall_layer_beside_a_column_nests_three_levels() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 40.0, 10.0, 200.0, 200.0);
|
||||
let header = rect(&mut s, f, 0.0, 0.0, 200.0, 40.0);
|
||||
let tall = rect(&mut s, f, 0.0, 60.0, 50.0, 110.0);
|
||||
let sq = [60.0, 120.0].map(|y| rect(&mut s, f, 110.0, y, 50.0, 50.0));
|
||||
let all = [header, tall, sq[0], sq[1]];
|
||||
let before = boxes(&s, &all);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let top = kids(&s, f);
|
||||
assert_eq!(top.len(), 2);
|
||||
assert_eq!(top.first(), Some(&header));
|
||||
let band = top[1];
|
||||
assert_band(&s, band, LayoutMode::Horizontal);
|
||||
let cols = kids(&s, band);
|
||||
assert_eq!(cols.len(), 2);
|
||||
assert_eq!(cols.first(), Some(&tall));
|
||||
assert_band(&s, cols[1], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[1]), sq);
|
||||
assert_eq!(boxes(&s, &all), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_gaps_use_the_smallest_and_say_so() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 300.0, 100.0);
|
||||
let sq = [0.0, 60.0, 130.0].map(|x| rect(&mut s, f, x, 10.0, 50.0, 50.0));
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
let w = warnings(&result);
|
||||
assert_eq!(w.len(), 1, "{result}");
|
||||
assert!(w[0].contains("gaps"), "{}", w[0]);
|
||||
let b = boxes(&s, &sq);
|
||||
assert_eq!(b[0], [0.0, 10.0, 50.0, 60.0]);
|
||||
assert_eq!(b[1], [60.0, 10.0, 110.0, 60.0]);
|
||||
assert_eq!(b[2], [120.0, 10.0, 170.0, 60.0], "the last square moves along the row only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_layers_leave_the_frame_without_auto_layout_and_say_so() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let a = rect(&mut s, f, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, f, 50.0, 50.0, 100.0, 100.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), None);
|
||||
assert_eq!(kids(&s, f), vec![a, b]);
|
||||
assert_eq!(warnings(&result).len(), 1, "{result}");
|
||||
assert_eq!(boxes(&s, &[a, b]), vec![[0.0, 0.0, 100.0, 100.0], [50.0, 50.0, 150.0, 150.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_becomes_a_frame_in_place_and_follows_the_rules() {
|
||||
let mut s = Session::new();
|
||||
let page = s.page().unwrap();
|
||||
let (a, b, c, d) = (
|
||||
rect(&mut s, page, 10.0, 20.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 70.0, 20.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 10.0, 80.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 70.0, 80.0, 40.0, 40.0),
|
||||
);
|
||||
let group = id(&ex(&mut s, "object.group", json!({"ids": [a, b, c, d]})));
|
||||
let before = boxes(&s, &[group, a, b, c, d]);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [group]}));
|
||||
assert_eq!(result["ids"], json!([group]), "the group keeps its identity");
|
||||
assert!(matches!(s.doc().unwrap().node(group).unwrap().kind, NodeKind::Frame));
|
||||
assert_eq!(mode(&s, group), Some(LayoutMode::Vertical));
|
||||
let rows = kids(&s, group);
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_band(&s, rows[0], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, rows[0]), vec![a, b]);
|
||||
assert_eq!(kids(&s, rows[1]), vec![c, d]);
|
||||
assert_eq!(boxes(&s, &[group, a, b, c, d]), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_layers_are_wrapped_in_a_frame_that_is_then_split() {
|
||||
let mut s = Session::new();
|
||||
let page = s.page().unwrap();
|
||||
let sq = [(0.0, 0.0), (80.0, 0.0), (0.0, 80.0), (80.0, 80.0)].map(|(x, y)| rect(&mut s, page, x, y, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": sq}));
|
||||
let wrapper = id_of(&result["ids"][0]).unwrap();
|
||||
assert!(s.doc().unwrap().node(wrapper).unwrap().fills.is_empty());
|
||||
assert_eq!(mode(&s, wrapper), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, wrapper).len(), 2);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f], "direction": "horizontal"}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
let cols = kids(&s, f);
|
||||
assert_eq!(cols.len(), 2, "two columns");
|
||||
assert_band(&s, cols[0], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[0]), vec![sq[0], sq[2]]);
|
||||
assert_band(&s, cols[1], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[1]), vec![sq[1], sq[3]]);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_with_one_layer_is_laid_out_like_add_auto_layout() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
let a = rect(&mut s, f, 20.0, 20.0, 60.0, 40.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
assert_eq!(kids(&s, f), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_auto_layout_still_makes_a_single_row() {
|
||||
let (mut s, f, sq) = squares();
|
||||
ex(&mut s, "layout.add", json!({"ids": [f]}));
|
||||
let mut got = kids(&s, f);
|
||||
got.sort();
|
||||
assert_eq!(got, sq.to_vec(), "no nested frames");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let title = rect(&mut s, f, 60.0, 0.0, 80.0, 30.0);
|
||||
let card = rect(&mut s, f, 0.0, 40.0, 200.0, 100.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, f), vec![title, card]);
|
||||
let w = warnings(&result);
|
||||
assert_eq!(w.len(), 1, "{result}");
|
||||
assert!(w[0].contains("different offsets"), "{}", w[0]);
|
||||
assert_eq!(page_box(&s, title), [0.0, 0.0, 80.0, 30.0], "the title's left edge is the card's now");
|
||||
assert_eq!(page_box(&s, card), [0.0, 40.0, 200.0, 140.0], "the rest stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_and_layers_inside_them_are_refused_and_a_main_component_works() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
rect(&mut s, f, 0.0, 0.0, 50.0, 50.0);
|
||||
rect(&mut s, f, 0.0, 60.0, 50.0, 30.0);
|
||||
let nested = id(&ex(&mut s, "frame.create", json!({"parent": f, "x": 0, "y": 100, "width": 100, "height": 50})));
|
||||
rect(&mut s, nested, 0.0, 0.0, 20.0, 20.0);
|
||||
rect(&mut s, nested, 40.0, 0.0, 20.0, 20.0);
|
||||
let comp = id(&ex(&mut s, "component.create", json!({"ids": [f]})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
|
||||
let inside: Vec<NodeId> = kids(&s, inst).into_iter().filter(|k| matches!(s.doc().unwrap().node(*k).unwrap().kind, NodeKind::Frame)).collect();
|
||||
assert!(!inside.is_empty(), "the instance has a frame of its own");
|
||||
let page = s.page().unwrap();
|
||||
let snapshot = |s: &Session| (kids(s, page), kids(s, inst), kids(s, inside[0]));
|
||||
let before = snapshot(&s);
|
||||
let steps = s.ds().unwrap().history.undo.len();
|
||||
for target in [inst, inside[0]] {
|
||||
let e = s.execute("layout.suggest", &json!({"ids": [target]})).unwrap_err().to_string();
|
||||
assert!(e.contains("instance"), "{e}");
|
||||
}
|
||||
assert_eq!(snapshot(&s), before, "nothing changed");
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), steps, "no history step");
|
||||
assert!(s.doc().unwrap().node(inst).unwrap().layout.is_none());
|
||||
// The main component is a frame and works.
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [comp]}));
|
||||
assert_eq!(result["ids"], json!([comp]));
|
||||
}
|
||||
@@ -393,6 +393,8 @@ mod jpg_export_tests;
|
||||
#[cfg(test)]
|
||||
mod keymap_tests;
|
||||
#[cfg(test)]
|
||||
mod layout_suggest_tests;
|
||||
#[cfg(test)]
|
||||
mod library_beacon_tests;
|
||||
#[cfg(test)]
|
||||
mod library_path_tests;
|
||||
@@ -589,6 +591,8 @@ mod text_style_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod text_weight_step_tests;
|
||||
#[cfg(test)]
|
||||
mod textfit_tests;
|
||||
#[cfg(test)]
|
||||
mod theme_pages_tests;
|
||||
|
||||
@@ -592,4 +592,7 @@ fn same_server_ignores_the_default_port_before_a_path() {
|
||||
assert!(same_server("wss://share.example:443/figcraft/", "wss://share.example/figcraft/"));
|
||||
assert!(same_server("ws://host:80/x", "ws://host/x"));
|
||||
assert!(!same_server("wss://share.example:8443/figcraft/", "wss://share.example/figcraft/"));
|
||||
// The path is a route: owner tokens for /Team/ must never be sent to /team/.
|
||||
assert!(same_server("WSS://Share.Example/team/", "wss://share.example/team"));
|
||||
assert!(!same_server("wss://share.example/Team/", "wss://share.example/team/"));
|
||||
}
|
||||
|
||||
@@ -117,14 +117,17 @@ pub(crate) fn plain_server(server: &str) -> String {
|
||||
/// Two addresses name the same server (case, a closing slash and the scheme's own port aside).
|
||||
pub fn same_server(a: &str, b: &str) -> bool {
|
||||
let norm = |s: &str| {
|
||||
let s = plain_server(s).to_ascii_lowercase();
|
||||
let s = plain_server(s);
|
||||
let s = s.trim_end_matches('/');
|
||||
let port = if s.starts_with("wss://") { ":443" } else { ":80" };
|
||||
let start = s.find("://").map_or(0, |i| i + 3);
|
||||
let end = s[start..].find('/').map_or(s.len(), |i| start + i);
|
||||
match s[start..end].strip_suffix(port) {
|
||||
Some(host) => format!("{}{}{}", &s[..start], host, &s[end..]),
|
||||
None => s.to_string(),
|
||||
// The scheme and host compare without case; the path routes (a proxy may send
|
||||
// `/Team/` and `/team/` to different servers), so it keeps its case.
|
||||
let head = s[..end].to_ascii_lowercase();
|
||||
let port = if head.starts_with("wss://") { ":443" } else { ":80" };
|
||||
match head[start..].strip_suffix(port) {
|
||||
Some(host) => format!("{}{}{}", &head[..start], host, &s[end..]),
|
||||
None => format!("{head}{}", &s[end..]),
|
||||
}
|
||||
};
|
||||
norm(a) == norm(b)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Increase and decrease font weight step through the styles the family has, by weight with the
|
||||
//! same slant and width (#1831), not by 100 to a canonical name no face provides.
|
||||
|
||||
use figcraft_doc::{NodeId, TextStyle};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::cmd::text::{name_weight, next_style};
|
||||
|
||||
/// A family's styles listed by the weights their names say, as for faces not read yet.
|
||||
fn styles(names: &[&str]) -> Vec<(String, u16)> {
|
||||
names.iter().map(|s| ((*s).to_string(), name_weight(s))).collect()
|
||||
}
|
||||
|
||||
/// A family's styles with the faces' own weights.
|
||||
fn weighed(faces: &[(&str, u16)]) -> Vec<(String, u16)> {
|
||||
faces.iter().map(|(s, w)| ((*s).to_string(), *w)).collect()
|
||||
}
|
||||
|
||||
fn at(style: &str) -> TextStyle {
|
||||
let mut st = TextStyle::default();
|
||||
st.set_font_style(style);
|
||||
st
|
||||
}
|
||||
|
||||
/// Walk `from` heavier (`up`) or lighter until the family has nothing further.
|
||||
fn walk(family: &[(String, u16)], from: &str, up: bool) -> Vec<String> {
|
||||
let mut st = at(from);
|
||||
let mut out = Vec::new();
|
||||
while let Some(next) = next_style(family, &st, up) {
|
||||
st.set_font_style(next.clone());
|
||||
out.push(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_steps_follow_the_family_with_the_same_slant_and_width() {
|
||||
let arial = styles(&["Narrow", "Regular", "Italic", "Narrow Italic", "Bold", "Narrow Bold", "Bold Italic", "Narrow Bold Italic", "Black"]);
|
||||
assert_eq!(walk(&arial, "Regular", true), ["Bold", "Black"]);
|
||||
assert_eq!(walk(&arial, "Black", false), ["Bold", "Regular"]);
|
||||
assert_eq!(walk(&arial, "Italic", true), ["Bold Italic"]);
|
||||
assert_eq!(walk(&arial, "Narrow", true), ["Narrow Bold"]);
|
||||
assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]);
|
||||
let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]);
|
||||
assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]);
|
||||
assert_eq!(walk(&segoe, "Regular", false), ["Semilight", "Light"]);
|
||||
// A style the family doesn't have (as the old steps stored) moves to the next real one.
|
||||
assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_and_semi_before_a_width_keep_the_width() {
|
||||
let family = styles(&["Extra Condensed Regular", "Condensed Regular", "Condensed Bold", "Extra Condensed Bold", "Semi Condensed Extra Bold"]);
|
||||
assert_eq!(walk(&family, "Extra Condensed Regular", true), ["Extra Condensed Bold"]);
|
||||
assert_eq!(walk(&family, "Condensed Bold", false), ["Condensed Regular"]);
|
||||
assert_eq!(walk(&family, "Semi Condensed Extra Bold", false), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oblique_names_step_to_oblique_faces() {
|
||||
let dejavu = styles(&["Book", "Oblique", "Bold", "Bold Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Oblique", true), ["Bold Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Bold Oblique", false), ["Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Book", true), ["Bold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hairline_and_w_numbers_are_weights() {
|
||||
let family = styles(&["Hairline", "Thin", "Regular", "Bold"]);
|
||||
assert_eq!(walk(&family, "Regular", false), ["Thin", "Hairline"]);
|
||||
// Off the list (a stored style the family lacks): by weight, the nearer of two equal ones.
|
||||
assert_eq!(next_style(&family, &at("Extra Light"), false).as_deref(), Some("Thin"));
|
||||
assert_eq!(next_style(&family, &at("Extra Light"), true).as_deref(), Some("Regular"));
|
||||
let hiragino = styles(&["W3", "W6"]);
|
||||
assert_eq!(walk(&hiragino, "W3", true), ["W6"]);
|
||||
assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_weights_count_after_a_width_but_other_numbers_dont() {
|
||||
// An off-list "Condensed 600" is 600, as "600" alone is: between Condensed 500 and 700.
|
||||
let condensed = weighed(&[("Condensed 300", 300), ("Condensed 500", 500), ("Condensed 700", 700)]);
|
||||
assert_eq!(next_style(&condensed, &at("Condensed 600"), true).as_deref(), Some("Condensed 700"));
|
||||
assert_eq!(next_style(&condensed, &at("Condensed 600"), false).as_deref(), Some("Condensed 500"));
|
||||
assert_eq!((name_weight("Condensed 600"), name_weight("600 Italic"), name_weight("Condensed 1000")), (600, 600, 1000));
|
||||
// A number that isn't a weight (a width grade, an optical size) is part of the width.
|
||||
assert_eq!((name_weight("Condensed 2"), name_weight("Caption 12 Bold"), name_weight("Condensed +600")), (400, 700, 400));
|
||||
let optical = styles(&["Caption 12 Regular", "Caption 24 Regular", "Caption 12 Bold", "Caption 24 Bold"]);
|
||||
assert_eq!(walk(&optical, "Caption 12 Regular", true), ["Caption 12 Bold"]);
|
||||
assert_eq!(walk(&optical, "Caption 24 Bold", false), ["Caption 24 Regular"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn univers_numbers_step_by_weight_within_their_width() {
|
||||
// Helvetica Neue LT, Univers, Frutiger: the first digit grades the weight, the second the width.
|
||||
let hn = weighed(&[
|
||||
("45 Light", 300),
|
||||
("46 Light Italic", 300),
|
||||
("55 Roman", 400),
|
||||
("56 Italic", 400),
|
||||
("57 Condensed", 400),
|
||||
("65 Medium", 500),
|
||||
("67 Medium Condensed", 500),
|
||||
("75 Bold", 700),
|
||||
("76 Bold Italic", 700),
|
||||
("77 Bold Condensed", 700),
|
||||
]);
|
||||
assert_eq!(walk(&hn, "55 Roman", true), ["65 Medium", "75 Bold"]);
|
||||
assert_eq!(walk(&hn, "65 Medium", false), ["55 Roman", "45 Light"]);
|
||||
assert_eq!(walk(&hn, "57 Condensed", true), ["67 Medium Condensed", "77 Bold Condensed"]);
|
||||
assert_eq!(walk(&hn, "67 Medium Condensed", false), ["57 Condensed"]);
|
||||
assert_eq!(walk(&hn, "46 Light Italic", true), ["56 Italic", "76 Bold Italic"]);
|
||||
// Faces not read yet: the words after the number give the weight.
|
||||
let univers = styles(&["45 Light", "55 Roman", "65 Bold", "75 Black", "57 Condensed", "67 Bold Condensed"]);
|
||||
assert_eq!(walk(&univers, "45 Light", true), ["55 Roman", "65 Bold", "75 Black"]);
|
||||
assert_eq!(walk(&univers, "67 Bold Condensed", false), ["57 Condensed"]);
|
||||
assert_eq!((name_weight("45 Light"), name_weight("75 Black"), name_weight("57 Condensed")), (300, 900, 400));
|
||||
// Other leading numbers stay part of the width: before another word, or not a width digit.
|
||||
let other = styles(&["12 Regular", "12 Bold", "55 Rounded", "55 Rounded Bold", "Regular", "Bold"]);
|
||||
assert_eq!(walk(&other, "12 Regular", true), ["12 Bold"]);
|
||||
assert_eq!(walk(&other, "55 Rounded", true), ["55 Rounded Bold"]);
|
||||
assert_eq!(walk(&other, "Regular", true), ["Bold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_weight_axis_value_steps_from_where_it_is() {
|
||||
let family = styles(&["Light", "Regular", "Medium", "Bold"]);
|
||||
let mut st = at("Regular");
|
||||
st.variations.insert("wght".into(), 550.0);
|
||||
assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold"));
|
||||
assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_the_list_the_faces_own_weights_decide() {
|
||||
// From 500 between 400 and 700 faces: the neighbours, under their own names (the axis value goes).
|
||||
let family = weighed(&[("Light", 300), ("Regular", 400), ("Bold", 700)]);
|
||||
let mut st = at("Regular");
|
||||
st.variations.insert("wght".into(), 500.0);
|
||||
assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold"));
|
||||
assert_eq!(next_style(&family, &st, false).as_deref(), Some("Regular"));
|
||||
st.set_font_style("Bold");
|
||||
assert_eq!((st.weight(), st.variations.get("wght")), (700, None));
|
||||
// Segoe UI Variable's Semilight is 350, not the 300 its name says: from a `wght` of 325 it is
|
||||
// the next heavier style, and from 375 the next lighter.
|
||||
let segoe = weighed(&[("Light", 300), ("Semilight", 350), ("Regular", 400), ("Semibold", 600), ("Bold", 700)]);
|
||||
st.variations.insert("wght".into(), 325.0);
|
||||
assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Semilight"));
|
||||
assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Light"));
|
||||
st.variations.insert("wght".into(), 375.0);
|
||||
assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Semilight"));
|
||||
assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Regular"));
|
||||
// A W-numbered name with a slant after it is still that weight ("W7 Italic" is 700).
|
||||
let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]);
|
||||
assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic"));
|
||||
assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic"));
|
||||
// And after a width ("Condensed W7 Italic" is 700 too).
|
||||
let condensed = weighed(&[("Condensed W3 Italic", 300), ("Condensed W6 Italic", 600), ("Condensed W8 Italic", 800)]);
|
||||
assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), true).as_deref(), Some("Condensed W8 Italic"));
|
||||
assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), false).as_deref(), Some("Condensed W6 Italic"));
|
||||
}
|
||||
|
||||
fn font_style(s: &Session, t: NodeId) -> String {
|
||||
s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commands_land_on_styles_the_family_has() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
// Any installed family with a Regular face and a style the step takes it to (CI machines differ).
|
||||
let pick = figcraft_text::family_names().into_iter().find_map(|f| {
|
||||
let st = figcraft_text::family_style_weights(&f);
|
||||
let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|(x, _)| x == "Regular"))?;
|
||||
Some((f, st, up))
|
||||
});
|
||||
let Some((family, styles, heavier)) = pick else { return };
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap();
|
||||
let t = crate::params::id_of(&r["id"]).unwrap();
|
||||
s.execute("text.weightUp", &json!({"ids": [t]})).unwrap();
|
||||
let up = font_style(&s, t);
|
||||
assert_eq!(up, heavier, "{family}: {styles:?}");
|
||||
s.execute("text.weightDown", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}");
|
||||
// A family that isn't installed still steps by 100 under the canonical names.
|
||||
s.execute("node.set", &json!({"ids": [t], "props": {"fontFamily": "No Such Family 7f3a", "fontStyle": "Regular"}})).unwrap();
|
||||
s.execute("text.weightUp", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(font_style(&s, t), "Medium");
|
||||
}
|
||||
@@ -191,9 +191,13 @@ impl<'b> Reader<'b> {
|
||||
let mut shift = 0;
|
||||
loop {
|
||||
let b = self.byte()?;
|
||||
value |= u32::from(b & 127).checked_shl(shift).unwrap_or(0);
|
||||
let part = b & 127;
|
||||
if shift == 28 && (part > 0x0f || b & 128 != 0) {
|
||||
return err("u32 varint overflow");
|
||||
}
|
||||
value |= u32::from(part) << shift;
|
||||
shift += 7;
|
||||
if b & 128 == 0 || shift >= 35 {
|
||||
if b & 128 == 0 {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
@@ -670,3 +674,17 @@ fn numbered(token: &str, default: u32) -> Result<(String, u32), KiwiError> {
|
||||
Some((name, n)) => Ok((name.to_string(), n.parse().map_err(|_| KiwiError(format!("schema text: bad number in `{token}`")))?)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Reader;
|
||||
|
||||
#[test]
|
||||
fn overflowing_u32_varint_is_rejected() {
|
||||
let mut boundary = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x0f], pos: 0 };
|
||||
assert_eq!(boundary.var_uint(), Ok(u32::MAX));
|
||||
|
||||
let mut overflowing = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x7f], pos: 0 };
|
||||
assert!(overflowing.var_uint().is_err(), "overflowing u32 varint was accepted");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::layer::{cap_name, own_text, svg_path, valid_size};
|
||||
use super::paint::{paint, stroke};
|
||||
use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows};
|
||||
use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape};
|
||||
use figcraft_doc::{RouteEnd, Routing, Side, route_points};
|
||||
use figcraft_doc::{ConnectorPath, MAX_RUNS, RouteEnd, Routing, Side, attach_points, attached_sides, route_along};
|
||||
|
||||
/// How a connector imports: from its saved snapshot (`terminal`: as one vector, no room for its
|
||||
/// label), or drawn from its ends, as a frame with its line and `label` when it has one.
|
||||
@@ -48,7 +48,8 @@ impl<'a> Mapper<'a> {
|
||||
|
||||
/// A connector's end caps, and when it has no saved outline or network its line between its
|
||||
/// ends (free points, or a sibling layer): straight to the point given on the layer (its
|
||||
/// centre unless given), or elbowed or curved from a side of it, as a board connector runs.
|
||||
/// centre unless given), or elbowed or curved from a side of it, as a board connector runs;
|
||||
/// an elbow saved with its path (FigJam's control points) runs along it (#1910).
|
||||
/// Returns the middle of that line by length, in the connector's own coordinates.
|
||||
pub(super) fn connector(&mut self, o: &mut Obj, v: &View<'a>, space: Affine) -> Option<Point> {
|
||||
for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] {
|
||||
@@ -94,11 +95,13 @@ impl<'a> Mapper<'a> {
|
||||
};
|
||||
ok.then_some(end)
|
||||
};
|
||||
let Some(pts) = end("connectorStart").zip(end("connectorEnd")).and_then(|(a, b)| route_points(a, b, routing)) else {
|
||||
let ends = end("connectorStart").zip(end("connectorEnd"));
|
||||
let path = ends.filter(|_| routing == Routing::Elbow).and_then(|(a, b)| saved_runs(v, a, b));
|
||||
let Some(pts) = ends.and_then(|(a, b)| route_along(a, b, routing, path.as_ref())) else {
|
||||
self.warn("connectors whose ends can't be placed are empty");
|
||||
return None;
|
||||
};
|
||||
if routing != Routing::Straight {
|
||||
if routing != Routing::Straight && path.is_none() {
|
||||
self.warn("elbowed and curved connectors without a saved path follow FigCraft's own routing");
|
||||
}
|
||||
// A curved route is one curve: its ends and the two control points between them.
|
||||
@@ -407,6 +410,49 @@ pub(super) fn connector_has_saved_label(v: &View<'_>) -> bool {
|
||||
.is_some_and(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
/// The path a FigJam elbow connector was saved with: its `connectorControlPoints`, one per run
|
||||
/// between the first and the last, each a point on its run (in the connector's parent's
|
||||
/// coordinates, like its ends) with the run's axis; the first run leaves the start's side and the
|
||||
/// last arrives at the end's, so neither is saved. `None` without any, or when they don't make
|
||||
/// such a path: a point off both axes, two runs in a row the same way, a first or last run that
|
||||
/// would leave or arrive sideways to its side, or more runs than a hand could make here.
|
||||
fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option<ConnectorPath> {
|
||||
let saved = v.list("connectorControlPoints");
|
||||
if saved.is_empty() || saved.len() + 2 > MAX_RUNS {
|
||||
return None;
|
||||
}
|
||||
let (p0, p1) = attach_points(from, to);
|
||||
let mid = p0.midpoint(p1);
|
||||
let mut at = Vec::with_capacity(saved.len());
|
||||
let (mut first, mut last) = (None, None);
|
||||
for p in saved {
|
||||
let pos = p.get("position").and_then(|q| Some(Point::new(num(q, "x")?, num(q, "y")?)))?;
|
||||
let (ax, ay) = p.get("axis").and_then(|q| Some((num(q, "x")?, num(q, "y")?)))?;
|
||||
let sideways = match (ax != 0.0, ay != 0.0) {
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => return None,
|
||||
};
|
||||
if last == Some(sideways) {
|
||||
return None;
|
||||
}
|
||||
first.get_or_insert(!sideways);
|
||||
last = Some(sideways);
|
||||
at.push(if sideways { pos.y - mid.y } else { pos.x - mid.x });
|
||||
}
|
||||
// The run through each end goes the way its side faces, out of the object: the first leaves
|
||||
// the start's side for the first saved run, the last arrives at the end's from the last saved
|
||||
// run. One along the side, or back into the object, doesn't.
|
||||
let (across, last) = (first?, last?);
|
||||
let (&a0, &a1) = (at.first()?, at.last()?);
|
||||
// Where the run from `p` (`sideways`: going across) meets the saved run at `v`.
|
||||
let onto = |sideways: bool, p: Point, v: f64| if sideways { Point::new(mid.x + v, p.y) } else { Point::new(p.x, mid.y + v) };
|
||||
let out_of = |s: Option<Side>, p: Point, q: Point| s.is_none_or(|s| (q - p).dot(s.normal()) > 0.0);
|
||||
let (s0, s1) = attached_sides(from, to);
|
||||
let fits = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1));
|
||||
fits.then_some(ConnectorPath::Runs { across, at })
|
||||
}
|
||||
|
||||
/// The side of its layer a connector end leaves from: the `magnet` the file names, else the edge
|
||||
/// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end.
|
||||
fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side {
|
||||
|
||||
@@ -863,3 +863,85 @@ fn write_fixture() {
|
||||
std::fs::write(out, zip_file(&tail_canvas())).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// An elbow connector saved with its path (#1910): FigJam's control points, one per run between
|
||||
/// the first and the last, each on its run with the run's axis, give the path the connector keeps;
|
||||
/// the first run leaves the start's side and the last arrives at the end's.
|
||||
#[test]
|
||||
fn an_elbow_connector_saved_with_its_path_keeps_it() {
|
||||
let mut message = tail_message();
|
||||
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
|
||||
let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]);
|
||||
let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]);
|
||||
// From A's bottom, across at y 740, down at x 200, into B's left: four runs.
|
||||
let saved = node(
|
||||
66,
|
||||
Some((1, "+")),
|
||||
"CONNECTOR",
|
||||
"Saved",
|
||||
vec![
|
||||
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
|
||||
("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])),
|
||||
("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])),
|
||||
("connectorLineStyle", e("ELBOWED")),
|
||||
("connectorControlPoints", arr(vec![point(150.0, 740.0, 1.0, 0.0), point(200.0, 800.0, 0.0, 1.0)])),
|
||||
],
|
||||
);
|
||||
nodes.extend([box_at(64, "A", 0.0, 600.0), box_at(65, "B", 300.0, 800.0), saved]);
|
||||
let (doc, warnings) = import(&canvas(&schema(), &message), "Saved path").unwrap();
|
||||
let world = doc.world_transform(named(&doc, "Saved").id);
|
||||
let line: Vec<_> =
|
||||
network_of(&doc, "Saved").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
|
||||
// Each end starts `END_GAP` (4) outside its side's border.
|
||||
assert_eq!(line, [(50.0, 704.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (296.0, 850.0)]);
|
||||
// The fixture's own Link, saved without a path, is routed here: the note counts it alone.
|
||||
let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect();
|
||||
assert_eq!(routed.len(), 1, "{warnings:?}");
|
||||
assert!(!routed[0].contains('×'), "a connector with its path isn't counted among those routed here: {routed:?}");
|
||||
}
|
||||
|
||||
/// Saved control points that don't make a path from the connector's sides (#1910): a first run
|
||||
/// that would leave the bottom sideways, a point off both axes, or two runs in a row the same way
|
||||
/// leave the connector to FigCraft's routing, as one saved without a path is.
|
||||
#[test]
|
||||
fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() {
|
||||
let mut message = tail_message();
|
||||
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
|
||||
let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]);
|
||||
let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]);
|
||||
let elbow = |id, name: &str, points: Vec<Kv<'static>>| {
|
||||
let mut fields = vec![
|
||||
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
|
||||
("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])),
|
||||
("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])),
|
||||
("connectorLineStyle", e("ELBOWED")),
|
||||
];
|
||||
if !points.is_empty() {
|
||||
fields.push(("connectorControlPoints", arr(points)));
|
||||
}
|
||||
node(id, Some((1, "+")), "CONNECTOR", name, fields)
|
||||
};
|
||||
nodes.extend([
|
||||
box_at(64, "A", 0.0, 600.0),
|
||||
box_at(65, "B", 300.0, 800.0),
|
||||
elbow(66, "Plain", vec![]),
|
||||
elbow(67, "Sideways", vec![point(100.0, 650.0, 0.0, 1.0)]),
|
||||
elbow(68, "Askew", vec![point(150.0, 740.0, 1.0, 1.0)]),
|
||||
elbow(69, "Repeated", vec![point(150.0, 740.0, 1.0, 0.0), point(150.0, 760.0, 1.0, 0.0)]),
|
||||
// The first run would go up from A's bottom, through A; the last would arrive at B's left
|
||||
// from inside B. Each run is at right angles to its side, so only the way it goes is wrong.
|
||||
elbow(70, "Backwards", vec![point(100.0, 650.0, 1.0, 0.0), point(200.0, 740.0, 0.0, 1.0)]),
|
||||
elbow(71, "Inside", vec![point(150.0, 740.0, 1.0, 0.0), point(350.0, 800.0, 0.0, 1.0)]),
|
||||
]);
|
||||
let (doc, warnings) = import(&canvas(&schema(), &message), "Unfit paths").unwrap();
|
||||
let line = |name: &str| -> Vec<(f64, f64)> {
|
||||
let world = doc.world_transform(named(&doc, name).id);
|
||||
network_of(&doc, name).vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect()
|
||||
};
|
||||
let plain = line("Plain");
|
||||
assert!(plain.len() >= 3, "routed in right angles: {plain:?}");
|
||||
for name in ["Sideways", "Askew", "Repeated", "Backwards", "Inside"] {
|
||||
assert_eq!(line(name), plain, "{name} is routed as one without a path");
|
||||
}
|
||||
assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}");
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ message VariableSetID GUID guid, AssetRef assetRef
|
||||
message ConditionalActions Action[] actions, VariableData condition
|
||||
message VectorData uint vectorNetworkBlob, Vector normalizedSize, NodeChange[] styleOverrideTable
|
||||
message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition
|
||||
message ConnectorControlPoint Vector position, Vector axis
|
||||
message VariableData AnyValue value, DataType dataType
|
||||
message Paint PaintType type, Color color, float opacity, bool visible, Image image, Matrix transform, ColorStop[] stops, VariableData colorVar, ImageScaleMode imageScaleMode
|
||||
message ParentIndex GUID guid, string position
|
||||
@@ -74,7 +75,7 @@ message Event InteractionType interactionType
|
||||
message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions
|
||||
message Interaction Event event, Action[] actions
|
||||
message StartingPoint string name, string position
|
||||
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern
|
||||
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern, ConnectorControlPoint[] connectorControlPoints
|
||||
message Blob byte[] bytes
|
||||
message Message NodeChange[] nodeChanges, Blob[] blobs
|
||||
";
|
||||
|
||||
@@ -210,6 +210,13 @@ fn set_rotation_keeps_center() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_to_handles_large_precision_without_changing_finite_values() {
|
||||
assert_eq!(round_to(1.25, 400), 1.25);
|
||||
assert_eq!(round_to(-1.25, 400), -1.25);
|
||||
assert_eq!(round_to(1.23456, 2), 1.23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_subpaths_preserves_open_and_closed() {
|
||||
let mut open = BezPath::new();
|
||||
|
||||
@@ -57,6 +57,9 @@ pub fn rotate_about(xf: Affine, pivot: Point, degrees: f64) -> Affine {
|
||||
/// Round a value to `digits` decimals for display (avoids `-0` and float noise).
|
||||
pub fn round_to(v: f64, digits: i32) -> f64 {
|
||||
let f = 10f64.powi(digits);
|
||||
if v.is_finite() && !f.is_finite() {
|
||||
return v;
|
||||
}
|
||||
let r = (v * f).round() / f;
|
||||
if r == 0.0 { 0.0 } else { r }
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) {
|
||||
let strong = |k: i64| k.rem_euclid(major) == 0;
|
||||
// The device-pixel span of the mark on line `k` along an axis `len` pixels long from `o`.
|
||||
let span = |k: i64, o: f64, len: i64| {
|
||||
let a = ((k as f64 * d.step * s - o).round() as i64).saturating_sub(lead);
|
||||
let a = (nearest_px(k as f64 * d.step * s, o) as i64).saturating_sub(lead);
|
||||
(a.max(0), a.saturating_add(side).min(len))
|
||||
};
|
||||
let row = w as usize * 4;
|
||||
@@ -92,6 +92,22 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first device pixel of a mark whose edge is `at` pixels from the page origin, in a view whose
|
||||
/// top-left is `o` pixels from it: the pixel whose left (or top) edge is nearest, and the right (or
|
||||
/// lower) one when two are as near. A view a whole number of pixels off (a pan, a band, a patch)
|
||||
/// gets `o` back from its origin with a rounding error, so `at` and `o` are each rounded to
|
||||
/// 1/65536 px first: the mark's own position decides the pixel, and the view only counts it out
|
||||
/// from its corner. The mark's halves go up and the origin's down: far out, where the origin's
|
||||
/// error is half a step, it still comes back to the whole pixel. Past 2³⁷ px the step is finer
|
||||
/// than `f64` and values are used as they are.
|
||||
fn nearest_px(at: f64, o: f64) -> f64 {
|
||||
const STEPS: f64 = 65_536.0;
|
||||
const EXACT: f64 = 137_438_953_472.0; // 2³⁷
|
||||
let up = |v: f64| if v.abs() < EXACT { (v * STEPS + 0.5).floor() / STEPS } else { v };
|
||||
let down = |v: f64| if v.abs() < EXACT { (v * STEPS - 0.5).ceil() / STEPS } else { v };
|
||||
(up(at) - down(o) + 0.5).floor()
|
||||
}
|
||||
|
||||
/// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one.
|
||||
type Cover = Vec<u8>;
|
||||
|
||||
|
||||
@@ -134,3 +134,103 @@ fn graph_paper_is_strong_every_major_line() {
|
||||
assert_eq!(at(x, -195), strong, "a strong line at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// At a zoom of 1.0625, a step of 24 is 25.5 pixels: every second dot falls halfway between two
|
||||
/// pixels. A view a whole number of pixels on (a pan, a band, a patch) has to put it on the same
|
||||
/// one, on whichever side of that view's origin it is.
|
||||
#[test]
|
||||
fn dots_halfway_between_pixels_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() };
|
||||
let s = 1.0625;
|
||||
let full = View { origin: (0.0, 0.0), scale: s, width: 400, height: 300 };
|
||||
let a = render_view_single(&d, page, &full, &opts).unwrap();
|
||||
for dx in 1..100u32 {
|
||||
let dy = (dx * 37) % 100;
|
||||
let v = View { origin: (f64::from(dx) / s, f64::from(dy) / s), scale: s, width: 250, height: 180 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..180 {
|
||||
for x in 0..250 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y + dy), "lines {lines}, a pan by ({dx}, {dy}), at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mark that rounds to a half step of 1/65536 px goes the same way on both sides of a view's
|
||||
/// origin too: at a step of 25.5 − 2⁻¹⁷ px, the first mark is where 1/65536 px rounds up.
|
||||
#[test]
|
||||
fn dots_on_the_rounding_step_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let step = 25.5 - 2f64.powi(-17);
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { step, lines, ..dots() }), ..Default::default() };
|
||||
let full = View { origin: (0.0, 0.0), scale: 1.0, width: 300, height: 200 };
|
||||
let a = render_view_single(&d, page, &full, &opts).unwrap();
|
||||
for pan in 1..60u32 {
|
||||
let v = View { origin: (f64::from(pan), f64::from(pan)), scale: 1.0, width: 200, height: 120 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..120 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The view's origin is quantized apart from the marks: converted to pixels, a whole-pixel origin
|
||||
/// comes back a hair off, and taken together with a mark one step short of a half it would push the
|
||||
/// mark across.
|
||||
#[test]
|
||||
fn dots_one_rounding_step_short_of_a_half_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let s = (75.5 - 2f64.powi(-17)) / 24.0;
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() };
|
||||
let a = render_view_single(&d, page, &View { origin: (0.0, 0.0), scale: s, width: 300, height: 200 }, &opts).unwrap();
|
||||
for pan in 1..100u32 {
|
||||
let v = View { origin: (f64::from(pan) / s, f64::from(pan) / s), scale: s, width: 200, height: 100 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..100 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Far out (some 4 × 10¹⁰ pixels), a whole-pixel origin comes back from page units exactly half a
|
||||
/// rounding step off: rounded up, it would move the marks that fall halfway between pixels.
|
||||
#[test]
|
||||
fn far_out_dots_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let s = 0.3;
|
||||
let at = 42_536_140_695.0;
|
||||
let opts = Options { dots: Some(Dots { step: 5.0, ..dots() }), ..Default::default() };
|
||||
let a = render_view_single(&d, page, &View { origin: (at / s, 0.0), scale: s, width: 420, height: 40 }, &opts).unwrap();
|
||||
for dx in 1..200u32 {
|
||||
let v = View { origin: ((at + f64::from(dx)) / s, 0.0), scale: s, width: 200, height: 40 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..40 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y), "a pan by {dx}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Positions too far out to quantize draw nothing rather than a mark at the corner.
|
||||
#[test]
|
||||
fn dots_out_past_any_page_draw_nothing() {
|
||||
let (d, page) = page_with_square();
|
||||
let plain = render_view_single(&d, page, &View { origin: (1e304, 0.0), scale: 1.0, width: 40, height: 40 }, &Options::default()).unwrap();
|
||||
for (step, x) in [(1e290, 1e304), (1e299, 1e305), (3e303, 1.5e308)] {
|
||||
let opts = Options { dots: Some(Dots { step, ..dots() }), ..Default::default() };
|
||||
let p = render_view_single(&d, page, &View { origin: (x, 0.0), scale: 1.0, width: 40, height: 40 }, &opts).unwrap();
|
||||
assert_eq!(p.data(), plain.data(), "a step of {step} at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,3 +192,58 @@ fn arc_stroke_mitres_are_not_cut_off() {
|
||||
assert!(worst <= 2, "{align:?}: {worst} levels cut off");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dashed stroke is cut into separate dashes with square ends, a width profile can step its
|
||||
/// width and a brush lays down shapes of its own: round a whole ellipse or a rounded box, a spread
|
||||
/// mitres out at their corners, past the box grown by the spread, and keeps its whole shadow.
|
||||
#[test]
|
||||
fn stroke_corners_spread_mitres_are_not_cut_off() {
|
||||
use figcraft_doc::{Brush, Node, StrokeAlign, StrokeCap, WidthProfile};
|
||||
type Style = fn(&mut Node);
|
||||
let strokes: [(&str, Style); 4] = [
|
||||
("dashed", |n| n.stroke.dashes = vec![30.0, 30.0]),
|
||||
("dashed with square caps", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))),
|
||||
("stepped", |n| n.stroke.width_profile = Some(WidthProfile::new([(0.0, 1.0), (0.25, 4.0), (0.26, 0.2), (0.75, 4.0)]))),
|
||||
("starry", |n| n.stroke.brush = Some(Brush::new("stars"))),
|
||||
];
|
||||
let shapes = [(NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, 0.0), (NodeKind::Rectangle, 100.0)];
|
||||
for (kind, radius) in shapes {
|
||||
for (name, style) in strokes {
|
||||
for align in [StrokeAlign::Outside, StrokeAlign::Center] {
|
||||
let make = |effects: Vec<EffectKind>| {
|
||||
let (mut d, n) = shape(kind.clone(), effects);
|
||||
let node = d.get_mut(n).unwrap();
|
||||
node.corners.radii = [radius; 4];
|
||||
node.strokes = vec![Paint::solid(Color::WHITE)];
|
||||
(node.stroke.weight, node.stroke.align) = (20.0, align);
|
||||
style(node);
|
||||
(d, n)
|
||||
};
|
||||
let (d, n) = make(vec![EffectKind::DropShadow(shadow(30.0))]);
|
||||
let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(120.0) };
|
||||
let (roomy, m) = make(vec![EffectKind::DropShadow(shadow(30.0)), EffectKind::DropShadow(clear)]);
|
||||
let (a, b) = (render(&d, n), render(&roomy, m));
|
||||
let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0);
|
||||
// The stroke lands a little differently on a layer of another size, even when
|
||||
// both have room to spare: up to 16 levels at a pixel or two. Cut off is 255.
|
||||
assert!(worst <= 16, "{kind:?} radius {radius}, {name} {align:?}: {worst} levels cut off");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a spread, a dashed stroke reaches no further than a solid one: the bounds an export
|
||||
/// goes by stay the box grown by the stroke.
|
||||
#[test]
|
||||
fn a_dashed_stroke_without_a_spread_keeps_its_bounds() {
|
||||
use figcraft_doc::StrokeAlign;
|
||||
for kind in [NodeKind::Rectangle, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }] {
|
||||
let (mut d, n) = shape(kind.clone(), vec![]);
|
||||
let node = d.get_mut(n).unwrap();
|
||||
node.strokes = vec![Paint::solid(Color::WHITE)];
|
||||
(node.stroke.weight, node.stroke.align) = (20.0, StrokeAlign::Outside);
|
||||
node.stroke.dashes = vec![30.0, 30.0];
|
||||
let b = crate::export_bounds(&d, n).unwrap();
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (80.0, 80.0, 320.0, 320.0), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -755,6 +755,12 @@ impl FontDb {
|
||||
|
||||
/// Style names of a family, by weight then italic.
|
||||
pub fn styles(&mut self, family: &str) -> Vec<String> {
|
||||
self.style_weights(family).into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
|
||||
/// [`styles`](Self::styles) with the weight each is listed by: the face's own (Segoe UI
|
||||
/// Semilight is 350), a named instance's `wght`, or for a face not read yet its name's.
|
||||
pub fn style_weights(&mut self, family: &str) -> Vec<(String, u16)> {
|
||||
self.load_family(family, None);
|
||||
let key = self.key(family);
|
||||
// (weight, italic, order in the font, name): named instances keep the font's order.
|
||||
@@ -773,14 +779,29 @@ impl FontDb {
|
||||
v.push((w, f.italic || italic_name(&inst.name), k, inst.name.clone()));
|
||||
}
|
||||
}
|
||||
// A family installed as one family per weight offers those weights too.
|
||||
for (_, style) in self.split_families(&key) {
|
||||
v.push((pending_weight(&style).clamp(1, 1000) as u16, italic_name(&style), 0, style));
|
||||
// A family installed as one family per weight offers those weights too, upright and italic
|
||||
// as that family's faces are ("Foo Bold" with Regular and Italic faces: Bold and Bold
|
||||
// Italic, the names `resolve` finds them by). A face read gives its own weight, one not
|
||||
// read the name's; the families aren't read for this.
|
||||
for (k, style) in self.split_families(&key) {
|
||||
let named = pending_weight(&style).clamp(1, 1000) as u16;
|
||||
let italic = italic_name(&style);
|
||||
let read = self.families.get(&k).map(|(_, idx)| idx.as_slice()).unwrap_or_default().iter().filter_map(|i| self.faces.get(*i));
|
||||
let unread = self.pending.get(&k).into_iter().flat_map(|(_, entries)| entries).map(|e| (named, italic_name(&e.style)));
|
||||
let faces: Vec<(u16, bool)> = read.map(|f| (f.weight, f.italic)).chain(unread).collect();
|
||||
if faces.is_empty() {
|
||||
v.push((named, italic, 0, style));
|
||||
continue;
|
||||
}
|
||||
for (w, slanted) in faces {
|
||||
let name = if slanted && !italic { format!("{style} Italic") } else { style.clone() };
|
||||
v.push((w, slanted || italic, 0, name));
|
||||
}
|
||||
}
|
||||
v.sort();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
v.retain(|x| seen.insert(norm_style(&x.3)));
|
||||
v.into_iter().map(|x| x.3).collect()
|
||||
v.into_iter().map(|x| (x.3, x.0)).collect()
|
||||
}
|
||||
|
||||
/// The key `family` is known under: itself in any case; for a name designs use for Apple's
|
||||
@@ -1514,6 +1535,11 @@ pub fn family_styles(family: &str) -> Vec<String> {
|
||||
db().write().unwrap_or_else(std::sync::PoisonError::into_inner).styles(family)
|
||||
}
|
||||
|
||||
/// [`family_styles`] with the weight each is listed by (see [`FontDb::style_weights`]).
|
||||
pub fn family_style_weights(family: &str) -> Vec<(String, u16)> {
|
||||
db().write().unwrap_or_else(std::sync::PoisonError::into_inner).style_weights(family)
|
||||
}
|
||||
|
||||
/// Scan system fonts into the global db (desktop; a no-op on the web, or with
|
||||
/// `FIGCRAFT_NO_SYSTEM_FONTS` set). Runs once per process: a concurrent caller waits for that scan.
|
||||
/// The directory walk runs without holding the database lock; results are merged in one short write.
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! case; the picker lists what is installed. Synthetic family names only, over pending entries
|
||||
//! (no files) and the embedded faces when the build has them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{CRAFT_FONTS, Face, FontBytes, FontDb, Pending, style_words};
|
||||
use super::{CRAFT_FONTS, Face, FontBytes, FontDb, LocalFont, Pending, scan_dir, style_words, system_font_dirs};
|
||||
|
||||
fn entry(style: &str) -> Pending {
|
||||
Pending { path: format!("no-such-dir/{style}.ttf").into(), index: 0, style: style.into(), postscript: None, local: None }
|
||||
@@ -104,3 +105,43 @@ fn faces_are_found_and_listed_under_either_name() {
|
||||
assert!(Arc::ptr_eq(&db.find("Synthetic Text SemiBold", "Regular").unwrap(), &semibold));
|
||||
assert!(Arc::ptr_eq(&db.find("synthetictext", "Semibold").unwrap(), &semibold));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_per_weight_offers_its_italics_too() {
|
||||
// Listed by name before anything is read: Synthetic Slab Bold's Italic face is Bold Italic.
|
||||
let local = |id: usize, family: &str, style: &str| LocalFont { id, family: family.into(), style: style.into(), postscript: String::new() };
|
||||
let mut db = FontDb::default();
|
||||
db.add_local(vec![
|
||||
local(0, "Synthetic Slab", "Regular"),
|
||||
local(1, "Synthetic Slab", "Italic"),
|
||||
local(2, "Synthetic Slab Bold", "Regular"),
|
||||
local(3, "Synthetic Slab Bold", "Italic"),
|
||||
]);
|
||||
let listed = |db: &mut FontDb| db.style_weights("Synthetic Slab");
|
||||
let want = |v: &[(&str, u16)]| v.iter().map(|(s, w)| ((*s).to_string(), *w)).collect::<Vec<_>>();
|
||||
assert_eq!(listed(&mut db), want(&[("Regular", 400), ("Italic", 400), ("Bold", 700), ("Bold Italic", 700)]));
|
||||
assert_eq!(resolved(&db, "Synthetic Slab", "Bold Italic"), pair("synthetic slab bold", "Italic"), "the style drawn by that face");
|
||||
// Faces read give their own weights: Synthetic Slab Semi Light's are 350, not the name's 300.
|
||||
let stand_in = CRAFT_FONTS.first().map(|f| f.bytes.to_vec()).or_else(|| {
|
||||
let mut installed = BTreeMap::new();
|
||||
for dir in system_font_dirs() {
|
||||
scan_dir(&dir, 0, &mut installed);
|
||||
}
|
||||
installed.values().flat_map(|(_, v)| v).find_map(|p| std::fs::read(&p.path).ok())
|
||||
});
|
||||
let Some(bytes) = stand_in.map(Arc::new) else {
|
||||
eprintln!("skipping the read faces: no font to stand in");
|
||||
return;
|
||||
};
|
||||
let face = |family: &str, style: &str, weight: u16, italic: bool| {
|
||||
let mut f = Face::from_bytes(FontBytes::Shared(bytes.clone()), 0, Some(family), Some(style)).unwrap();
|
||||
f.instances.clear();
|
||||
(f.weight, f.italic) = (weight, italic);
|
||||
f
|
||||
};
|
||||
let mut db = FontDb::default();
|
||||
db.add(face("Synthetic Slab", "Regular", 400, false));
|
||||
db.add(face("Synthetic Slab Semi Light", "Regular", 350, false));
|
||||
db.add(face("Synthetic Slab Semi Light", "Italic", 350, true));
|
||||
assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)]));
|
||||
}
|
||||
|
||||
@@ -17,8 +17,8 @@ pub use breaks::{backspace_step, grapheme_step};
|
||||
pub use color::{ColorBitmap, ColorInk, ColorLayer};
|
||||
pub use fontdb::{
|
||||
Axis, CRAFT_FONTS, Coords, Face, FontDb, LocalFont, NamedInstance, Rescan, add_local_fonts, axis_label, db, face_with_char, family_names,
|
||||
family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, opt_out_of_system_fonts,
|
||||
rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts,
|
||||
family_style_weights, family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords,
|
||||
opt_out_of_system_fonts, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts,
|
||||
};
|
||||
pub use layout::{Decoration, Glyph, Line, TextLayout, layout};
|
||||
pub use onpath::OnPath;
|
||||
|
||||
@@ -63,27 +63,53 @@ const NAMED: usize = 3;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Warnings {
|
||||
seen: std::collections::BTreeMap<Warn, Vec<String>>,
|
||||
/// Per warning: the distinct names so far (a set, so a document with many distinct names
|
||||
/// doesn't make each check a scan of all before it), and the first few in order.
|
||||
seen: std::collections::BTreeMap<Warn, (std::collections::BTreeSet<String>, Vec<String>)>,
|
||||
}
|
||||
|
||||
impl Warnings {
|
||||
pub fn add(&mut self, w: Warn, layer: &str) {
|
||||
let names = self.seen.entry(w).or_default();
|
||||
if !names.iter().any(|n| n == layer) {
|
||||
names.push(layer.to_string());
|
||||
let (distinct, first) = self.seen.entry(w).or_default();
|
||||
if distinct.insert(layer.to_string()) && first.len() < NAMED {
|
||||
first.push(layer.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Vec<String> {
|
||||
self.seen
|
||||
.into_iter()
|
||||
.map(|(w, names)| {
|
||||
.map(|(w, (distinct, names))| {
|
||||
let shown: Vec<String> =
|
||||
names.iter().take(NAMED).map(|n| if n.is_empty() { "unnamed layer".to_string() } else { n.clone() }).collect();
|
||||
let more = names.len().saturating_sub(NAMED);
|
||||
let more = distinct.len().saturating_sub(NAMED);
|
||||
let more = if more > 0 { format!(", {more} more") } else { String::new() };
|
||||
format!("{} ({}{more})", w.message(), shown.join(", "))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_are_counted_once_each_and_the_first_three_shown() {
|
||||
let mut w = Warnings::default();
|
||||
for name in ["a", "b", "a", "c", "d", "b", "e"] {
|
||||
w.add(Warn::NothingDrawn, name);
|
||||
}
|
||||
let lines = w.finish();
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].ends_with("(a, b, c, 2 more)"), "{}", lines[0]);
|
||||
// Many distinct names: each is one set insertion, not a scan of all before it.
|
||||
let mut w = Warnings::default();
|
||||
let start = std::time::Instant::now();
|
||||
for i in 0..200_000 {
|
||||
w.add(Warn::TooLarge, &format!("layer {i}"));
|
||||
}
|
||||
assert!(w.finish()[0].ends_with("199997 more)"));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Auto layout and constraints parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Auto layout is the most used layout feature in Figma and the one where small differences (a
|
||||
hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%,
|
||||
@@ -92,7 +92,8 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
|
||||
| Arrow keys move children one place (flows, rows, columns, grid cells, into neighbours) | done | `al_keys_tests.rs` |
|
||||
| Constraints: left, right, left and right, centre, scale; top/bottom likewise | done | |
|
||||
| Layout grids: columns, rows, grid; stretch/left/centre/right; variables bound | done | |
|
||||
| Suggest auto layout / "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) |
|
||||
| Suggest auto layout | done | The target works out which layers belong together and adds as many auto layout frames as the design needs, in one step, keeping the placement. `layout.suggest` used to run `layout.add` and made one row of everything (#1823). Now it splits a frame's layers, by their boxes in the frame, along the vertical axis first: sorted by top edge, a layer joins the current row while it starts above the row's bottom (or together with it), and a gap, even a zero one, between the row and the next layer starts a new row. With two or more rows the frame becomes a Vertical auto layout whose items are the rows; otherwise the same split by columns gives a Horizontal one; if the layers overlap along both axes the frame gets no auto layout and the result carries a warning. A row or column of several layers goes into a new frame without fill or clipping, sized to it and inserted in its place (it hugs its content once the split gives it auto layout; a band whose own layers overlap along both axes gets none, with a warning, and stays a Fixed frame that cannot reflow those layers), and the split repeats inside it, to a depth of 16 and for up to 1,000 layers per frame (past that, or when a mask is among the layers, the layers are laid out in one list as Add auto layout does, with a warning). The frame keeps its size, Fixed: the gap is the distance between the bands, the padding along the flow is the first band's offset and the room left after the last, across the flow the smallest offset (alignment start), so with equal gaps and bands that start at the same offset every layer keeps its box exactly. When the gaps differ by more than 0.5 px the smallest is used and `warnings` says the later bands move; when the bands start at different offsets across the flow (a centred title above a card) they line up at the smallest, which moves the others, and `warnings` says so. Instances and layers inside them are refused with the error Convert to group gives, before anything changes; a main component works. `direction` sets the top level only. A single group becomes a frame in place and several layers are wrapped in a frame (both hug), as Add auto layout does; a frame with fewer than two layers is laid out as Add auto layout does. One undo step. Tests in `crates/engine/src/layout_suggest_tests.rs`: `two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows`, `suggesting_auto_layout_is_one_undo_step`, `three_squares_in_a_row_get_one_horizontal_layout_without_nesting`, `three_squares_in_a_column_get_one_vertical_layout_without_nesting`, `a_header_above_two_columns_of_squares_gives_a_row_per_line`, `a_header_above_a_tall_layer_beside_a_column_nests_three_levels`, `unequal_gaps_use_the_smallest_and_say_so`, `overlapping_layers_leave_the_frame_without_auto_layout_and_say_so`, `a_group_becomes_a_frame_in_place_and_follows_the_rules`, `several_layers_are_wrapped_in_a_frame_that_is_then_split`, `a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps`, `a_frame_with_one_layer_is_laid_out_like_add_auto_layout`, `add_auto_layout_still_makes_a_single_row`, `a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning`, `instances_and_layers_inside_them_are_refused_and_a_main_component_works`. Not attempted: overlapping layers, keeping uneven offsets across the flow (they line up at the smallest, with a warning), grids |
|
||||
| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) |
|
||||
| Real Figma files laid out identically | **not checked** | needs `.fig` or REST import of real files ([gaps](gaps.md) #1, #3) |
|
||||
| Performance: re-flow only where sizes or places changed | done | measured in `cargo xtask bench` (components at scale) |
|
||||
|
||||
@@ -100,6 +101,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` |
|
||||
| 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. |
|
||||
| 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` |
|
||||
| 2026-11-02 | patch | M2, #1838: a double-click on an edge of an auto layout frame's bounding box sets Hug contents on that axis, Alt+double-click on an edge of a child's Fill container ("Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents", "Hold ⌥ Option or Alt and double-click ... to set it to Fill container", Guide to auto layout); a vertical edge sizes the width, a horizontal one the height; the Keyboard shortcuts panel lists both gestures. Test: `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills`. Numbers unchanged. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Boards parity
|
||||
|
||||
> **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)
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); 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
|
||||
@@ -66,7 +66,7 @@ all end with the same geometry.
|
||||
| Audio and huddles | missing | |
|
||||
| AI features (summaries, sorting stickies, generating boards) | missing | |
|
||||
| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none |
|
||||
| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies and shapes with text come in as frames with their generated layers and its connectors as vectors, not as native board objects; no export | see [`file-format-parity.md`](file-format-parity.md) |
|
||||
| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies and shapes with text come in as frames with their generated layers and its connectors as vectors, not as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) |
|
||||
|
||||
## Revision history
|
||||
|
||||
@@ -74,6 +74,7 @@ all end with the same geometry.
|
||||
|---|---|---|
|
||||
| 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-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). |
|
||||
| 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. |
|
||||
| 2026-10-31 | minor | M12, #1710: a selected elbow or curved connector shows path handles. 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, is saved with the file, and goes back to routing itself when the style changes or an end moves to something else. |
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -753,6 +753,18 @@ sudo -u figcraft figcraft-server --config /etc/figcraft-server/server.toml key
|
||||
The other commands ([Managing files and links](#managing-files-and-links)) run the same way, as
|
||||
the `figcraft` user with `--config /etc/figcraft-server/server.toml`.
|
||||
|
||||
**Browser editor on the same hostname (optional).** The steps above install the collaboration
|
||||
server. To also serve the editor, copy the complete contents of the matching
|
||||
`figcraft-web-<version>/` release directory into `/srv/figcraft-web`, with `index.html` directly
|
||||
inside it; keep subdirectories such as `snippets/`. Use the commented browser-and-server block
|
||||
in [`packaging/server/Caddyfile`](../packaging/server/Caddyfile) in place of its active server-only
|
||||
block. Keep the loopback `listen`, `public_url` and `trusted_proxy` settings from steps 2 and 4.
|
||||
The editor opens at `https://figcraft.example.com/app/`; the hostname root remains the
|
||||
`wss://figcraft.example.com/` collaboration endpoint, not an editor homepage. Configure the
|
||||
browser's `figcraft-server` meta tag as described in the
|
||||
[web-hosting guide](../packaging/web/README.md#live-sessions), using the server address without a
|
||||
publishing key. That guide also covers browser requirements, fonts and static-file delivery.
|
||||
|
||||
**In Docker instead of systemd.** [`packaging/server/Dockerfile`](../packaging/server/Dockerfile)
|
||||
builds a small image (the binary on a distroless base, no shell) that runs as an unprivileged
|
||||
user, keeps its files in the `/data` volume and stops gracefully on `docker stop`. Build it from
|
||||
|
||||
@@ -16,3 +16,38 @@ figcraft.example.com {
|
||||
# reverse_proxy 127.0.0.1:47900
|
||||
# }
|
||||
# }
|
||||
|
||||
# Browser editor and server on the same hostname instead. Use this block IN PLACE OF the
|
||||
# active block above. Copy the complete browser release into /srv/figcraft-web, with index.html
|
||||
# directly inside it and subdirectories such as snippets/ kept. See packaging/web/README.md for
|
||||
# the browser's figcraft-server meta tag; never put a publishing key in public HTML.
|
||||
# Open the editor at /app/. The hostname root remains the WSS endpoint, not an editor homepage.
|
||||
#
|
||||
# figcraft.example.com {
|
||||
# encode gzip
|
||||
#
|
||||
# redir /app /app/?{query} 308
|
||||
#
|
||||
# @entry path /app/ /app/index.html
|
||||
# header @entry Cache-Control "no-cache"
|
||||
#
|
||||
# @release_assets path /app/figcraft-web-*.js /app/figcraft-web-*_bg.wasm
|
||||
# # Defer so a missing asset does not receive the one-year cache header.
|
||||
# header @release_assets Cache-Control "public, max-age=31536000, immutable" {
|
||||
# defer
|
||||
# }
|
||||
#
|
||||
# # No root favicon is configured: do not forward its implicit request to the WS server.
|
||||
# handle /favicon.ico {
|
||||
# respond 204
|
||||
# }
|
||||
#
|
||||
# handle_path /app/* {
|
||||
# root * /srv/figcraft-web
|
||||
# file_server
|
||||
# }
|
||||
#
|
||||
# handle {
|
||||
# reverse_proxy 127.0.0.1:47900
|
||||
# }
|
||||
# }
|
||||
|
||||
Executable
+119
@@ -0,0 +1,119 @@
|
||||
#!/bin/sh
|
||||
# Exercise the optional browser/server example with synthetic files over loopback HTTP.
|
||||
# Requires caddy and nc; no backend, root access, public DNS or certificate is needed.
|
||||
# Usage: packaging/server/caddy-test.sh
|
||||
# Overrides: CADDY=/path/to/caddy CADDYFILE=/path/to/Caddyfile CADDY_TEST_PORT=18080
|
||||
set -eu
|
||||
|
||||
HERE="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)"
|
||||
CADDY="${CADDY:-caddy}"
|
||||
CADDYFILE="${CADDYFILE:-$HERE/Caddyfile}"
|
||||
PORT="${CADDY_TEST_PORT:-18080}"
|
||||
case "$PORT" in ''|*[!0-9]*) echo 'CADDY_TEST_PORT must be a port number' >&2; exit 1 ;; esac
|
||||
[ "$PORT" -gt 1023 ] && [ "$PORT" -lt 65536 ] || exit 1
|
||||
command -v "$CADDY" >/dev/null
|
||||
command -v nc >/dev/null
|
||||
|
||||
WORK="$(mktemp -d)"
|
||||
PID=''
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - 0
|
||||
if [ -n "$PID" ]; then
|
||||
kill "$PID" 2>/dev/null || true
|
||||
wait "$PID" 2>/dev/null || true
|
||||
fi
|
||||
rm -rf "$WORK"
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup 0
|
||||
trap 'exit 1' HUP INT TERM
|
||||
fail() { printf 'FAIL: %s\n' "$*" >&2; cat "$WORK/caddy.log" >&2; exit 1; }
|
||||
|
||||
mkdir "$WORK/web"
|
||||
printf 'synthetic editor\n' >"$WORK/web/index.html"
|
||||
printf 'synthetic JavaScript asset\n' >"$WORK/web/figcraft-web-present.js"
|
||||
printf 'synthetic WebAssembly asset\n' >"$WORK/web/figcraft-web-present_bg.wasm"
|
||||
|
||||
# Extract the real commented block, changing only the hostname and filesystem root.
|
||||
# The admin endpoint is disabled; state directories stay inside the temporary fixture.
|
||||
printf '{\n\tadmin off\n}\n' >"$WORK/Caddyfile"
|
||||
awk -v port="$PORT" -v root="$WORK/web" '
|
||||
$0 == "# figcraft.example.com {" { active = 1; found++; print "http://127.0.0.1:" port " {"; next }
|
||||
active {
|
||||
if ($0 !~ /^#/) exit 1
|
||||
if ($0 == "# }") { print "}"; active = 0; next }
|
||||
sub(/^# ?/, "")
|
||||
if ($1 == "root" && $2 == "*" && $3 == "/srv/figcraft-web") $0 = "\t\troot * \"" root "\""
|
||||
print
|
||||
}
|
||||
END { if (found != 1 || active) exit 1 }
|
||||
' "$CADDYFILE" >>"$WORK/Caddyfile"
|
||||
|
||||
XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \
|
||||
"$CADDY" validate --config "$WORK/Caddyfile" --adapter caddyfile >"$WORK/caddy.log" 2>&1 ||
|
||||
fail 'extracted example did not validate'
|
||||
XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \
|
||||
"$CADDY" run --config "$WORK/Caddyfile" --adapter caddyfile >>"$WORK/caddy.log" 2>&1 &
|
||||
PID=$!
|
||||
|
||||
request() {
|
||||
printf '%s %s HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n' "$1" "$2" |
|
||||
nc -w 2 127.0.0.1 "$PORT" >"$WORK/response" || return 1
|
||||
tr -d '\r' <"$WORK/response" >"$WORK/clean"
|
||||
awk 'BEGIN { headers = 1 } headers && /^$/ { headers = 0; next } !headers { print }' \
|
||||
"$WORK/clean" >"$WORK/body"
|
||||
}
|
||||
status() { awk 'NR == 1 { print $2 }' "$WORK/clean"; }
|
||||
cache() {
|
||||
awk '/^$/ { exit } tolower($0) ~ /^cache-control:/ { sub(/^[^:]*:[ \t]*/, ""); print }' "$WORK/clean"
|
||||
}
|
||||
|
||||
attempt=0
|
||||
until request GET /app/ 2>/dev/null && [ "$(status)" = 200 ]; do
|
||||
kill -0 "$PID" 2>/dev/null || fail 'Caddy did not start (port may be in use)'
|
||||
attempt=$((attempt + 1))
|
||||
[ "$attempt" -lt 30 ] || fail 'Caddy did not become ready'
|
||||
sleep 0.1
|
||||
done
|
||||
kill -0 "$PID" 2>/dev/null || fail 'Caddy exited during startup'
|
||||
|
||||
IMMUTABLE='public, max-age=31536000, immutable'
|
||||
checks=0
|
||||
check() {
|
||||
method=$1
|
||||
name=$2
|
||||
expected=$3
|
||||
request "$method" "/app/$name" || fail "$method $name request failed"
|
||||
[ "$(status)" = "$expected" ] || fail "$method $name: expected HTTP $expected, got $(status)"
|
||||
if [ "$expected" = 200 ]; then
|
||||
[ "$(cache)" = "$IMMUTABLE" ] || fail "$method $name: successful asset lost its cache policy"
|
||||
if [ "$method" = GET ]; then
|
||||
cmp -s "$WORK/body" "$WORK/web/$name" || fail "$method $name: wrong file contents"
|
||||
fi
|
||||
else
|
||||
[ -z "$(cache)" ] || fail "$method $name: a missing asset received Cache-Control: $(cache)"
|
||||
fi
|
||||
if [ "$method" = HEAD ]; then
|
||||
[ ! -s "$WORK/body" ] || fail "$method $name: HEAD returned a body"
|
||||
fi
|
||||
checks=$((checks + 1))
|
||||
printf 'PASS: %s %s -> %s\n' "$method" "$name" "$expected"
|
||||
}
|
||||
|
||||
for method in GET HEAD; do
|
||||
check "$method" figcraft-web-present.js 200
|
||||
check "$method" figcraft-web-present_bg.wasm 200
|
||||
check "$method" figcraft-web-later.js 404
|
||||
check "$method" figcraft-web-later_bg.wasm 404
|
||||
done
|
||||
|
||||
# The same URLs must work immediately when deployment supplies the previously missing files.
|
||||
printf 'new JavaScript asset\n' >"$WORK/web/figcraft-web-later.js"
|
||||
printf 'new WebAssembly asset\n' >"$WORK/web/figcraft-web-later_bg.wasm"
|
||||
for method in GET HEAD; do
|
||||
check "$method" figcraft-web-later.js 200
|
||||
check "$method" figcraft-web-later_bg.wasm 200
|
||||
done
|
||||
|
||||
printf 'Caddy browser asset caching: %s checks passed (%s)\n' "$checks" "$("$CADDY" version)"
|
||||
Reference in New Issue
Block a user