diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 5fd971c629..5b9c965a79 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -3,9 +3,9 @@ name: Shared audio on: push: branches: [main] - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: - paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] + paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index f4c4e6689b..7d570980dd 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -3,9 +3,9 @@ name: Shared media on: push: branches: [main] - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: - paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 20afe0d700..0db0f19f30 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -3,9 +3,9 @@ name: Shared video on: push: branches: [main] - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: - paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] + paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] workflow_dispatch: permissions: diff --git a/Cargo.lock b/Cargo.lock index ec4810f1f5..c319ea1631 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1905,6 +1905,7 @@ dependencies = [ "craft-pst", "craft-quit", "craft-raster-codecs", + "craft-raster3d", "craft-raw", "craft-review", "craft-rtf", @@ -2799,6 +2800,7 @@ dependencies = [ "serde", "serde_json", "skrifa 0.47.0", + "write-fonts 0.54.1", ] [[package]] @@ -2958,6 +2960,7 @@ name = "craft-gpu-wgpu" version = "0.1.0" dependencies = [ "craft-gpu", + "craft-gpu-device", "craft-gpu-providers", "pollster 0.4.0", "wgpu", @@ -3253,9 +3256,11 @@ dependencies = [ "craft-ui-macros", "craft-xml", "egui", + "global-hotkey", "serde", "serde_json", "tempfile", + "x11rb", ] [[package]] @@ -3508,6 +3513,7 @@ dependencies = [ name = "craft-nightly" version = "0.1.0" dependencies = [ + "uds_windows", "winsafe", ] @@ -3802,6 +3808,7 @@ dependencies = [ "craft-docpath", "craft-host", "craft-i18n", + "craft-testkit", "craft-theme", "fmv-macos-events", "futures-lite", @@ -4016,6 +4023,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-raster3d" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-raw" version = "0.1.0" @@ -4353,7 +4368,9 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "log", "png 0.18.1", + "proptest", "rustix 1.1.6", "serde_json", "sha2 0.10.9", @@ -4746,6 +4763,7 @@ dependencies = [ "base64 0.22.1", "chrono", "craft-host", + "craft-testkit", "craft-theme", "craft-ui", "dunce", @@ -6942,6 +6960,23 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "global-hotkey" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "once_cell", + "thiserror 2.0.21", + "windows-sys 0.59.0", + "x11rb", + "xkeysym", +] + [[package]] name = "glow" version = "0.17.0" diff --git a/Cargo.toml b/Cargo.toml index 817f5c1065..f8bc4506d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -236,6 +236,7 @@ craft-text = { path = "crates/text" } craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } craft-pbr = { path = "crates/pbr" } +craft-raster3d = { path = "crates/raster3d" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } @@ -291,7 +292,7 @@ smallvec = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" typeid = "1" -proptest = "1" +proptest = "1.7" # Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause. encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). diff --git a/NOTICE b/NOTICE index baa994eb47..9e09cf4494 100644 --- a/NOTICE +++ b/NOTICE @@ -486,3 +486,11 @@ The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed MIT OR Apache-2.0. Source notice retained: Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. + +The CPU renderer in crates/raster3d (rasterizer, shading, shadow maps, resolve and encoding) and +the copy of it in crates/raster3d/tests/it/reference/ are moved from: +- EffectCraft, crates/render/src/three_d/adv.rs, adv/raster.rs, adv/shade.rs and adv/scene.rs, + revision 2f16feb12f4d5ef601b35b2858f9c9a87077f61e, licensed under the MIT License or the Apache + License, Version 2.0, at your option. + https://github.com/storytold/effectcraft + Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. diff --git a/README.md b/README.md index 8169bedf9a..64698d8c48 100644 --- a/README.md +++ b/README.md @@ -394,6 +394,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved documents, the Quit menu item id and the unsaved-changes question one document at a time (`CloseGuard`). The prompt and the saving stay in each app. +- [`craft-raster3d`](crates/raster3d/README.md): a CPU renderer for a prepared 3D scene, from + EffectCraft: clipping, rasterization with a top-left fill rule, physically based shading, + shadow maps, a box resolve of supersampled output and sRGB encoding. Scenes and sizes are + checked before the target is allocated. `Limits` bounds sizes and coverage work. Preparation can + allocate clipping and triangle buffers before a work-limit error. Building the scene stays in each app. - [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages (`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer for a small neutral model (paragraphs, character formatting, outline levels, tables). @@ -436,7 +441,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit test when the variable the caller names is `1`. Any other value of that variable except empty fails the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures - under `target/fixtures` and publishes each one under a lock. Not published. + under `target/fixtures` and publishes each one under a lock. Its `temp` module makes a new test folder, private to the user on + Unix, that is removed with its contents when dropped (best effort). Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 132fd5a0a6..05ce79d82d 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -241,6 +241,35 @@ fn temp_name_format_is_valid() { assert!(name.ends_with(".craft_tmp")); } +#[test] +fn temp_name_keeps_long_non_latin_names_under_the_name_limit() { + // 62 four-byte characters plus ".json" is a valid 253-byte name. + let file = format!("{}.json", "\u{1F600}".repeat(62)); + assert_eq!(file.len(), 253); + let name = temp_name(&file); + assert!(name.len() <= 255, "{} bytes", name.len()); + assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(TEMP_STEM_BYTES / 4)))); + assert!(name.ends_with(".craft_tmp")); +} + +#[test] +fn temp_name_cuts_at_a_character_boundary() { + // TEMP_STEM_BYTES - 1 ASCII bytes, then a two-byte character that would end one byte past the limit. + let file = format!("{}\u{e9}tail", "a".repeat(TEMP_STEM_BYTES - 1)); + let name = temp_name(&file); + assert!(name.starts_with(&format!(".{}.", "a".repeat(TEMP_STEM_BYTES - 1)))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saves_a_long_non_latin_name() { + let d = TempDir::new("long-name"); + let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62))); + assert!(atomic_write(&p, b"saved").is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec())); + assert_no_temp(&d.0); +} + /// What a [`Planting`] filesystem puts at a stage name just before the stage is created there. #[derive(Clone, Copy, Debug)] enum Obstacle { diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 227098fa3f..d1765008c6 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -584,6 +584,23 @@ impl Open { !self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some() } + /// The pointer reached `at`, by a move or by the button going up there: once past `slop` from the press, a target + /// that senses a drag starts one, one that clicks and passes its drag waits for its hand-over, and any other loses + /// its click. A release with no move before it (the pointer jumped) is judged where it went up, so only a release + /// within slop clicks. + fn reach(&mut self, at: Pos2, slop: f32) { + if self.released_at.is_none() && !self.dragging && !self.abandoned && self.passing.is_none() && at.distance(self.start.origin) > slop { + if self.sense.contains(Sense::DRAG) { + self.dragging = true; + self.silent = false; + } else if self.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { + self.passing = Some(at); + } else { + self.abandoned = true; + } + } + } + /// A release now is a click. fn clicks(&self) -> bool { !self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK) @@ -693,21 +710,8 @@ impl PressMachine { match *event { PointerEvent::Moved { at, .. } => { pos = at; - if let Some(open) = &mut self.open - && open.released_at.is_none() - && !open.dragging - && !open.abandoned - && open.passing.is_none() - && at.distance(open.start.origin) > input.slop - { - if open.sense.contains(Sense::DRAG) { - open.dragging = true; - open.silent = false; - } else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { - open.passing = Some(at); - } else { - open.abandoned = true; - } + if let Some(open) = &mut self.open { + open.reach(at, input.slop); } } PointerEvent::Gone => { @@ -717,11 +721,14 @@ impl PressMachine { } PointerEvent::Pressed { button, pos: at, time, clicks } => { pos = at; - // A release held for the next pass gives way to a new press; it ends in this pass. + // A release held for the next pass gives way to a new press; it ends in this pass. A drag whose + // start that pass still owed was never reported, so the release is no drag either: every part reads + // `Down`, a `Release`, or `DragStart` then `Drag`, never a drag's end that never began. The press's + // target hears where the button went up in `Release::pos`, and no click is at that distance. if let Some(open) = self.open && let Some((up, click)) = open.released_at { - released = Some((open.target, open.start, up, open.dragging, click, open.silent)); + released = Some((open.target, open.start, up, open.drag_reported, click, open.silent)); self.open = None; } // A secondary press during an open primary press goes beside it, to the context target `pick` gives @@ -788,6 +795,9 @@ impl PressMachine { if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) { continue; } + if let Some(open) = &mut self.open { + open.reach(at, input.slop); + } if let Some(open) = &mut self.open && open.owes_phase() { @@ -1114,4 +1124,136 @@ mod tests { assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); assert_eq!(end.activated, None); } + + /// A release past slop with no move before it (the pointer jumped while the button was down) reads as a move there + /// and a release: it does what a move past slop and a release in one pass do, for every sense. A target that drags + /// starts its drag and ends it, with no click. + #[test] + fn a_jump_release_past_slop_starts_and_ends_a_drag() { + let sense = Sense::CLICK | Sense::DRAG; + let (far, near) = (SLOP * 4.0, SLOP / 2.0); + let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)], &[]], sense); + assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)], &[]], sense), "a jump is a move and a release"); + assert_eq!(jumped, "D S R", "the drag starts where the button went up, then ends with no click"); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], sense), "D R!", "a jump within slop still clicks"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + let start = pass(&mut machine, &[up(far)], sense); + assert!(matches!(start.phase, Some(PressPhase::DragStart { pos, .. }) if pos == pos2(far, 0.0)), "{:?}", start.phase); + assert!(machine.release_held(), "the release waits for the owed DragStart"); + let end = pass(&mut machine, &[], sense); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(end.dragging, "the release ends a drag"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + } + + /// A jump release past slop on a target that clicks and passes its drag passes the press as a move past slop does: + /// the pass reports it in `passes`, a shape below that takes it drags and releases with no click, and a press no + /// shape takes is abandoned with no click. + #[test] + fn a_jump_release_past_slop_on_a_part_that_passes_its_drag_passes_the_press() { + let far = SLOP * 4.0; + let origin = pos2(0.0, 0.0); + for events in [&[up(far)][..], &[moved(far), up(far)][..]] { + // No shape takes the press: the next pass abandons it, and its release is no click. + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + let passed = passing_pass(&mut machine, events); + assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{events:?}: {passed:?}"); + assert!(matches!(passed.phase, Some(PressPhase::Held { .. })) && passed.activated.is_none(), "{events:?}: {passed:?}"); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase); + assert_eq!(end.activated, None, "{events:?}: a passed press no shape took is no click"); + + // The shape below takes it: it starts the drag where the button went up and ends it with no click. + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(passing_pass(&mut machine, events).passes.is_some(), "{events:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!( + matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(far, 0.0)), + "{events:?}: {:?}", + handed.phase + ); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase); + assert_eq!(end.activated, None, "{events:?}: a passed press is no click"); + } + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "a jump within slop is the shape's click"); + } + + /// A press whose button jumped far and came up in a batch that also pressed again: the release ends the press in + /// that pass, so the `DragStart` the jump owed never comes. The release is then no drag either, and the parts read + /// `Down` then a `Release` with no drag between them: a drag's end that never began would leave a part that tracks + /// a drag holding a press forever. The new press reports its `Down` in the next pass. + #[test] + fn a_jump_release_that_gives_way_to_a_new_press_reports_no_drag() { + let sense = Sense::CLICK | Sense::DRAG; + let far = SLOP * 4.0; + let jumped = [up(far), press(far, 1.1)]; + assert_eq!(phases(&[&[press(0.0, 1.0)], &jumped[..], &[]], sense), "D R D", "the release ends the press with no drag of its own"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + let end = pass(&mut machine, &jumped, sense); + assert!( + matches!(end.phase, Some(PressPhase::Release { start, pos, click: false }) if start.origin == pos2(0.0, 0.0) && pos == pos2(far, 0.0)), + "{:?}", + end.phase + ); + assert!(!end.dragging, "the press never reported its drag's start, so its release claims none"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + assert!(!machine.dragging(), "the new press is no drag either"); + pass(&mut machine, &[], sense); + let next = machine.open.map(|open| open.start.origin); + assert!(matches!(next, Some(place) if place == pos2(far, 0.0)), "the new press is open from where it went down"); + + // A press that did report its drag's start keeps its drag's end, whatever gives way to it. + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + assert!(matches!(pass(&mut machine, &[up(far)], sense).phase, Some(PressPhase::DragStart { .. })), "the jump starts the drag"); + let end = pass(&mut machine, &[up(far), press(far, 1.3)], sense); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert!(end.dragging, "the release ends the drag the part saw start"); + } + + /// A jump release past slop on a part that clicks and passes its drag reads the same when a new press shares its + /// batch: the release ends the press before the move ever passes the drag on, so it reports no drag, and the new + /// press opens from where it went down. + #[test] + fn a_passed_jump_release_that_gives_way_to_a_new_press_reports_no_drag() { + let far = SLOP * 4.0; + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + let end = passing_pass(&mut machine, &[up(far), press(far, 1.5)]); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(!end.dragging, "no shape was ever told the drag started, so its release claims none"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + assert_eq!(machine.target(), Some(1), "the new press is open"); + assert!(!machine.dragging(), "and it is no drag"); + } + + /// A jump release past slop on a target that only clicks abandons the click as a move past slop does: the release + /// is reported with no click and nothing activates. + #[test] + fn a_jump_release_past_slop_on_a_click_only_part_abandons_the_click() { + let (far, near) = (SLOP * 4.0, SLOP / 2.0); + let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)]], Sense::CLICK); + assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)]], Sense::CLICK), "a jump is a move and a release"); + assert_eq!(jumped, "D R", "the release is no click"); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], Sense::CLICK), "D R!", "a jump within slop still clicks"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], Sense::CLICK); + let end = pass(&mut machine, &[up(far)], Sense::CLICK); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(!end.dragging, "a click-only part never drags"); + assert_eq!(end.activated, None, "the abandoned click activates nothing"); + assert!(machine.target().is_none(), "the release ends the press"); + } } diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index c64efa2fbd..99281664b3 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -55,6 +55,11 @@ bitflags! { /// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`, /// without `DRAG`. const PASSES_DRAG = 131072; + /// The vertical wheel share, taken only while the component holds key focus or a press armed it, in any wheel + /// scope: a control whose wheel steps what focus picks rather than what the pointer is over (the focused thumb + /// of a range). Every other wheel bit the shape senses waits for focus with it. A control that senses no wheel + /// bit takes no wheel at all, so the wheel over it scrolls the region around it. + const WHEEL_Y_FOCUSED = 262144; } } @@ -63,7 +68,12 @@ impl Sense { pub const PRESS: Sense = Sense::CLICK.union(Sense::DRAG); /// The bits that make a shape register a wheel taker. - pub const WHEELS: Sense = Sense::WHEEL.union(Sense::WHEEL_X).union(Sense::WHEEL_Y).union(Sense::WHEEL_ZOOM).union(Sense::WHEEL_ZOOMS_VIEW); + pub const WHEELS: Sense = Sense::WHEEL + .union(Sense::WHEEL_X) + .union(Sense::WHEEL_Y) + .union(Sense::WHEEL_ZOOM) + .union(Sense::WHEEL_ZOOMS_VIEW) + .union(Sense::WHEEL_Y_FOCUSED); /// Whether a press can start on a shape with this sense. pub const fn takes_press(self) -> bool { diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 2e860a6d26..a5de8554a7 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -455,14 +455,17 @@ impl WheelTaker { /// The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll /// axes and zoom; `WHEEL_X`, `WHEEL_Y` and `WHEEL_ZOOM` take one share each and combine; `WHEEL_ZOOMS_VIEW` - /// makes a zoom zone. + /// makes a zoom zone; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes + /// waits for focus or arming. pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option { let all = sense.contains(Sense::WHEEL); + let focused = sense.contains(Sense::WHEEL_Y_FOCUSED); let taker = WheelTaker::new(owner, rect) .horizontal(all || sense.contains(Sense::WHEEL_X)) - .vertical(all || sense.contains(Sense::WHEEL_Y)) + .vertical(all || focused || sense.contains(Sense::WHEEL_Y)) .zoom(all || sense.contains(Sense::WHEEL_ZOOM)) - .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)); + .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)) + .gated(focused); (taker.horizontal || taker.vertical || taker.zoom || taker.zooms_view).then_some(taker) } diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b99ea2f612..457fb357d5 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -6,7 +6,7 @@ //! that says whose storage this is, a Save As page that picks a folder and //! names a file, and a save that refuses to overwrite somebody else's work. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A //! host writes that half. This module never learns what it reaches. That keeps @@ -21,6 +21,12 @@ //! list under a heading reads to a user as a broken window. A feature the //! provider does not have is therefore absent, heading and all. //! +//! Nothing here acts on a stale answer. Every answer carries the account +//! generation its job was issued in, and [`pump`] drops one whose generation +//! is no longer current, so a reply that arrives after a sign-out or a new +//! sign-in is not applied to the session that replaced its own. A new kind of +//! answer follows the same rule. +//! //! The application supplies [`CloudApp`]. That is what it alone can answer. //! What its documents are, how bytes become one and back, and the words it //! shows them in. diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index 9d03472e50..91c9673e38 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -5,12 +5,11 @@ //! look or change, add a note, decide whether an email goes out, and see who //! already has access so one of them can be taken away again. //! -//! Three things shape the implementation. +//! Four things shape the implementation. //! //! Nothing here opens a socket. Every call goes through [`ShareBackend`], and //! nothing here reaches the network. A host writes the backend, and this //! module never learns what it talks to. -//! this file. //! //! Nothing here blocks. Answers arrive on a channel and are read once per //! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it @@ -21,6 +20,17 @@ //! false until the service says sharing exists, and an app hides its Share //! control rather than offering a button that fails. Contacts and mail are //! reported separately and are hidden the same way. +//! +//! Nothing here acts on a stale answer. Every request carries a sequence +//! number, and its answer comes back with it. An answer is applied only while +//! the request it answers still stands: an answer to a query the +//! user has typed past, a link granted or an account linked for a sheet that +//! has since closed or moved to another document, and a capabilities answer +//! to a question asked before [`ShareDialog::refresh`], +//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A +//! withdrawal is the one answer applied by share id instead: the share is gone +//! on the service, so it leaves every list that still shows it. A new kind of +//! answer follows the sequence rule. use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; @@ -226,7 +236,9 @@ struct Sheet { /// Where it could be saved. `None` until the answer arrives. destinations: Option>, destinations_seq: Option, - link_seq: Option, + /// Account links in flight, by request. More than one can be: every + /// unlinked destination stays clickable while another one links. + linking: Vec, /// Which one is selected, by id. destination: Option, /// The name typed while the document still has nowhere to live. @@ -248,7 +260,7 @@ impl Sheet { Sheet { destinations: None, destinations_seq: None, - link_seq: None, + linking: Vec::new(), destination: None, save_as: title.clone(), saving: None, @@ -740,16 +752,16 @@ impl ShareDialog { } } Answer::Linked => { - // An account arrived, so the list is stale. With no sheet open - // there is no list to reload. - if self.open.is_some() { - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } - let seq = self.issue(Request::Destinations); - if let Some(sheet) = &mut self.open { - sheet.destinations_seq = Some(seq); - } + // Only for the sheet that asked: after the sheet closed, moved + // to another document or the account signed out, a late + // answer asks the service for nothing. + let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return }; + // An account arrived, so the list is stale. + sheet.linking.retain(|s| *s != seq); + sheet.destinations = None; + let seq = self.issue(Request::Destinations); + if let Some(sheet) = &mut self.open { + sheet.destinations_seq = Some(seq); } } Answer::Withdrawn { share_id } => { @@ -802,8 +814,8 @@ impl ShareDialog { sheet.destinations_seq = None; sheet.destinations = Some(Vec::new()); sheet.save_error = Some(reason); - } else if sheet.link_seq == Some(seq) { - sheet.link_seq = None; + } else if sheet.linking.contains(&seq) { + sheet.linking.retain(|s| *s != seq); sheet.save_error = Some(reason); } } @@ -845,7 +857,7 @@ impl ShareDialog { // application's business and not this crate's. let seq = self.issue(Request::Link { destination }); if let Some(sheet) = &mut self.open { - sheet.link_seq = Some(seq); + sheet.linking.push(seq); sheet.error = None; } } diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index 283ce0274b..188fcdb7fc 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() { assert!(copied(&ctx).is_empty(), "nor after the sheet closed"); } +fn destinations_asked(backend: &Silent) -> usize { + backend.seen().iter().filter(|r| **r == Request::Destinations).count() +} + +fn last_link(dialog: &ShareDialog) -> u64 { + dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked") +} + +#[test] +fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() { + let (ctx, mut dialog, _) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let first = last_link(&dialog); + // A second destination is clicked before the first one answers. + dialog.apply(&ctx, vec![Act::Link("mail".into())]); + let second = last_link(&dialog); + dialog.receive(&ctx, first, Ok(Answer::Linked)); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again"); + assert_eq!(sheet.linking, [second], "the later link is still in flight"); + dialog.receive(&ctx, second, Err("no account".into())); + let sheet = dialog.open.as_ref().expect("open"); + assert!(sheet.linking.is_empty()); + assert_eq!(sheet.save_error.as_deref(), Some("no account")); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.close(); + dialog.open("files/plan.docx", "Plan"); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan"); + + let (ctx, mut dialog, backend) = ready(); + dialog.apply(&ctx, vec![Act::Link("drive".into())]); + let linking = last_link(&dialog); + dialog.signed_out(); + let before = destinations_asked(&backend); + dialog.receive(&ctx, linking, Ok(Answer::Linked)); + assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out"); +} + /// Whether one frame of the sheet offers "Get a link" as a button that can /// be pressed, read off the accessibility tree. fn link_button_enabled(dialog: &mut ShareDialog) -> Option { diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 3aa4039ef3..fbaafba855 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -238,6 +238,7 @@ craft-shared-vec = { workspace = true, optional = true } craft-ease = { workspace = true, optional = true } craft-i18n-build = { workspace = true, optional = true } craft-pbr = { workspace = true, optional = true } +craft-raster3d = { workspace = true, optional = true } [features] ui = [ @@ -622,6 +623,7 @@ jxl-encode = ["jxl", "craft-jxl/encode"] keymap = ["dep:craft-keymap"] keymap-egui = ["keymap", "craft-keymap/egui"] +keymap-global = ["keymap", "craft-keymap/global"] kiwi = ["dep:craft-kiwi"] @@ -801,6 +803,8 @@ quit = ["dep:craft-quit"] raster-codecs = ["dep:craft-raster-codecs"] +raster3d = ["dep:craft-raster3d"] + raw = ["dep:craft-raw"] raw-arw = ["raw", "craft-raw/arw"] raw-cr2 = ["raw", "craft-raw/cr2"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index ed6ccb2f84..f3865fae1d 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -331,6 +331,8 @@ pub use craft_pst as pst; pub use craft_quit as quit; #[cfg(feature = "raster-codecs")] pub use craft_raster_codecs as raster_codecs; +#[cfg(feature = "raster3d")] +pub use craft_raster3d as raster3d; #[cfg(feature = "raw")] pub use craft_raw as raw; #[cfg(feature = "review")] diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index dcc2db8025..367e024e95 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -57,6 +57,8 @@ craft-fonts-build = { workspace = true } craft-font-manager = { path = ".", features = ["suite"] } # The shared preview test vectors. serde_json = { workspace = true } +# Test faces built for the script filter (a script no shipped test font covers). +write-fonts = "0.54" [[test]] name = "it" diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 45ab39f1d5..2d61945957 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -86,6 +86,15 @@ craft_ui::words! { script_east_asian: "fontPicker.scriptEastAsian" = "East Asian"; script_japanese: "fontPicker.scriptJapanese" = "Japanese"; script_thai: "fontPicker.scriptThai" = "Thai"; + script_devanagari: "fontPicker.scriptDevanagari" = "Devanagari"; + script_bengali: "fontPicker.scriptBengali" = "Bengali"; + script_gurmukhi: "fontPicker.scriptGurmukhi" = "Gurmukhi"; + script_gujarati: "fontPicker.scriptGujarati" = "Gujarati"; + script_odia: "fontPicker.scriptOdia" = "Odia"; + script_tamil: "fontPicker.scriptTamil" = "Tamil"; + script_telugu: "fontPicker.scriptTelugu" = "Telugu"; + script_kannada: "fontPicker.scriptKannada" = "Kannada"; + script_malayalam: "fontPicker.scriptMalayalam" = "Malayalam"; any_kind: "fontPicker.anyKind" = "Any Kind"; font_technology: "fontPicker.fontTechnology" = "Font Technology"; preview_size: "fontPicker.previewSize" = "Font Preview Size"; @@ -206,7 +215,7 @@ fn chosen_sample<'s, 'a>(texts: &'s [SampleText<'a>], settings: Option<&FontPick /// Coverage from the face: Latin, the basic Latin letters in the cmap; East Asian, the CJK Windows code pages /// (JIS, Simplified/Traditional Chinese, Wansung, Johab) or CJK ideographs/kana/Hangul when no code pages are declared; /// Japanese, the OS/2 kana or CJK unicode-range bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01 -/// and U+0E32 in the cmap. Read lazily like the class. +/// and U+0E32 in the cmap; an Indic script, its letter KA and vowel sign AA in the cmap. Read lazily like the class. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FontScript { @@ -218,11 +227,43 @@ pub enum FontScript { Japanese, /// Thai. Thai, + /// Devanagari. + Devanagari, + /// Bengali. + Bengali, + /// Gurmukhi. + Gurmukhi, + /// Gujarati. + Gujarati, + /// Odia. + Odia, + /// Tamil. + Tamil, + /// Telugu. + Telugu, + /// Kannada. + Kannada, + /// Malayalam. + Malayalam, } impl FontScript { /// Every script the script row can offer, in order. - pub const ALL: [FontScript; 4] = [FontScript::Latin, FontScript::EastAsian, FontScript::Japanese, FontScript::Thai]; + pub const ALL: [FontScript; 13] = [ + FontScript::Latin, + FontScript::EastAsian, + FontScript::Japanese, + FontScript::Thai, + FontScript::Devanagari, + FontScript::Bengali, + FontScript::Gurmukhi, + FontScript::Gujarati, + FontScript::Odia, + FontScript::Tamil, + FontScript::Telugu, + FontScript::Kannada, + FontScript::Malayalam, + ]; } /// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 5955c4c5e0..2c578ee7a8 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -200,9 +200,26 @@ const JAPANESE_RANGES: u32 = (1 << (49 - 32)) | (1 << (50 - 32)) | (1 << (59 - 3 /// Hangul Syllables (56) plus [`JAPANESE_RANGES`]. const EAST_ASIAN_RANGES: u32 = JAPANESE_RANGES | (1 << (56 - 32)); +/// The Indic scripts and the first code point of their Unicode block. Every block has its letter KA and vowel sign AA +/// at the same offsets. +const INDIC_BLOCKS: [(FontScript, u32); 9] = [ + (FontScript::Devanagari, 0x0900), + (FontScript::Bengali, 0x0980), + (FontScript::Gurmukhi, 0x0A00), + (FontScript::Gujarati, 0x0A80), + (FontScript::Odia, 0x0B00), + (FontScript::Tamil, 0x0B80), + (FontScript::Telugu, 0x0C00), + (FontScript::Kannada, 0x0C80), + (FontScript::Malayalam, 0x0D00), +]; +const INDIC_KA: u32 = 0x15; +const INDIC_AA: u32 = 0x3E; + /// The scripts a face covers: Latin, the basic Latin letters in its `cmap`; East Asian, its East Asian Windows code /// pages, CJK/kana/Hangul Unicode ranges, CJK ideographs in `cmap`, or a CJK localized name; Japanese, the JIS code -/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`. +/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`; +/// an Indic script, its letter KA and vowel sign AA in its `cmap` (no code page covers these scripts). fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option> { let data = catalog.load(face).ok()?; let font = FontRef::from_index(&data.bytes, face.index).ok()?; @@ -217,7 +234,11 @@ fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option> { let japanese = face.code_pages[0] & JIS_CODE_PAGE != 0 || ranges & JAPANESE_RANGES != 0 || japanese_name(face); let thai = ['\u{0E01}', '\u{0E32}'].into_iter().all(&mapped); let scripts = [(FontScript::Latin, latin), (FontScript::EastAsian, east_asian), (FontScript::Japanese, japanese), (FontScript::Thai, thai)]; - Some(scripts.into_iter().filter_map(|(script, covered)| covered.then_some(script)).collect()) + let indic = INDIC_BLOCKS.into_iter().map(|(script, block)| { + let at = |offset: u32| char::from_u32(block + offset).is_some_and(&mapped); + (script, at(INDIC_KA) && at(INDIC_AA)) + }); + Some(scripts.into_iter().chain(indic).filter_map(|(script, covered)| covered.then_some(script)).collect()) } /// The class of a family from its regular face, `None` when the catalog lacks it. diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 3c54d291f4..b58599e1a2 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -350,6 +350,15 @@ fn script_label(script: FontScript, words: &FontPickerWords) -> Label { FontScript::EastAsian => words.script_east_asian.clone(), FontScript::Japanese => words.script_japanese.clone(), FontScript::Thai => words.script_thai.clone(), + FontScript::Devanagari => words.script_devanagari.clone(), + FontScript::Bengali => words.script_bengali.clone(), + FontScript::Gurmukhi => words.script_gurmukhi.clone(), + FontScript::Gujarati => words.script_gujarati.clone(), + FontScript::Odia => words.script_odia.clone(), + FontScript::Tamil => words.script_tamil.clone(), + FontScript::Telugu => words.script_telugu.clone(), + FontScript::Kannada => words.script_kannada.clone(), + FontScript::Malayalam => words.script_malayalam.clone(), } } diff --git a/crates/font-manager/src/picker/stories.rs b/crates/font-manager/src/picker/stories.rs index a7ed553a42..b29c67e378 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -232,7 +232,7 @@ fn font_picker_filter_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { FamilySet::new("document", "Document", &document), FamilySet::new("added", "Recently Added", &added).ordered().enabled(false).hint("No fonts were added recently"), ]; - let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai]; + let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai, FontScript::Devanagari, FontScript::Gujarati]; let filters = FontFilters { sets: vec!["document".to_owned()], ..FontFilters::default() }; let extras = Extras { sets: &sets, scripts: &scripts, layout: FilterLayout::Chips, ..Extras::default() }; show_with(ui, data, demo("Hack", FontPickerSettings::default(), filters), &catalog(), &extras) diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 9f830a4b4a..31e7c20ab6 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -385,6 +385,54 @@ fn a_thai_and_a_cjk_face_each_pass_their_own_scripts_filter() { assert!(!thai.iter().chain(&japanese).any(|family| family.contains("Inter")), "Inter covers neither"); } +/// A face named `family` whose `cmap` maps the basic Latin letters and `extra`: only the tables the catalog and the +/// coverage read, with an empty `glyf` so it counts as drawable. +fn face_mapping(family: &str, extra: &[char]) -> Vec { + use write_fonts::FontBuilder; + use write_fonts::tables::cmap::Cmap; + use write_fonts::tables::maxp::Maxp; + use write_fonts::tables::name::{Name, NameRecord}; + use write_fonts::tables::os2::Os2; + use write_fonts::types::{GlyphId, NameId, Tag}; + + let chars: Vec = ('A'..='Z').chain('a'..='z').chain(extra.iter().copied()).collect(); + let cmap = Cmap::from_mappings(chars.iter().zip(1u32..).map(|(&c, g)| (c, GlyphId::new(g)))).expect("a cmap"); + let mut records = vec![ + NameRecord::new(3, 1, 0x409, NameId::new(1), family.to_owned().into()), + NameRecord::new(3, 1, 0x409, NameId::new(2), "Regular".to_owned().into()), + NameRecord::new(3, 1, 0x409, NameId::new(4), format!("{family} Regular").into()), + NameRecord::new(3, 1, 0x409, NameId::new(6), format!("{}-Regular", family.replace(' ', "")).into()), + ]; + records.sort_by_key(|r| r.name_id); + let mut builder = FontBuilder::new(); + builder.add_table(&Name::new(records)).expect("name"); + builder.add_table(&Os2 { us_weight_class: 400, us_width_class: 5, ..Default::default() }).expect("OS/2"); + builder.add_table(&cmap).expect("cmap"); + builder.add_table(&Maxp::new(u16::try_from(chars.len() + 1).expect("few glyphs"))).expect("maxp"); + builder.add_raw(Tag::new(b"glyf"), vec![0u8; 4]); + builder.build() +} + +/// An Indic script is read from the face's `cmap` (KA and vowel sign AA); no code page marks it. A face with +/// Devanagari passes the Devanagari filter, not the Gujarati one, and Latin-only and Thai faces pass neither. +#[trial] +fn an_indic_face_passes_its_own_scripts_filter() { + const THAI: &[u8] = include_bytes!("../../../font-subset/tests/data/sarabun/Sarabun-Regular.ttf"); + let deva = face_mapping("Test Devanagari", &['\u{0915}', '\u{093E}']); + // A lone KA, as a symbol font might carry, is not coverage. + let ka_only = face_mapping("Test Lone Ka", &['\u{0A95}']); + let catalog = catalog_of(&[INTER_REGULAR, THAI, &deva, &ka_only]); + let with = |script: FontScript| { + let mut filters = FontFilters::default(); + filters.script = Some(script); + listed(&catalog, &filters, &[]) + }; + let devanagari = with(FontScript::Devanagari); + assert!(devanagari.iter().any(|family| family.contains("Test Devanagari")), "Devanagari: {devanagari:?}"); + assert!(!devanagari.iter().any(|family| family.contains("Inter") || family.contains("Sarabun")), "Devanagari: {devanagari:?}"); + assert!(with(FontScript::Gujarati).is_empty(), "nothing covers Gujarati: {:?}", with(FontScript::Gujarati)); +} + #[trial] fn a_host_set_keeps_only_its_families_and_an_ordered_one_lists_them_in_its_order() { let catalog = three_faces(); diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index 4d72f41aad..f987b9ca9e 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -106,7 +106,10 @@ index, bytes, role }` literals; any struct with those fields and that name in sc `None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature` face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`, -`has_script(tag)`, `is_cjk()` and `weight()`. +`has_script(tag)`, `is_cjk()` and `weight()`. Tests and tables written by hand build a face with +`EmbeddedFace::new(family, style, scripts, bytes)`, which sets no `role`, plus `.with_index(n)` +for a face in a collection; both are `const fn`. Code that uses `new` keeps compiling when a +field with a default is added; a struct literal does not. ## Document fonts diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index e2d7ed3868..b453ac8b97 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -87,6 +87,26 @@ pub struct EmbeddedFace { } impl EmbeddedFace { + /// A face at index 0 of `bytes` with no `role`, for tests and for tables written by hand. Code + /// that builds faces with `new` keeps compiling when a field with a default is added; a struct + /// literal does not. + /// + /// ``` + /// use craft_fonts_build::EmbeddedFace; + /// + /// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2); + /// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2)); + /// ``` + pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self { + Self { family, style, scripts, index: 0, bytes, role: None } + } + + /// The same face at `index` in a font collection (`.ttc`). + #[must_use] + pub const fn with_index(self, index: u32) -> Self { + Self { index, ..self } + } + /// `"