diff --git a/AGENTS.md b/AGENTS.md index ac0f5b17..061934eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,9 @@ a new crate needs a row here and in its `LAYERS` table. ## Licensing and legal compliance (read `docs/legal/compliance.md`) * AniCraft is **MIT OR Apache-2.0**, like PhotoCraft (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). -* **Dependencies**: permissive only, from crates.io only. `deny.toml` is the policy, and +* **Dependencies**: permissive only, from crates.io or the explicitly allowlisted + `storytold/craft-libs` Git source, pinned to a reviewed `rev` in `Cargo.toml`. + `deny.toml` is the policy; unknown registries and Git sources remain denied, and `cargo deny check licenses bans sources` must pass. Adding a crate with a new licence needs a deliberate `deny.toml` change and a note in `compliance.md`. No copyleft, "non-commercial" or source-available terms. @@ -143,3 +145,13 @@ cargo run -- --screenshot shots/now.png ``` Update `docs/roadmap.md` › Honest status when you move a capability. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. + +ADR 0040 Decision 2 remains a deliberate, scoped exception for the existing app-local +craft-i18n catalog parser until a separately reviewed parity-preserving cutover updates +that ADR and its implementation together. Its historical crates.io-only rationale does +not override the reviewed/pinned craft-libs source exception above. This guidance alone +does not migrate that parser or supersede its runtime behavior. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 71ed329e..ed03b130 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -87,6 +87,7 @@ OR Apache-2.0) is noted in the table. | Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). | | Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), , Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. | | Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. | +| Superscript and subscript size and offset; underline position and thickness | `crates/text/src/rich.rs` | Microsoft and Adobe, *OpenType specification*, `OS/2` table (`ySuperscriptYSize`, `ySuperscriptYOffset`, `ySubscriptYSize`, `ySubscriptYOffset`) and `post` table (`underlinePosition`, `underlineThickness`), | Metrics read from the font as the specification describes them; no code copied. | | Desktop integration of an AppImage: desktop entry `Exec` quoting and string escapes, MIME packages, hicolor icons, the user's data folder | `crates/engine/src/cmds_desktop.rs`, `src/platform.rs` | freedesktop.org *Desktop Entry Specification* 1.5, *Shared MIME-info Database*, *Icon Theme Specification*, *XDG Base Directory Specification*, ; AppImage documentation on `$APPIMAGE` (public docs) | Written from the specifications (ADR 0094); no code copied. | | Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. | | Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). | diff --git a/CHANGELOG.md b/CHANGELOG.md index 1593be99..40f10554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,37 @@ * Files: a document with a mixed armature is saved as format version 4, which earlier versions refuse with a clear message. Every other document is saved exactly as before. * Fixed: duplicating a symbol that holds a shape armature kept the copy's shape from bending. +* **Styled text: per-character and paragraph styles** (ADR 0085, M5). + * Select characters while typing on the stage and set their **font, size, colour, bold, + italic, letter spacing, superscript or subscript, underline and link** in Properties; the + section shows what the selection shares and marks the rest **mixed**. + * **Paragraph styles**: alignment, first-line indent, left and right margins and line spacing + per paragraph. + * Typing continues the style before the caret; copy and paste inside AniCraft keeps styles, + text from other apps pastes plain. + * Each run is shaped on its own and lines wrap across runs; outlines are stored as before, so + older files open and save unchanged. Every export draws each colour; SVG writes links. + Break Apart gives one shape per colour. + * **Animate files** keep their `DOMTextRun` styles in one block per field (they were split into + a block per style before), with superscripts, indents, margins and links. + * Headless: `text.style`, `text.paragraph`, `text.styles`; `text.create` and `text.edit` take + `runs` and `paragraphs`. +* **Floating windows open below the menu bar**: no dialog (the Custom Ease window among them) can + cover File, Edit and View any more. +* **Security: safer reads and temp files.** Import to Library checks an image's size (256 MiB) before reading it, and saves, audio exports and the video soundtrack write their temporary files under unguessable names, created exclusively. +* **Saved commands (command macros)** (ADR 0097, M6). + * In the **History** panel, **Ctrl+click** steps (Shift+click a range) and choose **Save As + Command…**: the steps come back at the end of the **Commands** menu, to run on whatever is + selected as **one undo step**. Steps that name a layer or object of this document act on the + active layer or the selection instead; a step that can't be kept (the clipboard, particular + path points or Library items) is named with the reason. + * A run that fails at a step changes nothing and says which step stopped it. + * **Commands › Manage Saved Commands…**: run, reorder, rename, delete, give a **shortcut** (the + Keyboard Shortcuts editor, under Commands) and add one from a file. **Commands › Run + Command…** runs a saved command file. + * Saved commands are small JSON files in the settings folder's `Commands`, easy to share. They + may do only what a plug-in may (no files, clipboard or preferences), and plug-ins can't run + them. `anicraft-cli run` takes them; `macro.*` commands work headless and over MCP. * **Search the user guide, and help for what you are working on** (ADR 0096, M8). * **Search** in every page of the bundled guide, offline: results as you type with the chapter, heading and a passage with your words marked; `/` goes to the field, arrows move diff --git a/Cargo.lock b/Cargo.lock index 8fccc897..3bb1dfc7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,6 +297,7 @@ dependencies = [ "anicraft-geom", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "craft-mime", + "craft-palette", "serde", "serde_json", ] @@ -381,6 +382,7 @@ dependencies = [ "boa_engine", "craft-html", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-lottie", "rayon", "serde_json", "thiserror 2.0.21", @@ -416,8 +418,10 @@ dependencies = [ "anicraft-text", "anicraft-xml", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-video", "craft-xfl", "miniz_oxide 0.8.9", + "serde_json", "thiserror 2.0.21", ] @@ -426,7 +430,7 @@ name = "anicraft-xml" version = "0.3.0" dependencies = [ "craft-xfl", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11)", "thiserror 2.0.21", ] @@ -1218,9 +1222,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=e2bf53f2bdba4828e21097774a568ed9c74b0004#e2bf53f2bdba4828e21097774a568ed9c74b0004" dependencies = [ - "craft-media", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2bf53f2bdba4828e21097774a568ed9c74b0004)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2bf53f2bdba4828e21097774a568ed9c74b0004)", "log", "symphonia", "thiserror 2.0.21", @@ -1308,14 +1313,29 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-lottie" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=83cb1133dd2bdd0d655ba2300f88863f0f53db0b#83cb1133dd2bdd0d655ba2300f88863f0f53db0b" +dependencies = [ + "craft-zip", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=e2bf53f2bdba4828e21097774a568ed9c74b0004#e2bf53f2bdba4828e21097774a568ed9c74b0004" dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd91be74f078d7062945ff6512cf65afea0c73ac#fd91be74f078d7062945ff6512cf65afea0c73ac" + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1350,6 +1370,11 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-palette" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=de97c35f2b2af01c62371647e57a6affeab456fd#de97c35f2b2af01c62371647e57a6affeab456fd" + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1393,6 +1418,16 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-video" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd91be74f078d7062945ff6512cf65afea0c73ac#fd91be74f078d7062945ff6512cf65afea0c73ac" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fd91be74f078d7062945ff6512cf65afea0c73ac)", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-webp" version = "0.1.0" @@ -1406,7 +1441,7 @@ name = "craft-xfl" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11#b67b9f90c50091a3090f93fa054c34e409edba11" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11)", "miniz_oxide 0.8.9", "thiserror 2.0.21", ] @@ -1421,6 +1456,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2bf53f2bdba4828e21097774a568ed9c74b0004#e2bf53f2bdba4828e21097774a568ed9c74b0004" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=83cb1133dd2bdd0d655ba2300f88863f0f53db0b#83cb1133dd2bdd0d655ba2300f88863f0f53db0b" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.3" diff --git a/Cargo.toml b/Cargo.toml index 2446dee1..52f50612 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,9 @@ repository = "https://github.com/storytold/AniCraft" rust-version = "1.95" [workspace.dependencies] +craft-video = { git = "https://github.com/storytold/craft-libs", rev = "fd91be74f078d7062945ff6512cf65afea0c73ac", default-features = false, features = ["screen-video"] } +craft-palette = { git = "https://github.com/storytold/craft-libs", rev = "de97c35f2b2af01c62371647e57a6affeab456fd" } +craft-lottie = { git = "https://github.com/storytold/craft-libs", rev = "83cb1133dd2bdd0d655ba2300f88863f0f53db0b" } anicraft-geom = { path = "crates/geom" } anicraft-doc = { path = "crates/doc" } anicraft-render = { path = "crates/render" } @@ -30,7 +33,7 @@ anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-html = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false } -craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } +craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "e2bf53f2bdba4828e21097774a568ed9c74b0004", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } # Isolate the already-merged APNG container from the existing raster-codec pin. craft-apng-container = { package = "craft-image-codecs", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "55b1d7f3c598b600a130ae63f4a40334a230ae7b", default-features = false } diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index 203fc9ab..3cf47788 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -1,65 +1,6 @@ //! WAV (RIFF WAVE) writing via `craft-audio`. -/// Sample formats written. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Bits { - Int16, - Int24, - Float32, -} - -impl Bits { - fn bytes(self) -> u16 { - match self { - Bits::Int16 => 2, - Bits::Int24 => 3, - Bits::Float32 => 4, - } - } -} - -const PCM: u16 = 1; -const FLOAT: u16 = 3; - -/// A WAV header for `frames` frames of `channels` channels. -pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option> { - let b = bits.bytes(); - let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?; - let riff = data.checked_add(36)?; - let block = channels.checked_mul(b)?; - let tag = if bits == Bits::Float32 { FLOAT } else { PCM }; - let mut h = Vec::with_capacity(44); - h.extend_from_slice(b"RIFF"); - h.extend_from_slice(&riff.to_le_bytes()); - h.extend_from_slice(b"WAVEfmt "); - h.extend_from_slice(&16u32.to_le_bytes()); - h.extend_from_slice(&tag.to_le_bytes()); - h.extend_from_slice(&channels.to_le_bytes()); - h.extend_from_slice(&rate.to_le_bytes()); - h.extend_from_slice(&(rate.saturating_mul(u32::from(block))).to_le_bytes()); - h.extend_from_slice(&block.to_le_bytes()); - h.extend_from_slice(&(b * 8).to_le_bytes()); - h.extend_from_slice(b"data"); - h.extend_from_slice(&data.to_le_bytes()); - Some(h) -} - -/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768` -/// for 16-bit, so 16-bit sources read by [`decode`] come back bit-identical. -pub fn append(out: &mut Vec, samples: &[f32], bits: Bits) { - out.reserve(samples.len() * usize::from(bits.bytes())); - for &s in samples { - let s = if s.is_finite() { s } else { 0.0 }; - match bits { - Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()), - Bits::Int24 => { - let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32; - out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0])); - } - Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()), - } - } -} +pub use craft_audio::wav_stream::{Bits, append, header}; /// A whole WAV file in memory (empty when it would not fit a WAV's 4 GB limit). pub fn encode(rate: u32, channels: u16, samples: &[f32], bits: Bits) -> Vec { @@ -79,8 +20,23 @@ mod tests { use super::*; use crate::{AudioError, decode}; + const PCM: u16 = 1; const EXTENSIBLE: u16 = 0xFFFE; + #[test] + fn streaming_blocks_round_trip_all_formats() { + let samples = [0.25, -0.5, 0.0, 0.75, -1.0, 0.5]; + for bits in [Bits::Int16, Bits::Int24, Bits::Float32] { + let mut bytes = header(48_000, 2, bits, 3).unwrap(); + for block in samples.chunks(2) { + append(&mut bytes, block, bits); + } + let decoded = decode(&bytes).unwrap(); + assert_eq!((decoded.rate, decoded.channels, decoded.frames()), (48_000, 2, 3)); + assert_eq!(decoded.samples, samples); + } + } + #[test] fn sixteen_bit_round_trips_bit_exactly() { let src: Vec = vec![0, 1, -1, 32_767, -32_768, 12_345, -54, 7]; diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index b5965591..f0bd8dff 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -30,6 +30,8 @@ USAGE: anicraft-cli formats lists every export format, plug-ins included (JSON) anicraft-cli commands anicraft-cli run [--save ] + a JSON array of {cmd, params}, or a saved command + (one undo step; nothing changes if a step fails) anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] anicraft-cli guide --out writes the user guide as HTML pages (open index.html) @@ -260,7 +262,16 @@ pub fn run(argv: &[String]) -> Result { let script = a.positional.get(1).ok_or("run needs a script.json")?; let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?; // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. - let steps: Vec = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; + let parsed: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}} or a saved command: {e}"))?; + // A saved command (ADR 0097) runs as one transactional step, as in the app. + if parsed.is_object() { + let v = exec(&mut s, "macro.run", &json!({"path": script}))?; + if let Some(out) = a.flag("save") { + exec(&mut s, "file.save", &json!({"path": out}))?; + } + return serde_json::to_string_pretty(&v).map_err(|e| e.to_string()); + } + let steps: Vec = serde_json::from_value(parsed).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; let mut results = Vec::new(); for (i, step) in steps.iter().enumerate() { let id = step.get("cmd").and_then(Value::as_str).ok_or_else(|| format!("step {}: missing \"cmd\"", i + 1))?; @@ -720,6 +731,23 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn run_takes_a_saved_command_file() { + let dir = std::env::temp_dir().join(format!("anicraft-cli-macro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Spin.json"); + std::fs::write(&file, r#"{"format": "anicraft-command", "version": 1, "steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}]}"#).unwrap(); + let out = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap(); + let v: Value = serde_json::from_str(&out).unwrap(); + assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{out}"); + // A failing step names itself and leaves nothing behind. + std::fs::write(&file, r#"{"steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap(); + let e = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap_err(); + assert!(e.contains("stopped at step 3 of 3"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn usage_and_errors() { assert!(run(&[]).unwrap().contains("USAGE")); diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 1f75a22f..0d5985bc 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-palette.workspace = true craft-mime.workspace = true anicraft-geom.workspace = true serde = { workspace = true, features = ["rc"] } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 489372f4..053b0210 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -65,6 +65,9 @@ pub struct DisplayList { /// through each other. A group's items are one unbroken run of `items`, nested runs for /// nested groups; a parent always has a lower index. pub groups: Vec, + /// Links on text (ADR 0085): `(item, url)` for each item drawing characters that link + /// somewhere, in item order. Sparse: most lists have none. + pub links: Vec<(u32, Arc)>, } /// A group that fades as one (see [`DisplayList::groups`]). @@ -138,6 +141,8 @@ impl DisplayList { self.set_clip_mode(base + i as u32, m); } self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) })); + let ibase = self.items.len() as u32; + self.links.extend(other.links.into_iter().map(|(i, u)| (i + ibase, u))); self.items.extend(other.items.into_iter().map(|mut i| { i.clip = shift(i.clip); i.masks = shift(i.masks); @@ -665,10 +670,11 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice()))); field_items(t, f, live, xf, clip, out, item); } - _ => { - let path = child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()).map_or_else(|| t.outline.clone(), |l| l.outline.clone()); - out.items.push(item(path, xf, Some(Paint::Solid(t.color)), None, clip, masks)); - } + _ => match child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()) { + Some(l) => out.items.push(item(l.outline.clone(), xf, Some(Paint::Solid(t.color)), None, clip, masks)), + // One item per colour (ADR 0085), with its link. + None => text_fills(t, out, |path, color| item(path, xf, Some(Paint::Solid(color)), None, clip, masks)), + }, } } ElementKind::Camera => {} @@ -731,6 +737,17 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: } } +/// A text block's authored outline as items, one per colour piece (ADR 0085), recording the +/// links of pieces that have one. +fn text_fills(t: &crate::TextBlock, out: &mut DisplayList, item: impl Fn(Arc, Rgba) -> DisplayItem) { + for (color, url, path) in t.fill_paths() { + if !url.is_empty() { + out.links.push((out.items.len() as u32, Arc::from(url))); + } + out.items.push(item(path, color)); + } +} + /// The highlight behind selected text in a focused field. pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0); @@ -769,13 +786,10 @@ fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option< } // The text: laid out by the player when it changed, else the authored outline (a field whose // text changed but couldn't be laid out shows none). - let outline = match (state.and_then(|s| s.text.as_ref()), look) { - (_, Some(l)) => Some(l.outline.clone()), - (None, None) => Some(t.outline.clone()), - (Some(_), None) => None, - }; - if let Some(path) = outline { - out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)); + match (state.and_then(|s| s.text.as_ref()), look) { + (_, Some(l)) => out.items.push(item(l.outline.clone(), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)), + (None, None) => text_fills(t, out, |path, color| item(path, text_xf, Some(Paint::Solid(color)), None, Some(inner), None)), + (Some(_), None) => {} } // The caret, in an input field with the keyboard and nothing selected. if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind) diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs index a1d8e5c4..7279e72c 100644 --- a/crates/doc/src/field_tests.rs +++ b/crates/doc/src/field_tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::{Rgba, TextAlign}; fn block(text: &str, f: TextField) -> TextBlock { - TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None } + TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None, ..Default::default() } } /// Runs edits on a field as the player does: each change of text lays it out again (10 px per diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6bd870f8..edbfe458 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -29,6 +29,7 @@ pub mod width; pub mod stroke_style; pub mod player; pub mod publish; +pub mod rich_text; pub mod sample; pub mod templates; pub mod sound; @@ -48,6 +49,7 @@ pub use camera::{Camera, DepthKey}; pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint}; pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES}; pub use nine_slice::symbol_box; +pub use rich_text::{BaselineShift, CharStyle, MAX_TEXT_RUNS, MAX_URL, ParagraphStyle, StyleSummary, TextFill, TextRun, safe_url}; pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_shown, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; @@ -777,6 +779,68 @@ pub struct TextBlock { /// `outline` holds the glyphs set along it. Static text only. #[serde(default, skip_serializing_if = "Option::is_none")] pub on_path: Option, + /// The first run's baseline shift, underline and link (ADR 0085). + #[serde(default, skip_serializing_if = "rich_text_is_normal")] + pub shift: BaselineShift, + #[serde(default, skip_serializing_if = "is_false")] + pub underline: bool, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + /// The first paragraph's indent and margins (ADR 0085). + #[serde(default, skip_serializing_if = "is_zero")] + pub indent: f32, + #[serde(default, skip_serializing_if = "is_zero")] + pub left_margin: f32, + #[serde(default, skip_serializing_if = "is_zero")] + pub right_margin: f32, + /// Styled runs covering the text, when its characters differ in style (ADR 0085; empty: + /// all in the style above). Set with [`TextBlock::set_styles`]. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub runs: Vec, + /// One style per paragraph, when they differ (empty: all as above). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paragraphs: Vec, + /// The outline cut into pieces by colour and link, in order (empty: all in `color`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fills: Vec, + #[serde(skip)] + pub fill_cache: rich_text::FillCache, +} + +fn rich_text_is_normal(s: &BaselineShift) -> bool { + *s == BaselineShift::Normal +} + +impl Default for TextBlock { + fn default() -> Self { + TextBlock { + text: String::new(), + font: String::new(), + size: 32.0, + bold: false, + italic: false, + color: Rgba::BLACK, + align: TextAlign::Left, + letter_spacing: 0.0, + line_spacing: 0.0, + width: None, + outline: Arc::new(Path::new()), + box_width: 0.0, + box_height: 0.0, + field: None, + on_path: None, + shift: BaselineShift::Normal, + underline: false, + url: String::new(), + indent: 0.0, + left_margin: 0.0, + right_margin: 0.0, + runs: Vec::new(), + paragraphs: Vec::new(), + fills: Vec::new(), + fill_cache: rich_text::FillCache::default(), + } + } } /// The path a text block follows (ADR 0070), and where along it the text sits. diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index 00f04fc9..8868bc3a 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -504,6 +504,7 @@ pub fn hit_frame(len: u32) -> u32 { pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList { let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None); dl.items.retain(|i| !i.guide && i.masks.is_none()); + dl.links.clear(); for i in &mut dl.items { i.clip = None; } diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 2114efba..170f4839 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -722,7 +722,7 @@ impl ScriptHost for Mono { } fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc { - let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None }; + let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None, ..Default::default() }; Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }) } diff --git a/crates/doc/src/rich_text.rs b/crates/doc/src/rich_text.rs new file mode 100644 index 00000000..2d638c11 --- /dev/null +++ b/crates/doc/src/rich_text.rs @@ -0,0 +1,522 @@ +//! Styled text (ADR 0085): runs of characters with their own style, paragraphs with their own +//! layout, and the outline cut into one filled piece per colour and link. +//! +//! A [`TextBlock`] with no runs is one run in the block's own style, and with no paragraph +//! styles every paragraph has the block's alignment and line spacing: files from before styled +//! text open unchanged and save byte for byte the same. When a block has runs, its own style +//! fields mirror the first run (and its alignment and line spacing the first paragraph), so code +//! that reads "the block's style" sees the style the text starts with. +//! +//! The run edits here are pure functions on run lists, so typing, deleting, pasting and styling +//! a range split and merge runs the same way in the engine, the shell and the tests. + +use crate::{Rgba, TextAlign, TextBlock}; +use anicraft_geom::Path; +use serde::{Deserialize, Serialize}; +use std::sync::{Arc, OnceLock}; + +/// Most runs one block keeps; past it, the rest of the text takes the last run's style. +pub const MAX_TEXT_RUNS: usize = 10_000; + +/// Longest link a run keeps (characters). +pub const MAX_URL: usize = 2048; + +/// Where characters sit against the line's baseline. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BaselineShift { + #[default] + Normal, + /// Smaller and raised (the font's superscript size and offset). + Superscript, + /// Smaller and lowered (the font's subscript size and offset). + Subscript, +} + +impl BaselineShift { + pub const ALL: [BaselineShift; 3] = [BaselineShift::Normal, BaselineShift::Superscript, BaselineShift::Subscript]; + pub fn key(self) -> &'static str { + match self { + BaselineShift::Normal => "normal", + BaselineShift::Superscript => "superscript", + BaselineShift::Subscript => "subscript", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase(); + BaselineShift::ALL.into_iter().find(|k| k.key() == s) + } +} + +/// A link a run may keep: trimmed and cut to [`MAX_URL`]; `None` for schemes that run code +/// where the link is followed (`javascript:`, `vbscript:`, `data:`), which exports must never +/// write. +pub fn safe_url(url: &str) -> Option { + let url: String = url.trim().chars().filter(|c| !c.is_control()).take(MAX_URL).collect(); + let scheme: String = url.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c != ':').collect::().to_ascii_lowercase(); + let has_scheme = url.contains(':') && !scheme.contains(['/', '?', '#']); + (!(has_scheme && ["javascript", "vbscript", "data"].contains(&scheme.as_str()))).then_some(url) +} + +fn is_false(b: &bool) -> bool { + !*b +} +fn is_zero(v: &f32) -> bool { + *v == 0.0 +} +fn is_normal(s: &BaselineShift) -> bool { + *s == BaselineShift::Normal +} + +/// One character style: what a run of characters is drawn in. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CharStyle { + /// Font family the outlines were laid out with. + pub font: String, + /// Font size in pixels. + pub size: f32, + #[serde(default, skip_serializing_if = "is_false")] + pub bold: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub italic: bool, + pub color: Rgba, + /// Extra space after each character, in pixels. + #[serde(default, skip_serializing_if = "is_zero")] + pub letter_spacing: f32, + #[serde(default, skip_serializing_if = "is_normal")] + pub shift: BaselineShift, + #[serde(default, skip_serializing_if = "is_false")] + pub underline: bool, + /// A link the characters go to (empty: none). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, +} + +impl Default for CharStyle { + fn default() -> Self { + CharStyle { font: String::new(), size: 32.0, bold: false, italic: false, color: Rgba::BLACK, letter_spacing: 0.0, shift: BaselineShift::Normal, underline: false, url: String::new() } + } +} + +impl CharStyle { + /// The style clamped to what layout accepts (sizes 1 to 2000 px, spacing within ±1000 px, + /// names and links cut to length). + pub fn sanitized(&self) -> CharStyle { + let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; + CharStyle { + font: self.font.chars().take(256).collect(), + size: fin(self.size, 32.0).clamp(1.0, 2000.0), + letter_spacing: fin(self.letter_spacing, 0.0).clamp(-1000.0, 1000.0), + color: Rgba::new(fin(self.color.r, 0.0).clamp(0.0, 1.0), fin(self.color.g, 0.0).clamp(0.0, 1.0), fin(self.color.b, 0.0).clamp(0.0, 1.0), fin(self.color.a, 1.0).clamp(0.0, 1.0)), + url: safe_url(&self.url).unwrap_or_default(), + ..self.clone() + } + } +} + +/// A run: this many characters (`char`s, line breaks included) in one style. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextRun { + pub chars: u32, + #[serde(flatten)] + pub style: CharStyle, +} + +/// One paragraph's layout (a paragraph is a line of the text, up to a line break). +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ParagraphStyle { + #[serde(default)] + pub align: TextAlign, + /// The first line starts this much further in (pixels; negative hangs it out). + #[serde(default, skip_serializing_if = "is_zero")] + pub indent: f32, + /// Space kept clear at the box's left and right (pixels). + #[serde(default, skip_serializing_if = "is_zero")] + pub left_margin: f32, + #[serde(default, skip_serializing_if = "is_zero")] + pub right_margin: f32, + /// Extra space below each of its lines (pixels). + #[serde(default, skip_serializing_if = "is_zero")] + pub line_spacing: f32, +} + +impl ParagraphStyle { + /// Clamped to what layout accepts (indent within ±10000 px, margins 0 to 10000 px, line + /// spacing within ±1000 px). + pub fn sanitized(&self) -> ParagraphStyle { + let fin = |v: f32| if v.is_finite() { v } else { 0.0 }; + ParagraphStyle { + align: self.align, + indent: fin(self.indent).clamp(-10_000.0, 10_000.0), + left_margin: fin(self.left_margin).clamp(0.0, 10_000.0), + right_margin: fin(self.right_margin).clamp(0.0, 10_000.0), + line_spacing: fin(self.line_spacing).clamp(-1000.0, 1000.0), + } + } +} + +/// One filled piece of a block's outline: the next `cmds` path commands, in one colour, with a +/// link if its characters have one. A block's fills cut its outline in order. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextFill { + pub color: Rgba, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + pub cmds: u32, +} + +/// The fills' outlines, cut once from the block's outline the first time they are drawn (never +/// saved, and empty again in a copy). +#[derive(Default)] +pub struct FillCache(OnceLock<(usize, Vec, Vec>)>); + +impl Clone for FillCache { + fn clone(&self) -> Self { + FillCache::default() + } +} +impl PartialEq for FillCache { + fn eq(&self, _: &Self) -> bool { + true + } +} +impl std::fmt::Debug for FillCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("FillCache") + } +} + +impl TextBlock { + /// The style the block's own fields hold (its first run's). + pub fn char_style(&self) -> CharStyle { + CharStyle { + font: self.font.clone(), + size: self.size, + bold: self.bold, + italic: self.italic, + color: self.color, + letter_spacing: self.letter_spacing, + shift: self.shift, + underline: self.underline, + url: self.url.clone(), + } + } + + /// The paragraph style the block's own fields hold (its first paragraph's). + pub fn para_style(&self) -> ParagraphStyle { + ParagraphStyle { align: self.align, indent: self.indent, left_margin: self.left_margin, right_margin: self.right_margin, line_spacing: self.line_spacing } + } + + /// Its characters. + pub fn char_count(&self) -> u32 { + self.text.chars().count() as u32 + } + + /// Its runs, covering every character (one run in the block's style when it has none). + pub fn styled_runs(&self) -> Vec { + let n = self.char_count(); + if self.runs.is_empty() { + return vec![TextRun { chars: n, style: self.char_style() }]; + } + fit_runs(self.runs.clone(), n) + } + + /// One style per paragraph (the block's when it has none; a missing one takes the last). + pub fn paragraph_styles(&self) -> Vec { + let n = paragraph_count(&self.text); + let own = self.para_style(); + (0..n).map(|i| self.paragraphs.get(i).or(self.paragraphs.last()).copied().unwrap_or(own)).collect() + } + + /// Whether characters differ in style (more than one run). + pub fn has_runs(&self) -> bool { + self.runs.len() > 1 + } + + /// Sets the runs and paragraph styles (fitted to the text, merged, capped and sanitized), + /// and the block's own style fields to the first of each. A block whose characters all share + /// one style, and paragraphs one layout, keeps none, as text always was. + pub fn set_styles(&mut self, runs: Vec, paragraphs: Vec) { + let n = self.char_count(); + let runs = normalize_runs(runs.into_iter().map(|r| TextRun { chars: r.chars, style: r.style.sanitized() }).collect(), n); + let first = runs.first().map_or_else(|| self.char_style(), |r| r.style.clone()); + self.font = first.font.clone(); + self.size = first.size; + self.bold = first.bold; + self.italic = first.italic; + self.color = first.color; + self.letter_spacing = first.letter_spacing; + self.shift = first.shift; + self.underline = first.underline; + self.url = first.url.clone(); + self.runs = if runs.len() > 1 { runs } else { Vec::new() }; + let count = paragraph_count(&self.text); + let mut paras: Vec = paragraphs.iter().take(count).map(ParagraphStyle::sanitized).collect(); + let fill = paras.last().copied().unwrap_or_else(|| self.para_style()); + paras.resize(count, fill); + if let Some(p) = paras.first() { + self.align = p.align; + self.indent = p.indent; + self.left_margin = p.left_margin; + self.right_margin = p.right_margin; + self.line_spacing = p.line_spacing; + } + self.paragraphs = if paras.windows(2).all(|w| matches!(w, [a, b] if a == b)) { Vec::new() } else { paras }; + } + + /// Each fill's outline with its colour and link: the block's outline cut by its fills, or + /// the whole outline in the block's colour when it has none. + pub fn fill_paths(&self) -> Vec<(Rgba, &str, Arc)> { + if self.fills.is_empty() { + return vec![(self.color, self.url.as_str(), self.outline.clone())]; + } + let key = Arc::as_ptr(&self.outline) as usize; + let counts: Vec = self.fills.iter().map(|f| f.cmds).collect(); + let cut = || split_outline(&self.outline, &counts); + let paths = match self.fill_cache.0.get() { + Some((k, c, p)) if *k == key && *c == counts => p.clone(), + Some(_) => cut(), + None => self.fill_cache.0.get_or_init(|| (key, counts.clone(), cut())).2.clone(), + }; + self.fills.iter().zip(paths).map(|(f, p)| (f.color, f.url.as_str(), p)).collect() + } + + /// Sets the outline from pieces in their colours and links (one after another), keeping + /// no fills when there is one piece in the block's colour without a link. + pub fn set_outline(&mut self, pieces: Vec<(Rgba, String, Path)>) { + let single = matches!(pieces.as_slice(), [(c, u, _)] if *c == self.color && u.is_empty()) || pieces.is_empty(); + let mut outline = Path::new(); + let mut fills = Vec::with_capacity(pieces.len()); + for (color, url, p) in pieces { + fills.push(TextFill { color, url, cmds: p.cmds.len() as u32 }); + outline.cmds.extend(p.cmds); + } + self.outline = Arc::new(outline); + self.fills = if single { Vec::new() } else { fills }; + self.fill_cache = FillCache::default(); + } +} + +/// `outline` cut into pieces of `counts` commands (the last takes what is left; extra counts +/// past the end are empty). +fn split_outline(outline: &Path, counts: &[u32]) -> Vec> { + let mut at = 0usize; + let n = counts.len(); + counts + .iter() + .enumerate() + .map(|(i, c)| { + let end = if i + 1 == n { outline.cmds.len() } else { at.saturating_add(*c as usize).min(outline.cmds.len()) }; + let p = Path { cmds: outline.cmds.get(at..end).map(<[_]>::to_vec).unwrap_or_default() }; + at = end; + Arc::new(p) + }) + .collect() +} + +/// The paragraphs in `text` (one more than its line breaks). +pub fn paragraph_count(text: &str) -> usize { + text.bytes().filter(|b| *b == b'\n').count() + 1 +} + +/// Runs fitted to `n` characters: the last runs cut or the last one lengthened. +fn fit_runs(mut runs: Vec, n: u32) -> Vec { + let mut at = 0u32; + let mut keep = 0; + for r in &mut runs { + if at >= n && keep > 0 { + break; + } + r.chars = r.chars.min(n - at); + at += r.chars; + keep += 1; + } + runs.truncate(keep.max(1)); + if let Some(last) = runs.last_mut() { + last.chars += n - at.min(n); + } + runs +} + +/// Runs fitted to `n` characters, empty ones dropped, neighbours in one style joined, at most +/// [`MAX_TEXT_RUNS`] (the rest of the text takes the last kept run's style). Always at least one. +pub fn normalize_runs(runs: Vec, n: u32) -> Vec { + let fallback = runs.first().map(|r| r.style.clone()).unwrap_or_default(); + let mut out: Vec = Vec::with_capacity(runs.len().min(MAX_TEXT_RUNS)); + for r in fit_runs(runs, n) { + if r.chars == 0 { + continue; + } + let full = out.len() >= MAX_TEXT_RUNS; + match out.last_mut() { + Some(last) if last.style == r.style || full => last.chars += r.chars, + _ => out.push(r), + } + } + if out.is_empty() { + out.push(TextRun { chars: n, style: fallback }); + } + out +} + +/// The style typing at character boundary `at` continues: the character before it, or the +/// first character's at the start. +pub fn style_at(runs: &[TextRun], at: u32) -> CharStyle { + let mut end = 0u32; + for r in runs { + end = end.saturating_add(r.chars); + if at <= end && (at > end - r.chars || at == 0) { + return r.style.clone(); + } + } + runs.last().map(|r| r.style.clone()).unwrap_or_default() +} + +/// The runs of characters `start..end`. +pub fn slice_runs(runs: &[TextRun], start: u32, end: u32) -> Vec { + let mut out = Vec::new(); + let mut at = 0u32; + for r in runs { + let (a, b) = (at.max(start), at.saturating_add(r.chars).min(end)); + if a < b { + out.push(TextRun { chars: b - a, style: r.style.clone() }); + } + at = at.saturating_add(r.chars); + if at >= end { + break; + } + } + out +} + +/// Characters `start..end` replaced by `inserted` (runs of the new characters): the runs on +/// either side are cut, the new ones go between, neighbours in one style join. +pub fn replace_runs(runs: &[TextRun], start: u32, end: u32, inserted: Vec) -> Vec { + let total: u32 = runs.iter().map(|r| r.chars).fold(0, u32::saturating_add); + let (start, end) = (start.min(total), end.clamp(start.min(total), total)); + let mut out = slice_runs(runs, 0, start); + out.extend(inserted); + out.extend(slice_runs(runs, end, total)); + let n = out.iter().map(|r| r.chars).fold(0, u32::saturating_add); + let style = runs.first().map(|r| r.style.clone()).unwrap_or_default(); + if out.is_empty() { + return vec![TextRun { chars: 0, style }]; + } + normalize_runs(out, n) +} + +/// Characters `start..end` replaced by `inserted` characters that continue the style before +/// `start` (typing). +pub fn type_into_runs(runs: &[TextRun], start: u32, end: u32, inserted: u32) -> Vec { + let style = style_at(runs, start); + replace_runs(runs, start, end, vec![TextRun { chars: inserted, style }]) +} + +/// Characters `start..end` restyled by `f`, the runs split at both ends and joined again. +pub fn restyle_runs(runs: &[TextRun], start: u32, end: u32, f: impl Fn(&mut CharStyle)) -> Vec { + let total: u32 = runs.iter().map(|r| r.chars).fold(0, u32::saturating_add); + let (start, end) = (start.min(total), end.clamp(start.min(total), total)); + let mut mid = slice_runs(runs, start, end); + for r in &mut mid { + f(&mut r.style); + } + replace_runs(runs, start, end, mid) +} + +/// Paragraph styles after characters `start..end` of `old` are replaced by `inserted`: a +/// paragraph a line break splits gives both halves its style; paragraphs joined keep the +/// first's. +pub fn edit_paragraphs(paras: &[ParagraphStyle], old: &str, start: u32, end: u32, inserted: &str) -> Vec { + let count = paragraph_count(old); + let fill = paras.last().copied().unwrap_or_default(); + let full: Vec = (0..count).map(|i| paras.get(i).copied().unwrap_or(fill)).collect(); + let before = old.chars().take(start as usize).filter(|c| *c == '\n').count(); + let removed = old.chars().skip(start as usize).take(end.saturating_sub(start) as usize).filter(|c| *c == '\n').count(); + let added = inserted.chars().filter(|c| *c == '\n').count(); + let here = full.get(before).copied().unwrap_or(fill); + let mut out: Vec = full.iter().take(before + 1).copied().collect(); + out.extend(std::iter::repeat_n(here, added)); + out.extend(full.iter().skip(before + 1 + removed).copied()); + out +} + +/// The one edit that turns `old` into `new`: the characters `start..old_end` of `old` became +/// `start..new_end` of `new` (the longest common start and end kept). +pub fn diff_chars(old: &str, new: &str) -> (u32, u32, u32) { + let (a, b): (Vec, Vec) = (old.chars().collect(), new.chars().collect()); + let prefix = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + let room = a.len().min(b.len()) - prefix; + let suffix = a.iter().rev().zip(b.iter().rev()).take(room).take_while(|(x, y)| x == y).count(); + (prefix as u32, (a.len() - suffix) as u32, (b.len() - suffix) as u32) +} + +/// What characters `start..end` share, attribute by attribute (`None`: mixed). An empty range +/// is the style typing there would use. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StyleSummary { + pub font: Option, + pub size: Option, + pub bold: Option, + pub italic: Option, + pub color: Option, + pub letter_spacing: Option, + pub shift: Option, + pub underline: Option, + pub url: Option, +} + +impl StyleSummary { + /// The summary of one style (nothing mixed). + pub fn of(s: &CharStyle) -> StyleSummary { + StyleSummary { + font: Some(s.font.clone()), + size: Some(s.size), + bold: Some(s.bold), + italic: Some(s.italic), + color: Some(s.color), + letter_spacing: Some(s.letter_spacing), + shift: Some(s.shift), + underline: Some(s.underline), + url: Some(s.url.clone()), + } + } +} + +/// What characters `start..end` of `runs` share ([`StyleSummary`]). +pub fn summarize(runs: &[TextRun], start: u32, end: u32) -> StyleSummary { + if start >= end { + return StyleSummary::of(&style_at(runs, start)); + } + let part = slice_runs(runs, start, end); + let Some(first) = part.first() else { return StyleSummary::of(&style_at(runs, start)) }; + let mut s = StyleSummary::of(&first.style); + for r in part.iter().skip(1) { + let st = &r.style; + fn keep(v: &mut Option, x: &T) { + if v.as_ref().is_some_and(|v| v != x) { + *v = None; + } + } + keep(&mut s.font, &st.font); + keep(&mut s.size, &st.size); + keep(&mut s.bold, &st.bold); + keep(&mut s.italic, &st.italic); + keep(&mut s.color, &st.color); + keep(&mut s.letter_spacing, &st.letter_spacing); + keep(&mut s.shift, &st.shift); + keep(&mut s.underline, &st.underline); + keep(&mut s.url, &st.url); + } + s +} + +/// The paragraphs characters `start..end` of `text` touch (indices, first to last). +pub fn paragraphs_in(text: &str, start: u32, end: u32) -> std::ops::RangeInclusive { + let first = text.chars().take(start as usize).filter(|c| *c == '\n').count(); + let last = text.chars().take(end.max(start) as usize).filter(|c| *c == '\n').count(); + first..=last +} + +#[cfg(test)] +#[path = "rich_text_tests.rs"] +mod tests; diff --git a/crates/doc/src/rich_text_tests.rs b/crates/doc/src/rich_text_tests.rs new file mode 100644 index 00000000..b0368ffc --- /dev/null +++ b/crates/doc/src/rich_text_tests.rs @@ -0,0 +1,154 @@ +use super::*; +use crate::{Rgba, TextAlign, TextBlock}; + +fn st(size: f32) -> CharStyle { + CharStyle { size, ..CharStyle::default() } +} +fn run(chars: u32, size: f32) -> TextRun { + TextRun { chars, style: st(size) } +} +fn sizes(runs: &[TextRun]) -> Vec<(u32, f32)> { + runs.iter().map(|r| (r.chars, r.style.size)).collect() +} + +#[test] +fn typing_continues_the_style_before_the_caret() { + let runs = vec![run(3, 10.0), run(3, 20.0)]; + // Inside a run, at its end, and at the very start (the first character's style). + assert_eq!(sizes(&type_into_runs(&runs, 1, 1, 2)), vec![(5, 10.0), (3, 20.0)]); + assert_eq!(sizes(&type_into_runs(&runs, 3, 3, 1)), vec![(4, 10.0), (3, 20.0)], "after the last small character: small"); + assert_eq!(sizes(&type_into_runs(&runs, 0, 0, 1)), vec![(4, 10.0), (3, 20.0)]); + assert_eq!(sizes(&type_into_runs(&runs, 6, 6, 1)), vec![(3, 10.0), (4, 20.0)]); + // Typing over a selection that crosses runs takes the style before it. + assert_eq!(sizes(&type_into_runs(&runs, 2, 5, 1)), vec![(3, 10.0), (1, 20.0)]); + // Deleting a whole run joins its neighbours when they match. + let three = vec![run(2, 10.0), run(2, 20.0), run(2, 10.0)]; + assert_eq!(sizes(&replace_runs(&three, 2, 4, Vec::new())), vec![(4, 10.0)]); + // Deleting everything leaves one empty run in the first style. + assert_eq!(sizes(&replace_runs(&three, 0, 6, Vec::new())), vec![(0, 10.0)]); +} + +#[test] +fn styling_a_range_splits_and_merges_runs() { + let runs = vec![run(10, 10.0)]; + let big = restyle_runs(&runs, 2, 5, |s| s.size = 30.0); + assert_eq!(sizes(&big), vec![(2, 10.0), (3, 30.0), (5, 10.0)]); + // Restyling it back joins the runs again. + assert_eq!(sizes(&restyle_runs(&big, 2, 5, |s| s.size = 10.0)), vec![(10, 10.0)]); + // A range across runs; an attribute set on a part keeps the others. + let both = restyle_runs(&big, 4, 7, |s| s.bold = true); + assert_eq!(both.iter().map(|r| (r.chars, r.style.size, r.style.bold)).collect::>(), vec![(2, 10.0, false), (2, 30.0, false), (1, 30.0, true), (2, 10.0, true), (3, 10.0, false)]); + // Out-of-range and backwards ranges are clamped, never a panic. + assert_eq!(sizes(&restyle_runs(&runs, 8, 99, |s| s.size = 1.0)), vec![(8, 10.0), (2, 1.0)]); + assert_eq!(sizes(&restyle_runs(&runs, 7, 3, |s| s.size = 1.0)), vec![(10, 10.0)]); +} + +#[test] +fn a_selection_reports_what_it_shares_and_what_is_mixed() { + let mut runs = vec![run(3, 10.0), run(3, 10.0)]; + runs[1].style.bold = true; + runs[1].style.color = Rgba::hex(0xff0000); + let s = summarize(&runs, 1, 5); + assert_eq!((s.size, s.bold, s.color, s.font.as_deref()), (Some(10.0), None, None, Some(""))); + let caret = summarize(&runs, 4, 4); + assert_eq!(caret.bold, Some(true), "a caret shows the style typing there would use"); + assert_eq!(summarize(&runs, 0, 3).bold, Some(false)); +} + +#[test] +fn line_breaks_split_and_join_paragraph_styles() { + let c = ParagraphStyle { align: TextAlign::Center, ..ParagraphStyle::default() }; + let r = ParagraphStyle { align: TextAlign::Right, indent: 4.0, ..ParagraphStyle::default() }; + let paras = vec![c, r]; + // A line break in the first paragraph: both halves centred. + assert_eq!(edit_paragraphs(¶s, "ab\ncd", 1, 1, "\n"), vec![c, c, r]); + // Joining the two keeps the first's style. + assert_eq!(edit_paragraphs(¶s, "ab\ncd", 2, 3, ""), vec![c]); + // Pasting two lines into the second. + assert_eq!(edit_paragraphs(¶s, "ab\ncd", 4, 4, "x\ny\nz"), vec![c, r, r, r]); + assert_eq!(paragraphs_in("ab\ncd\nef", 1, 4), 0..=1); + assert_eq!(paragraphs_in("ab\ncd\nef", 7, 7), 2..=2); +} + +#[test] +fn one_edit_turns_old_text_into_new() { + assert_eq!(diff_chars("hello", "help me"), (3, 5, 7)); + assert_eq!(diff_chars("abc", "abc"), (3, 3, 3)); + assert_eq!(diff_chars("aaa", "aa"), (2, 3, 2), "the common end never overlaps the common start"); + assert_eq!(diff_chars("", "é!"), (0, 0, 2)); + assert_eq!(diff_chars("xÿz", "xz"), (1, 2, 1)); +} + +#[test] +fn a_block_keeps_runs_only_when_characters_differ() { + let mut b = TextBlock { text: "Hello".into(), size: 20.0, ..TextBlock::default() }; + b.set_styles(vec![TextRun { chars: 5, style: CharStyle { size: 20.0, ..CharStyle::default() } }], vec![ParagraphStyle::default()]); + assert!(b.runs.is_empty() && b.paragraphs.is_empty(), "one style: no runs"); + let red = CharStyle { color: Rgba::hex(0xff0000), shift: BaselineShift::Superscript, ..b.char_style() }; + b.set_styles(vec![TextRun { chars: 2, style: red.clone() }, TextRun { chars: 3, style: b.char_style() }], Vec::new()); + assert_eq!(b.runs.len(), 2); + assert_eq!((b.color, b.shift), (red.color, BaselineShift::Superscript), "the block's fields are its first run's"); + assert_eq!(b.styled_runs().iter().map(|r| r.chars).sum::(), 5); + // Too many runs are capped; lengths past the text are cut. + let many: Vec = (0..MAX_TEXT_RUNS as u32 + 50).map(|i| TextRun { chars: 1, style: CharStyle { size: 10.0 + (i % 2) as f32, ..CharStyle::default() } }).collect(); + let mut long = TextBlock { text: "x".repeat(MAX_TEXT_RUNS + 50), ..TextBlock::default() }; + long.set_styles(many, Vec::new()); + assert_eq!(long.runs.len(), MAX_TEXT_RUNS); + assert_eq!(long.runs.iter().map(|r| r.chars as usize).sum::(), MAX_TEXT_RUNS + 50); + // Hostile styles are clamped. + let mut h = TextBlock { text: "ab".into(), ..TextBlock::default() }; + h.set_styles(vec![TextRun { chars: u32::MAX, style: CharStyle { size: f32::NAN, letter_spacing: 1e9, url: "u".repeat(5000), ..CharStyle::default() } }], vec![ParagraphStyle { indent: f32::INFINITY, left_margin: -3.0, ..ParagraphStyle::default() }; 9]); + assert_eq!((h.size, h.letter_spacing, h.url.len(), h.indent, h.left_margin), (32.0, 1000.0, MAX_URL, 0.0, 0.0)); + assert!(h.paragraphs.is_empty(), "one paragraph"); +} + +#[test] +fn fills_cut_the_outline_by_colour() { + let mut b = TextBlock { text: "ab".into(), ..TextBlock::default() }; + let red = Rgba::hex(0xff0000); + b.set_outline(vec![(Rgba::BLACK, String::new(), Path::rect(0.0, 0.0, 1.0, 1.0)), (red, "https://example.org".into(), Path::rect(2.0, 0.0, 1.0, 1.0))]); + assert_eq!(b.fills.len(), 2); + assert_eq!(b.outline.cmds.len(), 10); + let parts = b.fill_paths(); + assert_eq!(parts.len(), 2); + assert_eq!((parts[1].0, parts[1].1), (red, "https://example.org")); + assert_eq!(*parts[1].2, Path::rect(2.0, 0.0, 1.0, 1.0)); + // Cut once: drawing again shares the pieces. + assert!(Arc::ptr_eq(&b.fill_paths()[0].2, &parts[0].2)); + // One piece in the block's colour keeps no fills. + b.set_outline(vec![(Rgba::BLACK, String::new(), Path::rect(0.0, 0.0, 1.0, 1.0))]); + assert!(b.fills.is_empty()); + assert_eq!(b.fill_paths().len(), 1); + // Counts that don't add up never panic: the last fill takes the rest. + let odd = TextBlock { fills: vec![TextFill { color: red, url: String::new(), cmds: 99 }, TextFill { color: red, url: String::new(), cmds: 0 }], outline: Arc::new(Path::rect(0.0, 0.0, 1.0, 1.0)), ..TextBlock::default() }; + assert_eq!(odd.fill_paths().iter().map(|p| p.2.cmds.len()).collect::>(), vec![5, 0]); +} + +#[test] +fn older_text_saves_byte_for_byte_and_runs_round_trip() { + // A block as files before styled text wrote it: nothing new is written. + let old = r#"{"text":"Hi","font":"Inter","size":20.0,"bold":false,"italic":false,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0},"align":"left","letter_spacing":0.0,"line_spacing":0.0,"width":null,"outline":"","box_width":10.0,"box_height":12.0}"#; + let b: TextBlock = serde_json::from_str(old).unwrap(); + assert!(b.runs.is_empty() && b.paragraphs.is_empty() && b.fills.is_empty()); + assert_eq!(serde_json::to_string(&b).unwrap(), old); + // Runs, paragraphs and fills come back as they were. + let mut rich = b.clone(); + rich.set_styles(vec![TextRun { chars: 1, style: CharStyle { underline: true, url: "a".into(), ..b.char_style() } }, TextRun { chars: 1, style: b.char_style() }], Vec::new()); + rich.text = "H\ni".into(); + rich.set_styles(rich.runs.clone(), vec![ParagraphStyle::default(), ParagraphStyle { align: TextAlign::Right, right_margin: 3.0, ..ParagraphStyle::default() }]); + let json = serde_json::to_string(&rich).unwrap(); + let back: TextBlock = serde_json::from_str(&json).unwrap(); + assert_eq!(back, rich); + assert!(json.contains("\"runs\"") && json.contains("\"paragraphs\"")); +} + +#[test] +fn links_that_run_code_are_dropped() { + assert_eq!(safe_url(" https://example.org/a "), Some("https://example.org/a".into())); + assert_eq!(safe_url("mailto:me@example.org"), Some("mailto:me@example.org".into())); + assert_eq!(safe_url("page.html#top"), Some("page.html#top".into())); + assert_eq!(safe_url("JavaScript:alert(1)"), None); + assert_eq!(safe_url(" java script:alert(1)"), None, "control characters don't hide a scheme"); + assert_eq!(safe_url("data:text/html,x"), None); + assert_eq!(safe_url("/a:b"), Some("/a:b".into()), "a colon in a path is no scheme"); +} diff --git a/crates/doc/src/swatch.rs b/crates/doc/src/swatch.rs index 53521829..76cea335 100644 --- a/crates/doc/src/swatch.rs +++ b/crates/doc/src/swatch.rs @@ -157,51 +157,25 @@ pub fn is_default_set(v: &[Swatch]) -> bool { } /// Largest palette file read, in bytes. -pub const MAX_PALETTE_BYTES: usize = 1 << 20; +pub const MAX_PALETTE_BYTES: usize = craft_palette::MAX_BYTES; /// Reads a GIMP palette (`.gpl`): a `GIMP Palette` line, optional `Name:` and `Columns:` /// lines and `#` comments, then one colour per line, `R G B` (0 to 255) and an optional name. /// Lines that aren't colours are skipped; at most [`MAX_SWATCHES`] colours are read. The /// palette's own name comes back with the colours. pub fn parse_gpl(text: &str) -> Result<(String, Vec), String> { - if text.len() > MAX_PALETTE_BYTES { - return Err("the palette file is too large".into()); - } - let mut lines = text.lines(); - let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); - if first != "GIMP Palette" { - return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); - } - let mut name = String::new(); - let mut out = Vec::new(); - for line in lines { - let l = line.trim(); - if l.is_empty() || l.starts_with('#') { - continue; - } - if let Some(n) = l.strip_prefix("Name:") { - name = clean_name(n); - continue; - } - if l.starts_with("Columns:") || l.starts_with("Channels:") { - continue; - } - let mut parts = l.split_whitespace(); - let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| f32::from(v) / 255.0); - let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; - let rest: Vec<&str> = parts.collect(); - let label = rest.join(" "); - // GIMP names unnamed colours "Untitled"; the hex says more. - let label = if label == "Untitled" { String::new() } else { label }; - out.push(Swatch::new(&label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) })); - if out.len() >= MAX_SWATCHES { - break; - } - } - if out.is_empty() { - return Err("the palette has no colours in it".into()); - } - Ok((name, out)) + let palette = craft_palette::parse_gpl(text)?; + let colors = palette + .colors + .into_iter() + .map(|entry| { + let [r, g, b] = entry.rgb.map(|v| f32::from(v) / 255.0); + // GIMP's placeholder is an application display policy, not a format rule. + let label = if entry.name == "Untitled" { "" } else { &entry.name }; + Swatch::new(label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) }) + }) + .collect(); + Ok((clean_name(&palette.name), colors)) } #[cfg(test)] @@ -244,6 +218,18 @@ mod tests { assert!(SwatchPaint::from_paint(&Paint::Bitmap { bitmap: crate::BitmapId(1), repeat: true, matrix: crate::Affine::IDENTITY }).is_none()); } + #[test] + fn gpl_adapter_preserves_name_limit_and_display_policy() { + assert_eq!(MAX_SWATCHES, craft_palette::MAX_COLORS); + let title = format!(" {}", "é".repeat(MAX_SWATCH_NAME + 1)); + let text = format!("GIMP Palette\nName:{title}\n1 2 3 Untitled\n4 5 6 Named colour\n"); + let (name, swatches) = parse_gpl(&text).unwrap(); + assert_eq!(name, clean_name(&title)); + assert_eq!(name.chars().count(), MAX_SWATCH_NAME - 1); + assert!(swatches[0].name.is_empty()); + assert_eq!(swatches[1].name, "Named colour"); + } + #[test] fn gimp_palettes_are_read() { let text = "GIMP Palette\nName: Brand\nColumns: 4\n# a comment\n255 0 0\tCrimson red\n 0 128 255 Untitled\n300 0 0 too bright\nnot a colour\n\n10 20 30\n"; diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 74095142..e288ffb2 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -891,15 +891,17 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { objects.push(c); continue; } - // Text breaks apart into a shape with the same outlines. + // Text breaks apart into shapes with the same outlines, one per colour (ADR 0085). if let ElementKind::Text(t) = &e.kind && sel.contains(&e.id) { - let mut c = (*e).clone(); - c.id = ElementId(s.doc.alloc_id()); - c.kind = ElementKind::Shape(crate::cmds_text::to_shape(t)); - fresh_ids.push(c.id); - out.push(Arc::new(c)); + for shape in crate::cmds_text::to_shapes(t) { + let mut c = (*e).clone(); + c.id = ElementId(s.doc.alloc_id()); + c.kind = ElementKind::Shape(shape); + fresh_ids.push(c.id); + out.push(Arc::new(c)); + } continue; } // A group breaks apart into its members (Animate's Ctrl+B on a group ungroups it). diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 0f4375dd..d00a2540 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -264,7 +264,7 @@ fn export_png(s: &mut Session, p: &Value) -> Result { } /// Largest file Import to Stage reads. -const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; +pub(crate) const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// Import to Stage: the drawing's shapes and text become editable elements on a new layer /// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing diff --git a/crates/engine/src/cmds_macro.rs b/crates/engine/src/cmds_macro.rs new file mode 100644 index 00000000..82cafb66 --- /dev/null +++ b/crates/engine/src/cmds_macro.rs @@ -0,0 +1,542 @@ +//! Saved commands (command macros, ADR 0097): steps picked in the History panel, kept as a +//! small JSON file and run again as one undo step. +//! +//! Every undo step remembers the commands it ran (`history::Recorded`). Save As Command turns +//! the picked steps into a saved command, rewriting what only makes sense in this document +//! (an element's or layer's id) to act on the current selection or active layer where the +//! command allows it, and refusing, with the step named, what can't be kept. A saved command +//! may call what a plug-in may (`plugin_may_call`) and never the `macro.*` commands, so it +//! can't recurse, touch files or the clipboard. +//! +//! A saved command is a file `/.json`: `{"format": "anicraft-command", +//! "version": 1, "steps": [{"cmd", "params", "label"}]}`. The file's name is the command's +//! name, so a shared file keeps whatever name it is given. `anicraft-cli run` scripts (a bare +//! JSON array of `{cmd, params}`) run the same way. Their order in the Commands menu is kept +//! in `/.order.json`. The shell passes the folder (its settings folder's `Commands`); +//! the engine never looks for it, as with templates. + +use crate::history::Recorded; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, vfs}; +use serde_json::{Map, Value, json}; +use std::path::{Path, PathBuf}; + +/// The `format` a saved command's file declares. +pub const FORMAT: &str = "anicraft-command"; +/// The newest file version this build reads and the one it writes. +pub const VERSION: u64 = 1; +/// Most steps in one saved command. +pub const MAX_STEPS: usize = 1000; +/// Largest saved command file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// Most saved commands listed from one folder. +pub const MAX_LISTED: usize = 500; +/// The file that keeps the order of the saved commands (a dot-name: no command is called that). +pub const ORDER_FILE: &str = ".order.json"; +/// Longest command id and step label kept from a file. +const MAX_CMD_CHARS: usize = 128; +const MAX_LABEL_CHARS: usize = 200; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c("macro.run", "Run Command…", "Commands", "{name + folder (a saved command) | path (a saved command's file, or a JSON array of {cmd, params}) | steps: [{cmd, params?, label?}], name? (for steps)} → {name, steps, results}: runs the steps in order as one undo step named after it. At the first step that fails nothing is changed and the error names the step. Steps may call what a plug-in may, never macro.*", true, run as crate::RunFn), + c("macro.list", "Manage Saved Commands…", "Commands", "{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)", false, list), + c("macro.history", "List History Steps", "", "{} → {steps: [{index, label, undone, keep, commands?, why?, rewritten?}]}: every undo-history step as Save As Command keeps it: `keep` false says `why` it can't be kept; `rewritten` names params dropped so the step acts on the selection or active layer", false, history), + c("macro.save", "Save As Command…", "", "{folder, name, history: [index, ..] (as macro.history lists them) | steps: [{cmd, params?, label?}], confirm? (to replace a saved command of that name)} → {name, path, steps, rewritten}: keeps the steps as /.json, last in the list", false, save), + c("macro.rename", "Rename Saved Command", "", "{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays", false, rename), + c("macro.delete", "Delete Saved Command", "", "{folder, name, confirm}: deletes a saved command's file (cannot be undone)", false, delete), + c("macro.move", "Move Saved Command", "", "{folder, name, index (its new place in the list, 0-based)}", false, move_to), + c("macro.import", "Add Saved Command from File", "", "{folder, path (a saved command's file), name? (default: the file's), confirm? (to replace one of that name)} → {name, path, steps}: checks it and copies it in, last in the list", false, import), + ] +} + +/// Whether a saved command may run command `id`, and if not, why: what a plug-in may, and +/// never a `macro.*` command (a saved command doesn't run, save or change saved commands). +pub fn macro_may_call(id: &str) -> std::result::Result<(), String> { + if id.split('.').next() == Some("macro") { + return Err("a saved command can't run, save or change saved commands".into()); + } + crate::cmds_plugin::plugin_may_call(id).map_err(|why| format!("{why} (a saved command may do only what a plug-in may)")) +} + +/// One step of a saved command. +#[derive(Clone, Debug, PartialEq)] +pub struct Step { + pub cmd: String, + /// Always an object. + pub params: Value, + /// What the History panel called it (may be empty: then the command's label). + pub label: String, +} + +impl Step { + /// The step's name in messages. + pub fn name(&self) -> String { + if !self.label.is_empty() { + return self.label.clone(); + } + crate::find_command(&self.cmd).map_or_else(|| self.cmd.clone(), |c| c.label.trim_end_matches('…').to_string()) + } +} + +/// A saved command: its name and steps. +#[derive(Clone, Debug, PartialEq)] +pub struct Macro { + pub name: String, + pub steps: Vec, +} + +impl Macro { + /// The file's content. + pub fn to_json(&self) -> Value { + let steps: Vec = self.steps.iter().map(|s| json!({"cmd": s.cmd, "params": s.params, "label": s.label})).collect(); + json!({"format": FORMAT, "version": VERSION, "steps": steps}) + } + + /// Reads a saved command named `name`: a file's object, or a bare array of steps (an + /// `anicraft-cli run` script). Every step is checked: a known command a saved command may + /// call, with object params. + pub fn from_json(v: &Value, name: &str) -> Result { + let steps = match v { + Value::Array(a) => a, + Value::Object(o) => { + if let Some(f) = o.get("format") + && f.as_str() != Some(FORMAT) + { + return Err(EngineError::Format(format!("not a saved command (its format is {f}, not \"{FORMAT}\")"))); + } + if let Some(v) = o.get("version") { + let v = v.as_u64().ok_or_else(|| EngineError::Format("a saved command's version is a whole number".into()))?; + if v > VERSION { + return Err(EngineError::Format(format!("this saved command was made by a newer AniCraft (version {v}); update AniCraft to run it"))); + } + } + o.get("steps").and_then(Value::as_array).ok_or_else(|| EngineError::Format("a saved command has a \"steps\" list".into()))? + } + _ => return Err(EngineError::Format("a saved command is a JSON object with \"steps\", or a list of {cmd, params}".into())), + }; + if steps.len() > MAX_STEPS { + return Err(EngineError::Format(format!("a saved command has at most {MAX_STEPS} steps (this one has {})", steps.len()))); + } + let mut out = Vec::with_capacity(steps.len()); + for (i, st) in steps.iter().enumerate() { + let n = i + 1; + let o = st.as_object().ok_or_else(|| EngineError::Format(format!("step {n} is not an object {{cmd, params}}")))?; + let cmd = o.get("cmd").or_else(|| o.get("command")).and_then(Value::as_str).ok_or_else(|| EngineError::Format(format!("step {n} has no \"cmd\"")))?; + if cmd.chars().count() > MAX_CMD_CHARS || crate::find_command(cmd).is_none() { + let shown: String = cmd.chars().take(40).collect(); + return Err(EngineError::Format(format!("step {n}: unknown command '{shown}'"))); + } + macro_may_call(cmd).map_err(|why| EngineError::Format(format!("step {n} ({cmd}) can't be in a saved command: {why}")))?; + let params = match o.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(EngineError::Format(format!("step {n} ({cmd}): params are an object"))), + }; + let label: String = o.get("label").and_then(Value::as_str).unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_LABEL_CHARS).collect(); + out.push(Step { cmd: cmd.to_string(), params, label }); + } + Ok(Macro { name: name.to_string(), steps: out }) + } +} + +/// The file of the saved command called `name` in `folder`. +pub fn command_path(folder: &Path, name: &str) -> Result { + let name = crate::cmds_template::clean_name(name, "command")?; + Ok(folder.join(format!("{name}.json"))) +} + +/// Reads a saved command's file (its name is the file's). +pub fn load(path: &Path) -> Result { + let len = vfs::len(path).map_err(|e| EngineError::Io(std::io::Error::new(e.kind(), format!("{}: {e}", path.display()))))?; + if len > MAX_FILE_BYTES { + return Err(EngineError::Format(format!("{} is larger than a saved command can be ({} KiB at most)", path.display(), MAX_FILE_BYTES / 1024))); + } + let text = vfs::read_to_string(path)?; + // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Format(format!("{}: not JSON ({e})", path.display())))?; + let name = path.file_stem().map_or_else(|| "Command".to_string(), |n| n.to_string_lossy().into_owned()); + Macro::from_json(&v, &name) +} + +/// A saved command found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Saved { + pub name: String, + pub path: PathBuf, + pub steps: usize, +} + +fn read_order(folder: &Path) -> Vec { + let path = folder.join(ORDER_FILE); + if vfs::len(&path).map_or(true, |n| n > MAX_FILE_BYTES) { + return Vec::new(); + } + let v: Value = vfs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()).unwrap_or(Value::Null); + v.as_array().into_iter().flatten().filter_map(Value::as_str).take(MAX_LISTED).map(str::to_string).collect() +} + +fn write_order(folder: &Path, names: &[String]) -> Result<()> { + let text = serde_json::to_string_pretty(names).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(&folder.join(ORDER_FILE), text)?; + Ok(()) +} + +/// The saved commands in `folder`, in their order (then by name), and the files that aren't +/// saved commands with why: `(file name, error)`. +pub fn saved_commands(folder: &Path) -> (Vec, Vec<(String, String)>) { + let order: Vec = read_order(folder).into_iter().map(|n| n.to_lowercase()).collect(); + let mut found = Vec::new(); + let mut problems = Vec::new(); + for f in vfs::list(folder, MAX_LISTED * 2) { + let Some(stem) = f.file_stem().map(|n| n.to_string_lossy().into_owned()) else { continue }; + if stem.starts_with('.') || !f.extension().is_some_and(|e| e.eq_ignore_ascii_case("json")) || !vfs::is_file(&f) { + continue; + } + let file = f.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + match load(&f) { + Ok(m) if found.len() < MAX_LISTED => found.push(Saved { name: m.name, path: f, steps: m.steps.len() }), + Ok(_) => {} + Err(e) => problems.push((file, e.to_string())), + } + } + found.sort_by_key(|s| (order.iter().position(|o| *o == s.name.to_lowercase()).unwrap_or(usize::MAX), s.name.to_lowercase())); + problems.sort(); + (found, problems) +} + +fn folder(p: &Value) -> Result { + let f = str_req(p, "folder")?; + if f.trim().is_empty() { + return Err(EngineError::Param("name the saved commands' folder".into())); + } + Ok(PathBuf::from(f)) +} + +/// The saved command file the params name (`folder` and `name`). +pub(crate) fn target(p: &Value) -> Result { + command_path(&folder(p)?, str_req(p, "name")?) +} + +/// Where `macro.import` copies its file to. +pub(crate) fn import_target(p: &Value) -> Result { + let from = PathBuf::from(str_req(p, "path")?); + let name = match opt_str(p, "name")? { + Some(n) => n.to_string(), + None => from.file_stem().map(|n| n.to_string_lossy().into_owned()).ok_or_else(|| EngineError::Param("the file has no name".into()))?, + }; + command_path(&folder(p)?, &name) +} + +fn name_of(path: &Path) -> String { + path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The saved command the params name: by `name` in `folder`, a file's `path`, or `steps`. +fn resolve(p: &Value) -> Result { + if let Some(steps) = p.get("steps") { + let name = opt_str(p, "name")?.map_or_else(|| "Saved command".to_string(), |n| n.chars().filter(|c| !c.is_control()).take(crate::cmds_template::MAX_NAME_CHARS).collect()); + return Macro::from_json(steps, &name); + } + if let Some(path) = opt_str(p, "path")? { + return load(Path::new(path)); + } + let path = target(p).map_err(|e| EngineError::Param(format!("name a saved command (name and folder), a file (path) or steps: {e}")))?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + load(&path) +} + +fn run(s: &mut Session, p: &Value) -> Result { + let m = resolve(p)?; + if m.steps.is_empty() { + return Err(EngineError::State(format!("“{}” has no steps to run", m.name))); + } + let n = m.steps.len(); + let mut results = Vec::with_capacity(n); + for (i, st) in m.steps.iter().enumerate() { + // (Checked when it was read; the rule is the run's, so it is checked here too.) + let r = macro_may_call(&st.cmd).map_err(EngineError::State).and_then(|()| s.execute_nested(&st.cmd, &st.params)); + match r { + Ok(v) => results.push(v), + // The session puts the document back as it was before the run. + Err(e) => return Err(EngineError::State(format!("“{}” stopped at step {} of {n} ({}): {e}. Nothing was changed.", m.name, i + 1, st.name()))), + } + } + s.step_label = Some(m.name.clone()); + // History keeps the steps, so a run can itself be saved again with other steps. + s.record_as = Some(m.steps.iter().map(|st| Recorded::new(&st.cmd, &st.params)).collect()); + Ok(json!({"name": m.name, "steps": n, "results": results})) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let (found, problems) = saved_commands(&folder(p)?); + let commands: Vec = found.iter().map(|c| json!({"name": c.name, "path": c.path.display().to_string(), "steps": c.steps})).collect(); + let problems: Vec = problems.iter().map(|(f, e)| json!({"file": f, "error": e})).collect(); + Ok(json!({"commands": commands, "problems": problems})) +} + +/// Params naming who a step acts on: dropped, where the command then acts on the selection +/// (or, for layers, the active layer), so the step replays elsewhere. +const TARGETS: &[&str] = &["layer", "layers", "element", "elements", "id", "ids", "shape", "path", "symbol"]; +/// Params naming things that exist only in this document: Library items, folders and bones. +const FIXED: &[&str] = &["bitmap", "sound", "folder", "bone", "parent", "items"]; + +/// What a param names, in a sentence. +fn noun(key: &str) -> &'static str { + match key { + "layer" | "layers" => "particular layers", + "symbol" | "bitmap" | "sound" | "folder" | "items" => "particular Library items", + "bone" | "parent" | "from" | "to" => "particular bones", + _ => "particular objects", + } +} + +/// Whether the command's params doc makes `key` optional (`key?`), and, but for layers, says +/// it defaults to what is selected. +fn defaults_to_selection(doc: &str, key: &str) -> bool { + let pat = format!("{key}?"); + doc.match_indices(&pat).any(|(i, _)| { + let whole = doc.get(..i).and_then(|b| b.chars().next_back()).is_none_or(|c| !c.is_alphanumeric() && c != '_'); + let after: String = doc.get(i + pat.len()..).unwrap_or("").chars().take(90).collect(); + whole && (key.starts_with("layer") || after.contains("select")) + }) +} + +/// Whether a recorded command can be kept: the params it would drop (they name this +/// document's layers or objects and the command can act on the selection or active layer +/// instead), or why it can't be kept. Reads only: listing a long history costs no copies. +fn check(cmd: &str, params: &Value) -> std::result::Result, String> { + macro_may_call(cmd)?; + let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; + let mut dropped = Vec::new(); + for (k, v) in params.as_object().into_iter().flatten() { + let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); + let target = TARGETS.iter().find(|t| **t == k.as_str()); + match target { + _ if v.is_null() => {} + Some(t) if !fixed && defaults_to_selection(spec.params, t) => dropped.push(*t), + None if !fixed => {} + _ => return Err(format!("it works on {} of this document", noun(k))), + } + } + Ok(dropped) +} + +/// A recorded command as a saved command keeps it: its params without what names this +/// document's layers and objects (and which of those went), or why it can't be kept. +pub fn portable(cmd: &str, params: &Value) -> std::result::Result<(Value, Vec), String> { + let dropped = check(cmd, params)?; + let out: Map = params.as_object().into_iter().flatten().filter(|(k, _)| !dropped.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + Ok((Value::Object(out), dropped.into_iter().map(str::to_string).collect())) +} + +/// An undo step as a saved command keeps it: its steps and the params dropped, or why not. +fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec, Vec), String> { + let cmds = usable(cmds)?; + let mut steps = Vec::with_capacity(cmds.len()); + let mut dropped = Vec::new(); + for r in cmds { + let (params, gone) = portable(&r.cmd, &r.params)?; + for g in gone { + if !dropped.contains(&g) { + dropped.push(g); + } + } + steps.push(Step { cmd: r.cmd.clone(), params, label: label.to_string() }); + } + Ok((steps, dropped)) +} + +fn usable(cmds: Option<&[Recorded]>) -> std::result::Result<&[Recorded], String> { + let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; + if cmds.is_empty() { + return Err("it has nothing to run again".into()); + } + Ok(cmds) +} + +/// [`keep_step`] without building the steps: how many commands, and the params dropped. +fn check_step(cmds: Option<&[Recorded]>) -> std::result::Result<(usize, Vec), String> { + let cmds = usable(cmds)?; + let mut dropped: Vec = Vec::new(); + for r in cmds { + for g in check(&r.cmd, &r.params)? { + if !dropped.iter().any(|d| d == g) { + dropped.push(g.to_string()); + } + } + } + Ok((cmds.len(), dropped)) +} + +/// What dropped params mean for the step, in a sentence. +fn rewritten_note(dropped: &[String]) -> Option { + let layers = dropped.iter().any(|d| d.starts_with("layer")); + let objects = dropped.iter().any(|d| !d.starts_with("layer")); + match (objects, layers) { + (true, true) => Some("acts on the selection and the active layer".into()), + (true, false) => Some("acts on the selection".into()), + (false, true) => Some("acts on the active layer".into()), + (false, false) => None, + } +} + +fn history(s: &mut Session, _: &Value) -> Result { + let done = s.history().undo_len(); + let steps: Vec = s + .history() + .steps() + .enumerate() + .map(|(i, (label, cmds))| { + let mut v = json!({"index": i, "label": label, "undone": i >= done}); + match check_step(cmds) { + Ok((n, dropped)) => { + v["keep"] = json!(true); + v["commands"] = json!(n); + if let Some(note) = rewritten_note(&dropped) { + v["rewritten"] = json!(note); + } + } + Err(why) => { + v["keep"] = json!(false); + v["why"] = json!(why); + } + } + v + }) + .collect(); + Ok(json!({"steps": steps})) +} + +/// The steps the params ask to save: history steps by index, or steps given outright; and +/// what was rewritten, a sentence per step. +fn steps_to_save(s: &Session, p: &Value) -> Result<(Vec, Vec)> { + if let Some(v) = p.get("steps") { + return Ok((Macro::from_json(v, "")?.steps, Vec::new())); + } + let mut picked = opt_u64_list(p, "history")?.ok_or_else(|| EngineError::Param("pick the steps to keep: history (as macro.history lists them) or steps".into()))?; + picked.sort_unstable(); + picked.dedup(); + if picked.is_empty() { + return Err(EngineError::Param("pick at least one step to keep".into())); + } + let all: Vec<(&str, Option<&[Recorded]>)> = s.history().steps().collect(); + let mut steps = Vec::new(); + let mut notes = Vec::new(); + for i in picked { + let (label, cmds) = usize::try_from(i).ok().and_then(|i| all.get(i).copied()).ok_or_else(|| EngineError::Param(format!("there is no history step {i} (macro.history lists them)")))?; + let (kept, dropped) = keep_step(label, cmds).map_err(|why| EngineError::State(format!("step {} “{label}” can't be kept: {why}", i + 1)))?; + if let Some(note) = rewritten_note(&dropped) { + notes.push(json!({"index": i, "label": label, "note": note})); + } + steps.extend(kept); + if steps.len() > MAX_STEPS { + return Err(EngineError::State(format!("a saved command has at most {MAX_STEPS} steps"))); + } + } + Ok((steps, notes)) +} + +/// Adds `name` to the end of the folder's order (or leaves it where it is). +fn order_add(folder: &Path, name: &str) -> Result<()> { + let mut order = read_order(folder); + if !order.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { + // The order holds every listed command, so a new one goes after all of them. + let (found, _) = saved_commands(folder); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + names.push(name.to_string()); + order = names; + } + write_order(folder, &order) +} + +fn write_macro(path: &Path, m: &Macro) -> Result<()> { + if let Some(dir) = path.parent() { + vfs::create_dir_all(dir)?; + } + let text = serde_json::to_string_pretty(&m.to_json()).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(path, text)?; + Ok(()) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + let (steps, rewritten) = steps_to_save(s, p)?; + if steps.is_empty() { + return Err(EngineError::Param("a saved command needs at least one step".into())); + } + let m = Macro { name: name_of(&path), steps }; + write_macro(&path, &m)?; + if let Some(dir) = path.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": path.display().to_string(), "steps": m.steps.len(), "rewritten": rewritten})) +} + +fn import(_: &mut Session, p: &Value) -> Result { + let to = import_target(p)?; + let from = PathBuf::from(str_req(p, "path")?); + let m = Macro { name: name_of(&to), ..load(&from)? }; + write_macro(&to, &m)?; + if let Some(dir) = to.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": to.display().to_string(), "steps": m.steps.len()})) +} + +fn existing(p: &Value) -> Result { + let path = target(p)?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + Ok(path) +} + +fn rename(_: &mut Session, p: &Value) -> Result { + let from = existing(p)?; + let dir = folder(p)?; + let to = command_path(&dir, str_req(p, "to")?)?; + let (old, new) = (name_of(&from), name_of(&to)); + if old == new { + return Ok(json!({"name": new, "from": old})); + } + // A change of case only is the same file on Windows and macOS. + if old.to_lowercase() != new.to_lowercase() && vfs::exists(&to) { + return Err(EngineError::State(format!("there is already a saved command “{new}”"))); + } + vfs::rename(&from, &to)?; + let mut order = read_order(&dir); + for o in &mut order { + if o.to_lowercase() == old.to_lowercase() { + o.clone_from(&new); + } + } + write_order(&dir, &order)?; + Ok(json!({"name": new, "from": old, "path": to.display().to_string()})) +} + +fn delete(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + vfs::remove_file(&path)?; + let order: Vec = read_order(&dir).into_iter().filter(|o| o.to_lowercase() != name.to_lowercase()).collect(); + write_order(&dir, &order)?; + Ok(json!({"deleted": name})) +} + +fn move_to(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + let index = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("give the new place: index (0-based)".into()))?; + let (found, _) = saved_commands(&dir); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + let at = usize::try_from(index).unwrap_or(usize::MAX).min(names.len()); + names.insert(at, name.clone()); + write_order(&dir, &names)?; + Ok(json!({"name": name, "index": at})) +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 5fa3167c..4b00ff27 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -56,6 +56,9 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), + // Saved commands are files in your preferences (ADR 0097), and running one from a + // plug-in would let the two call each other. + "macro" => Err("plug-ins can't run, save or change saved commands"), "desktop" => Err("plug-ins can't change your applications menu or which app opens your files"), "control" => Err("plug-ins can't play the movie"), // A scene's guides are the document's (ADR 0076); whether rulers, grid and guides diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index abef14ef..e055f1fa 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -108,6 +108,9 @@ pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { } let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); if matches!(ext.as_deref(), Some("png" | "jpg" | "jpeg")) { + if crate::vfs::len(&path)? > crate::cmds_file::MAX_IMPORT_BYTES { + return Err(EngineError::Format(format!("{} is too large to import", path.display()))); + } let bytes = crate::vfs::read(&path)?; let id = anicraft_doc::BitmapId(s.doc.alloc_id()); let bitmap = anicraft_doc::Bitmap::from_image(id, file_name(&path, "image"), bytes).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; @@ -357,9 +360,9 @@ pub(crate) fn write_mix(path: &Path, voices: &[Voice], rate: u32, from: u64, to: use std::io::Write; let frames = to.saturating_sub(from); let header = wav::header(rate, 2, bits, frames).ok_or_else(|| EngineError::Param("that much audio does not fit in a WAV file (4 GB); lower 'rate' or the frame range".into()))?; - let tmp = path.with_extension("wav.tmp"); + let tmp = path.with_extension(format!("{}.wav.tmp", crate::vfs::random_suffix())); let result = (|| -> Result { - let mut f = crate::vfs::Writer::create(&tmp)?; + let mut f = crate::vfs::Writer::create_new(&tmp)?; f.write_all(&header)?; const BLOCK: u64 = 65_536; let mut buf = vec![0f32; BLOCK as usize * 2]; @@ -420,8 +423,7 @@ impl Drop for TempTrack { /// The soundtrack of movie frames `first..=last` as a 48 kHz 16-bit WAV in the temp folder. pub(crate) fn temp_track(s: &Session, first: u32, last: u32) -> Result { const RATE: u32 = 48_000; - let nanos = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); - let track = TempTrack(std::env::temp_dir().join(format!("anicraft-track-{}-{nanos}.wav", std::process::id()))); + let track = TempTrack(std::env::temp_dir().join(format!("anicraft-track-{}-{}.wav", std::process::id(), crate::vfs::random_suffix()))); let (voices, a, b) = soundtrack(s, first, last, RATE); write_mix(&track.0, &voices, RATE, a, b, wav::Bits::Int16)?; Ok(track) diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs index 881eb2ba..17c0e2c8 100644 --- a/crates/engine/src/cmds_template.rs +++ b/crates/engine/src/cmds_template.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { } /// A name usable as a file or folder name on every system, or why not. -fn clean_name(raw: &str, what: &str) -> Result { +pub(crate) fn clean_name(raw: &str, what: &str) -> Result { let name = raw.trim(); if name.is_empty() { return Err(EngineError::Param(format!("give the {what} a name"))); diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index f73a94b6..d0bebf4e 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -8,16 +8,24 @@ //! Text on a path (ADR 0070): `text.attach_path` sets static text along a shape's outline (a //! copy of it, in the text's own space), `text.path` moves it along, flips it or releases it. //! The glyphs are set by arc length and stored as outlines, as all text is. +//! +//! Styled text (ADR 0085): a block's characters come in runs with their own font, size, style, +//! colour, letter spacing, baseline shift, underline and link, and its paragraphs have their own +//! alignment, indent, margins and line spacing. `text.style` styles a range of characters, +//! `text.paragraph` the paragraphs a range touches, `text.styles` reads them back (mixed values +//! as `null`); `text.edit` keeps the runs through a change of text (typing continues the style +//! before it) or takes new ones. Every layout here goes through [`lay_out_block`]. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath}; +use anicraft_doc::rich_text::{self as rt, StyleSummary}; +use anicraft_doc::{BaselineShift, CharStyle, ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, MAX_TEXT_RUNS, MAX_URL, ParagraphStyle, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath, TextRun}; use anicraft_geom::{Affine, Path, Vec2}; use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; use std::sync::Arc; -/// The text style new text gets: the last one used. +/// The text style new text gets: the last one used, as in Animate. #[derive(Clone, Debug, PartialEq)] pub struct TextStyle { pub font: String, @@ -36,12 +44,18 @@ impl Default for TextStyle { } } +const CHAR_KEYS: &str = "font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? (\"\": none)"; +const PARA_KEYS: &str = "align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px)"; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + let leak = |s: String| -> &'static str { Box::leak(s.into_boxed_str()) }; vec![ - c("text.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), - c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), + c("text.create", "New Text", "", None, leak(format!("{{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), width?, {CHAR_KEYS}, {PARA_KEYS}, runs?: [{{chars, …character keys}}] (styles of the text's characters in order; unset keys take the style above), paragraphs?: [{{…paragraph keys}}] (one per line of the text)}} (ADR 0085)")), true, create as crate::RunFn), + c("text.edit", "Edit Text", "", None, leak(format!("{{text? (the runs follow the change: typed characters continue the style before them), runs?, paragraphs? (as text.create: replace the styles), width? (px, wraps; null: one line per paragraph), {CHAR_KEYS} (every character), {PARA_KEYS} (every paragraph)}} on the selected text")), true, |s, p| s.each_layer(false, |s| edit(s, p))), + c("text.style", "Text Character Style", "", None, leak(format!("{{start?, end? (characters; default: all), {CHAR_KEYS}}} styles those characters of the selected text, splitting and joining its runs (ADR 0085)")), true, |s, p| s.each_layer(false, |s| style_range(s, p))), + c("text.paragraph", "Text Paragraph Style", "", None, leak(format!("{{start?, end? (characters; default: all), {PARA_KEYS}}} sets the layout of the paragraphs those characters touch in the selected text (ADR 0085)")), true, |s, p| s.each_layer(false, |s| paragraph_range(s, p))), + c("text.styles", "Text Styles", "", None, "{start?, end? (characters; default: all)} of the first selected text: its runs, paragraphs, and what those characters share (a mixed value is null) (ADR 0085)", false, styles_of), c("text.fonts", "Fonts", "", None, "{}", false, fonts), c( "text.attach_path", @@ -58,13 +72,13 @@ pub fn specs() -> Vec { ] } -fn align_param(p: &Value) -> Result> { - Ok(match opt_str(p, "align")? { +fn align_of(p: &Value, key: &str) -> Result> { + Ok(match opt_str(p, key)? { None => None, Some("left") => Some(TextAlign::Left), Some("center" | "centre") => Some(TextAlign::Center), Some("right") => Some(TextAlign::Right), - Some(other) => return Err(EngineError::Param(format!("'align' is left, center or right, not '{other}'"))), + Some(other) => return Err(EngineError::Param(format!("'{key}' is left, center or right, not '{other}'"))), }) } @@ -80,102 +94,284 @@ fn width_param(p: &Value, current: Option) -> Result> { } } -/// The style in `p` over `base`. -fn style_param(p: &Value, base: &TextStyle) -> Result { - let size = opt_f32(p, "size")?.unwrap_or(base.size); - if !(1.0..=2000.0).contains(&size) { - return Err(EngineError::Param("'size' must be between 1 and 2000 px".into())); +fn ranged(p: &Value, key: &str, lo: f32, hi: f32) -> Result> { + match opt_f32(p, key)? { + Some(v) if !(lo..=hi).contains(&v) => Err(EngineError::Param(format!("'{key}' must be between {lo} and {hi} px"))), + v => Ok(v), } - let spacing = |key: &str, d: f32| -> Result { - let v = opt_f32(p, key)?.unwrap_or(d); - if (-1000.0..=1000.0).contains(&v) { Ok(v) } else { Err(EngineError::Param(format!("'{key}' must be between -1000 and 1000 px"))) } - }; - Ok(TextStyle { - font: opt_str(p, "font")?.map_or_else(|| base.font.clone(), |f| f.chars().take(256).collect()), - size, - bold: opt_bool(p, "bold")?.unwrap_or(base.bold), - italic: opt_bool(p, "italic")?.unwrap_or(base.italic), - color: opt_color(p, "color")?.unwrap_or(base.color), - align: align_param(p)?.unwrap_or(base.align), - letter_spacing: spacing("letter_spacing", base.letter_spacing)?, - line_spacing: spacing("line_spacing", base.line_spacing)?, - }) } -/// Lays a block out with this computer's fonts. Also says when the family asked for isn't -/// installed and another was used. -pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option)> { +/// Character style keys in a command's params: each one given changes that attribute only. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharPatch { + pub font: Option, + pub size: Option, + pub bold: Option, + pub italic: Option, + pub color: Option, + pub letter_spacing: Option, + pub shift: Option, + pub underline: Option, + pub url: Option, +} + +impl CharPatch { + pub fn parse(p: &Value) -> Result { + let shift = opt_str(p, "shift")?.map(|k| BaselineShift::from_key(k).ok_or_else(|| EngineError::Param(format!("'shift' is normal, superscript or subscript, not '{k}'")))).transpose()?; + let url = match opt_str(p, "url")? { + None => None, + Some(u) if u.chars().count() > MAX_URL => return Err(EngineError::Param(format!("'url' is at most {MAX_URL} characters"))), + Some(u) => Some(rt::safe_url(u).ok_or_else(|| EngineError::Param("'url' can't run script (javascript:, vbscript: and data: links aren't allowed)".into()))?), + }; + Ok(CharPatch { + font: opt_str(p, "font")?.map(|f| f.chars().take(256).collect()), + size: ranged(p, "size", 1.0, 2000.0)?, + bold: opt_bool(p, "bold")?, + italic: opt_bool(p, "italic")?, + color: opt_color(p, "color")?, + letter_spacing: ranged(p, "letter_spacing", -1000.0, 1000.0)?, + shift, + underline: opt_bool(p, "underline")?, + url, + }) + } + pub fn is_empty(&self) -> bool { + *self == CharPatch::default() + } + pub fn apply(&self, s: &mut CharStyle) { + if let Some(v) = &self.font { + s.font.clone_from(v); + } + if let Some(v) = self.size { + s.size = v; + } + if let Some(v) = self.bold { + s.bold = v; + } + if let Some(v) = self.italic { + s.italic = v; + } + if let Some(v) = self.color { + s.color = v; + } + if let Some(v) = self.letter_spacing { + s.letter_spacing = v; + } + if let Some(v) = self.shift { + s.shift = v; + } + if let Some(v) = self.underline { + s.underline = v; + } + if let Some(v) = &self.url { + s.url.clone_from(v); + } + } +} + +/// Paragraph style keys in a command's params. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParaPatch { + pub align: Option, + pub indent: Option, + pub left_margin: Option, + pub right_margin: Option, + pub line_spacing: Option, +} + +impl ParaPatch { + pub fn parse(p: &Value) -> Result { + Ok(ParaPatch { + align: align_of(p, "align")?, + indent: ranged(p, "indent", -1000.0, 1000.0)?, + left_margin: ranged(p, "left_margin", 0.0, 1000.0)?, + right_margin: ranged(p, "right_margin", 0.0, 1000.0)?, + line_spacing: ranged(p, "line_spacing", -1000.0, 1000.0)?, + }) + } + pub fn is_empty(&self) -> bool { + *self == ParaPatch::default() + } + pub fn apply(&self, s: &mut ParagraphStyle) { + s.align = self.align.unwrap_or(s.align); + s.indent = self.indent.unwrap_or(s.indent); + s.left_margin = self.left_margin.unwrap_or(s.left_margin); + s.right_margin = self.right_margin.unwrap_or(s.right_margin); + s.line_spacing = self.line_spacing.unwrap_or(s.line_spacing); + } +} + +/// `runs: [{chars, …character keys}]` over `base` (unset keys take it), at most +/// [`MAX_TEXT_RUNS`] of them. +fn runs_param(p: &Value, base: &CharStyle) -> Result>> { + let Some(v) = p.get("runs").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = v.as_array().ok_or_else(|| EngineError::Param("'runs' must be a list of {chars, …style}".into()))?; + if list.len() > MAX_TEXT_RUNS { + return Err(EngineError::Param(format!("'runs' has at most {MAX_TEXT_RUNS} runs"))); + } + let mut out = Vec::with_capacity(list.len()); + for r in list { + let chars = opt_u32(r, "chars")?.ok_or_else(|| EngineError::Param("each run needs 'chars' (how many characters it styles)".into()))?; + let mut style = base.clone(); + CharPatch::parse(r)?.apply(&mut style); + out.push(TextRun { chars, style }); + } + Ok(Some(out)) +} + +/// `paragraphs: [{…paragraph keys}]` over `base`. +fn paragraphs_param(p: &Value, base: &ParagraphStyle) -> Result>> { + let Some(v) = p.get("paragraphs").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = v.as_array().ok_or_else(|| EngineError::Param("'paragraphs' must be a list of {align?, indent?, …}".into()))?; + if list.len() > anicraft_text::MAX_CHARS + 1 { + return Err(EngineError::Param("'paragraphs' has more entries than a block has lines".into())); + } + list.iter() + .map(|q| { + let mut s = *base; + ParaPatch::parse(q)?.apply(&mut s); + Ok(s) + }) + .collect::>>() + .map(Some) +} + +/// `start`, `end` (characters, default the whole text), clamped to `n`. +fn range_param(p: &Value, n: u32) -> Result<(u32, u32)> { + let start = opt_u32(p, "start")?.unwrap_or(0).min(n); + let end = opt_u32(p, "end")?.unwrap_or(n).min(n); + if end < start { + return Err(EngineError::Param("'end' comes before 'start'".into())); + } + Ok((start, end)) +} + +fn align_text(a: TextAlign) -> Align { + match a { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + } +} + +/// `d`'s runs and paragraphs as the text engine takes them, and the paints (colour, link) the +/// runs' `paint` numbers stand for. +fn rich_parts(d: &TextBlock) -> (Vec, Vec, Vec<(Rgba, String)>) { + let mut paints: Vec<(Rgba, String)> = Vec::new(); + let runs = d + .styled_runs() + .into_iter() + .map(|r| { + let key = (r.style.color, r.style.url.clone()); + let paint = match paints.iter().position(|k| *k == key) { + Some(i) => i, + None => { + paints.push(key); + paints.len() - 1 + } + } as u32; + let shift = match r.style.shift { + BaselineShift::Normal => anicraft_text::Shift::Normal, + BaselineShift::Superscript => anicraft_text::Shift::Superscript, + BaselineShift::Subscript => anicraft_text::Shift::Subscript, + }; + anicraft_text::Run { + chars: r.chars as usize, + style: anicraft_text::RunStyle { family: r.style.font, size: r.style.size, bold: r.style.bold, italic: r.style.italic, letter_spacing: r.style.letter_spacing, shift, underline: r.style.underline, paint }, + } + }) + .collect(); + let paras = d + .paragraph_styles() + .into_iter() + .map(|p| anicraft_text::ParaStyle { align: align_text(p.align), indent: p.indent, left_margin: p.left_margin, right_margin: p.right_margin, line_spacing: p.line_spacing }) + .collect(); + (runs, paras, paints) +} + +/// The block with its outline from laid-out pieces and its runs' fonts the families actually +/// used; with a note when a family asked for isn't installed. +fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, families: &[String], paints: &[(Rgba, String)]) -> (TextBlock, Option) { + let mut note = None; + let mut runs = d.styled_runs(); + for (r, used) in runs.iter_mut().zip(families) { + let asked = r.style.font.trim(); + if note.is_none() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) { + note = Some(format!("“{asked}” isn't installed on this computer; used {used}")); + } + r.style.font.clone_from(used); + } + let paras = d.paragraph_styles(); + d.set_styles(runs, paras); + let pieces = pieces.into_iter().map(|(k, p)| paints.get(k as usize).map_or((d.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p))).collect(); + d.set_outline(pieces); + (d, note) +} + +fn layout_err(e: anicraft_text::TextError) -> EngineError { + EngineError::State(format!("can't lay out text: {e}")) +} + +/// Lays out a block from its text, runs, paragraphs and width, as static text, a field (in its +/// box) or text on a path, with the fonts on this computer. Returns the laid-out block, a note +/// when a family wasn't installed, and (text on a path) where the block's origin moved to, +/// which the element's transform must move by for nothing to move (`transform × +/// translate(shift)`; zero otherwise). +pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option, Vec2)> { let fonts = Fonts::get(); - let layout = fonts - .layout( - text, - &anicraft_text::Style { - family: style.font.clone(), - size: style.size, - bold: style.bold, - italic: style.italic, - align: match style.align { - TextAlign::Left => Align::Left, - TextAlign::Center => Align::Center, - TextAlign::Right => Align::Right, - }, - letter_spacing: style.letter_spacing, - line_spacing: style.line_spacing, - width, - }, - ) - .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); - let block = TextBlock { - text: text.to_string(), - font: layout.family, - size: style.size, - bold: style.bold, - italic: style.italic, - color: style.color, - align: style.align, - letter_spacing: style.letter_spacing, - line_spacing: style.line_spacing, - width, - outline: Arc::new(layout.outline), - box_width: layout.width, - box_height: layout.height, - field: None, - on_path: None, - }; - Ok((block, note)) + let mut d = d.clone(); + let (runs, paras, paints) = rich_parts(&d); + match (d.field.clone(), d.on_path.clone()) { + (_, Some(on)) => { + // One line along the path (line breaks become spaces), anchored by the alignment. + let line: String = d.text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + let l = fonts.layout_rich(&anicraft_text::RichText { text: &line, runs: &runs, paragraphs: &[anicraft_text::ParaStyle::default()], width: None }, true).map_err(layout_err)?; + let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; + let set = anicraft_text::on_path_boxed(&l.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align: align_text(d.align) }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; + d.width = None; + d.field = None; + d.box_width = set.width; + d.box_height = set.height; + d.on_path = Some(TextPath { path: set.path, offset, flip: on.flip }); + let shift = set.shift; + let (b, n) = finish(d, set.pieces, &l.families, &paints); + Ok((b, n, shift)) + } + (Some(f), None) => { + d.text = d.text.chars().take(MAX_FIELD_CHARS).collect(); + let (runs, paras, paints) = rich_parts(&d); + let shown = f.shown(&d.text); + let l = field_lay(fonts, &anicraft_text::RichText { text: &shown, runs: &runs, paragraphs: ¶s, width: f.wrap_width(d.box_width) }, d.align, &f, d.box_width).map_err(layout_err)?; + d.width = f.wrap_width(d.box_width); + let (b, n) = finish(d, l.pieces, &l.families, &paints); + Ok((b, n, Vec2::ZERO)) + } + (None, None) => { + let l = fonts.layout_rich(&anicraft_text::RichText { text: &d.text, runs: &runs, paragraphs: ¶s, width: d.width }, false).map_err(layout_err)?; + d.box_width = l.width; + d.box_height = l.height; + let (b, n) = finish(d, l.pieces, &l.families, &paints); + Ok((b, n, Vec2::ZERO)) + } + } } -/// A field's text laid out (ADR 0066): `shown` in the block's style, wrapped at the box less its -/// gutters when it is multiline, aligned in the box, with the outline moved into the gutter. -/// The carets are from the text's left edge (the alignment applied, not the gutter). -pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result { - let wrap = field.wrap_width(box_width); - let mut l = fonts.layout( - shown, - &anicraft_text::Style { - family: style.font.clone(), - size: style.size, - bold: style.bold, - italic: style.italic, - align: match style.align { - TextAlign::Left => Align::Left, - TextAlign::Center => Align::Center, - TextAlign::Right => Align::Right, - }, - letter_spacing: style.letter_spacing, - line_spacing: style.line_spacing, - width: wrap, - }, - )?; - // Lines that don't wrap align against the widest; the widest aligns in the box. +/// A field's rich text laid out in its box (ADR 0066): wrapped at the box less its gutters +/// when multiline, the widest line aligned in the box when it doesn't wrap, and the outline +/// (and its pieces) moved into the gutter. The carets are from the text's left edge. +fn field_lay(fonts: &Fonts, rich: &anicraft_text::RichText, align: TextAlign, field: &TextField, box_width: f32) -> std::result::Result { + let mut l = fonts.layout_rich(rich, false)?; let inner = (box_width - 2.0 * FIELD_GUTTER).max(0.0); - let shift = match (wrap, style.align) { + let shift = match (field.wrap_width(box_width), align) { (Some(_), _) | (None, TextAlign::Left) => 0.0, (None, TextAlign::Center) => ((inner - l.width) * 0.5).max(0.0), (None, TextAlign::Right) => (inner - l.width).max(0.0), }; - l.outline = l.outline.transformed(&Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER)); + let to = Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER); + l.outline = l.outline.transformed(&to); + for (_, p) in &mut l.pieces { + *p = p.transformed(&to); + } if shift != 0.0 { for line in &mut l.carets { for s in &mut line.stops { @@ -187,89 +383,46 @@ pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_wid Ok(l) } -/// A field block for `text`: laid out in its box (`box_width` × `box_height`). -pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, box_width: f32, box_height: f32) -> Result<(TextBlock, Option)> { - let fonts = Fonts::get(); - let text: String = text.chars().take(MAX_FIELD_CHARS).collect(); - let l = field_layout(fonts, style, field, box_width, &field.shown(&text)).map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !l.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), l.family)); - let block = TextBlock { - text, - font: l.family, - size: style.size, - bold: style.bold, - italic: style.italic, - color: style.color, - align: style.align, - letter_spacing: style.letter_spacing, - line_spacing: style.line_spacing, - width: field.wrap_width(box_width), - outline: Arc::new(l.outline), - box_width, - box_height, - field: Some(field.clone()), - on_path: None, - }; - Ok((block, note)) +/// A field's text laid out in one style, as the player lays out text a script set or a viewer +/// typed (ADR 0066). +pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result { + let run = anicraft_text::Run { chars: usize::MAX, style: anicraft_text::RunStyle { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, letter_spacing: style.letter_spacing, ..anicraft_text::RunStyle::default() } }; + let para = anicraft_text::ParaStyle { align: align_text(style.align), line_spacing: style.line_spacing, ..anicraft_text::ParaStyle::default() }; + field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &[run], paragraphs: &[para], width: field.wrap_width(box_width) }, style.align, field, box_width) } -/// Text on a path (ADR 0070): `text` on one line (line breaks become spaces) set along `on`'s -/// path. The block's space is moved so its box (the path and the glyphs together) starts at -/// the origin, as every text box does: the second value is where that origin was, which the -/// element's transform must move by (`transform × translate(shift)`) for nothing to move. -pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> Result<(TextBlock, Option, Vec2)> { - let fonts = Fonts::get(); - let line: String = text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); - let layout = fonts - .layout_glyphs(&line, &anicraft_text::Style { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, align: Align::Left, letter_spacing: style.letter_spacing, line_spacing: 0.0, width: None }) - .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); - let align = match style.align { - TextAlign::Left => Align::Left, - TextAlign::Center => Align::Center, - TextAlign::Right => Align::Right, - }; - let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; - let set = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; - let shift = set.shift; - let block = TextBlock { - text: text.to_string(), - font: layout.family, - size: style.size, - bold: style.bold, - italic: style.italic, - color: style.color, - align: style.align, - letter_spacing: style.letter_spacing, - line_spacing: style.line_spacing, - width: None, - outline: Arc::new(set.outline), - box_width: set.width, - box_height: set.height, - field: None, - on_path: Some(TextPath { path: set.path, offset, flip: on.flip }), - }; - Ok((block, note, shift)) -} - -/// The block `t` with new text or style: a field keeps its box (or takes `width` as its new -/// width); static text wraps at `width`; text on a path stays on it. With where the block's -/// origin moved to ([`lay_out_on_path`]; zero for the others). -pub(crate) fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option, Vec2)> { - match (&t.field, &t.on_path) { - (_, Some(on)) => lay_out_on_path(text, style, on), - (Some(f), None) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height).map(|(b, n)| (b, n, Vec2::ZERO)), - (None, None) => lay_out(text, style, width).map(|(b, n)| (b, n, Vec2::ZERO)), +/// `t` with its text changed to `text`, its runs and paragraphs following the change (one +/// edit: what was typed continues the style before it). +pub(crate) fn retext(t: &TextBlock, text: &str) -> TextBlock { + let mut d = t.clone(); + if d.text == text { + return d; } + let (start, old_end, new_end) = rt::diff_chars(&t.text, text); + let runs = rt::type_into_runs(&t.styled_runs(), start, old_end, new_end - start); + let inserted: String = text.chars().skip(start as usize).take((new_end - start) as usize).collect(); + let paras = rt::edit_paragraphs(&t.paragraph_styles(), &t.text, start, old_end, &inserted); + d.text = text.to_string(); + d.set_styles(runs, paras); + d } -/// What Find and Replace lays text out with: as before (static text, its fields' boxes -/// dropped), except that text on a path stays on its path. -pub(crate) fn relay_static(t: &TextBlock, text: &str, style: &TextStyle) -> Result<(TextBlock, Option, Vec2)> { - match &t.on_path { - Some(on) => lay_out_on_path(text, style, on), - None => lay_out(text, style, t.width).map(|(b, n)| (b, n, Vec2::ZERO)), - } +/// What Find and Replace lays text out with: the runs following the change, as static text +/// (its fields' boxes dropped), except that text on a path stays on its path. +pub(crate) fn relay_static(t: &TextBlock, text: &str) -> Result<(TextBlock, Option, Vec2)> { + let mut d = retext(t, text); + d.field = None; + lay_out_block(&d) +} + +/// `t` with every run's font set to `family`, laid out as [`relay_static`] does. +pub(crate) fn refont_static(t: &TextBlock, family: &str) -> Result<(TextBlock, Option, Vec2)> { + let mut d = t.clone(); + let runs = rt::restyle_runs(&t.styled_runs(), 0, t.char_count(), |s| s.font = family.to_string()); + let paras = d.paragraph_styles(); + d.set_styles(runs, paras); + d.field = None; + lay_out_block(&d) } /// The selected static text, along a copy of a shape's outline (ADR 0070). @@ -326,13 +479,12 @@ fn attach_path(s: &mut Session, p: &Value) -> Result { continue; } let ElementKind::Text(t) = &e.kind else { continue }; - let style = style_of(t); let offset = offset.unwrap_or(match t.align { TextAlign::Left => 0.0, TextAlign::Center => length * 0.5, TextAlign::Right => length, }); - let (block, note, shift) = lay_out_on_path(&t.text, &style, &TextPath { path: first.clone(), offset, flip })?; + let (block, note, shift) = lay_out_block(&TextBlock { field: None, width: None, on_path: Some(TextPath { path: first.clone(), offset, flip }), ..(**t).clone() })?; // The path is in stage space; the text's new space is the path's, moved to its box. e.transform = Affine::translate(shift.x, shift.y); out = json!({"element": e.id.0, "length": length, "offset": offset, "flip": flip, "note": note}); @@ -354,17 +506,16 @@ fn set_path(s: &mut Session, p: &Value) -> Result { for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; let Some(on) = &t.on_path else { continue }; - let style = style_of(t); if release { // Back to a line of text, its box where the text started along the path. let start = t.outline.bounds(); - let (block, _) = lay_out(&t.text, &style, None)?; + let (block, _, _) = lay_out_block(&TextBlock { on_path: None, width: None, ..(**t).clone() })?; let at = if start.min.x.is_finite() { start.min } else { Vec2::ZERO }; e.transform = e.transform.mul(&Affine::translate(at.x, at.y)); e.kind = ElementKind::Text(Arc::new(block)); } else { let on = TextPath { offset: offset.unwrap_or(on.offset), flip: flip.unwrap_or(on.flip), ..on.clone() }; - let (block, _, shift) = lay_out_on_path(&t.text, &style, &on)?; + let (block, _, shift) = lay_out_block(&TextBlock { on_path: Some(on), ..(**t).clone() })?; e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); e.kind = ElementKind::Text(Arc::new(block)); } @@ -411,7 +562,6 @@ fn set_field(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State("text on a path is static text (release it from the path first)".into())); } let to = kind.unwrap_or(t.kind()); - let style = style_of(t); let (block, note) = if to == TextKind::Static { if t.field.is_none() { continue; @@ -419,7 +569,8 @@ fn set_field(s: &mut Session, p: &Value) -> Result { // Back to static text: laid out as before fields, the words where they were. e.transform = e.transform.mul(&Affine::translate(FIELD_GUTTER, FIELD_GUTTER)); e.name.clear(); - lay_out(&t.text, &style, t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)))? + let (b, n, _) = lay_out_block(&TextBlock { field: None, width: t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)), ..(**t).clone() })?; + (b, n) } else { let (bw, bh) = if t.field.is_some() { (t.box_width, t.box_height) } else { field_box(t) }; // Wrapped text becomes a multiline field, text with line breaks a multiline one @@ -455,7 +606,8 @@ fn set_field(s: &mut Session, p: &Value) -> Result { if let Some(v) = &variable { f.variable.clone_from(v); } - lay_out_field(&t.text, &style, &f.sanitized(), width.unwrap_or(bw), height.unwrap_or(bh))? + let (b, n, _) = lay_out_block(&TextBlock { field: Some(f.sanitized()), box_width: width.unwrap_or(bw), box_height: height.unwrap_or(bh), ..(**t).clone() })?; + (b, n) }; notes.extend(note); e.kind = ElementKind::Text(Arc::new(block)); @@ -468,8 +620,19 @@ fn set_field(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": changed, "note": notes.first()})) } -pub(crate) fn style_of(t: &TextBlock) -> TextStyle { - TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } + +/// The style a block starts with: `base`, with the params' character and paragraph keys. +fn new_style(p: &Value, base: &TextStyle) -> Result<(CharStyle, ParagraphStyle)> { + let mut c = CharStyle { font: base.font.clone(), size: base.size, bold: base.bold, italic: base.italic, color: base.color, letter_spacing: base.letter_spacing, ..CharStyle::default() }; + CharPatch::parse(p)?.apply(&mut c); + let mut q = ParagraphStyle { align: base.align, line_spacing: base.line_spacing, ..ParagraphStyle::default() }; + ParaPatch::parse(p)?.apply(&mut q); + Ok((c, q)) +} + +/// The last style used, from a block (what new text gets next). +fn remember(s: &mut Session, b: &TextBlock) { + s.text_style = TextStyle { font: b.font.clone(), size: b.size, bold: b.bold, italic: b.italic, color: b.color, align: b.align, letter_spacing: b.letter_spacing, line_spacing: b.line_spacing }; } fn create(s: &mut Session, p: &Value) -> Result { @@ -479,65 +642,243 @@ fn create(s: &mut Session, p: &Value) -> Result { if text.trim().is_empty() && kind == TextKind::Static { return Err(EngineError::Param("'text' is empty".into())); } - let style = style_param(p, &s.text_style)?; + if text.chars().count() > anicraft_text::MAX_CHARS { + return Err(EngineError::Param(format!("text is limited to {} characters per block", anicraft_text::MAX_CHARS))); + } + let (cs, ps) = new_style(p, &s.text_style)?; let width = width_param(p, None)?; - let (block, note) = lay_out(&text, &style, width)?; + let mut d = TextBlock { text: text.clone(), width, ..TextBlock::default() }; + let runs = runs_param(p, &cs)?.unwrap_or_else(|| vec![TextRun { chars: u32::MAX, style: cs.clone() }]); + let paras = paragraphs_param(p, &ps)?.unwrap_or_else(|| vec![ps]); + d.set_styles(runs, paras); + let (block, note, _) = lay_out_block(&d)?; let (block, note) = if kind == TextKind::Static { (block, note) } else { let (bw, bh) = field_box(&block); - let f = TextField { lines: if width.is_some() { LineType::Multiline } else if text.contains('\n') { LineType::MultilineNoWrap } else { LineType::Single }, ..TextField::new(kind) }; - lay_out_field(&text, &style, &f, bw, bh)? + let lines = if width.is_some() { + LineType::Multiline + } else if text.contains('\n') { + LineType::MultilineNoWrap + } else { + LineType::Single + }; + let f = TextField { lines, ..TextField::new(kind) }; + let (b, n, _) = lay_out_block(&TextBlock { field: Some(f), box_width: bw, box_height: bh, ..block })?; + (b, n) }; let x = opt_f32(p, "x")?.unwrap_or((s.doc.stage.width as f32 - block.box_width) * 0.5); let y = opt_f32(p, "y")?.unwrap_or((s.doc.stage.height as f32 - block.box_height) * 0.5); let id = ElementId(s.doc.alloc_id()); - let out = json!({"element": id.0, "font": block.font, "width": block.box_width, "height": block.box_height, "note": note}); - s.text_style = TextStyle { font: block.font.clone(), ..style }; + let out = json!({"element": id.0, "font": block.font, "width": block.box_width, "height": block.box_height, "runs": block.runs.len().max(1), "note": note}); + remember(s, &block); let el = Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }; s.editable_keyframe()?.elements.push(Arc::new(el)); s.select_only([id]); Ok(out) } +/// Lays `d` out where `e` stands (text on a path keeps its place) and puts it in. +fn put(e: &mut Element, d: &TextBlock) -> Result<(TextBlock, Option)> { + let (block, note, shift) = lay_out_block(d)?; + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); + e.kind = ElementKind::Text(Arc::new(block.clone())); + Ok((block, note)) +} + fn edit(s: &mut Session, p: &Value) -> Result { let new_text = opt_str(p, "text")?.map(str::to_string); + if new_text.as_ref().is_some_and(|t| t.chars().count() > anicraft_text::MAX_CHARS) { + return Err(EngineError::Param(format!("text is limited to {} characters per block", anicraft_text::MAX_CHARS))); + } + let (cp, pp) = (CharPatch::parse(p)?, ParaPatch::parse(p)?); let mut notes = Vec::new(); let mut edited = 0; - let mut last_style = None; + let mut last = None; for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; - let style = style_param(p, &style_of(t))?; let text = new_text.clone().unwrap_or_else(|| t.text.clone()); // Fields may be empty (a script or the viewer fills them); static text may not. if text.trim().is_empty() && t.field.is_none() { return Err(EngineError::Param("'text' is empty (delete the text instead)".into())); } - let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? }; - let (block, note, shift) = relay(t, &text, &style, width)?; + // The text changed: the runs follow; then new runs and paragraphs, if given. + let mut d = retext(t, &text); + let runs = runs_param(p, &d.char_style())?.unwrap_or_else(|| d.styled_runs()); + let paras = paragraphs_param(p, &d.para_style())?.unwrap_or_else(|| d.paragraph_styles()); + // Style keys apply to every character and paragraph. + let n = d.char_count(); + let runs = if cp.is_empty() { runs } else { rt::restyle_runs(&runs, 0, n, |st| cp.apply(st)) }; + let paras: Vec = paras + .into_iter() + .map(|mut q| { + pp.apply(&mut q); + q + }) + .collect(); + d.set_styles(runs, paras); + if t.field.is_some() { + d.box_width = width_param(p, Some(t.box_width))?.unwrap_or(t.box_width).max(1.0); + } else { + d.width = width_param(p, t.width)?; + } + let (block, note) = put(e, &d)?; notes.extend(note); - last_style = Some(TextStyle { font: block.font.clone(), ..style }); - e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); - e.kind = ElementKind::Text(Arc::new(block)); + last = Some(block); edited += 1; } if edited == 0 { return Err(EngineError::State("the selection has no text".into())); } - if let Some(st) = last_style { - s.text_style = st; + if let Some(b) = last { + remember(s, &b); } notes.dedup(); Ok(json!({"edited": edited, "note": notes.first()})) } +/// `text.style`: characters `start..end` of the selected text restyled. +fn style_range(s: &mut Session, p: &Value) -> Result { + let cp = CharPatch::parse(p)?; + if cp.is_empty() { + return Err(EngineError::Param(format!("give a style to set: {CHAR_KEYS}"))); + } + let mut changed = 0; + let mut notes = Vec::new(); + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let (start, end) = range_param(p, t.char_count())?; + let mut d = (**t).clone(); + let runs = rt::restyle_runs(&t.styled_runs(), start, end, |st| cp.apply(st)); + d.set_styles(runs, t.paragraph_styles()); + let (_, note) = put(e, &d)?; + notes.extend(note); + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text".into())); + } + Ok(json!({"changed": changed, "note": notes.first()})) +} + +/// `text.paragraph`: the paragraphs characters `start..end` touch, laid out anew. +fn paragraph_range(s: &mut Session, p: &Value) -> Result { + let pp = ParaPatch::parse(p)?; + if pp.is_empty() { + return Err(EngineError::Param(format!("give a paragraph setting: {PARA_KEYS}"))); + } + let mut changed = 0; + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let (start, end) = range_param(p, t.char_count())?; + let range = rt::paragraphs_in(&t.text, start, end); + let mut paras = t.paragraph_styles(); + for (i, q) in paras.iter_mut().enumerate() { + if range.contains(&i) { + pp.apply(q); + } + } + let mut d = (**t).clone(); + d.set_styles(t.styled_runs(), paras); + put(e, &d)?; + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text".into())); + } + Ok(json!({"changed": changed})) +} + +fn hex_of(c: Rgba) -> String { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b)) +} + +fn style_json(c: &CharStyle) -> Value { + json!({"font": c.font, "size": c.size, "bold": c.bold, "italic": c.italic, "color": hex_of(c.color), "letter_spacing": c.letter_spacing, "shift": c.shift.key(), "underline": c.underline, "url": c.url}) +} + +fn align_key(a: TextAlign) -> &'static str { + match a { + TextAlign::Left => "left", + TextAlign::Center => "center", + TextAlign::Right => "right", + } +} + +fn para_json(q: &ParagraphStyle) -> Value { + json!({"align": align_key(q.align), "indent": q.indent, "left_margin": q.left_margin, "right_margin": q.right_margin, "line_spacing": q.line_spacing}) +} + +/// What a summary shares (a mixed attribute is `null`). +pub fn summary_json(m: &StyleSummary) -> Value { + json!({ + "font": m.font, "size": m.size, "bold": m.bold, "italic": m.italic, "color": m.color.map(hex_of), + "letter_spacing": m.letter_spacing, "shift": m.shift.map(BaselineShift::key), "underline": m.underline, "url": m.url, + }) +} + +/// `text.styles`: the first selected text's runs, paragraphs, and what a range shares. +fn styles_of(s: &mut Session, p: &Value) -> Result { + let t = s + .selected_elements() + .into_iter() + .find_map(|(_, e)| match &e.kind { + ElementKind::Text(t) => Some(t.clone()), + _ => None, + }) + .ok_or_else(|| EngineError::State("select a text block".into()))?; + let (start, end) = range_param(p, t.char_count())?; + let runs: Vec = t + .styled_runs() + .iter() + .map(|r| { + let mut v = style_json(&r.style); + v["chars"] = json!(r.chars); + v + }) + .collect(); + let range = rt::paragraphs_in(&t.text, start, end); + let paras = t.paragraph_styles(); + let shared = |f: &dyn Fn(&ParagraphStyle) -> Value| -> Value { + let mut it = paras.iter().enumerate().filter(|(i, _)| range.contains(i)).map(|(_, q)| f(q)); + let first = it.next().unwrap_or(Value::Null); + if it.all(|v| v == first) { first } else { Value::Null } + }; + let paragraph = json!({ + "align": shared(&|q| json!(align_key(q.align))), + "indent": shared(&|q| json!(q.indent)), + "left_margin": shared(&|q| json!(q.left_margin)), + "right_margin": shared(&|q| json!(q.right_margin)), + "line_spacing": shared(&|q| json!(q.line_spacing)), + }); + Ok(json!({ + "text": t.text, + "runs": runs, + "paragraphs": paras.iter().map(para_json).collect::>(), + "start": start, + "end": end, + "selection": summary_json(&rt::summarize(&t.styled_runs(), start, end)), + "paragraph": paragraph, + })) +} + fn fonts(_: &mut Session, _: &Value) -> Result { let f = Fonts::get(); Ok(json!({"families": f.families(), "default": f.resolve("")})) } -/// A text block as a plain shape with the same outlines (Break Apart). -pub(crate) fn to_shape(t: &TextBlock) -> anicraft_doc::Shape { - let path: Arc = t.outline.clone(); - anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None } +/// A text block as plain shapes with the same outlines, one per colour (Break Apart). +pub(crate) fn to_shapes(t: &TextBlock) -> Vec { + t.fill_paths() + .into_iter() + .filter(|(_, _, p)| !p.cmds.is_empty() || t.fills.is_empty()) + .map(|(color, _, path)| anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None }) + .collect() +} + +/// The one style a block's runtime text is laid out in (its first run's), for fields a script +/// or the viewer changes (ADR 0066). +pub(crate) fn style_of(t: &TextBlock) -> TextStyle { + TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } } diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index ea2402e2..b8cc70a1 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -116,6 +116,25 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } + // Saved commands are files in your preferences (ADR 0097). + "macro.save" => { + let path = crate::cmds_macro::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the command")) + } + "macro.import" => { + let path = crate::cmds_macro::import_target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Adding the command")) + } + "macro.delete" => { + let path = crate::cmds_macro::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::vfs::is_file(&path).then(|| Confirmation { + title: "Delete saved command?".into(), + message: format!("The saved command “{name}” will be deleted from your commands. This cannot be undone."), + action: "Delete Command".into(), + irreversible: true, + }) + } // Brushes of your own live in your preferences, outside undo (ADR 0068). "brush.preset_delete" => { let name = p.get("name").and_then(Value::as_str)?; diff --git a/crates/engine/src/find.rs b/crates/engine/src/find.rs index ce601a20..e84ea069 100644 --- a/crates/engine/src/find.rs +++ b/crates/engine/src/find.rs @@ -891,7 +891,7 @@ fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With t.note("a text field can't be left empty (delete it instead)".into()); } else { // Laid out again as it is: text on a path stays on it (ADR 0070). - let (block, note, shift) = crate::cmds_text::relay_static(tb, &n, &crate::cmds_text::style_of(tb))?; + let (block, note, shift) = crate::cmds_text::relay_static(tb, &n)?; t.note_opt(note); *tb = Arc::new(block); e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); @@ -900,16 +900,23 @@ fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With } } (Field::Font, ElementKind::Text(tb), With::Font(family)) => { - let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) }; - let (block, note, shift) = crate::cmds_text::relay_static(tb, &tb.text, &style)?; + let (block, note, shift) = crate::cmds_text::refont_static(tb, family)?; t.note_opt(note); *tb = Arc::new(block); e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); t.replaced += 1; } (Field::TextColor, ElementKind::Text(tb), With::Color(c)) => { + // Every run and colour piece takes the colour, keeping its own opacity (ADR 0085). let tb = Arc::make_mut(tb); - tb.color = Rgba { a: tb.color.a, ..*c }; + let n = tb.char_count(); + let runs = anicraft_doc::rich_text::restyle_runs(&tb.styled_runs(), 0, n, |st| st.color = Rgba { a: st.color.a, ..*c }); + let paras = tb.paragraph_styles(); + tb.set_styles(runs, paras); + for f in &mut tb.fills { + f.color = Rgba { a: f.color.a, ..*c }; + } + tb.fill_cache = Default::default(); t.replaced += 1; } (Field::Fill | Field::Stroke, ElementKind::Shape(sh), With::Color(c)) => { diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs index 609a93d1..543f0fc5 100644 --- a/crates/engine/src/find_tests.rs +++ b/crates/engine/src/find_tests.rs @@ -38,7 +38,7 @@ impl Build { self.doc.alloc_id() } pub fn text(&mut self, t: &str, color: Rgba) -> Element { - let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None }; + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None, ..Default::default() }; Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } } pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { diff --git a/crates/engine/src/format.rs b/crates/engine/src/format.rs index dbf51dfa..084e65d2 100644 --- a/crates/engine/src/format.rs +++ b/crates/engine/src/format.rs @@ -92,9 +92,13 @@ pub fn load(path: &std::path::Path) -> Result { pub fn save(doc: &Document, path: &std::path::Path) -> Result<(), EngineError> { let json = to_json(doc)?; // Write next to the target, then rename: a crash mid-write never corrupts the old file. - let tmp = path.with_extension("anicraft.tmp"); - crate::vfs::write(&tmp, json)?; - crate::vfs::rename(&tmp, path)?; + // The temp name is unguessable and created exclusively, so a planted file or symlink can't redirect the write. + let tmp = path.with_extension(format!("anicraft.{}.tmp", crate::vfs::random_suffix())); + crate::vfs::write_new(&tmp, json)?; + if let Err(e) = crate::vfs::rename(&tmp, path) { + let _ = crate::vfs::remove_file(&tmp); + return Err(e.into()); + } Ok(()) } diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index a621124a..e62ab2e1 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -35,6 +35,89 @@ pub struct Snapshot { pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, + /// The commands the step from this state ran, in order, as a saved command would run them + /// again (ADR 0097). `None`: they weren't kept (too many, or the step came from elsewhere). + pub commands: Option>, +} + +/// A command a history step ran: its id and params (ADR 0097). +#[derive(Clone, Debug, PartialEq)] +pub struct Recorded { + pub cmd: String, + pub params: serde_json::Value, + /// Roughly how much memory the params hold (their JSON's length). + pub bytes: usize, +} + +impl Recorded { + pub fn new(cmd: &str, params: &serde_json::Value) -> Recorded { + Recorded { cmd: cmd.to_string(), params: params.clone(), bytes: cmd.len() + params.to_string().len() } + } +} + +/// Most commands one step keeps: a longer step (a very long drag) can't be saved as a command. +pub const MAX_RECORDED: usize = 4096; +/// Most bytes of params one step keeps. +pub const MAX_RECORDED_BYTES: usize = 1 << 20; + +/// The commands run since the last step was recorded (ADR 0097). +#[derive(Clone, Debug, Default)] +pub(crate) struct Recording { + pub cmds: Vec, + pub bytes: usize, + /// More than [`MAX_RECORDED`] commands or [`MAX_RECORDED_BYTES`] bytes: none are kept. + pub overflow: bool, +} + +impl Recording { + /// Adds a command that changed the document. Moves in a row (a drag) add up into one. + pub fn push(&mut self, r: Recorded) { + if self.overflow { + return; + } + if let Some(last) = self.cmds.last_mut() + && let Some(sum) = merged_translate(last, &r) + { + *last = sum; + return; + } + self.bytes += r.bytes; + self.cmds.push(r); + if self.cmds.len() > MAX_RECORDED || self.bytes > MAX_RECORDED_BYTES { + self.overflow = true; + self.cmds = Vec::new(); + self.bytes = 0; + } + } + + pub fn truncate(&mut self, len: usize) { + if !self.overflow && len < self.cmds.len() { + self.cmds.truncate(len); + self.bytes = self.cmds.iter().map(|r| r.bytes).sum(); + } + } + + pub fn clear(&mut self) { + *self = Recording::default(); + } + + /// The commands for a step being recorded, leaving this empty. + pub fn take(&mut self) -> Option> { + let r = std::mem::take(self); + (!r.overflow).then(|| r.cmds.into()) + } +} + +/// Two `element.translate {dx, dy}` in a row as one, or `None`. +fn merged_translate(a: &Recorded, b: &Recorded) -> Option { + let plain = |r: &Recorded| { + let o = r.params.as_object()?; + (r.cmd == "element.translate" && o.len() == 2).then_some(())?; + Some((o.get("dx")?.as_f64()?, o.get("dy")?.as_f64()?)) + }; + let ((ax, ay), (bx, by)) = (plain(a)?, plain(b)?); + let (dx, dy) = (ax + bx, ay + by); + (dx.is_finite() && dy.is_finite()).then(|| Recorded::new("element.translate", &serde_json::json!({"dx": dx, "dy": dy}))) } /// Default memory budget for undo history. @@ -62,7 +145,7 @@ impl Default for History { impl History { /// Records `before` as an undo step leading to `current`, and clears redo. pub fn record(&mut self, mut before: Snapshot, current: &Document) { - before.bytes = unique_bytes(&before.doc, current); + before.bytes = unique_bytes(&before.doc, current) + before.commands.as_ref().map_or(0, |c| c.iter().map(|r| r.bytes).sum()); self.undo_bytes += before.bytes; self.undo.push_back(before); self.redo.clear(); @@ -85,6 +168,7 @@ impl History { self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.redo_bytes += current.bytes; self.redo.push(current); Some(s) @@ -96,6 +180,7 @@ impl History { self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.undo_bytes += current.bytes; self.undo.push_back(current); self.enforce_budget(); @@ -128,6 +213,12 @@ impl History { pub fn redo_labels(&self) -> impl Iterator { self.redo.iter().rev().map(|s| s.label.as_str()) } + /// Every step as the History panel lists it, oldest first: the steps that can be undone, + /// then the ones that can be redone (next to redo first), each with its label and the + /// commands it ran (ADR 0097). + pub fn steps(&self) -> impl Iterator)> { + self.undo.iter().chain(self.redo.iter().rev()).map(|s| (s.label.as_str(), s.commands.as_deref())) + } /// Estimated memory held by history. pub fn bytes(&self) -> usize { self.undo_bytes + self.redo_bytes diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 39a370d2..a1f124bb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ mod cmds_retime; mod cmds_hints; mod cmds_layer; pub mod cmds_library; +pub mod cmds_macro; pub mod cmds_paint; mod cmds_path; pub mod cmds_raw; @@ -180,6 +181,7 @@ pub fn commands() -> Vec { v.extend(cmds_sound::specs()); v.extend(cmds_actions::specs()); v.extend(cmds_script::specs()); + v.extend(cmds_macro::specs()); v } @@ -195,10 +197,23 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ ]; pub fn find_command(id: &str) -> Option { - commands().into_iter().find(|c| c.id == id) + // Built once: every command run looks itself up, and a saved command checks each of its + // steps (ADR 0097), so this must not rebuild the registry per call. + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX + .get_or_init(|| { + let mut m = std::collections::HashMap::new(); + for c in commands() { + // The first of a repeated id wins, as a search in registry order finds it. + m.entry(c.id).or_insert(c); + } + m + }) + .get(id) + .copied() } -pub use history::{Snapshot, StateId}; +pub use history::{Recorded, Snapshot, StateId}; pub use selection::Selection; pub use snap::{Accuracy, SnapTo, ViewAids}; pub use cmds_layer::LAYER_COLORS; @@ -380,6 +395,13 @@ pub struct Session { pub filter_clipboard: Option>, /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. pub(crate) envelope: Option, + /// The commands run since the last undo step was recorded, which the next step keeps so it + /// can be saved as a command (ADR 0097). + rec: history::Recording, + /// How many commands were recorded when the open gesture began (a revert goes back there). + gesture_rec: usize, + /// What the running command records instead of itself (`macro.run` records its steps). + pub(crate) record_as: Option>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -455,6 +477,9 @@ impl Session { filter_presets: filter_library::FilterLibrary::default(), filter_clipboard: None, envelope: None, + rec: history::Recording::default(), + gesture_rec: 0, + record_as: None, } } @@ -497,6 +522,7 @@ impl Session { } // On a marquee's cut, the step (if the gesture makes one) starts from before the cut. let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone())); + self.gesture_rec = self.rec.cmds.len(); match cut { Some((before, doc)) => { self.gesture_cut = Some(doc); @@ -520,8 +546,17 @@ impl Session { } self.provisional = None; } + self.record(before); + } + + /// Records `before` as the undo step to the current document, with the commands run since + /// the last step; an unchanged document records nothing and forgets them. + fn record(&mut self, mut before: Snapshot) { if self.doc != before.doc { + before.commands = self.rec.take(); self.history.record(before, &self.doc); + } else { + self.rec.clear(); } } @@ -565,10 +600,7 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } - // A group open for editing is one layer and one frame (ADR 0073). - if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { - return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); - } + self.group_allows(&spec)?; self.settle_cut(id, params); if !spec.mutates { let r = (spec.run)(self, params); @@ -588,7 +620,9 @@ impl Session { self.pending_cut = None; self.motion_edit = None; self.step_label = None; + self.record_as = None; let result = (spec.run)(self, params); + let record_as = self.record_as.take(); // Edits to a motion tween's target become property keys (auto-key). if let Some(edit) = self.motion_edit.take() && result.is_ok() @@ -610,6 +644,10 @@ impl Session { if changed { self.state = history::fresh_state(); self.revision += 1; + match record_as { + Some(steps) => steps.into_iter().for_each(|r| self.rec.push(r)), + None => self.rec.push(Recorded::new(id, params)), + } match pending.filter(|_| self.gesture.is_none()) { // A marquee's cut: provisional, no step (yet). Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside), @@ -617,8 +655,8 @@ impl Session { if cut.is_some() { self.provisional = None; } - if self.gesture.is_none() && self.doc != before.doc { - self.history.record(before, &self.doc); + if self.gesture.is_none() { + self.record(before); } } } @@ -635,6 +673,16 @@ impl Session { } } + /// A group open for editing is one layer and one frame (ADR 0073): commands that change + /// the timeline are refused inside it. + fn group_allows(&self, spec: &CommandSpec) -> Result<()> { + let id = spec.id; + if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { + return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); + } + Ok(()) + } + /// Inside a group (ADR 0073) the playhead stays on its only frame. fn hold_group_frame(&mut self) { if self.frame != 0 && self.editing_group() { @@ -699,6 +747,8 @@ impl Session { if self.saved_state == Some(p.state) { self.saved_state = Some(p.before.state); } + // The cut's commands went with it. + self.rec.clear(); self.doc = p.before.doc; self.state = p.before.state; self.selection = sel; @@ -720,9 +770,19 @@ impl Session { if !spec.mutates { return (spec.run)(self, params); } + self.group_allows(&spec)?; let before = self.snapshot(""); self.dl_cache.replace(None); + // Each command's edits to a motion tween's target become its keys, as when it runs on + // its own (the next one may work at another frame). + let outer = self.motion_edit.take(); let result = (spec.run)(self, params); + if let Some(edit) = self.motion_edit.take() + && result.is_ok() + { + cmds_motion::finish_edit(self, edit); + } + self.motion_edit = outer; self.dl_cache.replace(None); self.pending_cut = None; match result { @@ -752,14 +812,15 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0, commands: None }; + self.rec.truncate(self.gesture_rec); self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0, commands: None } } fn restore(&mut self, s: Snapshot) { @@ -790,6 +851,7 @@ impl Session { pub fn undo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; let label = s.label.clone(); @@ -802,6 +864,7 @@ impl Session { pub fn redo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; let label = s.label.clone(); @@ -1128,6 +1191,8 @@ mod motion_pin_tests; #[cfg(test)] mod plugin_tests; #[cfg(test)] +mod macro_tests; +#[cfg(test)] mod plugin_kinds_tests; #[cfg(test)] mod tests_sound; @@ -1198,6 +1263,8 @@ mod view_tests; #[cfg(test)] mod path_text_tests; #[cfg(test)] +mod rich_text_tests; +#[cfg(test)] mod group_tests; #[cfg(test)] mod swatch_tests; diff --git a/crates/engine/src/macro_tests.rs b/crates/engine/src/macro_tests.rs new file mode 100644 index 00000000..e41ca157 --- /dev/null +++ b/crates/engine/src/macro_tests.rs @@ -0,0 +1,353 @@ +//! Saved commands (ADR 0097): what history records, Save As Command from history steps, a run +//! as one transactional undo step, the folder's order, the policy, and hostile files. + +use super::*; +use crate::cmds_macro::{self, Macro, macro_may_call}; +use serde_json::json; +use std::path::PathBuf; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-macros-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The elements on the active layer at the playhead, without their ids (which differ between +/// documents), as JSON. +fn looks(s: &Session) -> Vec { + s.visible_elements() + .iter() + .map(|e| { + let mut v = serde_json::to_value(&**e).unwrap(); + v.as_object_mut().unwrap().remove("id"); + v + }) + .collect() +} + +/// A rectangle, selected. +fn with_rect(x: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": x, "y": 20, "w": 80, "h": 40})); + run(&mut s, "edit.select_all", json!({})); + s +} + +/// Three edits on the selection: a drag (many moves in one step), a quarter turn and a fade. +fn edit(s: &mut Session) { + s.begin_gesture("Move"); + for _ in 0..30 { + run(s, "element.translate", json!({"dx": 2, "dy": -1})); + } + s.end_gesture(); + run(s, "modify.rotate_cw", json!({})); + run(s, "element.set_color_effect", json!({"style": "alpha", "alpha": 40})); +} + +#[test] +fn history_keeps_each_steps_commands_and_a_drag_as_one_move() { + let mut s = with_rect(10.0); + edit(&mut s); + let steps: Vec<(String, Option>)> = s.history().steps().map(|(l, c)| (l.to_string(), c.map(<[Recorded]>::to_vec))).collect(); + assert_eq!(steps.len(), 4, "{:?}", steps.iter().map(|s| &s.0).collect::>()); + let cmds = |i: usize| steps[i].1.clone().unwrap(); + assert_eq!(cmds(0)[0].cmd, "draw.rect"); + // Thirty moves in a drag add up to one. + assert_eq!(cmds(1).len(), 1); + assert_eq!(cmds(1)[0].params, json!({"dx": 60.0, "dy": -30.0})); + assert_eq!(cmds(2)[0].cmd, "modify.rotate_cw"); + assert_eq!(cmds(3)[0].params, json!({"style": "alpha", "alpha": 40})); + // Undo and redo carry them along. + s.undo().unwrap(); + s.redo().unwrap(); + assert_eq!(s.history().steps().nth(3).and_then(|(_, c)| c).map(<[Recorded]>::len), Some(1)); +} + +#[test] +fn a_live_preview_records_only_what_it_ended_on() { + let mut s = with_rect(10.0); + s.begin_gesture("Nudge"); + run(&mut s, "modify.rotate_cw", json!({})); + s.revert_gesture(); + run(&mut s, "element.translate", json!({"dx": 5, "dy": 0})); + s.end_gesture(); + let last = s.history().steps().last().and_then(|(_, c)| c.map(<[Recorded]>::to_vec)).unwrap(); + assert_eq!(last.iter().map(|r| r.cmd.as_str()).collect::>(), ["element.translate"]); +} + +#[test] +fn record_and_replay_equals_the_original_edits_on_a_fresh_selection() { + let dir = temp_dir("replay"); + let folder = dir.display().to_string(); + let mut original = with_rect(10.0); + edit(&mut original); + let listed = run(&mut original, "macro.history", json!({})); + let keep: Vec = listed["steps"].as_array().unwrap().iter().map(|v| v["keep"].as_bool().unwrap()).collect(); + assert_eq!(keep, [true, true, true, true], "{listed}"); + let saved = run(&mut original, "macro.save", json!({"folder": folder, "name": "Turn and Fade", "history": [1, 2, 3]})); + assert_eq!(saved["steps"], 3); + assert!(dir.join("Turn and Fade.json").is_file()); + + // Elsewhere: another document, another rectangle drawn the same way but with other ids. + let mut other = Session::default(); + run(&mut other, "draw.ellipse", json!({"x": 300, "y": 300, "w": 10, "h": 10})); + run(&mut other, "edit.deselect", json!({})); + run(&mut other, "draw.rect", json!({"x": 10, "y": 20, "w": 80, "h": 40})); + let rect = other.visible_elements().last().unwrap().id; + run(&mut other, "element.select", json!({"ids": [rect.0]})); + let steps = other.history_len(); + let before_run = looks(&other); + let oval = before_run.first().cloned(); + let v = run(&mut other, "macro.run", json!({"folder": folder, "name": "Turn and Fade"})); + assert_eq!(v["steps"], 3); + assert_eq!(other.history_len(), steps + 1, "one undo step"); + assert_eq!(other.undo_label(), Some("Turn and Fade")); + let mine = looks(&other); + assert_eq!(mine.last(), looks(&original).last(), "the rectangle ends up as in the original"); + // The oval, not selected, is untouched. + assert_eq!(mine.first().cloned(), oval); + // One undo takes the whole run back. + other.undo().unwrap(); + assert_eq!(looks(&other), before_run); + // And the run's step can itself be saved again: history keeps its steps, not macro.run. + other.redo().unwrap(); + let again = run(&mut other, "macro.history", json!({})); + let last = again["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!((last["keep"].as_bool(), last["commands"].as_u64()), (Some(true), Some(3)), "{last}"); +} + +#[test] +fn a_failing_step_changes_nothing_and_is_named() { + let mut s = with_rect(10.0); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let steps_json = json!([ + {"cmd": "element.translate", "params": {"dx": 10, "dy": 0}}, + {"cmd": "modify.rotate_cw"}, + {"cmd": "layer.set_height", "params": {"height": 7}, "label": "Taller row"}, + ]); + let e = s.execute("macro.run", &json!({"name": "Broken", "steps": steps_json})).unwrap_err().to_string(); + assert!(e.contains("“Broken” stopped at step 3 of 3 (Taller row)") && e.contains("Nothing was changed"), "{e}"); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!((s.state, s.history_len()), (state, steps)); + assert_eq!(s.selection.len(), 1, "the selection too"); +} + +#[test] +fn steps_tied_to_this_document_act_on_the_selection_or_say_why_they_cant_be_kept() { + let mut s = with_rect(10.0); + let layer = s.layer.0; + let id = s.selection.id_list()[0]; + // A layer named by id: the step acts on the active layer instead. + run(&mut s, "layer.set_color", json!({"color": "#ff0000", "layer": layer})); + // An element named by id where the command can take the selection instead. + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both", "id": id})); + // An element named by id where the command can't do without it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 3, "dy": 0})); + let v = run(&mut s, "macro.history", json!({})); + let steps = v["steps"].as_array().unwrap(); + assert_eq!(steps[1]["rewritten"], "acts on the active layer", "{v}"); + assert_eq!(steps[2]["rewritten"], "acts on the selection", "{v}"); + assert_eq!(steps[3]["keep"], false); + assert!(steps[3]["why"].as_str().unwrap().contains("particular objects"), "{v}"); + let dir = temp_dir("rewrite"); + let folder = dir.display().to_string(); + let e = s.execute("macro.save", &json!({"folder": folder, "name": "Mixed", "history": [1, 2, 3]})).unwrap_err().to_string(); + assert!(e.starts_with("step 4 “") && e.contains("can't be kept"), "{e}"); + assert!(!dir.join("Mixed.json").exists(), "nothing saved"); + let saved = run(&mut s, "macro.save", json!({"folder": folder, "name": "Mixed", "history": [2, 1]})); + assert_eq!(saved["rewritten"].as_array().map(Vec::len), Some(2)); + let m = cmds_macro::load(&dir.join("Mixed.json")).unwrap(); + assert_eq!(m.steps[0].params, json!({"color": "#ff0000"}), "in history order, the layer's id gone"); + assert_eq!(m.steps[1].params, json!({"profile": "taper_both"})); +} + +#[test] +fn saved_commands_call_only_what_a_plug_in_may() { + assert!(macro_may_call("element.translate").is_ok()); + for id in ["file.save", "edit.paste", "edit.undo", "plugin.run", "macro.run", "macro.delete", "prefs.set", "view.rulers"] { + assert!(macro_may_call(id).is_err(), "{id}"); + } + // Plug-ins can't reach saved commands either, so the two never call each other. + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + assert!(crate::cmds_plugin::plugin_may_call(c.id).is_err(), "{}", c.id); + } + for (step, why) in [(json!({"cmd": "file.save", "params": {"path": "x.anicraft"}}), "files"), (json!({"cmd": "macro.run", "params": {"path": "x.json"}}), "saved commands"), (json!({"cmd": "no.such"}), "unknown command")] { + let e = Macro::from_json(&json!([step]), "x").unwrap_err().to_string(); + assert!(e.contains("step 1") && e.contains(why), "{e}"); + } + // A history step that used the clipboard can't be kept. + let mut s = with_rect(10.0); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({})); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("clipboard"), "{last}"); +} + +#[test] +fn the_folder_keeps_order_renames_and_deletes_only_when_confirmed() { + let dir = temp_dir("manage"); + let folder = dir.display().to_string(); + let mut s = with_rect(10.0); + run(&mut s, "modify.rotate_cw", json!({})); + for name in ["Alpha", "Bravo", "Charlie"] { + run(&mut s, "macro.save", json!({"folder": folder, "name": name, "history": [1]})); + } + let names = |s: &mut Session| -> Vec { run(s, "macro.list", json!({"folder": folder}))["commands"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap().to_string()).collect() }; + assert_eq!(names(&mut s), ["Alpha", "Bravo", "Charlie"], "in the order saved"); + run(&mut s, "macro.move", json!({"folder": folder, "name": "Charlie", "index": 0})); + assert_eq!(names(&mut s), ["Charlie", "Alpha", "Bravo"]); + run(&mut s, "macro.rename", json!({"folder": folder, "name": "Alpha", "to": "Delta"})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a rename keeps its place"); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "Bravo"})).unwrap_err().to_string().contains("already")); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "a/b"})).is_err()); + // Saving over one asks first; deleting always does (a file: undo can't bring it back). + assert!(matches!(s.execute("macro.save", &json!({"folder": folder, "name": "Bravo", "history": [1]})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.save", json!({"folder": folder, "name": "Bravo", "history": [0, 1], "confirm": true})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a replaced command keeps its place"); + assert!(matches!(s.execute("macro.delete", &json!({"folder": folder, "name": "Charlie"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.delete", json!({"folder": folder, "name": "Charlie", "confirm": true})); + assert_eq!(names(&mut s), ["Delta", "Bravo"]); + // A shared file comes in under its own name, checked. + let shared = dir.join("shared"); + std::fs::create_dir_all(&shared).unwrap(); + std::fs::write(shared.join("Spin.json"), r#"[{"cmd": "modify.rotate_cw"}, {"command": "modify.rotate_cw"}]"#).unwrap(); + let v = run(&mut s, "macro.import", json!({"folder": folder, "path": shared.join("Spin.json").display().to_string()})); + assert_eq!(v["steps"], 2); + assert_eq!(names(&mut s), ["Delta", "Bravo", "Spin"]); + // ...and runs straight from where it is (Run Command…). + let before = s.visible_elements()[0].transform; + run(&mut s, "macro.run", json!({"path": shared.join("Spin.json").display().to_string()})); + assert_eq!(s.undo_label(), Some("Spin")); + assert_ne!(s.visible_elements()[0].transform, before); + // Files that aren't saved commands are listed as problems, never as commands. + std::fs::write(dir.join("junk.json"), "{nope").unwrap(); + let v = run(&mut s, "macro.list", json!({"folder": folder})); + assert_eq!(v["problems"][0]["file"], "junk.json"); + assert_eq!(names(&mut s).len(), 3); +} + +#[test] +fn hostile_saved_command_files_never_panic() { + let dir = temp_dir("hostile"); + let deep = format!("{}{}", "[".repeat(5000), "]".repeat(5000)); + let many = serde_json::to_string(&vec![json!({"cmd": "modify.rotate_cw"}); cmds_macro::MAX_STEPS + 1]).unwrap(); + let mut bodies: Vec> = vec![ + Vec::new(), + b"\xef\xbb\xbf".to_vec(), + b"\xff\xfe\x00\x01garbage".to_vec(), + deep.into_bytes(), + many.into_bytes(), + "x".repeat((cmds_macro::MAX_FILE_BYTES + 10) as usize).into_bytes(), + ]; + for text in [ + "null", + "7", + "\"steps\"", + "{}", + r#"{"format": "something-else", "steps": []}"#, + r#"{"format": "anicraft-command", "version": 99, "steps": []}"#, + r#"{"format": "anicraft-command", "version": -1, "steps": []}"#, + r#"{"steps": "no"}"#, + r#"{"steps": [7, null, "x"]}"#, + r#"{"steps": [{"cmd": 7}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": [1, 2]}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": 1e308, "dy": -1e308}}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": "a"}}]}"#, + r#"{"steps": [{"cmd": "draw.rect", "params": {"x": 0, "y": 0, "w": 1e30, "h": -1}, "label": 5}]}"#, + r#"{"steps": [{"cmd": "layer.delete"}, {"cmd": "layer.delete"}, {"cmd": "layer.delete"}]}"#, + r#"{"steps": [{"cmd": "edit.undo"}]}"#, + r#"{"steps": [{"cmd": "file.export_png", "params": {"path": "/tmp/x.png"}}]}"#, + r#"{"steps": [{"cmd": "macro.run", "params": {"path": "self.json"}}]}"#, + r#"{"steps": [{"cmd": "plugin.run", "params": {"id": "x"}}]}"#, + ] { + bodies.push(text.as_bytes().to_vec()); + } + bodies.push(json!({"steps": [{"cmd": "modify.rotate_cw", "label": "\u{0}\u{202e} evil"}]}).to_string().into_bytes()); + // Truncations of a good file at every byte, and a few flipped bytes. + let good = serde_json::to_vec(&Macro { name: String::new(), steps: vec![cmds_macro::Step { cmd: "element.translate".into(), params: json!({"dx": 3, "dy": 4}), label: "Move".into() }] }.to_json()).unwrap(); + for i in 0..good.len() { + bodies.push(good[..i].to_vec()); + let mut flipped = good.clone(); + flipped[i] ^= 0x5a; + bodies.push(flipped); + } + let mut s = with_rect(10.0); + for (i, body) in bodies.iter().enumerate() { + let path = dir.join(format!("h{i}.json")); + std::fs::write(&path, body).unwrap(); + let (doc, steps) = (s.doc.clone(), s.history_len()); + match s.execute("macro.run", &json!({"path": path.display().to_string()})) { + Ok(_) => assert!(s.history_len() <= steps + 1), + Err(_) => assert!(s.doc == doc && s.history_len() == steps, "a refused file changed the document"), + } + let _ = s.execute("macro.import", &json!({"folder": dir.join("in").display().to_string(), "path": path.display().to_string(), "confirm": true})); + } + // Listing a folder full of them never panics either. + let v = run(&mut s, "macro.list", json!({"folder": dir.display().to_string()})); + assert!(!v["problems"].as_array().unwrap().is_empty()); + // Hostile params, with every folder inside the temporary one. + let folder = dir.display().to_string(); + for p in [ + Value::Null, + json!({"folder": folder}), + json!({"folder": folder, "name": "", "history": [u64::MAX]}), + json!({"folder": folder, "name": "x", "history": "all"}), + json!({"folder": folder, "name": "x", "history": []}), + json!({"folder": folder, "name": "..", "history": [0]}), + json!({"folder": folder, "name": "CON", "history": [0]}), + json!({"folder": folder, "name": "a", "to": "", "index": u64::MAX}), + json!({"folder": "", "name": "a"}), + json!({"steps": {"steps": []}, "name": "\u{0}".repeat(500)}), + json!({"steps": []}), + json!({"path": folder}), + ] { + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + let _ = s.execute(c.id, &p); + } + } +} + +#[test] +fn a_step_too_long_to_keep_says_so() { + let mut s = with_rect(10.0); + s.begin_gesture("Scribble"); + for i in 0..(history::MAX_RECORDED + 2) { + // Alternating commands, so they don't add up into one. + let id = if i % 2 == 0 { "element.translate" } else { "modify.rotate_cw" }; + run(&mut s, id, json!({"dx": 1, "dy": 0, "snap": 0})); + } + s.end_gesture(); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("too many"), "{last}"); +} + +#[test] +fn steps_run_inside_a_motion_tween_key_it_as_on_their_own() { + // Each step's edit becomes the tween's keys at the frame it ran at. + let tweened = || { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s + }; + let (mut a, mut b) = (tweened(), tweened()); + a.set_frame(5); + run(&mut a, "edit.select_all", json!({})); + run(&mut a, "element.translate", json!({"dx": 40, "dy": 0})); + b.set_frame(5); + run(&mut b, "edit.select_all", json!({})); + run(&mut b, "macro.run", json!({"steps": [{"cmd": "element.translate", "params": {"dx": 40, "dy": 0}}]})); + assert!(a.doc == b.doc, "a step in a saved command keys the tween as the command does alone"); +} diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index cc51e5e8..9adfa704 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -285,6 +285,7 @@ pub fn multi_frames(tl: &Timeline, playhead: u32, first: u32, last: u32) -> Vec< fn keep_layers(dl: &mut DisplayList, layers: &[LayerId]) { let set: HashSet = layers.iter().copied().collect(); dl.items.retain(|i| set.contains(&i.layer) || (i.masks.is_some() && i.group.is_none())); + dl.links.clear(); } /// The parts as one list, layer by layer: each layer's items from every part, in part order, diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 73944b76..454a95a6 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -179,7 +179,7 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" | "prefs" | "desktop" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" | "desktop" | "macro" => assert!(verdict.is_err(), "{} must be refused", c.id), // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), // Brushes (ADR 0068): list yes; your own brushes and brush set files no. diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs new file mode 100644 index 00000000..a7b8f03c --- /dev/null +++ b/crates/engine/src/rich_text_tests.rs @@ -0,0 +1,229 @@ +//! Styled text (ADR 0085): runs set on a range, typing that continues a style, paragraphs, mixed +//! selections, fields and paths keeping runs, Break Apart by colour, the file, the renderer. + +use crate::Session; +use anicraft_doc::{BaselineShift, ElementId, ElementKind, TextAlign, TextBlock}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn fonts() -> bool { + let ok = !anicraft_text::Fonts::get().families().is_empty(); + if !ok { + eprintln!("no fonts on this computer: styled text tests skipped"); + } + ok +} + +fn text_of(s: &Session, id: ElementId) -> Arc { + let e = s.visible_elements().into_iter().find(|e| e.id == id).unwrap(); + match &e.kind { + ElementKind::Text(t) => t.clone(), + other => panic!("not text: {other:?}"), + } +} + +fn hello(s: &mut Session) -> ElementId { + ElementId(run(s, "text.create", json!({"text": "Hello world", "x": 20, "y": 20, "size": 40, "color": "#000000"}))["element"].as_u64().unwrap()) +} + +#[test] +fn styling_a_range_splits_runs_and_colours_the_outline() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = hello(&mut s); + let plain = text_of(&s, id); + assert!(plain.runs.is_empty() && plain.fills.is_empty(), "one style: as text always was"); + let steps = s.history().undo_len(); + run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": true, "color": "#cc0000"})); + assert_eq!(s.history().undo_len(), steps + 1, "one undo step"); + let t = text_of(&s, id); + assert_eq!(t.runs.iter().map(|r| (r.chars, r.style.bold)).collect::>(), vec![(5, true), (6, false)]); + assert_eq!(t.fills.len(), 2, "a piece per colour"); + assert_eq!(t.fills.iter().map(|f| f.cmds as usize).sum::(), t.outline.cmds.len()); + assert_eq!(t.fill_paths()[0].0, anicraft_doc::Rgba::hex(0xcc0000)); + // The block's own style is its first run's. + assert!(t.bold && t.color == anicraft_doc::Rgba::hex(0xcc0000)); + // The renderer draws the first word red and the second black. + let px = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let count = |want: fn(u8, u8, u8) -> bool| { + let raw = px.to_rgba8(); + raw.as_chunks::<4>().0.iter().filter(|p| want(p[0], p[1], p[2])).count() + }; + assert!(count(|r, g, b| r > 150 && g < 60 && b < 60) > 50, "red glyphs drawn"); + assert!(count(|r, g, b| r < 40 && g < 40 && b < 40) > 50, "black glyphs drawn"); + // Restyling it back joins the runs again. + run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": false, "color": "#000000"})); + let back = text_of(&s, id); + assert!(back.runs.is_empty() && back.fills.is_empty()); + assert_eq!(back.outline, plain.outline, "laid out exactly as before"); +} + +#[test] +fn styles_report_mixed_values_and_typing_continues_the_style_before() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = hello(&mut s); + run(&mut s, "text.style", json!({"start": 6, "end": 11, "size": 20, "italic": true})); + let v = run(&mut s, "text.styles", json!({"start": 3, "end": 8})); + assert_eq!(v["selection"]["size"], Value::Null, "mixed"); + assert_eq!(v["selection"]["bold"], json!(false), "shared"); + assert_eq!(v["runs"].as_array().unwrap().len(), 2); + assert_eq!(run(&mut s, "text.styles", json!({"start": 9, "end": 9}))["selection"]["italic"], json!(true), "a caret: the style typing there gets"); + // Typing at the end continues the small italic run; typing at the start the first run. + run(&mut s, "text.edit", json!({"text": "Hello world!"})); + run(&mut s, "text.edit", json!({"text": ">Hello world!"})); + let t = text_of(&s, id); + assert_eq!(t.runs.iter().map(|r| (r.chars, r.style.size)).collect::>(), vec![(7, 40.0), (6, 20.0)]); + // Deleting the small word joins nothing it shouldn't; deleting all of it leaves one run. + run(&mut s, "text.edit", json!({"text": ">Hello "})); + assert!(text_of(&s, id).runs.is_empty()); + // Hostile ranges and junk styles are errors or clamps, never a panic. + assert!(s.execute("text.style", &json!({"start": 4, "end": 2, "bold": true})).is_err()); + assert!(s.execute("text.style", &json!({"start": 0})).is_err(), "no style given"); + assert!(s.execute("text.style", &json!({"shift": "sideways"})).is_err()); + assert!(s.execute("text.style", &json!({"url": "javascript:alert(1)"})).is_err()); + run(&mut s, "text.style", json!({"start": 3, "end": 999_999, "underline": true})); +} + +#[test] +fn a_superscript_sits_above_the_line_and_runs_wrap_across() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = ElementId(run(&mut s, "text.create", json!({"text": "E = mc2", "x": 0, "y": 0, "size": 60}))["element"].as_u64().unwrap()); + let before = text_of(&s, id); + run(&mut s, "text.style", json!({"start": 6, "end": 7, "shift": "superscript"})); + let t = text_of(&s, id); + assert_eq!(t.runs.last().map(|r| r.style.shift), Some(BaselineShift::Superscript)); + // The "2" moved up and got smaller: the outline's top is no lower, the text narrower. + assert!(t.box_width < before.box_width - 5.0, "{} vs {}", t.box_width, before.box_width); + assert!(t.outline.bounds().min.y <= before.outline.bounds().min.y + 0.5); + // Wrapping across runs: a width that fits two words per line. + run(&mut s, "text.edit", json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]})); + let w = text_of(&s, id); + assert!(w.box_height > 150.0, "several lines: {}", w.box_height); + assert!(w.outline.bounds().max.x <= 182.0, "{:?}", w.outline.bounds()); + assert_eq!(w.runs.len(), 2); +} + +#[test] +fn paragraphs_take_their_own_alignment_indent_and_margins() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = ElementId(run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap()); + run(&mut s, "text.paragraph", json!({"start": 0, "end": 0, "align": "center"})); + let t = text_of(&s, id); + assert_eq!(t.paragraphs.iter().map(|p| p.align).collect::>(), vec![TextAlign::Center, TextAlign::Left]); + let v = run(&mut s, "text.styles", json!({"start": 2, "end": 9})); + assert_eq!(v["paragraph"]["align"], Value::Null, "two paragraphs, two alignments"); + run(&mut s, "text.paragraph", json!({"start": 7, "end": 7, "indent": 40, "left_margin": 10})); + let t = text_of(&s, id); + assert_eq!((t.paragraphs[1].indent, t.paragraphs[1].left_margin), (40.0, 10.0)); + // A line break typed in the centred title gives both halves its alignment. + run(&mut s, "text.edit", json!({"text": "Ti\ntle\nbody text"})); + assert_eq!(text_of(&s, id).paragraphs.iter().map(|p| p.align).collect::>(), vec![TextAlign::Center, TextAlign::Center, TextAlign::Left]); + assert!(s.execute("text.paragraph", &json!({"indent": 1e6})).is_err()); + assert!(s.execute("text.paragraph", &json!({"align": "justify"})).is_err()); +} + +#[test] +fn runs_survive_the_file_fields_paths_and_break_apart() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = hello(&mut s); + run(&mut s, "text.style", json!({"start": 0, "end": 5, "color": "#00aa00", "url": "https://example.org"})); + // The file keeps runs, paragraphs and fills. + let json = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&json).unwrap(); + let mut s2 = Session::new(back); + s2.frame = 0; + let t2 = text_of(&s2, id); + let t = text_of(&s, id); + assert_eq!((&t2.runs, &t2.fills, &t2.outline), (&t.runs, &t.fills, &t.outline)); + // Links reach the display list for exports. + let dl = anicraft_doc::evaluate(&s.doc, 0); + assert_eq!(dl.links.len(), 1); + assert_eq!(&*dl.links[0].1, "https://example.org"); + // A field keeps its runs inside its box. + run(&mut s, "text.field", json!({"type": "dynamic"})); + let f = text_of(&s, id); + assert!(f.field.is_some() && f.runs.len() == 2 && f.fills.len() == 2); + run(&mut s, "text.field", json!({"type": "static"})); + // On a path, the colours stay. + let line = ElementId(run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 600, "y1": 300}))["element"].as_u64().unwrap()); + run(&mut s, "element.select", json!({"ids": [id.0, line.0]})); + run(&mut s, "text.attach_path", json!({})); + let p = text_of(&s, id); + assert!(p.on_path.is_some() && p.fills.len() == 2); + run(&mut s, "text.release_path", json!({})); + // Break Apart: one shape per colour. + run(&mut s, "element.select", json!({"ids": [id.0]})); + let shapes_before = s.visible_elements().iter().filter(|e| matches!(e.kind, ElementKind::Shape(_))).count(); + run(&mut s, "modify.break_apart", json!({})); + let shapes = s.visible_elements().iter().filter(|e| matches!(e.kind, ElementKind::Shape(_))).count(); + assert_eq!(shapes, shapes_before + 2); +} + +#[test] +fn whole_block_keys_restyle_every_run_and_hostile_runs_are_capped() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = hello(&mut s); + run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": true})); + // A size for the whole block keeps the bold run bold. + run(&mut s, "text.edit", json!({"size": 24})); + let t = text_of(&s, id); + assert_eq!(t.runs.iter().map(|r| (r.style.size, r.style.bold)).collect::>(), vec![(24.0, true), (24.0, false)]); + // Thousands of one-character runs, alternating: capped at the limit, laid out. + let text = "ab".repeat(6000); + let runs: Vec = (0..anicraft_doc::MAX_TEXT_RUNS).map(|i| json!({"chars": 1, "bold": i % 2 == 0})).collect(); + let t0 = std::time::Instant::now(); + run(&mut s, "text.edit", json!({"text": text, "runs": runs, "width": 800})); + eprintln!("{} runs edited in {:?}", anicraft_doc::MAX_TEXT_RUNS, t0.elapsed()); + let t = text_of(&s, id); + assert_eq!(t.runs.len(), anicraft_doc::MAX_TEXT_RUNS); + assert_eq!(t.styled_runs().iter().map(|r| r.chars).sum::(), 12_000); + let too_many: Vec = (0..anicraft_doc::MAX_TEXT_RUNS + 1).map(|_| json!({"chars": 1})).collect(); + assert!(s.execute("text.edit", &json!({"runs": too_many})).is_err()); + assert!(s.execute("text.edit", &json!({"runs": [{"size": 3}]})).is_err(), "a run needs its length"); + assert!(s.execute("text.edit", &json!({"runs": [{"chars": 1, "size": 1e9}]})).is_err()); +} + +#[test] +fn every_export_draws_each_colour_and_svg_keeps_the_link() { + if !fonts() { + return; + } + let mut s = Session::default(); + let id = hello(&mut s); + run(&mut s, "text.style", json!({"start": 0, "end": 5, "color": "#00aa00", "url": "https://example.org/?a=1&b=2"})); + let dl = anicraft_doc::evaluate(&s.doc, 0); + let svg = anicraft_render::svg::to_svg(&dl, &s.doc.stage); + assert!(svg.contains(""), "the linked word is a link"); + assert_eq!(svg.matches("").count(), 1); + assert!(svg.contains("#00aa00") || svg.contains("rgb(0,170,0)"), "green piece"); + let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html; + assert!(html.matches("{\"s\":").count() >= 2, "the page draws a paint per colour"); + let lottie = anicraft_render::lottie::to_lottie(&s.doc, "t", 0, 0, false).json; + assert!(lottie.matches("\"ty\":\"fl\"").count() >= 2, "a fill per colour"); + // A field's authored text keeps its colours in the page, as pieces. + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "text.field", json!({"type": "dynamic"})); + let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html; + assert!(html.contains("\"pp\":"), "field pieces"); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 05fd166a..ec5c6cf1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -610,6 +610,12 @@ fn panic_hunt_every_command() { json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}), json!({"id": 5, "cmd": u64::MAX, "slot": 9, "dx": 1, "dy": 1, "with": "x", "x0": 0, "y0": 0, "x1": 1e9, "y1": 1e9}), json!({"id": 4, "cmd": 2, "slot": 1, "dx": -3, "dy": 2, "x": 60, "y": 60, "to_x": 61, "to_y": 61, "with": [[60, 60], [30, 90], [90, 30]], "merge": false}), + // Styled text (ADR 0085): thousands of runs, hostile sizes, ranges and links. + json!({"text": "ab +cd", "start": 1, "end": 99_999, "runs": (0..12_000).map(|i| json!({"chars": i % 3, "size": 10 + i % 5})).collect::>(), "paragraphs": [{"indent": 1e9}], "shift": "superscript", "url": "javascript:x", "underline": "y"}), + json!({"start": u64::MAX, "end": 0, "size": 12, "shift": "sub", "runs": "x", "paragraphs": 3}), + json!({"text": "Hi +there", "runs": [{"chars": 1, "bold": true, "shift": "superscript", "color": "#ff0000", "url": "https://a.b"}, {"chars": u32::MAX, "size": 2000, "letter_spacing": -1000}], "paragraphs": [{"align": "right", "left_margin": 1000, "right_margin": 1000}, {"indent": -1000}, {}], "start": 0, "end": 1, "underline": true, "indent": -1000}), // Kept scripts (ADR 0013 tier 1): odd text, unknown languages, class names that aren't. json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}), json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}), diff --git a/crates/engine/src/vfs.rs b/crates/engine/src/vfs.rs index f4f25f88..dd759767 100644 --- a/crates/engine/src/vfs.rs +++ b/crates/engine/src/vfs.rs @@ -208,6 +208,22 @@ pub fn write(path: &Path, data: impl AsRef<[u8]>) -> io::Result<()> { } } +/// Like [`write`], but the file must not exist yet (`O_EXCL`: a planted file or symlink makes it +/// fail instead of being written through). For temporary files. +pub fn write_new(path: &Path, data: impl AsRef<[u8]>) -> io::Result<()> { + match mem(|m| m.write(path, data.as_ref().to_vec())) { + Some(r) => r, + None => std::fs::OpenOptions::new().write(true).create_new(true).open(path).and_then(|mut f| io::Write::write_all(&mut f, data.as_ref())), + } +} + +/// 16 hex digits an outsider can't guess (the standard library's randomly seeded hasher), for +/// temporary file names. +pub fn random_suffix() -> String { + use std::hash::{BuildHasher, Hasher}; + format!("{:016x}", std::collections::hash_map::RandomState::new().build_hasher().finish()) +} + /// The file's size in bytes (`std::fs::metadata(path)?.len()`). pub fn len(path: &Path) -> io::Result { mem(|m| m.len(path)).unwrap_or_else(|| std::fs::metadata(path).map(|m| m.len())) @@ -265,6 +281,14 @@ impl Writer { Ok(Writer::Disk(io::BufWriter::new(std::fs::File::create(path)?))) } + /// Like [`Writer::create`], but the file must not exist yet. + pub fn create_new(path: &Path) -> io::Result { + if in_memory() { + return Writer::create(path); + } + Ok(Writer::Disk(io::BufWriter::new(std::fs::OpenOptions::new().write(true).create_new(true).open(path)?))) + } + pub fn finish(self) -> io::Result<()> { match self { Writer::Disk(mut f) => io::Write::flush(&mut f), @@ -299,6 +323,19 @@ impl io::Write for Writer { mod tests { use super::*; + #[test] + fn temp_files_are_created_exclusively() { + let dir = std::env::temp_dir().join(format!("anicraft-vfs-{}-{}", std::process::id(), random_suffix())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("t.tmp"); + write_new(&f, b"a").unwrap(); + assert_eq!(write_new(&f, b"b").unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(Writer::create_new(&f).err().map(|e| e.kind()), Some(io::ErrorKind::AlreadyExists)); + assert_eq!(std::fs::read(&f).unwrap(), b"a"); + assert_ne!(random_suffix(), random_suffix()); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn paths_have_one_spelling_and_stay_inside() { assert_eq!(key(Path::new("/a/./b/../c.txt")).unwrap(), PathBuf::from("a").join("c.txt")); diff --git a/crates/engine/tests/read_bounds.rs b/crates/engine/tests/read_bounds.rs new file mode 100644 index 00000000..514054a0 --- /dev/null +++ b/crates/engine/tests/read_bounds.rs @@ -0,0 +1,33 @@ +//! Files commands read are size-checked before they are read, and saves leave no predictable temp file. +#![cfg(not(target_arch = "wasm32"))] + +use anicraft_engine::Session; +use serde_json::json; + +#[test] +fn import_to_library_checks_an_image_size_before_reading() { + let dir = std::env::temp_dir().join(format!("anicraft-readbounds-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.png"); + // A sparse file: the size is claimed without being stored (or read, if the check works). + std::fs::File::create(&big).unwrap().set_len(256 * 1024 * 1024 + 1).unwrap(); + let mut s = Session::default(); + let e = s.execute("file.import_to_library", &json!({"path": big})).unwrap_err().to_string(); + assert!(e.contains("too large"), "{e}"); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn save_does_not_write_through_a_planted_predictable_temp_path() { + let dir = std::env::temp_dir().join(format!("anicraft-savetmp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let target = dir.join("a.anicraft"); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, "keep").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&victim, dir.join("a.anicraft.tmp")).unwrap(); + anicraft_engine::format::save(&Session::default().doc, &target).unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep"); + assert!(target.is_file()); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0186c76f..ee8e8500 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -190,7 +190,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)])); let mut out = Vec::new(); // A mask: a gradient seen through a circle, an unclipped shape over it, and one under it. - let dl = DisplayList { + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))], clip_parents: vec![None], @@ -213,10 +213,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { } let mut items = stripes; items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]); - out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); + out.push(("nested masks", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); // Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles // and the render bands; a top-level shape between two groups. - let dl = DisplayList { + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0), @@ -244,9 +244,9 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g)); items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g)); } - out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); + out.push(("blend modes", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); // Masks inside groups and groups inside masks, with a blend mode, on transparent. - let dl = DisplayList { + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0), @@ -262,7 +262,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { out.push(("masks and groups", dl, view(110, 90, None))); // Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides // what it clips), a group whose parent is later (top-level), a clip index past the list. - let dl = DisplayList { + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![ clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0), @@ -648,7 +648,7 @@ fn binning_shapes_the_scene_into_tiles() { assert!(b.index.iter().all(|&v| v == 0)); // A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In // the middle tile the mask has no artwork, so the clipped fill is left out there. - let dl = DisplayList { + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0), @@ -677,7 +677,7 @@ fn binning_shapes_the_scene_into_tiles() { #[test] fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { - let deep = |n: usize| DisplayList { + let deep = |n: usize| DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)], clip_parents: Vec::new(), @@ -690,7 +690,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let masks = |n: usize| { let mut items: Vec = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect(); items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)); - DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } + DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } }; assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok()); assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips)); @@ -861,7 +861,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); it.color = ColorTransform::alpha(0.5); - DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } + DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters)))); @@ -972,7 +972,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { // Inside a mask and a faded group, over a gradient. let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]))); let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); - let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); @@ -1065,7 +1065,7 @@ fn gpu_matches_the_oracle_on_every_filter() { for (name, f) in filters_to_test() { let mut items = vec![backdrop.clone()]; items.extend(symbol_items(0)); - let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; // At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface. for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] { let d = assert_parity(g, name, &dl, &v); @@ -1090,7 +1090,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { (grp.alpha, grp.blend) = (0.7, BlendMode::Multiply); let mut items = vec![bg.clone()]; items.extend(symbol_items(0)); - scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); + scenes.push(("filters in a row, faded and multiplied", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); // A filtered symbol inside a filtered symbol, inside a faded one. let mut outer = filtered_group(vec![shadow.clone()]); outer.parent = Some(0); @@ -1098,22 +1098,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { inner.parent = Some(1); let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)]; items.extend(symbol_items(2)); - scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); + scenes.push(("nested filtered symbols", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); // Masked from outside (after filtering) and inside (before). let mut clipped_grp = filtered_group(vec![glow.clone()]); clipped_grp.clip = Some(0); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0)); - scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); + scenes.push(("masked after filtering", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0)); - scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); + scenes.push(("masked inside the symbol", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); // A bitmap inside a filtered symbol. let px = pixels(9, 7, 4); let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)]; - scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); + scenes.push(("filtered bitmap", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); for (name, dl) in scenes { for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] { let d = assert_parity(g, name, &dl, &v); diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index 4db8419d..b1bd6dd4 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -57,6 +57,7 @@ pub const PAGES: &[Page] = &[ page!("opening-animate-files.md"), page!("preferences-shortcuts-accessibility.md"), page!("plugins.md"), + page!("saved-commands.md"), page!("working-headless.md"), page!("using-this-guide.md"), page!("troubleshooting-and-faq.md"), diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index da7fb7c5..f96f629e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-lottie.workspace = true craft-html.workspace = true anicraft-geom.workspace = true anicraft-doc.workspace = true diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 7f05f22a..69890e7d 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -563,6 +563,11 @@ impl<'a> Bake<'a> { if f.max_chars > 0 { o["mx"] = json!(f.max_chars.min(MAX_FIELD_CHARS as u32)); } + // Authored text in several colours: its pieces, each in its colour (ADR 0085). + if !t.fills.is_empty() { + let pieces: Vec = t.fill_paths().iter().map(|(c, _, p)| json!([self.path(p), self.paint(&Paint::Solid(*c))])).collect(); + o["pp"] = json!(pieces); + } if f.background { o["bg"] = json!(self.paint(&Paint::Solid(f.background_color))); } @@ -631,9 +636,12 @@ impl<'a> Bake<'a> { let item = self.field(el, t, f); out.push(item); } + // One shape per colour piece (ADR 0085). None => { - let fill = Paint::Solid(t.color); - out.push(self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero)); + for (color, _, path) in t.fill_paths() { + let fill = Paint::Solid(color); + out.push(self.shape(&path, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero)); + } } }, ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 439cf6b4..677dd236 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -419,7 +419,11 @@ var AniCraft = (function () { dl.clips.push(clip); items.push(mk(tf.r, tf.kp, null, null, clip, inner)); // Changed text has no outline here (it isn't laid out): the page draws it. - if (text === null) items.push(mk(tf.p, tf.f, null, null, inner, null)); + // Authored text in several colours comes in pieces (ADR 0085). + if (text === null) { + if (tf.pp) for (const [pp, pf] of tf.pp) items.push(mk(pp, pf, null, null, inner, null)); + else items.push(mk(tf.p, tf.f, null, null, inner, null)); + } if (focused && fs && tf.k === "input" && fs.caret === fs.anchor) items.push(mk(tf.cr, tf.f, null, null, inner, null)); if (tf.bd) items.push(mk(tf.r, -1, tf.bd, tf.bk || null, clip, null)); for (const it of items) dl.items.push(it); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index cb97b147..bc67fa29 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -893,7 +893,7 @@ fn the_js_player_draws_random_numbers_like_the_rust_player() { /// (layout isn't compared: neither player lays text out here). fn field_el(id: u64, name: &str, at: Vec2, (w, h): (f32, f32), text: &str, f: Option) -> Arc { let n = text.chars().count() as f32; - let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f, on_path: None }; + let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f, on_path: None, ..Default::default() }; Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(t)) }) } @@ -1250,7 +1250,7 @@ fn filters_and_soft_masks_compose_in_the_page_as_in_the_renderer() { // A mask over the symbol: its artwork drawn as it looks on its own, read as the // page reads it (canvas.js `maskEnd`). let reveal: Option> = (!inside).then(|| { - let art = anicraft_doc::DisplayList { items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() }; + let art = anicraft_doc::DisplayList { links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() }; let (mp, _) = crate::render(&art, &crate::View { background: None, ..view }).unwrap(); mp.data.iter().map(|p| mode.reveal(*p)).collect() }); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 668ab7c7..900da316 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -531,6 +531,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect clip_parents: dl.clip_parents.iter().map(|p| p.filter(|c| inner.contains(c))).collect(), clip_modes: dl.clip_modes.clone(), groups, + links: Vec::new(), }; let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None }; let filters = group.filters.iter().map(|f| filters::resolve(f, scale)).collect(); @@ -979,7 +980,7 @@ mod tests { } fn list(items: Vec) -> DisplayList { - DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() } + DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() } } /// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent. @@ -1074,7 +1075,7 @@ mod tests { let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2))); mask.masks = Some(0); mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0)); - let dl = DisplayList { clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; let (pm, _) = render(&dl, &view(40, 40)).unwrap(); // Pixel for pixel, the same as the circle drawn in the square's colour. let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); @@ -1142,7 +1143,7 @@ mod tests { let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); red.group = Some(0); blue.group = Some(0); - let grouped = DisplayList { clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; + let grouped = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; let (pm, _) = render(&grouped, &white).unwrap(); let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4); // In the overlap only the top square shows through: half blue, half white, no red. @@ -1158,7 +1159,7 @@ mod tests { // Nested groups multiply; a group with a bad parent link is a top-level group. let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK)); inner.group = Some(1); - let nested = DisplayList { + let nested = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![inner], clip_parents: vec![], @@ -1173,7 +1174,7 @@ mod tests { // Spanning several render bands changes nothing. let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK)); tall.group = Some(0); - let (t, _) = render(&DisplayList { clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); + let (t, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0]))); } @@ -1203,7 +1204,7 @@ mod tests { inner.masks = Some(1); let mut lost = clipped.clone(); lost.clip = Some(2); - let dl = DisplayList { clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap(); let (_, rst) = render(&dl, &view(16, 16)).unwrap(); assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched)); @@ -1216,7 +1217,7 @@ mod tests { let mut grouped = sq.clone(); grouped.group = Some(1); let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None }; - let dl = DisplayList { clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap(); assert!(scene.fills.iter().all(|f| f.group == Some(1))); assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply)); @@ -1258,7 +1259,7 @@ mod tests { let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)); clipped.clip = Some(0); let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK)); - let (pm, st) = render(&DisplayList { clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); + let (pm, st) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); assert_eq!(st.drawn, 1); assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0); } @@ -1273,11 +1274,11 @@ mod tests { inner.masks = Some(1); let items = vec![fill, outer, inner]; // Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives. - let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm)); // A parent link pointing forward (malformed) or out of range masks everything out. for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] { - let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); assert_eq!(alpha_sum(&pm), 0.0); } } @@ -1499,7 +1500,7 @@ mod tests { let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0))); let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))); top.group = Some(0); - let dl = DisplayList { clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap(); let p = pm.pixel(5, 5).unwrap(); assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}"); diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index 62552b5b..eeaa5b1c 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -132,11 +132,13 @@ impl Bez { /// The path of [`Bez::flat`] values, as Lottie writes it. fn flat_value(closed: bool, f: &[f64]) -> Value { - let pts: Vec = f.chunks(2).map(|c| json!([num(c.first().copied().unwrap_or(0.0)), num(c.get(1).copied().unwrap_or(0.0))])).collect(); + let pts: Vec<[f64; 2]> = f.chunks(2).map(|c| [c.first().copied().unwrap_or(0.0), c.get(1).copied().unwrap_or(0.0)]).collect(); let k = pts.len() / 3; let (v, rest) = pts.split_at(k.min(pts.len())); let (i, o) = rest.split_at(k.min(rest.len())); - json!({"c": closed, "v": v, "i": i, "o": o}) + // Geometry/easing stay application-owned; the shared path schema uses our + // existing compact numeric policy without a second rounding pass. + craft_lottie::Bezier { closed, vertices: v.to_vec(), in_tangents: i.to_vec(), out_tangents: o.to_vec() }.to_json_with(num) } } @@ -358,6 +360,16 @@ struct Track { first_index: usize, } +/// Keep color sanitation and stop policy local; share only the flat Lottie wire order. +fn gradient_values(stops: &[(f32, Rgba)]) -> Vec { + let colors = stops.iter().map(|(o, c)| { + let c = c.sanitized(); + (f64::from(o.clamp(0.0, 1.0)), [f64::from(c.r), f64::from(c.g), f64::from(c.b)]) + }); + let opacities = stops.iter().map(|(o, c)| (f64::from(o.clamp(0.0, 1.0)), f64::from(c.sanitized().a))); + craft_lottie::flat_gradient_values(colors, opacities).collect() +} + fn rgb(c: Rgba) -> Vec { let c = c.sanitized(); vec![f64::from(c.r), f64::from(c.g), f64::from(c.b), 1.0] @@ -658,8 +670,13 @@ pub fn to_lottie_keyed(doc: &Document, name: &str, from: u32, to: u32, backgroun let mattes = layers.len() - shape_layers; if background { let bg = doc.stage.background.sanitized(); - layers.push(json!({"ddd": 0, "ind": shape_layers + mattes + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": static_ks(), "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, - "sc": bg.to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); + // A fully transparent stage has no background layer; otherwise alpha is the layer opacity. + if bg.a > 0.0 { + let mut ks = static_ks(); + ks["o"]["k"] = n(bg.a.clamp(0.0, 1.0) * 100.0); + layers.push(json!({"ddd": 0, "ind": shape_layers + mattes + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": ks, "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, + "sc": bg.to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); + } } let root = json!({ "v": "5.7.0", @@ -960,16 +977,7 @@ fn layer(tr: &Track, ind: usize, w: &mut Writer<'_>) -> Value { }; start.push(vec![f64::from(a.x), f64::from(a.y)]); end.push(vec![f64::from(b.x), f64::from(b.y)]); - // Colour stops, then opacity stops: [offset, r, g, b, …, offset, a, …]. - let mut k: Vec = Vec::with_capacity(count * 6); - for (o, c) in stops { - let c = c.sanitized(); - k.extend([f64::from(o.clamp(0.0, 1.0)), f64::from(c.r), f64::from(c.g), f64::from(c.b)]); - } - for (o, c) in stops { - k.extend([f64::from(o.clamp(0.0, 1.0)), f64::from(c.sanitized().a)]); - } - colors.push(k); + colors.push(gradient_values(stops)); } } let (s, e, g) = (w.prop(first, &start, TOL_PX, Enc::Vector), w.prop(first, &end, TOL_PX, Enc::Vector), w.prop(first, &colors, TOL_COLOR, Enc::Vector)); @@ -1068,6 +1076,39 @@ mod tests { d } + #[test] + fn shared_gradient_values_match_legacy_before_keyframe_fitting() { + fn legacy(stops: &[(f32, Rgba)]) -> Vec { + let mut k = Vec::with_capacity(stops.len() * 6); + for (o, c) in stops { + let c = c.sanitized(); + k.extend([f64::from(o.clamp(0.0, 1.0)), f64::from(c.r), f64::from(c.g), f64::from(c.b)]); + } + for (o, c) in stops { + k.extend([f64::from(o.clamp(0.0, 1.0)), f64::from(c.sanitized().a)]); + } + k + } + let cases = [ + vec![], + vec![(0.12345679, Rgba::WHITE), (1.0, Rgba::BLACK)], + vec![(0.5, Rgba::new(0.2, 0.4, 0.6, 0.25)), (0.5, Rgba::WHITE)], + vec![ + (-1.0, Rgba { r: f32::NAN, g: f32::INFINITY, b: -1.0, a: 2.0 }), + (f32::NAN, Rgba::BLACK), + (f32::INFINITY, Rgba::WHITE), + (-0.0, Rgba::WHITE), + ], + ]; + for stops in cases { + let actual = gradient_values(&stops); + let expected = legacy(&stops); + assert_eq!(actual.iter().map(|x| x.to_bits()).collect::>(), expected.iter().map(|x| x.to_bits()).collect::>()); + assert_eq!(actual.iter().map(|x| num(*x)).collect::>(), expected.iter().map(|x| num(*x)).collect::>()); + assert_eq!(actual.len(), stops.len() * 6, "opaque alpha stops must survive animated fitting"); + } + } + #[test] fn soft_masks_become_track_mattes() { use anicraft_doc::MaskMode; @@ -1091,6 +1132,44 @@ mod tests { assert_eq!(v["layers"][0]["hasMask"], true); } + #[test] + fn transparent_stage_background_has_no_solid_layer() { + let mut d = sample::demo(); + d.stage.background = anicraft_doc::Rgba::new(1.0, 0.0, 0.0, 0.0); + let v = parse(&to_lottie(&d, "x", 0, 1, true)); + assert!(v["layers"].as_array().unwrap().iter().all(|l| l["ty"] != 1)); + } + + #[test] + fn semi_transparent_stage_background_sets_layer_opacity() { + let mut d = sample::demo(); + d.stage.background = anicraft_doc::Rgba::new(1.0, 0.0, 0.0, 0.5); + let v = parse(&to_lottie(&d, "x", 0, 1, true)); + let l = v["layers"].as_array().unwrap().iter().find(|l| l["ty"] == 1).unwrap(); + assert_eq!(l["ks"]["o"]["k"].as_f64(), Some(50.0)); + assert_eq!(l["sc"], "#ff0000"); + } + + #[test] + fn shared_path_wire_keeps_legacy_values_and_precision() { + for closed in [false, true] { + for flat in [ + vec![], + vec![1.23456], + vec![0.0, -0.0, f64::NAN, f64::INFINITY, 1.23456, -2.34567], + vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], + vec![1e303, -1e303, f64::MAX, -f64::MAX, 0.0, 0.0], + ] { + let pts: Vec = + flat.chunks(2).map(|c| json!([num(c.first().copied().unwrap_or(0.0)), num(c.get(1).copied().unwrap_or(0.0))])).collect(); + let k = pts.len() / 3; + let (v, rest) = pts.split_at(k); + let (i, o) = rest.split_at(k); + assert_eq!(Bez::flat_value(closed, &flat), json!({"c": closed, "v": v, "i": i, "o": o})); + } + } + } + #[test] fn beziers_bake_lines_quads_and_closing_points() { let mut p = Path::new(); diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 88f3f137..08f8975c 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -656,7 +656,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() }); } } - std::borrow::Cow::Owned(DisplayList { clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) + std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) } #[cfg(test)] diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index c92217a4..19f2efd0 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -79,8 +79,9 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { // Groups that fade as one become `` around their run of items. let chains = crate::group_chains(&dl.groups); let mut open: Vec = Vec::new(); - for item in dl.items.iter().filter(|it| it.masks.is_none() && !it.guide) { + for (index, item) in dl.items.iter().enumerate().filter(|(_, it)| it.masks.is_none() && !it.guide) { let Some(d) = stage_path(item) else { continue }; + let link = dl.links.binary_search_by_key(&(index as u32), |l| l.0).ok().and_then(|i| dl.links.get(i)).and_then(|l| anicraft_doc::safe_url(&l.1)); let want = item.group.and_then(|g| chains.get(g as usize)).map_or(&[][..], Vec::as_slice); let keep = open.iter().zip(want).take_while(|(o, g)| o == g).count(); while open.len() > keep { @@ -103,7 +104,14 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { open.push(g); } let clip = item.clip.filter(|&c| (c as usize) < dl.clip_parents.len()).map(|c| clip_attrs(dl, c)).unwrap_or_default(); + // Characters with a link (ADR 0085) are a link in the SVG. + if let Some(url) = &link { + let _ = write!(body, "", attr_escape(url)); + } draw(item, &d, &clip, &mut body, &mut defs, &mut grad, &mut images); + if link.is_some() { + body.push_str(""); + } } for _ in open { body.push_str(""); @@ -583,7 +591,7 @@ mod tests { *spread = anicraft_doc::Spread::Reflect; } let items = vec![item(Path::rect(0.0, 0.0, 60.0, 60.0), Some(rad)), item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(lin))]; - let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.contains("spreadMethod=\"repeat\"") && svg.contains("spreadMethod=\"reflect\""), "{svg}"); assert!(svg.contains("color-interpolation=\"linearRGB\""), "{svg}"); assert!(svg.contains("fx=\"40\" fy=\"30\""), "focal point half way along the ring's x axis: {svg}"); @@ -612,7 +620,7 @@ mod tests { a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0)); a.color = ColorTransform::alpha(0.5); a.fill_rule = FillRule::EvenOdd; - let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.starts_with("")); assert!(svg.contains(""), "background"); assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}"); @@ -627,7 +635,7 @@ mod tests { let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None); a.transform = Affine::scale(2.0, 2.0); a.stroke = Some(st); - to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) + to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) }; // The default style is written as before: round, no dashes. let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0)); @@ -647,7 +655,7 @@ mod tests { fn variable_width_strokes_are_written_as_filled_outlines() { let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000)))); a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile())); - let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}"); assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour"); assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays"); @@ -664,7 +672,7 @@ mod tests { outer.masks = Some(0); let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK))); inner.masks = Some(1); - let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}"); assert!(svg.contains("")); assert!(svg.contains(""), "nested clip"); @@ -717,7 +725,7 @@ mod tests { let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT))); let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK))); lost.clip = Some(7); - let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); assert_eq!(svg.matches(""), "a malformed clip clips everything"); assert!(!svg.contains("NaN") && !svg.contains("inf")); @@ -751,7 +759,7 @@ mod group_tests { smooth: true, warp: None, }; - let dl = DisplayList { clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }; + let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }; let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE }); assert!(svg.contains("") && svg.contains(""), "{svg}"); assert_eq!(svg.matches("").count(), "balanced"); @@ -760,3 +768,20 @@ mod group_tests { assert_eq!(order, ["path", "g", "path", "g", "path", "/g", "path", "/g", "path"], "{svg}"); } } + +/// `s` safe inside a double-quoted XML attribute. +fn attr_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => {} + c => out.push(c), + } + } + out +} diff --git a/crates/svg/src/text.rs b/crates/svg/src/text.rs index 925fa7ae..0ff1db8c 100644 --- a/crates/svg/src/text.rs +++ b/crates/svg/src/text.rs @@ -539,6 +539,7 @@ impl<'a> Builder<'a> { box_height: layout.height, field: None, on_path: None, + ..TextBlock::default() }; Ok(Some((block, ascent))) } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index ce73b89d..7a60f3fe 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -11,9 +11,11 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use anicraft_geom::{Path, PathCmd, Vec2}; -use skrifa::MetadataProvider as _; use std::sync::{Arc, OnceLock}; +mod rich; +pub use rich::{MAX_FACES, MAX_RUNS, ParaStyle, RichText, Run, RunStyle, Shift, sanitize_para, sanitize_run}; + /// Families tried, in order, when none is asked for or the one asked for isn't installed. pub const DEFAULT_FAMILIES: &[&str] = &["Inter", "Arial", "Helvetica", "Helvetica Neue", "Segoe UI", "DejaVu Sans", "Liberation Sans", "Noto Sans", "Roboto", "Ubuntu"]; @@ -83,6 +85,11 @@ pub struct Layout { /// Each glyph on its own, in drawing order: only from [`Fonts::layout_glyphs`] (empty /// otherwise). pub glyphs: Vec, + /// The outline cut by the runs' paints ([`RunStyle::paint`]), in the order paints first + /// appear: `outline` is these pieces one after another (ADR 0085). + pub pieces: Vec<(u32, Path)>, + /// The family each run was laid out in (the one asked for, or the fallback). + pub families: Vec, } /// One laid-out glyph on its own. @@ -98,6 +105,8 @@ pub struct PlacedGlyph { pub advance: f32, /// The character it starts at (`char`s of the whole text, line breaks included). pub index: u32, + /// Its run's paint ([`RunStyle::paint`]). + pub paint: u32, } /// How text follows a path (ADR 0070). @@ -114,8 +123,10 @@ pub struct PathPlacement { /// Glyphs set along a path. #[derive(Clone, Debug, PartialEq)] pub struct PathText { - /// Every glyph shown, in the path's space. + /// Every glyph shown, in the path's space: `pieces` one after another. pub outline: Path, + /// The glyphs by paint, in the order paints first appear. + pub pieces: Vec<(u32, Path)>, /// The path's length. pub length: f32, /// Each shown glyph's character, the point on the path under its middle and its angle @@ -144,7 +155,7 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio Align::Center => width * 0.5, Align::Right => width, }; - let mut out = PathText { outline: Path::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 }; + let mut out = PathText { outline: Path::new(), pieces: Vec::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 }; for g in glyphs { let mid = start + g.x + g.advance * 0.5; if !mid.is_finite() { @@ -162,9 +173,21 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio let (p, t) = if how.flip { (walk.at(length - s), walk.tangent(length - s) * -1.0) } else { (walk.at(s), walk.tangent(s)) }; let angle = t.y.atan2(t.x); let m = anicraft_geom::Affine::translate(p.x, p.y).mul(&anicraft_geom::Affine::rotate(angle)).mul(&anicraft_geom::Affine::translate(-g.advance * 0.5, 0.0)); - out.outline.cmds.extend(g.outline.transformed(&m).cmds); + let k = match out.pieces.iter().position(|(paint, _)| *paint == g.paint) { + Some(k) => k, + None => { + out.pieces.push((g.paint, Path::new())); + out.pieces.len() - 1 + } + }; + if let Some((_, piece)) = out.pieces.get_mut(k) { + piece.cmds.extend(g.outline.transformed(&m).cmds); + } out.placed.push((g.index, p, angle)); } + for (_, piece) in &out.pieces { + out.outline.cmds.extend_from_slice(&piece.cmds); + } Some(out) } @@ -173,6 +196,8 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio #[derive(Clone, Debug, PartialEq)] pub struct BoxedPathText { pub outline: Path, + /// The glyphs by paint (see [`PathText::pieces`]). + pub pieces: Vec<(u32, Path)>, pub path: Path, pub width: f32, pub height: f32, @@ -188,7 +213,8 @@ pub fn on_path_boxed(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> let shift = if b.min.x.is_finite() && b.min.y.is_finite() { b.min } else { Vec2::ZERO }; let back = anicraft_geom::Affine::translate(-shift.x, -shift.y); let size = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 }; - Some(BoxedPathText { outline: set.outline.transformed(&back), path: path.transformed(&back), width: size(b.width()), height: size(b.height()), shift, hidden: set.hidden }) + let pieces = set.pieces.iter().map(|(k, p)| (*k, p.transformed(&back))).collect(); + Some(BoxedPathText { outline: set.outline.transformed(&back), pieces, path: path.transformed(&back), width: size(b.width()), height: size(b.height()), shift, hidden: set.hidden }) } /// Whether a path's first subpath ends with a close. @@ -213,6 +239,11 @@ pub struct CaretLine { pub end: u32, /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending. pub stops: Vec<(u32, f32)>, + /// The line's top and height (to the next line's top, its line spacing included) and its + /// baseline, from the box's top (pixels). + pub top: f32, + pub height: f32, + pub baseline: f32, } impl CaretLine { @@ -395,19 +426,10 @@ impl Fonts { } fn lay_out_with(&self, text: &str, style: &Style, glyphs: bool) -> Result { - if text.chars().count() > MAX_CHARS { - return Err(TextError::TooLong); - } - let family = self.resolve(&style.family).ok_or(TextError::NoFonts)?; - let q = fontdb::Query { - families: &[fontdb::Family::Name(&family)], - weight: if style.bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL }, - stretch: fontdb::Stretch::Normal, - style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, - }; - let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style, glyphs)).flatten().ok_or(TextError::NoFonts)?; - Ok(Layout { family, ..laid }) + let style = sanitize(style); + let run = Run { chars: usize::MAX, style: RunStyle { family: style.family.clone(), size: style.size, bold: style.bold, italic: style.italic, letter_spacing: style.letter_spacing, ..RunStyle::default() } }; + let para = ParaStyle { align: style.align, line_spacing: style.line_spacing, ..ParaStyle::default() }; + self.layout_rich(&RichText { text, runs: &[run], paragraphs: &[para], width: style.width }, glyphs) } } @@ -449,192 +471,8 @@ pub fn sanitize(style: &Style) -> Style { } } -/// One shaped glyph: id, where its pen position starts, its offsets and advance (pixels). -struct Glyph { - id: skrifa::GlyphId, - cluster: usize, - x_offset: f32, - y_offset: f32, - advance: f32, -} - -fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool) -> Option { - let style = sanitize(style); - let font = skrifa::FontRef::from_index(data, index).ok()?; - let size = skrifa::instance::Size::new(style.size); - let metrics = font.metrics(size, skrifa::instance::LocationRef::default()); - let upem = f32::from(metrics.units_per_em.max(1)); - let scale = style.size / upem; - let ascent = metrics.ascent; - let line_height = (metrics.ascent - metrics.descent + metrics.leading).max(style.size * 0.5) + style.line_spacing; - let shaper_data = harfrust::ShaperData::new(&font); - let shaper = shaper_data.shaper(&font).build(); - let glyphs = font.outline_glyphs(); - let charmap = font.charmap(); - let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); - - // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. - let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new(); - // Per line: the character index its paragraph starts at, the paragraph's length in - // characters, and the byte → character map of the paragraph (shared by its lines). - let mut spans: Vec<(u32, u32, Arc>)> = Vec::new(); - let mut para_start = 0u32; - for raw in text.split('\n') { - let para = raw.strip_suffix('\r').unwrap_or(raw); - let mut to_char = vec![0u32; para.len() + 1]; - let mut n = 0u32; - for (b, _) in para.char_indices() { - if let Some(slot) = to_char.get_mut(b) { - *slot = n; - } - n += 1; - } - if let Some(last) = to_char.last_mut() { - *last = n; - } - let to_char = Arc::new(to_char); - let lines_before = lines.len(); - let mut buffer = harfrust::UnicodeBuffer::new(); - buffer.push_str(para); - buffer.guess_segment_properties(); - let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); - let run: Vec = shaped - .glyph_infos() - .iter() - .zip(shaped.glyph_positions()) - .map(|(info, pos)| Glyph { - id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, - x_offset: pos.x_offset as f32 * scale, - y_offset: pos.y_offset as f32 * scale, - advance: pos.x_advance as f32 * scale + style.letter_spacing, - }) - .collect(); - let is_space = |g: &Glyph| para.get(g.cluster..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace); - let mut line: Vec<(Glyph, f32)> = Vec::new(); - let mut x = 0.0f32; - // Where the current line could break: after its last space. - let mut break_at: Option = None; - for g in run { - let space = is_space(&g); - if let Some(w) = style.width - && !space - && x + g.advance > w - && !line.is_empty() - { - // Wrap: at the last space if there is one (dropping trailing spaces), else here. - let rest = match break_at { - Some(b) => line.split_off(b), - None => Vec::new(), - }; - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); - } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, std::mem::take(&mut line))); - let shift = rest.first().map_or(0.0, |(_, gx)| *gx); - line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); - x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - break_at = None; - } - line.push((g, x)); - x += line.last().map_or(0.0, |(g, _)| g.advance); - if space { - break_at = Some(line.len()); - } - } - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); - } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, line)); - for _ in lines_before..lines.len() { - spans.push((para_start, n, to_char.clone())); - } - para_start += raw.chars().count() as u32 + 1; - } - - let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); - let mut outline = Path::new(); - let mut placed: Vec = Vec::new(); - for (row, (width, line)) in lines.iter().enumerate() { - let shift = match style.align { - Align::Left => 0.0, - Align::Center => (box_width - width) * 0.5, - Align::Right => box_width - width, - }; - let baseline = ascent + row as f32 * line_height; - let span = spans.get(row); - for (g, gx) in line { - let Some(glyph) = glyphs.get(g.id) else { continue }; - if want_glyphs { - let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); - let mut own = Path::new(); - let mut pen = Pen { cmds: &mut own.cmds, x: g.x_offset, y: -g.y_offset }; - let _ = glyph.draw(settings, &mut pen); - let index = span.map_or(0, |(pstart, plen, to_char)| pstart + to_char.get(g.cluster).copied().unwrap_or(*plen).min(*plen)); - placed.push(PlacedGlyph { outline: own, x: shift + gx, baseline, advance: g.advance, index }); - } - let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); - let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; - let _ = glyph.draw(settings, &mut pen); - } - } - let height = (lines.len().max(1) as f32 - 1.0) * line_height + (metrics.ascent - metrics.descent); - let carets = caret_lines(&lines, &spans, box_width, style.align); - Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent, carets, glyphs: placed }) -} - -/// The caret positions of laid-out lines (see [`CaretLine`]). -fn caret_lines(lines: &[(f32, Vec<(Glyph, f32)>)], spans: &[(u32, u32, Arc>)], box_width: f32, align: Align) -> Vec { - let mut out: Vec = Vec::with_capacity(lines.len()); - for (row, ((width, line), (pstart, plen, to_char))) in lines.iter().zip(spans).enumerate() { - let shift = match align { - Align::Left => 0.0, - Align::Center => (box_width - width) * 0.5, - Align::Right => box_width - width, - }; - let ch = |cluster: usize| pstart + to_char.get(cluster).copied().unwrap_or(*plen).min(*plen); - // A paragraph's first line starts with it; a wrapped line at its first glyph. - let first_of_para = row == 0 || spans.get(row - 1).is_none_or(|p| p.0 != *pstart); - let start = if first_of_para { *pstart } else { line.first().map_or(*pstart, |(g, _)| ch(g.cluster)) }; - let mut stops: Vec<(u32, f32)> = line.iter().map(|(g, gx)| (ch(g.cluster), shift + gx)).collect(); - stops.sort_by_key(|s| s.0); - stops.dedup_by_key(|s| s.0); - if first_of_para && stops.first().is_none_or(|s| s.0 > start) { - stops.insert(0, (start, shift)); - } - // The boundary after the last glyph (its trailing spaces, if any, follow it). - if let Some(&(c, _)) = stops.last() { - stops.push((c + 1, shift + width)); - } - out.push(CaretLine { start, end: start, stops }); - // The previous line of the same paragraph ends where this one starts. - if !first_of_para && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) { - prev.end = start; - } - } - // The last line of each paragraph ends with it. - for (row, (pstart, plen, _)) in spans.iter().enumerate() { - let last_of_para = spans.get(row + 1).is_none_or(|p| p.0 != *pstart); - if last_of_para && let Some(l) = out.get_mut(row) { - l.end = pstart + plen; - } - } - for l in &mut out { - l.end = l.end.max(l.start); - let end = l.end; - l.stops.retain(|s| s.0 <= end); - if l.stops.last().is_none_or(|s| s.0 < end) { - let x = l.stops.last().map_or(0.0, |s| s.1); - l.stops.push((end, x)); - } - } - out -} - /// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position. -struct Pen<'a> { +pub(crate) struct Pen<'a> { cmds: &'a mut Vec, x: f32, y: f32, @@ -808,7 +646,7 @@ mod tests { /// Synthetic glyphs: a 10 × 20 box standing on the baseline, `n` of them 10 apart. fn boxes(n: u32) -> Vec { - (0..n).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 20.0, advance: 10.0, index: i }).collect() + (0..n).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 20.0, advance: 10.0, index: i, paint: 0 }).collect() } #[test] @@ -884,7 +722,7 @@ cd", &style(20.0)).unwrap(); assert_eq!((w.carets[0].start, w.carets[0].end, w.carets[1].start, w.carets[1].end), (0, 4, 4, 7)); // Empty text has one line with one place for the caret; centred text starts mid-box. let e = fonts.layout("", &style(20.0)).unwrap(); - assert_eq!(e.carets, vec![CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }]); + assert_eq!((e.carets.len(), e.carets[0].start, e.carets[0].end, e.carets[0].stops.clone()), (1, 0, 0, vec![(0, 0.0)])); let c = fonts.layout("", &Style { width: Some(100.0), align: Align::Center, ..style(20.0) }).unwrap(); assert_eq!(c.carets[0].x_at(0), 50.0); } diff --git a/crates/text/src/rich.rs b/crates/text/src/rich.rs new file mode 100644 index 00000000..50f5aaa1 --- /dev/null +++ b/crates/text/src/rich.rs @@ -0,0 +1,636 @@ +//! Styled text (ADR 0085): runs of characters, each in its own face, size, spacing, baseline +//! shift and underline, in paragraphs with their own alignment, indent, margins and line +//! spacing. Each run is shaped on its own with `harfrust`, lines break across runs, and the +//! glyphs come out grouped by the run's `paint` (the caller's colour and link), so a block with +//! several colours draws as one filled path per colour. +//! +//! One run in one paragraph lays out exactly as [`crate::Fonts::layout`] always has: the same +//! outline, box, lines and carets. + +use crate::{Align, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError}; +use anicraft_geom::{Path, PathCmd, Vec2}; +use skrifa::MetadataProvider as _; +use skrifa::raw::TableProvider as _; +use std::collections::HashMap; +use std::sync::Arc; + +/// Most runs laid out in one block; more are joined into the last. +pub const MAX_RUNS: usize = 10_000; + +/// Most different faces (family, bold, italic) in one block; runs past it use the first face. +pub const MAX_FACES: usize = 64; + +/// Where a run sits against the line's baseline. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Shift { + #[default] + Normal, + /// Smaller and raised, by the font's own superscript size and offset. + Superscript, + /// Smaller and lowered, by the font's own subscript size and offset. + Subscript, +} + +/// One run's character style. +#[derive(Clone, Debug, PartialEq)] +pub struct RunStyle { + pub family: String, + /// The em size in pixels (before a superscript or subscript makes it smaller). + pub size: f32, + pub bold: bool, + pub italic: bool, + /// Extra space after each character, in pixels. + pub letter_spacing: f32, + pub shift: Shift, + pub underline: bool, + /// The caller's paint for these glyphs (a colour and link): glyphs come out grouped by it. + pub paint: u32, +} + +impl Default for RunStyle { + fn default() -> Self { + RunStyle { family: String::new(), size: 32.0, bold: false, italic: false, letter_spacing: 0.0, shift: Shift::Normal, underline: false, paint: 0 } + } +} + +/// A run: this many characters (`char`s, line breaks included) in this style. +#[derive(Clone, Debug, PartialEq)] +pub struct Run { + pub chars: usize, + pub style: RunStyle, +} + +/// One paragraph's layout. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ParaStyle { + pub align: Align, + /// The first line starts this much further in (pixels; negative hangs it out). + pub indent: f32, + /// Space kept clear at the box's left and right (pixels). + pub left_margin: f32, + pub right_margin: f32, + /// Extra space below each of its lines (pixels), added to the font's line height. + pub line_spacing: f32, +} + +/// Text with its runs and paragraphs. Runs cover the text from its start (a shorter list leaves +/// the rest in the last run's style; a longer one is cut at the text's end); paragraphs are the +/// text's lines (split at `\n`), in order (missing ones take the last one's style). +#[derive(Clone, Copy, Debug)] +pub struct RichText<'a> { + pub text: &'a str, + pub runs: &'a [Run], + pub paragraphs: &'a [ParaStyle], + /// Lines wrap to this width (pixels); `None` keeps each paragraph on one line. + pub width: Option, +} + +fn fin(v: f32, d: f32) -> f32 { + if v.is_finite() { v } else { d } +} + +/// A run style clamped to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). +pub fn sanitize_run(s: &RunStyle) -> RunStyle { + RunStyle { size: fin(s.size, 32.0).clamp(1.0, 2000.0), letter_spacing: fin(s.letter_spacing, 0.0).clamp(-1000.0, 1000.0), ..s.clone() } +} + +/// A paragraph style clamped to sane ranges (indent within ±10000 px, margins 0 to 10000 px, +/// line spacing within ±1000 px). +pub fn sanitize_para(p: &ParaStyle) -> ParaStyle { + ParaStyle { + align: p.align, + indent: fin(p.indent, 0.0).clamp(-10_000.0, 10_000.0), + left_margin: fin(p.left_margin, 0.0).clamp(0.0, 10_000.0), + right_margin: fin(p.right_margin, 0.0).clamp(0.0, 10_000.0), + line_spacing: fin(p.line_spacing, 0.0).clamp(-1000.0, 1000.0), + } +} + +/// A run's vertical metrics at its own size (pixels): what a line it is on must make room for. +#[derive(Clone, Copy, Debug, Default)] +struct RunMetrics { + ascent: f32, + /// Below the baseline, positive. + descent: f32, + /// The font's line height ((ascent − descent + leading), at least half the size). + height: f32, + /// The underline's top above the baseline (negative: below) and its thickness. + underline: (f32, f32), + /// How far a superscript or subscript moves the baseline (pixels, y down) and the size its + /// glyphs are drawn at. + shift_y: f32, + glyph_size: f32, +} + +/// One shaped glyph, ready to place. +struct Shaped { + outline: Option>, + /// Character it starts at (of the whole text). + index: u32, + run: u32, + x_offset: f32, + y_offset: f32, + advance: f32, + space: bool, +} + +/// A stretch of one paragraph in one run: what is shaped on its own. +struct Segment { + run: usize, + /// Byte range in the text, and the character its start is. + bytes: (usize, usize), + first_char: u32, +} + +/// A laid-out line: its paragraph, whether it is the paragraph's first, its width, its glyphs +/// with their pen x (from the line's start). +struct Line { + para: usize, + first: bool, + width: f32, + glyphs: Vec<(Shaped, f32)>, +} + +/// One paragraph: its first character, its length in characters, and its byte range (without +/// a trailing `\r`). +struct Para { + start: u32, + len: u32, + bytes: (usize, usize), +} + +impl Fonts { + /// Lays styled text out ([`RichText`]). `glyphs` also hands back each glyph on its own. + pub fn layout_rich(&self, rich: &RichText, glyphs: bool) -> Result { + let text = rich.text; + let n_chars = text.chars().count(); + if n_chars > MAX_CHARS { + return Err(TextError::TooLong); + } + // Runs as character ranges over the whole text, sanitized. + let mut runs: Vec<(u32, u32, RunStyle)> = Vec::new(); + let mut at = 0usize; + for r in rich.runs.iter().take(MAX_RUNS) { + if at >= n_chars && !runs.is_empty() { + break; + } + let end = at.saturating_add(r.chars).min(n_chars); + runs.push((at as u32, end as u32, sanitize_run(&r.style))); + at = end; + } + if runs.is_empty() { + runs.push((0, n_chars as u32, RunStyle::default())); + } + if let Some(last) = runs.last_mut() { + last.1 = n_chars as u32; + } + // Faces: one per family, weight and slant. + let mut faces: Vec<(fontdb::ID, String)> = Vec::new(); + let mut face_of_run: Vec = Vec::with_capacity(runs.len()); + let mut families: Vec = Vec::with_capacity(runs.len()); + let mut keys: HashMap<(String, bool, bool), usize> = HashMap::new(); + for (_, _, st) in &runs { + let family = self.resolve(&st.family).ok_or(TextError::NoFonts)?; + let key = (family.clone(), st.bold, st.italic); + let face = match keys.get(&key) { + Some(&f) => f, + None if faces.len() >= MAX_FACES => 0, + None => { + let q = fontdb::Query { + families: &[fontdb::Family::Name(&family)], + weight: if st.bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL }, + stretch: fontdb::Stretch::Normal, + style: if st.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, + }; + let id = self.db.query(&q).ok_or(TextError::NoFonts)?; + faces.push((id, family.clone())); + keys.insert(key, faces.len() - 1); + faces.len() - 1 + } + }; + face_of_run.push(face); + families.push(faces.get(face).map_or(family, |f| f.1.clone())); + } + let chars: Vec = text.chars().collect(); + + // Paragraphs at line breaks. + let mut paras: Vec = Vec::new(); + let (mut byte, mut ch) = (0usize, 0u32); + for raw in text.split('\n') { + let body = raw.strip_suffix('\r').unwrap_or(raw); + let len = body.chars().count() as u32; + paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()) }); + byte += raw.len() + 1; + ch += raw.chars().count() as u32 + 1; + } + // Byte offset of every character (and of the end). + let mut byte_of: Vec = text.char_indices().map(|(b, _)| b).collect(); + byte_of.push(text.len()); + // Segments: each paragraph cut at run boundaries (both in order: one pass over each). + let mut segs: Vec<(usize, Segment)> = Vec::new(); + let mut ri = 0usize; + for (pi, p) in paras.iter().enumerate() { + let (s, e) = (p.start, p.start + p.len); + while runs.get(ri).is_some_and(|r| r.1 <= s) && ri + 1 < runs.len() { + ri += 1; + } + let mut k = ri; + while let Some((rs, re, _)) = runs.get(k) { + if *rs >= e { + break; + } + let (a, b) = (s.max(*rs), e.min(*re)); + if a < b { + let bytes = (byte_of.get(a as usize).copied().unwrap_or(p.bytes.1), byte_of.get(b as usize).copied().unwrap_or(p.bytes.1)); + segs.push((pi, Segment { run: k, bytes, first_char: a })); + } + k += 1; + } + } + // The segments of each run. + let mut segs_of_run: Vec> = vec![Vec::new(); runs.len()]; + for (si, (_, seg)) in segs.iter().enumerate() { + if let Some(list) = segs_of_run.get_mut(seg.run) { + list.push(si); + } + } + // Shape every segment and read every run's metrics, face by face. + let mut runs_of_face: Vec> = vec![Vec::new(); faces.len()]; + for (ri, f) in face_of_run.iter().enumerate() { + if let Some(list) = runs_of_face.get_mut(*f) { + list.push(ri); + } + } + let mut shaped: Vec> = (0..segs.len()).map(|_| Vec::new()).collect(); + let mut metrics: Vec = vec![RunMetrics::default(); runs.len()]; + let mut missing = 0usize; + for (fi, (id, _)) in faces.iter().enumerate() { + let ok = self.db.with_face_data(*id, |data, index| { + let font = skrifa::FontRef::from_index(data, index).ok()?; + let shaper_data = harfrust::ShaperData::new(&font); + let shaper = shaper_data.shaper(&font).build(); + let outlines = font.outline_glyphs(); + let charmap = font.charmap(); + let os2 = font.os2().ok(); + let mut cache: HashMap<(u32, u32), Option>> = HashMap::new(); + for &ri in runs_of_face.get(fi).map_or(&[][..], Vec::as_slice) { + let Some((rs, re, st)) = runs.get(ri) else { continue }; + let m = run_metrics(&font, os2.as_ref(), st); + if let Some(slot) = metrics.get_mut(ri) { + *slot = m; + } + missing += chars.get(*rs as usize..*re as usize).unwrap_or(&[]).iter().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(**c).is_none()).count(); + let size = skrifa::instance::Size::new(m.glyph_size); + let upem = f32::from(skrifa::MetadataProvider::metrics(&font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1)); + let scale = m.glyph_size / upem; + for &si in segs_of_run.get(ri).map_or(&[][..], Vec::as_slice) { + let Some((_, seg)) = segs.get(si) else { continue }; + let Some(piece) = text.get(seg.bytes.0..seg.bytes.1) else { continue }; + let mut to_char = vec![0u32; piece.len() + 1]; + let mut n = 0u32; + for (b, _) in piece.char_indices() { + if let Some(slot) = to_char.get_mut(b) { + *slot = n; + } + n += 1; + } + if let Some(last) = to_char.last_mut() { + *last = n; + } + let mut buffer = harfrust::UnicodeBuffer::new(); + buffer.push_str(piece); + buffer.guess_segment_properties(); + let out = shaper.shape(buffer, harfrust::ShapeOptions::new()); + let mut list: Vec = Vec::with_capacity(out.glyph_infos().len()); + for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) { + let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n); + let index = seg.first_char + local; + let outline = cache + .entry((info.glyph_id, m.glyph_size.to_bits())) + .or_insert_with(|| { + let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?; + let mut p = Path::new(); + let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); + let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 }; + let _ = g.draw(settings, &mut pen); + Some(Arc::new(p)) + }) + .clone(); + list.push(Shaped { + outline, + index, + run: ri as u32, + x_offset: pos.x_offset as f32 * scale, + y_offset: pos.y_offset as f32 * scale, + advance: pos.x_advance as f32 * scale + st.letter_spacing, + space: chars.get(index as usize).is_some_and(|c| c.is_whitespace()), + }); + } + if let Some(slot) = shaped.get_mut(si) { + *slot = list; + } + } + } + Some(()) + }); + if ok.flatten().is_none() { + return Err(TextError::NoFonts); + } + } + + // Paragraph styles, sanitized; missing ones take the last one's. + let para_style = |pi: usize| -> ParaStyle { rich.paragraphs.get(pi).or(rich.paragraphs.last()).map(sanitize_para).unwrap_or_default() }; + let width = rich.width.filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0)); + + // Lines: each paragraph's glyphs, wrapped at spaces to its room if there is a width. + let mut lines: Vec = Vec::new(); + let mut seg_iter = segs.into_iter().zip(shaped).peekable(); + for (pi, _) in paras.iter().enumerate() { + let ps = para_style(pi); + let mut run_glyphs: Vec = Vec::new(); + while let Some(((p, _), _)) = seg_iter.peek() { + if *p != pi { + break; + } + if let Some((_, g)) = seg_iter.next() { + run_glyphs.extend(g); + } + } + let room = |first: bool| width.map(|w| w - ps.left_margin - ps.right_margin - if first { ps.indent } else { 0.0 }); + let mut first = true; + let mut line: Vec<(Shaped, f32)> = Vec::new(); + let mut x = 0.0f32; + // Where the current line could break: after its last space. + let mut break_at: Option = None; + for g in run_glyphs { + if let Some(w) = room(first) + && !g.space + && x + g.advance > w + && !line.is_empty() + { + // Wrap: at the last space if there is one (dropping trailing spaces), else here. + let rest = match break_at { + Some(b) => line.split_off(b), + None => Vec::new(), + }; + while line.last().is_some_and(|(g, _)| g.space) { + line.pop(); + } + let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance); + lines.push(Line { para: pi, first, width: lw, glyphs: std::mem::take(&mut line) }); + first = false; + let shift = rest.first().map_or(0.0, |(_, gx)| *gx); + line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); + x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); + break_at = None; + } + line.push((g, x)); + x += line.last().map_or(0.0, |(g, _)| g.advance); + if line.last().is_some_and(|(g, _)| g.space) { + break_at = Some(line.len()); + } + } + while line.last().is_some_and(|(g, _)| g.space) { + line.pop(); + } + let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance); + lines.push(Line { para: pi, first, width: lw, glyphs: line }); + } + + // Each line's room above and below its baseline: the most any run on it needs (an + // empty line: the run its paragraph starts in). `(ascent, descent, line height)`, the + // height with the paragraph's line spacing. + let run_at = |c: u32| runs.partition_point(|r| r.0 <= c).saturating_sub(1); + let line_metrics = |l: &Line| -> (f32, f32, f32) { + let mut list: Vec = l.glyphs.iter().map(|(g, _)| g.run as usize).collect(); + if list.is_empty() { + let start = paras.get(l.para).map_or(0, |p| p.start); + list.push(run_at(if start > 0 && start as usize >= n_chars { start - 1 } else { start })); + } + list.sort_unstable(); + list.dedup(); + let ls = para_style(l.para).line_spacing; + if let [one] = list.as_slice() { + let m = metrics.get(*one).copied().unwrap_or_default(); + return (m.ascent, m.descent, m.height + ls); + } + let (mut asc, mut below, mut desc) = (f32::MIN, f32::MIN, f32::MIN); + for r in list { + let m = metrics.get(r).copied().unwrap_or_default(); + asc = asc.max(m.ascent); + below = below.max(m.height - m.ascent); + desc = desc.max(m.descent); + } + (asc, desc, asc + below + ls) + }; + let lm: Vec<(f32, f32, f32)> = lines.iter().map(line_metrics).collect(); + // Every line alike (one style): baselines a line height apart, as text always was. + let uniform = lm.windows(2).all(|w| matches!(w, [a, b] if a == b)); + let mut tops: Vec = Vec::with_capacity(lines.len()); + let first = lm.first().copied().unwrap_or((0.0, 0.0, 0.0)); + let line_height = first.2; + let height = if uniform { + for row in 0..lines.len() { + tops.push(row as f32 * line_height); + } + (lines.len().max(1) as f32 - 1.0) * line_height + (first.0 - -first.1) + } else { + let mut top = 0.0f32; + for m in &lm { + tops.push(top); + top += m.2; + } + let last = lm.last().copied().unwrap_or(first); + tops.last().copied().unwrap_or(0.0) + last.0 + last.1 + }; + + let box_width = width.unwrap_or_else(|| { + lines + .iter() + .map(|l| { + let ps = para_style(l.para); + ps.left_margin + if l.first { ps.indent } else { 0.0 } + l.width + ps.right_margin + }) + .fold(0.0, f32::max) + }); + let shift_of = |l: &Line| -> f32 { + let ps = para_style(l.para); + let start = ps.left_margin + if l.first { ps.indent } else { 0.0 }; + match ps.align { + Align::Left => start, + Align::Center => start + ((box_width - ps.right_margin - start) - l.width) * 0.5, + Align::Right => box_width - ps.right_margin - l.width, + } + }; + + // Draw: glyphs grouped by paint, in the order paints first appear. + let mut pieces: Vec<(u32, Path)> = Vec::new(); + let mut piece_of: HashMap = HashMap::new(); + let mut placed: Vec = Vec::new(); + let paint_of = |r: u32| runs.get(r as usize).map_or(0, |x| x.2.paint); + for (row, l) in lines.iter().enumerate() { + let shift = shift_of(l); + let top = tops.get(row).copied().unwrap_or(0.0); + let base = if uniform { first.0 + top } else { top + lm.get(row).map_or(0.0, |m| m.0) }; + let mut underline: Option<(u32, f32, f32)> = None; + let flush = |u: Option<(u32, f32, f32)>, pieces: &mut Vec<(u32, Path)>, piece_of: &mut HashMap| { + let Some((r, x0, x1)) = u else { return }; + let m = metrics.get(r as usize).copied().unwrap_or_default(); + let (top, thick) = m.underline; + let rect = Path::rect(x0, base + m.shift_y - top, (x1 - x0).max(0.0), thick); + let k = *piece_of.entry(paint_of(r)).or_insert_with(|| { + pieces.push((paint_of(r), Path::new())); + pieces.len() - 1 + }); + if let Some(p) = pieces.get_mut(k) { + p.1.cmds.extend(rect.cmds); + } + }; + for (g, gx) in &l.glyphs { + let st = runs.get(g.run as usize).map(|r| &r.2); + let m = metrics.get(g.run as usize).copied().unwrap_or_default(); + // Underlines: one bar per stretch of an underlined run on the line. + let under = st.is_some_and(|s| s.underline); + match underline { + Some((r, x0, _)) if under && r == g.run => underline = Some((r, x0, shift + gx + g.advance)), + _ => { + flush(underline.take(), &mut pieces, &mut piece_of); + if under { + underline = Some((g.run, shift + gx, shift + gx + g.advance)); + } + } + } + let Some(outline) = &g.outline else { continue }; + let paint = paint_of(g.run); + let k = *piece_of.entry(paint).or_insert_with(|| { + pieces.push((paint, Path::new())); + pieces.len() - 1 + }); + let (px, py) = (shift + gx + g.x_offset, base + m.shift_y - g.y_offset); + if let Some(p) = pieces.get_mut(k) { + p.1.cmds.extend(outline.cmds.iter().map(|c| moved(c, px, py))); + } + if glyphs { + let (ox, oy) = (g.x_offset, m.shift_y - g.y_offset); + let own = Path { cmds: outline.cmds.iter().map(|c| moved(c, ox, oy)).collect() }; + placed.push(PlacedGlyph { outline: own, x: shift + gx, baseline: base, advance: g.advance, index: g.index, paint }); + } + } + flush(underline.take(), &mut pieces, &mut piece_of); + } + let mut outline = Path::new(); + for (_, p) in &pieces { + outline.cmds.extend_from_slice(&p.cmds); + } + let carets = caret_lines(&lines, ¶s, &tops, &lm, uniform, first.0, &shift_of); + Ok(Layout { + outline, + width: box_width.max(0.0), + height: height.max(0.0), + family: families.first().cloned().unwrap_or_default(), + missing, + lines: lines.len().max(1), + line_height, + ascent: first.0, + carets, + glyphs: placed, + pieces, + families, + }) + } +} + +/// A path command moved by `(dx, dy)`, added the way a pen at that position draws it. +fn moved(c: &PathCmd, dx: f32, dy: f32) -> PathCmd { + let m = |p: Vec2| Vec2::new(dx + p.x, dy + p.y); + match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(m(p)), + PathCmd::LineTo(p) => PathCmd::LineTo(m(p)), + PathCmd::QuadTo(a, p) => PathCmd::QuadTo(m(a), m(p)), + PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(m(a), m(b), m(p)), + PathCmd::Close => PathCmd::Close, + } +} + +/// A run's metrics in its face at its size. +fn run_metrics(font: &skrifa::FontRef, os2: Option<&skrifa::raw::tables::os2::Os2>, st: &RunStyle) -> RunMetrics { + let size = skrifa::instance::Size::new(st.size); + let m = skrifa::MetadataProvider::metrics(font, size, skrifa::instance::LocationRef::default()); + let em = f32::from(m.units_per_em.max(1)); + // The font's superscript and subscript size and offset (OS/2), else the usual ones. + let (scale, raise) = match st.shift { + Shift::Normal => (1.0, 0.0), + Shift::Superscript => { + let s = os2.map_or(0.0, |o| f32::from(o.y_superscript_y_size()) / em); + let o = os2.map_or(0.0, |o| f32::from(o.y_superscript_y_offset()) / em); + (if (0.3..=1.0).contains(&s) { s } else { 0.65 }, if (0.05..=1.0).contains(&o) { o } else { 0.35 }) + } + Shift::Subscript => { + let s = os2.map_or(0.0, |o| f32::from(o.y_subscript_y_size()) / em); + let o = os2.map_or(0.0, |o| f32::from(o.y_subscript_y_offset()) / em); + (if (0.3..=1.0).contains(&s) { s } else { 0.65 }, -(if (0.0..=1.0).contains(&o) && o > 0.0 { o } else { 0.15 })) + } + }; + let glyph_size = (st.size * scale).max(0.5); + let underline = m.underline.filter(|d| d.thickness.is_finite() && d.thickness > 0.0 && d.offset.is_finite()).map_or((-0.1 * st.size, (0.05 * st.size).max(1.0)), |d| (d.offset, d.thickness)); + // A smaller underline for smaller glyphs. + let underline = if scale < 1.0 { (underline.0 * scale, underline.1 * scale) } else { underline }; + RunMetrics { + ascent: m.ascent, + descent: -m.descent, + height: (m.ascent - m.descent + m.leading).max(st.size * 0.5), + underline, + shift_y: -raise * st.size, + glyph_size, + } +} + +/// The caret positions of laid-out lines (see [`CaretLine`]). +fn caret_lines(lines: &[Line], paras: &[Para], tops: &[f32], lm: &[(f32, f32, f32)], uniform: bool, first_ascent: f32, shift_of: &dyn Fn(&Line) -> f32) -> Vec { + let mut out: Vec = Vec::with_capacity(lines.len()); + for (row, l) in lines.iter().enumerate() { + let shift = shift_of(l); + let (pstart, plen) = paras.get(l.para).map_or((0, 0), |p| (p.start, p.len)); + let ch = |i: u32| i.clamp(pstart, pstart + plen); + let start = if l.first { pstart } else { l.glyphs.first().map_or(pstart, |(g, _)| ch(g.index)) }; + let mut stops: Vec<(u32, f32)> = l.glyphs.iter().map(|(g, gx)| (ch(g.index), shift + gx)).collect(); + stops.sort_by_key(|s| s.0); + stops.dedup_by_key(|s| s.0); + if l.first && stops.first().is_none_or(|s| s.0 > start) { + stops.insert(0, (start, shift)); + } + // The boundary after the last glyph (its trailing spaces, if any, follow it). + if let Some(&(c, _)) = stops.last() { + stops.push((c + 1, shift + l.width)); + } + let m = lm.get(row).copied().unwrap_or_default(); + let top = tops.get(row).copied().unwrap_or(0.0); + let baseline = if uniform { first_ascent + top } else { top + m.0 }; + out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline }); + // The previous line of the same paragraph ends where this one starts. + if !l.first && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) { + prev.end = start; + } + } + // The last line of each paragraph ends with it. + for (row, l) in lines.iter().enumerate() { + let last_of_para = lines.get(row + 1).is_none_or(|n| n.para != l.para); + if last_of_para && let (Some(c), Some(p)) = (out.get_mut(row), paras.get(l.para)) { + c.end = p.start + p.len; + } + } + for l in &mut out { + l.end = l.end.max(l.start); + let end = l.end; + l.stops.retain(|s| s.0 <= end); + if l.stops.last().is_none_or(|s| s.0 < end) { + let x = l.stops.last().map_or(0.0, |s| s.1); + l.stops.push((end, x)); + } + } + out +} + +#[cfg(test)] +#[path = "rich_tests.rs"] +mod tests; diff --git a/crates/text/src/rich_tests.rs b/crates/text/src/rich_tests.rs new file mode 100644 index 00000000..f9bc8940 --- /dev/null +++ b/crates/text/src/rich_tests.rs @@ -0,0 +1,181 @@ +use super::*; +use crate::Style; + +fn fonts() -> Option<&'static Fonts> { + let f = Fonts::get(); + if f.families().is_empty() { + eprintln!("no fonts on this computer: rich text layout tests skipped"); + return None; + } + Some(f) +} + +fn run(chars: usize, size: f32, paint: u32) -> Run { + Run { chars, style: RunStyle { size, paint, ..RunStyle::default() } } +} + +fn lay(f: &Fonts, text: &str, runs: &[Run], paras: &[ParaStyle], width: Option) -> Layout { + f.layout_rich(&RichText { text, runs, paragraphs: paras, width }, true).unwrap() +} + +#[test] +fn one_run_is_the_plain_layout() { + let Some(f) = fonts() else { return }; + let plain = f.layout_glyphs("Hello there\nworld", &Style { size: 24.0, letter_spacing: 1.0, line_spacing: 3.0, width: Some(90.0), ..Style::default() }).unwrap(); + let runs = [Run { chars: 17, style: RunStyle { size: 24.0, letter_spacing: 1.0, ..RunStyle::default() } }]; + let rich = lay(f, "Hello there\nworld", &runs, &[ParaStyle { line_spacing: 3.0, ..ParaStyle::default() }], Some(90.0)); + assert_eq!(rich, plain); + assert_eq!(rich.pieces.len(), 1); + assert_eq!(rich.pieces[0].1, rich.outline); +} + +#[test] +fn paints_cut_the_outline_into_pieces() { + let Some(f) = fonts() else { return }; + let l = lay(f, "abcdef", &[run(2, 20.0, 7), run(2, 20.0, 3), run(2, 20.0, 7)], &[], None); + assert_eq!(l.pieces.iter().map(|p| p.0).collect::>(), vec![7, 3], "in the order paints first appear"); + let joined: Vec = l.pieces.iter().flat_map(|p| p.1.cmds.clone()).collect(); + assert_eq!(joined, l.outline.cmds, "the outline is the pieces one after another"); + assert_eq!(l.glyphs.iter().map(|g| g.paint).collect::>(), vec![7, 7, 3, 3, 7, 7]); + // The same glyphs as one run: paints don't move anything. + let one = lay(f, "abcdef", &[run(6, 20.0, 0)], &[], None); + assert_eq!((one.width, one.height), (l.width, l.height)); + assert_eq!(one.glyphs.iter().map(|g| g.x).collect::>(), l.glyphs.iter().map(|g| g.x).collect::>()); +} + +/// What the default face says a superscript is raised by at `size` (pixels). +fn expected_superscript_raise(f: &Fonts, size: f32) -> f32 { + let family = f.resolve("").unwrap(); + let q = fontdb::Query { families: &[fontdb::Family::Name(&family)], ..fontdb::Query::default() }; + let id = f.db.query(&q).unwrap(); + f.db.with_face_data(id, |d, i| { + let font = skrifa::FontRef::from_index(d, i).unwrap(); + let em = f32::from(skrifa::MetadataProvider::metrics(&font, skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()).units_per_em); + let o = font.os2().map(|o| f32::from(o.y_superscript_y_offset()) / em).unwrap_or(0.0); + if (0.05..=1.0).contains(&o) { o * size } else { 0.35 * size } + }) + .unwrap() +} + +#[test] +fn a_superscript_is_smaller_and_raised_by_the_fonts_offset() { + let Some(f) = fonts() else { return }; + let sup = RunStyle { size: 40.0, shift: Shift::Superscript, ..RunStyle::default() }; + let sub = RunStyle { shift: Shift::Subscript, ..sup.clone() }; + let l = lay(f, "x2y2", &[run(1, 40.0, 0), Run { chars: 1, style: sup }, run(1, 40.0, 0), Run { chars: 1, style: sub }], &[], None); + let plain = lay(f, "x2y2", &[run(4, 40.0, 0)], &[], None); + let b = |l: &Layout, i: usize| l.glyphs[i].outline.bounds(); + // Every glyph shares the line's baseline; the shift is in the glyph's own outline. + assert!(l.glyphs.iter().all(|g| g.baseline == l.ascent)); + let (up, down, normal) = (b(&l, 1), b(&l, 3), b(&plain, 1)); + assert!(up.height() < normal.height() * 0.9 && up.height() > normal.height() * 0.3, "smaller: {up:?} vs {normal:?}"); + // Raised by the font's offset: the digit's bottom (on its own baseline, within the + // outline's overshoot) is that far above the line's. + let raise = -up.max.y; + let want = expected_superscript_raise(f, 40.0); + assert!((raise - want).abs() < 1.0, "raised {raise}, the font says {want}"); + assert!(down.max.y > 0.5, "a subscript drops below the baseline: {down:?}"); + // Its advance is smaller too. + assert!(l.glyphs[1].advance < plain.glyphs[1].advance * 0.9); +} + +#[test] +fn lines_wrap_across_runs_and_make_room_for_the_tallest() { + let Some(f) = fonts() else { return }; + // "aaa " small, "BBB ccc" big: the wrap falls inside the big run. + let text = "aaa BBB ccc"; + let small = lay(f, "aaa ", &[run(4, 20.0, 0)], &[], None); + let big_word = lay(f, "BBB", &[run(3, 40.0, 0)], &[], None); + let space = lay(f, "a a", &[run(3, 20.0, 0)], &[], None); + let w = small.width + (space.width - 2.0 * lay(f, "a", &[run(1, 20.0, 0)], &[], None).width) + big_word.width + 2.0; + let l = lay(f, text, &[run(4, 20.0, 0), run(7, 40.0, 1)], &[], Some(w)); + assert_eq!(l.lines, 2, "{w}"); + assert_eq!((l.carets[0].start, l.carets[0].end, l.carets[1].start, l.carets[1].end), (0, 8, 8, 11)); + // The first line's baseline is the big run's ascent (the tallest on it), not the small one's. + let big = lay(f, "B", &[run(1, 40.0, 0)], &[], None); + assert!((l.ascent - big.ascent).abs() < 1e-3, "{} vs {}", l.ascent, big.ascent); + assert!(l.carets[1].baseline > l.carets[0].baseline + big.line_height * 0.9); + // A line of only small text after a big one keeps its own height. + let two = lay(f, "BIG\nsmall\nsmall", &[run(4, 60.0, 0), run(11, 15.0, 0)], &[], None); + let (a, b, c) = (&two.carets[0], &two.carets[1], &two.carets[2]); + assert!((b.top - a.height).abs() < 1e-3 && (c.top - b.top - b.height).abs() < 1e-3); + assert!(a.height > b.height * 3.0 && (b.height - c.height).abs() < 1e-3, "{} {} {}", a.height, b.height, c.height); + let s = lay(f, "s", &[run(1, 15.0, 0)], &[], None); + assert!((two.height - (c.baseline + s.height - s.ascent)).abs() < 0.01); +} + +#[test] +fn paragraphs_align_indent_and_keep_their_margins() { + let Some(f) = fonts() else { return }; + let p = |align, indent, left, right| ParaStyle { align, indent, left_margin: left, right_margin: right, line_spacing: 0.0 }; + let l = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[p(Align::Left, 30.0, 10.0, 0.0), p(Align::Right, 0.0, 0.0, 25.0), p(Align::Center, 0.0, 40.0, 0.0)], Some(200.0)); + let x = |i: usize| l.glyphs[i].x; + assert!((x(0) - 40.0).abs() < 1e-3, "indent and left margin: {}", x(0)); + let bw = l.glyphs[1].advance; + assert!((x(1) - (200.0 - 25.0 - bw)).abs() < 1e-3, "right margin: {}", x(1)); + let cw = l.glyphs[2].advance; + assert!((x(2) - (40.0 + (160.0 - cw) * 0.5)).abs() < 1e-3, "centred in what the margins leave: {}", x(2)); + // An indent only moves a paragraph's first line, and the margins narrow its wrap. + let words = "one two three four five six seven eight"; + let wrapped = lay(f, words, &[run(words.chars().count(), 20.0, 0)], &[p(Align::Left, 20.0, 15.0, 15.0)], Some(160.0)); + assert!(wrapped.lines >= 3); + let starts: Vec = wrapped.carets.iter().map(|c| c.stops[0].1).collect(); + assert!((starts[0] - 35.0).abs() < 1e-3 && starts[1..].iter().all(|s| (s - 15.0).abs() < 1e-3), "{starts:?}"); + assert!(wrapped.outline.bounds().max.x <= 160.0 - 15.0 + 1.0, "{:?}", wrapped.outline.bounds()); + // Without a width, the box is the widest line with its margins. + let free = lay(f, "ab", &[run(2, 20.0, 0)], &[p(Align::Left, 5.0, 10.0, 20.0)], None); + let line = free.glyphs[1].x + free.glyphs[1].advance - free.glyphs[0].x; + assert!((free.width - (35.0 + line)).abs() < 1e-3, "{}", free.width); + // Per-paragraph line spacing. + let spaced = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[ParaStyle { line_spacing: 30.0, ..ParaStyle::default() }, ParaStyle::default()], None); + let tight = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[], None); + assert!((spaced.height - tight.height - 30.0).abs() < 0.01, "only the first line is spaced: {} vs {}", spaced.height, tight.height); +} + +#[test] +fn underlines_run_under_their_glyphs_in_their_paint() { + let Some(f) = fonts() else { return }; + let u = RunStyle { size: 30.0, underline: true, paint: 1, ..RunStyle::default() }; + let l = lay(f, "ab cd", &[run(3, 30.0, 0), Run { chars: 2, style: u }], &[], None); + let plain = lay(f, "ab cd", &[run(3, 30.0, 0), run(2, 30.0, 1)], &[], None); + let (with, without) = (&l.pieces[1].1, &plain.pieces[1].1); + assert_eq!(with.cmds.len(), without.cmds.len() + 5, "one bar: a rectangle"); + let bar = Path { cmds: with.cmds[without.cmds.len()..].to_vec() }.bounds(); + assert!(bar.min.y > l.ascent - 1.0 && bar.max.y < l.height + 1.0, "under the baseline: {bar:?}"); + assert!((bar.min.x - l.glyphs[3].x).abs() < 1e-3 && (bar.max.x - l.width).abs() < 1e-3, "{bar:?}"); +} + +#[test] +fn hostile_runs_are_capped_and_sanitized() { + let Some(f) = fonts() else { return }; + // Thousands of runs: capped, the rest joins the last. + let text = "x".repeat(MAX_RUNS + 500); + let runs: Vec = (0..MAX_RUNS + 500).map(|i| run(1, 10.0 + (i % 7) as f32, i as u32 % 3)).collect(); + let t = std::time::Instant::now(); + let l = f.layout_rich(&RichText { text: &text, runs: &runs, paragraphs: &[], width: Some(400.0) }, false).unwrap(); + eprintln!("{} runs laid out in {:?}", MAX_RUNS, t.elapsed()); + assert_eq!(l.families.len(), MAX_RUNS); + assert!(l.width.is_finite() && l.height.is_finite()); + // As many paragraphs as runs, empty ones included: linear, not paragraphs × runs. + let text = "y + +".repeat(MAX_RUNS / 2); + let t = std::time::Instant::now(); + let l = f.layout_rich(&RichText { text: &text, runs: &runs, paragraphs: &[], width: None }, false).unwrap(); + eprintln!("{} paragraphs laid out in {:?}", MAX_RUNS, t.elapsed()); + assert_eq!(l.lines, MAX_RUNS + 1); + // Hostile sizes, spacing, margins and lengths: clamped, never a panic. + let bad = [ + Run { chars: usize::MAX, style: RunStyle { size: f32::NAN, letter_spacing: f32::INFINITY, ..RunStyle::default() } }, + Run { chars: 0, style: RunStyle { size: 1e30, ..RunStyle::default() } }, + ]; + let p = [ParaStyle { indent: f32::NEG_INFINITY, left_margin: -5.0, right_margin: 1e20, line_spacing: f32::NAN, align: Align::Center }]; + let l = f.layout_rich(&RichText { text: "a b\nc", runs: &bad, paragraphs: &p, width: Some(f32::NAN) }, true).unwrap(); + assert!(l.width.is_finite() && l.height.is_finite()); + // Runs longer than the text, shorter than it, or none. + for runs in [vec![run(100, 20.0, 0)], vec![run(1, 20.0, 0)], vec![]] { + let l = f.layout_rich(&RichText { text: "abc", runs: &runs, paragraphs: &[], width: None }, true).unwrap(); + assert_eq!(l.glyphs.len(), 3); + } + assert_eq!(f.layout_rich(&RichText { text: &"x".repeat(MAX_CHARS + 1), runs: &[], paragraphs: &[], width: None }, false), Err(TextError::TooLong)); +} diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml index 77507217..e105eb2d 100644 --- a/crates/xfl/Cargo.toml +++ b/crates/xfl/Cargo.toml @@ -8,17 +8,20 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-video.workspace = true anicraft-geom.workspace = true anicraft-doc.workspace = true anicraft-xml.workspace = true # Lays imported text out with the fonts on this computer (ADR 0012, ADR 0014). anicraft-text.workspace = true craft-xfl.workspace = true -miniz_oxide = "0.8" thiserror.workspace = true [dev-dependencies] +# Synthetic Screen Video key-frame fixture compression only. +miniz_oxide = "0.8" craft-image-codecs.workspace = true +serde_json.workspace = true [lints] workspace = true diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs index 886e1bf7..f573afd8 100644 --- a/crates/xfl/src/text.rs +++ b/crates/xfl/src/text.rs @@ -1,21 +1,22 @@ //! Text fields (`DOMStaticText`, `DOMDynamicText`, `DOMInputText`) → text blocks laid out by -//! `anicraft-text` (ADR 0014). +//! `anicraft-text` (ADR 0014, ADR 0085). //! //! A field holds text runs (`… //! `). An AniCraft text block has one style, so a field -//! becomes one block per run of consecutive lines that share a style, stacked as Animate -//! stacks them; a line that mixes styles takes the style most of its characters have, and the -//! report says so. +//! letterSpacing="1" lineSpacing="2"/>`). A field becomes one block with the same runs: each +//! `DOMTextRun`'s face, size, bold, italic, colour, letter spacing, character position +//! (superscript, subscript) and link are its characters' style, and each paragraph takes its +//! alignment, indent, margins and line spacing from the run it starts in, as Animate's +//! paragraph attributes do. //! -//! Dynamic and input fields (ADR 0066) become one field each, whatever their runs: a field is one -//! instance that scripts and the viewer use, so it takes its main style, keeps its instance name, -//! line type, border, selectability and maximum length, and the report counts them as running. +//! Dynamic and input fields (ADR 0066) are one field each, with the same runs for their authored +//! text, their instance name, line type, border, selectability and maximum length; text a script +//! or a viewer changes is laid out in the field's first style. use crate::import::Report; use crate::xml::Element as X; -use anicraft_doc::{LineType, Rgba, TextAlign, TextBlock, TextField, TextKind}; -use anicraft_geom::Vec2; +use anicraft_doc::{BaselineShift, CharStyle, LineType, ParagraphStyle, Rgba, TextAlign, TextBlock, TextField, TextKind, TextRun}; +use anicraft_geom::{Affine, Path, Vec2}; use anicraft_text::{Align, FaceMatch, Fonts, TextError}; use std::collections::HashMap; use std::sync::Arc; @@ -25,22 +26,7 @@ use std::sync::Arc; pub const GUTTER: f32 = 2.0; /// Most runs read from one field. -const MAX_RUNS: usize = 10_000; - -/// One run's style, as `DOMTextAttrs` gives it. -#[derive(Clone, Debug, PartialEq)] -struct RunStyle { - face: String, - size: f32, - bold: bool, - italic: bool, - color: Rgba, - align: TextAlign, - letter_spacing: f32, - line_spacing: f32, - left_margin: f32, - right_margin: f32, -} +const MAX_RUNS: usize = anicraft_doc::MAX_TEXT_RUNS; /// A laid-out block and where its box's top-left goes, in the field's coordinates. pub struct Placed { @@ -48,9 +34,17 @@ pub struct Placed { pub offset: Vec2, } -fn run_style(attrs: Option>, flags: &mut Flags) -> RunStyle { +/// What a field used that AniCraft draws differently, reported once per field. +#[derive(Default)] +struct Flags { + justified: bool, +} + +/// One run's character and paragraph style, as `DOMTextAttrs` gives it (the face still a +/// PostScript name). +fn run_style(attrs: Option>, url: &str, flags: &mut Flags) -> (CharStyle, ParagraphStyle) { let Some(a) = attrs else { - return RunStyle { face: String::new(), size: 12.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, left_margin: 0.0, right_margin: 0.0 }; + return (CharStyle { size: 12.0, ..CharStyle::default() }, ParagraphStyle::default()); }; let clamp = |number: Option, lo: f32, hi: f32| number.unwrap_or(0.0).clamp(lo, hi); let align = match a.alignment() { @@ -62,116 +56,77 @@ fn run_style(attrs: Option>, flags: &mut Flags } _ => TextAlign::Left, }; - if a.indent().is_some_and(|i| i != 0.0) { - flags.indented = true; - } - if a.character_position().is_some_and(|p| p != "normal") { - flags.shifted = true; - } + let shift = match a.character_position() { + Some("superscript") => BaselineShift::Superscript, + Some("subscript") => BaselineShift::Subscript, + _ => BaselineShift::Normal, + }; let color = a.color(); - RunStyle { - face: a.face().unwrap_or("").chars().take(256).collect(), + let c = CharStyle { + font: a.face().unwrap_or("").chars().take(256).collect(), size: a.size().unwrap_or(12.0).clamp(1.0, 2000.0), bold: a.bold().unwrap_or(false), italic: a.italic().unwrap_or(false), color: Rgba::hex(color.rgb).with_alpha(color.alpha), - align, letter_spacing: clamp(a.letter_spacing(), -1000.0, 1000.0), + shift, + underline: false, + url: anicraft_doc::safe_url(url).unwrap_or_default(), + }; + let p = ParagraphStyle { + align, + indent: clamp(a.indent(), -1000.0, 1000.0), + left_margin: clamp(a.left_margin(), 0.0, 1000.0), + right_margin: clamp(a.right_margin(), 0.0, 1000.0), line_spacing: clamp(a.line_spacing(), -1000.0, 1000.0), - left_margin: clamp(a.left_margin(), 0.0, 10_000.0), - right_margin: clamp(a.right_margin(), 0.0, 10_000.0), - } + }; + (c, p) } -/// What a field used that AniCraft draws differently, reported once per field. -#[derive(Default)] -struct Flags { - justified: bool, - indented: bool, - shifted: bool, +/// A field's text with its runs (faces resolved to installed families) and one style per +/// paragraph. +struct Styled { + text: String, + runs: Vec, + paragraphs: Vec, + /// Faces asked for that aren't installed (reported once the text is laid out). + missing: Vec, } -impl Flags { - fn report(&self, report: &mut Report) { - if self.justified { - report.skip("justified text (drawn left-aligned)"); - } - if self.indented { - report.skip("first-line indents"); - } - if self.shifted { - report.skip("superscript and subscript (drawn on the line)"); - } - } -} - -/// A line of the field: its pieces, each with the style of the run it came from. -type Line = Vec<(String, usize)>; - -/// The style a line is drawn in: that of the most visible characters (the first on a tie), or -/// of its first piece when it is empty. -fn main_style(line: &Line) -> (usize, bool) { - // Visible characters per style, in the order the styles first appear. - let mut totals: Vec<(usize, usize)> = Vec::new(); - for (t, s) in line { - let n = t.chars().filter(|c| !c.is_whitespace()).count(); - match totals.iter_mut().find(|(x, _)| x == s) { - Some(e) => e.1 += n, - None => totals.push((*s, n)), - } - } - let mut best: Option<(usize, usize)> = None; - for &(s, n) in &totals { - if best.is_none_or(|(_, b)| n > b) { - best = Some((s, n)); - } - } - (best.map_or(0, |(s, _)| s), totals.iter().filter(|(_, n)| *n > 0).count() > 1) -} - -/// Lays out one text field. Fonts are looked up once per face name (`faces`); missing ones go -/// into the report. -pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report) -> Vec { - let Some(field) = craft_xfl::text::TextField::new(el) else { return Vec::new() }; - if field.orientation().is_some_and(|o| o != "horizontal") { - report.skip("vertical text (drawn horizontal)"); - } - if field.has_filters() { - report.skip("filters on text"); - } - let mut flags = Flags::default(); - let mut styles: Vec = Vec::new(); - let mut lines: Vec = vec![Vec::new()]; +/// Reads a field's runs. Fonts are looked up once per face name (`faces`); missing ones go into +/// the report. +fn read_runs(el: &X, native: &craft_xfl::text::TextField<'_, X>, fonts: &Fonts, faces: &mut HashMap, report: &mut Report, flags: &mut Flags) -> Styled { + // Links aren't in the shared schema view: read them from the runs' attributes directly. + let urls: Vec = el.list("textRuns").iter().filter(|r| r.name == "DOMTextRun").map(|r| r.child("textAttrs").and_then(|t| t.child("DOMTextAttrs")).and_then(|a| a.attr("url")).unwrap_or("").to_string()).collect(); + let mut text = String::new(); + let mut runs: Vec = Vec::new(); + let mut para_of_run: Vec = Vec::new(); let mut chars = 0usize; - let mut cut = field.run_entries_count() > MAX_RUNS; - for run in field.runs().take(MAX_RUNS) { - let style = run_style(run.style(), &mut flags); - let s = match styles.iter().position(|x| *x == style) { - Some(i) => i, - None => { - styles.push(style); - styles.len() - 1 - } - }; - let text = run.characters(); - // Animate ends lines with a carriage return; any line break starts a new line here. - let text = text.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n"); - for (i, piece) in text.split('\n').enumerate() { - if i > 0 { - lines.push(Vec::new()); - chars += 1; - } - let room = anicraft_text::MAX_CHARS.saturating_sub(chars); - let n = piece.chars().count(); - if n > room { - cut = true; - } - let piece: String = piece.chars().take(room).collect(); - chars += n.min(room); - if let Some(l) = lines.last_mut() { - l.push((piece, s)); - } + let mut missing: Vec = Vec::new(); + let mut cut = native.run_entries_count() > MAX_RUNS; + for (i, run) in native.runs().take(MAX_RUNS).enumerate() { + let (mut c, p) = run_style(run.style(), urls.get(i).map_or("", String::as_str), flags); + // The face: a PostScript name, a family or a device font; bold and italic faces count. + let face = faces.entry(c.font.clone()).or_insert_with(|| fonts.find_face(&c.font)).clone(); + if face.family.is_none() && !face.wanted.is_empty() && !missing.contains(&face.wanted) { + missing.push(face.wanted.clone()); } + c.font = face.family.clone().unwrap_or_default(); + c.bold |= face.bold; + c.italic |= face.italic; + // Animate ends lines with a carriage return; any line break starts a new line here. + let piece = run.characters().replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n"); + let room = anicraft_text::MAX_CHARS.saturating_sub(chars); + let n = piece.chars().count(); + if n > room { + cut = true; + } + let piece: String = piece.chars().take(room).collect(); + let n = n.min(room); + chars += n; + text.push_str(&piece); + runs.push(TextRun { chars: n as u32, style: c }); + para_of_run.push(p); if chars >= anicraft_text::MAX_CHARS { break; } @@ -179,132 +134,124 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo if cut { report.skip("text cut to 100,000 characters per field"); } - if field.kind() != craft_xfl::text::TextFieldKind::Static { - flags.report(report); - return text_field(field, fonts, faces, report, &lines, &styles).into_iter().collect(); + // Each paragraph takes the paragraph attributes of the run its first character is in. + let mut paragraphs = Vec::new(); + let mut starts = vec![0usize]; + starts.extend(text.chars().enumerate().filter(|(_, c)| *c == '\n').map(|(i, _)| i + 1)); + let mut ends: Vec = Vec::with_capacity(runs.len()); + let mut at = 0usize; + for r in &runs { + at += r.chars as usize; + ends.push(at); } - // Trailing empty lines draw nothing. - while lines.last().is_some_and(|l| l.iter().all(|(t, _)| t.trim().is_empty())) { - lines.pop(); + for s in starts { + let k = ends.partition_point(|e| *e <= s).min(para_of_run.len().saturating_sub(1)); + paragraphs.push(para_of_run.get(k).copied().unwrap_or_default()); } - if lines.is_empty() || styles.is_empty() { - return Vec::new(); - } - flags.report(report); - - // Consecutive lines in the same style make one block. - let mut blocks: Vec<(usize, String)> = Vec::new(); - for line in &lines { - let (s, mixed) = main_style(line); - if mixed { - report.skip("lines with mixed text styles (drawn in their main style)"); - } - let text: String = line.iter().map(|(t, _)| t.as_str()).collect(); - match blocks.last_mut() { - Some((ls, t)) if *ls == s => { - t.push('\n'); - t.push_str(&text); - } - _ => blocks.push((s, text)), - } - } - - let auto = field.auto_expand().unwrap_or(false); - let field_width = field.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)); - let origin = Vec2::new(field.left().unwrap_or(0.0) + GUTTER, field.top().unwrap_or(0.0) + GUTTER); - let mut out: Vec = Vec::new(); - let mut y = 0.0f32; - for (s, text) in blocks { - let Some(st) = styles.get(s) else { continue }; - let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone(); - // A fixed-width field wraps inside its margins; an auto-size one never wraps. - let width = if auto { None } else { field_width.map(|w| (w - st.left_margin - st.right_margin).max(1.0)) }; - let style = anicraft_text::Style { - family: face.family.clone().unwrap_or_default(), - size: st.size, - bold: st.bold || face.bold, - italic: st.italic || face.italic, - align: match st.align { - TextAlign::Left => Align::Left, - TextAlign::Center => Align::Center, - TextAlign::Right => Align::Right, - }, - letter_spacing: st.letter_spacing, - line_spacing: st.line_spacing, - width, - }; - let layout = match fonts.layout(&text, &style) { - Ok(l) => l, - Err(TextError::NoFonts) => { - report.skip("text fields (no fonts on this computer)"); - return Vec::new(); - } - Err(TextError::TooLong) => { - report.skip("text cut to 100,000 characters per field"); - continue; - } - }; - // A family that isn't installed falls back to the default, as the text engine does - // (ADR 0012), and the report names it. - if face.family.is_none() && !face.wanted.is_empty() { - report.missing_fonts.insert(face.wanted.clone()); - report.fallback_font.get_or_insert_with(|| layout.family.clone()); - } - let block = TextBlock { - text, - font: layout.family, - size: style.size, - bold: style.bold, - italic: style.italic, - color: st.color, - align: st.align, - letter_spacing: st.letter_spacing, - line_spacing: st.line_spacing, - width, - outline: Arc::new(layout.outline), - box_width: layout.width, - box_height: layout.height, - field: None, - on_path: None, - }; - out.push(Placed { block, offset: Vec2::new(origin.x + st.left_margin, origin.y + y) }); - y += layout.lines as f32 * layout.line_height; - } - // Auto-size blocks align against the widest one, as lines of one field do. - if auto { - let widest = out.iter().map(|p| p.block.box_width).fold(0.0, f32::max); - for p in &mut out { - p.offset.x += match p.block.align { - TextAlign::Left => 0.0, - TextAlign::Center => (widest - p.block.box_width) * 0.5, - TextAlign::Right => widest - p.block.box_width, - }; - } - } - out + Styled { text, runs, paragraphs, missing } } -/// A dynamic or input field (ADR 0066): one block in the field's main style, its box from the +/// Lays a block out from its text, runs, paragraphs and width (the engine's text layout does +/// the same for edits; the importer sits below it, so this is its own copy of the few lines +/// that hand runs to the text engine). +fn lay_out(fonts: &Fonts, block: &mut TextBlock, shown: &str, wrap: Option) -> Result { + let mut paints: Vec<(Rgba, String)> = Vec::new(); + let align = |a: TextAlign| match a { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }; + let runs: Vec = block + .styled_runs() + .into_iter() + .map(|r| { + let key = (r.style.color, r.style.url.clone()); + let paint = paints.iter().position(|k| *k == key).unwrap_or_else(|| { + paints.push(key); + paints.len() - 1 + }) as u32; + let shift = match r.style.shift { + BaselineShift::Normal => anicraft_text::Shift::Normal, + BaselineShift::Superscript => anicraft_text::Shift::Superscript, + BaselineShift::Subscript => anicraft_text::Shift::Subscript, + }; + anicraft_text::Run { chars: r.chars as usize, style: anicraft_text::RunStyle { family: r.style.font, size: r.style.size, bold: r.style.bold, italic: r.style.italic, letter_spacing: r.style.letter_spacing, shift, underline: r.style.underline, paint } } + }) + .collect(); + let paras: Vec = block.paragraph_styles().into_iter().map(|p| anicraft_text::ParaStyle { align: align(p.align), indent: p.indent, left_margin: p.left_margin, right_margin: p.right_margin, line_spacing: p.line_spacing }).collect(); + let l = fonts.layout_rich(&anicraft_text::RichText { text: shown, runs: &runs, paragraphs: ¶s, width: wrap }, false)?; + // The runs record the families actually used. + let mut styled = block.styled_runs(); + for (r, used) in styled.iter_mut().zip(&l.families) { + r.style.font.clone_from(used); + } + let p = block.paragraph_styles(); + block.set_styles(styled, p); + let pieces = l.pieces.iter().map(|(k, p)| paints.get(*k as usize).map_or((block.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p.clone()))).collect(); + block.set_outline(pieces); + Ok(l) +} + +/// Lays out one text field: one block with the field's runs. +pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report) -> Vec { + let Some(native) = craft_xfl::text::TextField::new(el) else { return Vec::new() }; + if native.orientation().is_some_and(|o| o != "horizontal") { + report.skip("vertical text (drawn horizontal)"); + } + if native.has_filters() { + report.skip("filters on text"); + } + let mut flags = Flags::default(); + let styled = read_runs(el, &native, fonts, faces, report, &mut flags); + if flags.justified { + report.skip("justified text (drawn left-aligned)"); + } + if native.kind() != craft_xfl::text::TextFieldKind::Static { + return text_field(native, fonts, report, styled).into_iter().collect(); + } + // Trailing empty lines draw nothing. + let keep = styled.text.trim_end().chars().count(); + if keep == 0 || styled.runs.is_empty() { + return Vec::new(); + } + let text: String = styled.text.chars().take(keep).collect(); + let auto = native.auto_expand().unwrap_or(false); + // A fixed-width field wraps inside its margins; an auto-size one never wraps. + let width = if auto { None } else { native.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)) }; + let mut block = TextBlock { text: text.clone(), width, ..TextBlock::default() }; + block.set_styles(styled.runs, styled.paragraphs); + match lay_out(fonts, &mut block, &text, width) { + Ok(l) => { + // A family that isn't installed falls back to the default, as the text engine does + // (ADR 0012), and the report names it. + report.missing_fonts.extend(styled.missing); + if !report.missing_fonts.is_empty() { + report.fallback_font.get_or_insert_with(|| l.family.clone()); + } + block.box_width = l.width; + block.box_height = l.height; + } + Err(TextError::NoFonts) => { + report.skip("text fields (no fonts on this computer)"); + return Vec::new(); + } + Err(TextError::TooLong) => { + report.skip("text cut to 100,000 characters per field"); + return Vec::new(); + } + } + let origin = Vec2::new(native.left().unwrap_or(0.0) + GUTTER, native.top().unwrap_or(0.0) + GUTTER); + vec![Placed { block, offset: origin }] +} + +/// A dynamic or input field (ADR 0066): one block with the field's runs, its box from the /// field's `width` and `height` (or the text's size, for an auto-size field), its text laid out /// inside the gutter. Empty fields are kept (an empty input field is the usual kind). -fn text_field( - native: craft_xfl::text::TextField<'_, X>, - fonts: &Fonts, - faces: &mut HashMap, - report: &mut Report, - lines: &[Line], - styles: &[RunStyle], -) -> Option { +fn text_field(native: craft_xfl::text::TextField<'_, X>, fonts: &Fonts, report: &mut Report, styled: Styled) -> Option { let kind = if native.kind() == craft_xfl::text::TextFieldKind::Input { TextKind::Input } else { TextKind::Dynamic }; report.run(if kind == TextKind::Input { "input text fields" } else { "dynamic text fields" }); - let all: Line = lines.iter().flatten().cloned().collect(); - let (s, mixed) = main_style(&all); - if mixed { - report.skip("text fields with mixed text styles (drawn in their main style)"); - } - let st = styles.get(s).cloned().unwrap_or_else(|| run_style(None, &mut Flags::default())); - let text: String = lines.iter().map(|l| l.iter().map(|(t, _)| t.as_str()).collect::()).collect::>().join("\n"); - let text = text.trim_end_matches('\n').to_string(); + let keep = styled.text.trim_end_matches('\n').chars().count(); + let text: String = styled.text.chars().take(keep).collect(); let line_type = match native.line_type() { Some("multiline") => LineType::Multiline, Some("multiline no wrap") => LineType::MultilineNoWrap, @@ -324,59 +271,37 @@ fn text_field( let field = TextField { lines: line_type, selectable: native.is_selectable().unwrap_or(true), border, background: border, max_chars, variable, ..TextField::new(kind) }; let auto = native.auto_expand().unwrap_or(false); let width = native.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)); - let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone(); - let wrap = width.and_then(|w| field.wrap_width(w - st.left_margin - st.right_margin)); - let style = anicraft_text::Style { - family: face.family.clone().unwrap_or_default(), - size: st.size, - bold: st.bold || face.bold, - italic: st.italic || face.italic, - align: match st.align { - TextAlign::Left => Align::Left, - TextAlign::Center => Align::Center, - TextAlign::Right => Align::Right, - }, - letter_spacing: st.letter_spacing, - line_spacing: st.line_spacing, - width: wrap.or(if auto { None } else { width.map(|w| (w - 2.0 * GUTTER - st.left_margin - st.right_margin).max(1.0)).filter(|_| st.align != TextAlign::Left) }), - }; + let mut block = TextBlock { text: text.clone(), ..TextBlock::default() }; + block.set_styles(styled.runs, styled.paragraphs); + let missing = styled.missing; + let wrap = width.and_then(|w| field.wrap_width(w)); + // A fixed box that doesn't wrap still aligns its lines in the box. + let lay_width = wrap.or(if auto { None } else { width.map(|w| (w - 2.0 * GUTTER).max(1.0)).filter(|_| block.align != TextAlign::Left) }); let shown = field.shown(&text); - let (outline, family, tw, th) = match fonts.layout(&shown, &style) { + let (tw, th) = match lay_out(fonts, &mut block, &shown, lay_width) { Ok(l) => { - if face.family.is_none() && !face.wanted.is_empty() { - report.missing_fonts.insert(face.wanted.clone()); + report.missing_fonts.extend(missing); + if !report.missing_fonts.is_empty() { report.fallback_font.get_or_insert_with(|| l.family.clone()); } - let moved = l.outline.transformed(&anicraft_geom::Affine::translate(GUTTER + st.left_margin, GUTTER)); - (moved, l.family, l.width, l.height) + let to = Affine::translate(GUTTER, GUTTER); + let pieces: Vec<(Rgba, String, Path)> = block.fill_paths().into_iter().map(|(c, u, p)| (c, u.to_string(), p.transformed(&to))).collect(); + block.set_outline(pieces); + (l.width, l.height) } Err(e) => { report.skip(if e == TextError::NoFonts { "text fields (no fonts on this computer)" } else { "text cut to 100,000 characters per field" }); - (anicraft_geom::Path::new(), face.wanted.clone(), 0.0, st.size * 1.2) + block.outline = Arc::new(Path::new()); + (0.0, block.size * 1.2) } }; - let box_width = match (width, auto) { + block.box_width = match (width, auto) { (Some(w), false) => w, (Some(w), true) => w.max(tw + 2.0 * GUTTER), (None, _) => tw + 2.0 * GUTTER, }; - let box_height = native.height().filter(|h| *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0)); - let block = TextBlock { - text, - font: family, - size: style.size, - bold: style.bold, - italic: style.italic, - color: st.color, - align: st.align, - letter_spacing: st.letter_spacing, - line_spacing: st.line_spacing, - width: wrap, - outline: Arc::new(outline), - box_width, - box_height, - field: Some(field), - on_path: None, - }; + block.box_height = native.height().filter(|h| *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0)); + block.width = wrap; + block.field = Some(field); Some(Placed { block, offset: Vec2::new(native.left().unwrap_or(0.0), native.top().unwrap_or(0.0)) }) } diff --git a/crates/xfl/src/text_tests.rs b/crates/xfl/src/text_tests.rs index 48f107e7..d995014e 100644 --- a/crates/xfl/src/text_tests.rs +++ b/crates/xfl/src/text_tests.rs @@ -2,7 +2,7 @@ use crate::import::{Report, XflError, import_with, import_with_fonts}; use crate::text::GUTTER; -use anicraft_doc::{Document, Element, ElementKind, LineType, Paint, Rgba, TextAlign, TextBlock, TextKind, evaluate}; +use anicraft_doc::{BaselineShift, Document, Element, ElementKind, LineType, Paint, Rgba, TextAlign, TextBlock, TextKind, evaluate}; use anicraft_text::Fonts; use std::sync::Arc; @@ -75,38 +75,61 @@ fn fixed_width_fields_wrap_and_auto_size_ones_do_not() { } #[test] -fn runs_in_different_styles_become_blocks_stacked_line_by_line() { +fn runs_keep_their_styles_in_one_block() { let Some((fonts, family)) = fonts() else { return }; - let title = format!(r##"face="{family}" size="30" bold="true" fillColor="#112233""##); - let body = format!(r##"face="{family}" size="12" fillColor="#445566""##); - // A title line, two body lines (the second continues in a separate run of the same style), - // then a line that mixes both styles: most of its characters are body text. - let runs = [run("Title ", &title), run("line one line ", &body), run("two ", &body), run("Big", &title), run(" and mostly small", &body), run(" ", &body)].concat(); + let title = format!(r##"face="{family}" size="30" bold="true" fillColor="#112233" alignment="center""##); + let body = format!(r##"face="{family}" size="12" fillColor="#445566" indent="8" leftMargin="4""##); + let sup = format!(r##"face="{family}" size="12" fillColor="#445566" characterPosition="superscript" url="https://example.org""##); + // A title line, body lines (the second continues in a separate run of the same style), a + // line that mixes both styles and a superscript, then trailing empty lines. + let runs = [run("Title ", &title), run("line one line ", &body), run("two ", &body), run("Big", &title), run(" and small", &body), run("2", &sup), run(" ", &body)].concat(); let field = format!(r#"{runs}"#); let (doc, report) = import_doc(&doc_with(&field), fonts); let t = texts(&doc); - let blocks: Vec<(&str, f32, bool)> = t.iter().map(|(_, b)| (b.text.as_str(), b.size, b.bold)).collect(); - assert_eq!(blocks, [("Title", 30.0, true), ("line one\nline two\nBig and mostly small", 12.0, false)], "trailing empty lines are dropped"); - assert_eq!(t[1].1.color, Rgba::hex(0x445566)); - // The body starts where the title's next line would. - let title_layout = fonts.layout("Title", &anicraft_text::Style { family: family.clone(), size: 30.0, bold: true, ..Default::default() }).unwrap(); - let (y0, y1) = (t[0].0.transform.translation().y, t[1].0.transform.translation().y); - assert!((y0 - (20.0 + GUTTER)).abs() < 1e-4); - assert!((y1 - y0 - title_layout.line_height).abs() < 1e-3, "{y0} → {y1}, line height {}", title_layout.line_height); - assert_eq!(t[0].0.transform.translation().x, t[1].0.transform.translation().x, "left-aligned blocks share the left edge"); - assert_eq!(report.skipped.get("lines with mixed text styles (drawn in their main style)"), Some(&1)); + assert_eq!(t.len(), 1, "one field, one block"); + let b = &t[0].1; + assert_eq!(b.text, "Title\nline one\nline two\nBig and small2", "trailing empty lines are dropped"); + let runs: Vec<(u32, f32, bool, BaselineShift)> = b.styled_runs().iter().map(|r| (r.chars, r.style.size, r.style.bold, r.style.shift)).collect(); + assert_eq!(runs, [(6, 30.0, true, BaselineShift::Normal), (18, 12.0, false, BaselineShift::Normal), (3, 30.0, true, BaselineShift::Normal), (10, 12.0, false, BaselineShift::Normal), (1, 12.0, false, BaselineShift::Superscript)]); + assert_eq!(b.styled_runs()[1].style.color, Rgba::hex(0x445566)); + assert_eq!(b.styled_runs()[4].style.url, "https://example.org"); + // Paragraphs take their layout from the run they start in. + let aligns: Vec = b.paragraph_styles().iter().map(|p| p.align).collect(); + assert_eq!(aligns, [TextAlign::Center, TextAlign::Left, TextAlign::Left, TextAlign::Center]); + assert_eq!((b.paragraph_styles()[1].indent, b.paragraph_styles()[1].left_margin), (8.0, 4.0)); + // Colours become fill pieces; the element sits at the field's matrix plus the gutter. + assert_eq!(b.fills.len(), 3, "two colours, one with a link"); + assert!((t[0].0.transform.translation().y - (20.0 + GUTTER)).abs() < 1e-4); + assert!(report.skipped.is_empty(), "{report:?}"); } #[test] -fn centred_auto_size_blocks_centre_on_each_other() { +fn xfl_runs_round_trip_through_the_file() { + let Some((fonts, family)) = fonts() else { return }; + let a = format!(r##"face="{family}" size="20" fillColor="#ff0000""##); + let b = format!(r##"face="{family}" size="10" italic="true" characterPosition="subscript""##); + let field = format!(r#"{}{}"#, run("H", &a), run("2O", &b)); + let (doc, _) = import_doc(&doc_with(&field), fonts); + let json = serde_json::to_string(&doc).unwrap(); + let back: Document = serde_json::from_str(&json).unwrap(); + let (x, y) = (texts(&doc), texts(&back)); + assert_eq!((&x[0].1.runs, &x[0].1.fills, &x[0].1.outline), (&y[0].1.runs, &y[0].1.fills, &y[0].1.outline)); + assert_eq!(y[0].1.runs.len(), 2); +} + +#[test] +fn centred_lines_centre_on_each_other() { let Some((fonts, family)) = fonts() else { return }; let a = format!(r#"face="{family}" size="40" alignment="center""#); let b = format!(r#"face="{family}" size="12" alignment="center""#); let field = format!(r#"{}{}"#, run("WIDE HEADLINE ", &a), run("small", &b)); let (doc, _) = import_doc(&doc_with(&field), fonts); let t = texts(&doc); - let centre = |i: usize| t[i].0.transform.translation().x + t[i].1.box_width * 0.5; - assert!((centre(0) - centre(1)).abs() < 0.01, "{} vs {}", centre(0), centre(1)); + let b = &t[0].1; + let (head, small) = (b.fill_paths()[0].2.bounds(), b.outline.bounds()); + // The block is as wide as the headline, and the small line sits in its middle. + assert!((head.center().x - b.box_width * 0.5).abs() < 2.0, "{head:?} in {}", b.box_width); + assert!((small.center().x - b.box_width * 0.5).abs() < 2.0); } #[test] @@ -120,7 +143,7 @@ fn missing_fonts_fall_back_and_are_reported() { ); let (doc, report) = import_doc(&doc_with(&field), fonts); let t = texts(&doc); - assert_eq!(t.len(), 3); + assert_eq!(t.len(), 2, "one block per field"); assert_eq!((t[0].1.bold, t[0].1.italic), (true, true), "the face name says bold italic"); assert!(fonts.families().contains(&t[0].1.font), "laid out in an installed family: {}", t[0].1.font); assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::>(), ["No Such Face", "Zz Missing Mono"]); @@ -157,10 +180,13 @@ fn dynamic_and_input_text_become_fields_with_their_names() { assert_eq!(report.runs.get("dynamic text fields"), Some(&1)); assert_eq!(report.runs.get("input text fields"), Some(&2)); assert_eq!(report.kept.get("text field variables (ActionScript 1.0 and 2.0)"), Some(&1)); - for (what, n) in [("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1), ("first-line indents", 1), ("superscript and subscript (drawn on the line)", 1)] { + for (what, n) in [("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1)] { assert_eq!(report.skipped.get(what), Some(&n), "{what}: {report:?}"); } assert!(report.missing_fonts.is_empty(), "no face asks for the default family"); + // Indents and superscripts are kept now (ADR 0085). + let st = &t[3].1; + assert_eq!((st.indent, st.shift), (5.0, anicraft_doc::BaselineShift::Superscript)); // Every non-interactive render draws the authored text in its box, with its border. let dl = evaluate(&doc, 0); assert!(dl.items.iter().any(|i| i.stroke.is_some()), "the border"); diff --git a/crates/xfl/src/video.rs b/crates/xfl/src/video.rs index 3403c30d..3195fa37 100644 --- a/crates/xfl/src/video.rs +++ b/crates/xfl/src/video.rs @@ -96,43 +96,9 @@ fn flv(data: &[u8]) -> Option|auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/panels.rs b/src/panels.rs index 0f56bf94..17af6bc5 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -580,29 +580,77 @@ pub(crate) fn align_panel(app: &mut App, ui: &mut egui::Ui) { } /// Undo history: past steps (click to go back), the current state, and redoable steps (dimmed). +/// Ctrl+click picks steps (Shift+click a range) for Save As Command, which keeps them as a +/// saved command in the Commands menu (ADR 0097); so does each step's context menu. pub(crate) fn history(app: &mut App, ui: &mut egui::Ui) { + let picked: std::collections::BTreeSet = crate::macros_ui::picked(app).into_iter().collect(); let hist = app.s.history(); let past: Vec = hist.undo_labels().map(str::to_string).collect(); let future: Vec = hist.redo_labels().map(str::to_string).collect(); let evicted = hist.evicted; let mut target = None; - egui::ScrollArea::vertical().id_salt("history").max_height(ui.available_height().max(60.0)).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + // (step, toggle, range) + let mut pick: Option<(usize, bool, bool)> = None; + let mut save = false; + let footer = crate::theme::TARGET + 8.0; + let tip = tr!("Click to go back to this step · Ctrl+click picks it for Save As Command, Shift+click a range"); + egui::ScrollArea::vertical().id_salt("history").max_height((ui.available_height() - footer).max(crate::theme::TARGET)).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { let base = if evicted > 0 { tr!("… older steps freed (memory budget)") } else { tr!("Opened document") }; - if ui.selectable_label(past.is_empty(), text(Type::Body, base).color(if evicted > 0 { T.text_faint } else { T.text_dim })).clicked() { + if ui.selectable_label(past.is_empty() && picked.is_empty(), text(Type::Body, base).color(if evicted > 0 { T.text_faint } else { T.text_dim })).clicked() { target = Some(0); } - for (i, label) in past.iter().enumerate() { + let rows = past.iter().map(|l| (l, false)).chain(future.iter().map(|l| (l, true))); + for (i, (label, undone)) in rows.enumerate() { let current = i + 1 == past.len(); - if ui.selectable_label(current, crate::i18n::t_dyn(label).into_owned()).clicked() { - target = Some(i + 1); + let on = picked.contains(&i); + let shown = crate::i18n::t_dyn(label).into_owned(); + // With steps picked, the picks are highlighted and the current step is marked. + let shown = if current && !picked.is_empty() { format!("› {shown}") } else { shown }; + let t = if undone { text(Type::Body, shown).color(T.text_faint).italics() } else { text(Type::Body, shown) }; + let r = ui.selectable_label(if picked.is_empty() { current } else { on }, t).on_hover_text(tip); + if r.clicked() { + let m = ui.input(|i| i.modifiers); + if m.command || m.shift { + pick = Some((i, m.command, m.shift)); + } else { + target = Some(i + 1); + } } + r.context_menu(|ui| { + if ui.button(if on { tr!("Unpick Step") } else { tr!("Pick for Save As Command") }).clicked() { + pick = Some((i, true, false)); + ui.close(); + } + if ui.button(tr!("Save As Command…")).clicked() { + if !on { + pick = Some((i, true, false)); + } + save = true; + ui.close(); + } + }); } - for (i, label) in future.iter().enumerate() { - if ui.selectable_label(false, text(Type::Body, crate::i18n::t_dyn(label)).color(T.text_faint).italics()).clicked() { - target = Some(past.len() + i + 1); + }); + ui.horizontal_wrapped(|ui| { + ui.set_min_height(crate::theme::TARGET); + if picked.is_empty() { + ui.add(egui::Label::new(text(Type::Caption, tr!("Ctrl+click steps to save them as a command"))).wrap()); + } else { + if ui.button(tr!("Save As Command…")).on_hover_text(tr!("Keep the picked steps as a command in the Commands menu, to run on any selection")).clicked() { + save = true; + } + ui.label(text(Type::Caption, trn!("{n} step picked", "{n} steps picked", picked.len()))); + if ui.small_button(tr!("Clear")).on_hover_text(tr!("Unpick every step")).clicked() { + crate::macros_ui::clear_picks(app); } } }); + if let Some((i, toggle, range)) = pick { + crate::macros_ui::pick(app, i, toggle, range); + } + if save { + crate::macros_ui::open_save(app); + } if let Some(t) = target && let Err(e) = app.s.travel_to(t) { @@ -614,8 +662,15 @@ pub(crate) fn properties(app: &mut App, ui: &mut egui::Ui) { // The selection on every layer (ADR 0044). let sel: Vec<_> = app.s.selected_elements().into_iter().map(|(_, e)| e).collect(); + // ---- while typing on the stage: the selected characters' style (ADR 0085) ---- + app.text_props_rect = None; + if let Some(title) = app.text_edit.as_ref().map(crate::rich_edit::title) { + section(ui, "prop_text_selection", Section::Rule, &title, None, |ui| crate::rich_edit::selection_rows(app, ui)); + } // ---- tool options first while a drawing tool is in hand: they're what you reach for ---- - if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) { + // (While typing, the selected characters' section above takes the Text tool's place.) + let typing = app.text_edit.is_some(); + if (!typing || app.tool != Tool::Text) && matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) { let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label())); section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui)); } @@ -1010,13 +1065,32 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E // A field's lines wrap by its line type, at its box (rows above); static text by width. let mut width = t.width; let wrap = if t.field.is_some() { None } else { Some(&mut width) }; - if let Some((label, p)) = text_style_rows(app, ui, &mut st, wrap) { + // The whole block's characters: what they share, and "mixed" where they differ. + let n = t.char_count(); + let sum = anicraft_engine::doc::rich_text::summarize(&t.styled_runs(), 0, n); + let paras = t.paragraph_styles(); + let p0 = paras.first().copied().unwrap_or_default(); + let mx = TextMixed { + font: sum.font.is_none(), + size: sum.size.is_none(), + color: sum.color.is_none(), + bold: sum.bold.is_none(), + italic: sum.italic.is_none(), + letter_spacing: sum.letter_spacing.is_none(), + align: paras.iter().any(|p| p.align != p0.align), + line_spacing: paras.iter().any(|p| p.line_spacing != p0.line_spacing), + }; + if let Some((label, p)) = text_style_rows(app, ui, &mut st, wrap, Some(&mx)) { + live(app, label, "text.edit", p); + } + let mut extra = TextExtra { shift: sum.shift, underline: sum.underline, url: sum.url.clone(), indent: p0.indent, left_margin: p0.left_margin, right_margin: p0.right_margin, layout_mixed: paras.iter().any(|p| p.indent != p0.indent || p.left_margin != p0.left_margin || p.right_margin != p0.right_margin) }; + if let Some((label, p)) = text_more_rows(ui, &mut extra) { live(app, label, "text.edit", p); } row_prose(ui, tr!("Text"), |ui| { - if ui.button(tr!("Edit Text")).on_hover_text(tr!("Type on the stage (or double-click the text)")).clicked() { + if ui.button(tr!("Edit Text")).on_hover_text(tr!("Type on the stage (or double-click the text); select characters to style them on their own")).clicked() { let at = e.transform.apply(anicraft_engine::geom::Vec2::ZERO); - app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(e.id), text: t.text.clone(), original: t.text.clone(), focus: true }); + app.text_edit = Some(crate::app::TextEditing::new(pos2(at.x, at.y), Some(e.id), Some(t), &app.s.text_style)); } }); text_path_rows(app, ui, e, t); @@ -1864,10 +1938,101 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec, + pub underline: Option, + pub url: Option, + pub indent: f32, + pub left_margin: f32, + pub right_margin: f32, + /// The paragraphs' indents or margins differ. + pub layout_mixed: bool, +} + +/// Baseline shift, underline, link, indent and margin rows. Returns the edit made, as params +/// (one key per change), with an undo label. +pub fn text_more_rows(ui: &mut egui::Ui, x: &mut TextExtra) -> Option<(&'static str, Value)> { + use anicraft_engine::doc::BaselineShift; + let mut out: Option<(&'static str, Value)> = None; + row_prose(ui, tr!("Position"), |ui| { + let label = |s: BaselineShift| match s { + BaselineShift::Normal => tr!("Normal"), + BaselineShift::Superscript => tr!("Superscript"), + BaselineShift::Subscript => tr!("Subscript"), + }; + let shown = x.shift.map_or_else(|| tr!("mixed").to_string(), |s| label(s).to_string()); + egui::ComboBox::from_id_salt("text_shift").selected_text(shown).show_ui(ui, |ui| { + for s in BaselineShift::ALL { + if ui.selectable_label(x.shift == Some(s), label(s)).clicked() { + x.shift = Some(s); + out = Some((tr_noop!("Superscript and subscript"), json!({"shift": s.key()}))); + } + } + }) + .response + .set_name(tr!("Character position")); + // The letter on the button is the usual underline mark. + let on = x.underline == Some(true); + if ui.selectable_label(on, text(Type::Body, "U").underline()).named(tr!("Underline")).on_hover_text(tr!("Underline")).clicked() { + x.underline = Some(!on); + out = Some((tr_noop!("Underline"), json!({"underline": !on}))); + } + mixed_chars(ui, x.underline.is_none()); + }); + row_prose(ui, tr!("Link"), |ui| { + let mut url = x.url.clone().unwrap_or_default(); + let r = ui.add(egui::TextEdit::singleline(&mut url).desired_width(170.0).font(crate::theme::font(Type::Path)).hint_text(if x.url.is_none() { tr!("mixed") } else { tr!("https://…") })).named(tr!("Link")).on_hover_text(tr!("Where the characters link to in SVG and other exports; empty for no link")); + if r.lost_focus() && x.url.as_deref() != Some(url.trim()) { + x.url = Some(url.trim().to_string()); + out = Some((tr_noop!("Text link"), json!({"url": url.trim()}))); + } + }); + row(ui, tr!("Indent"), |ui| { + if ui.add(egui::DragValue::new(&mut x.indent).suffix(" px").speed(0.5).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("First-line indent")).on_hover_text(tr!("First-line indent")).changed() { + out = Some((tr_noop!("Indent"), json!({"indent": x.indent}))); + } + mixed_chars(ui, x.layout_mixed); + }); + row(ui, tr!("Margins"), |ui| { + if ui.add(egui::DragValue::new(&mut x.left_margin).prefix(format!("{} ", tr!("Left"))).suffix(" px").speed(0.5).range(0.0..=1000.0).max_decimals(1)).named(tr!("Left margin")).changed() { + out = Some((tr_noop!("Margins"), json!({"left_margin": x.left_margin}))); + } + if ui.add(egui::DragValue::new(&mut x.right_margin).prefix(format!("{} ", tr!("Right"))).suffix(" px").speed(0.5).range(0.0..=1000.0).max_decimals(1)).named(tr!("Right margin")).changed() { + out = Some((tr_noop!("Margins"), json!({"right_margin": x.right_margin}))); + } + }); + out +} + /// Font, size, style, colour, alignment and spacing rows for text. Returns the edit made, as /// `text.edit` params (one key per change), with an undo label. -pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engine::cmds_text::TextStyle, width: Option<&mut Option>) -> Option<(&'static str, Value)> { +pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engine::cmds_text::TextStyle, width: Option<&mut Option>, mx: Option<&TextMixed>) -> Option<(&'static str, Value)> { use anicraft_engine::doc::TextAlign; + let mx = mx.copied().unwrap_or_default(); let families = app.font_families.get_or_insert_with(|| anicraft_engine::text::Fonts::get().families().to_vec()).clone(); let mut out: Option<(&'static str, Value)> = None; row_prose(ui, tr!("Font"), |ui| { @@ -1885,6 +2050,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin }) .response .set_name(tr!("Font")); + mixed_chars(ui, mx.font); }); row(ui, tr!("Size"), |ui| { if ui.add(egui::DragValue::new(&mut st.size).suffix(" px").speed(0.25).range(1.0..=2000.0).max_decimals(1)).named(tr!("Font size")).changed() { @@ -1895,6 +2061,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin st.color = Rgba::hex(u32::from(c[0]) << 16 | u32::from(c[1]) << 8 | u32::from(c[2])); out = Some((tr_noop!("Text colour"), json!({"color": hex(c)}))); } + mixed_chars(ui, mx.size || mx.color); }); row_prose(ui, tr!("Style"), |ui| { // The letters on the two buttons are the usual bold and italic marks. @@ -1906,6 +2073,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin st.italic = !st.italic; out = Some((tr_noop!("Italic"), json!({"italic": st.italic}))); } + mixed_chars(ui, mx.bold || mx.italic); ui.separator(); for (a, label, name, key) in [(TextAlign::Left, tr!("Left"), tr!("Align left"), "left"), (TextAlign::Center, tr!("Centre"), tr!("Align centre"), "center"), (TextAlign::Right, tr!("Right"), tr!("Align right"), "right")] { if ui.selectable_label(st.align == a, label).named(name).on_hover_text(name).clicked() { @@ -1913,6 +2081,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin out = Some((tr_noop!("Text alignment"), json!({"align": key}))); } } + mixed_chars(ui, mx.align); }); row(ui, tr!("Spacing"), |ui| { if ui.add(egui::DragValue::new(&mut st.letter_spacing).prefix(format!("{} ", tr!("Letters"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Letter spacing")).changed() { @@ -1921,6 +2090,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin if ui.add(egui::DragValue::new(&mut st.line_spacing).prefix(format!("{} ", tr!("Lines"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Line spacing")).changed() { out = Some((tr_noop!("Line spacing"), json!({"line_spacing": st.line_spacing}))); } + mixed_chars(ui, mx.letter_spacing || mx.line_spacing); }); if let Some(width) = width { row(ui, tr!("Width"), |ui| { @@ -2552,7 +2722,7 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { if app.tool == Tool::Text { // What new text gets (the last style used). let mut st = app.s.text_style.clone(); - if text_style_rows(app, ui, &mut st, None).is_some() { + if text_style_rows(app, ui, &mut st, None, None).is_some() { app.s.text_style = st; } return; diff --git a/src/platform.rs b/src/platform.rs index 2780253d..e8d21068 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -397,7 +397,7 @@ pub fn places() -> Vec<(&'static str, Option)> { return Vec::new(); } #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] - let mut v = vec![(tr_noop!("Preferences"), config_dir()), (tr_noop!("Autosave"), recovery_dir()), (tr_noop!("Logs"), log_dir()), (tr_noop!("Plug-ins"), plugins_dir()), (tr_noop!("Templates"), templates_dir())]; + let mut v = vec![(tr_noop!("Preferences"), config_dir()), (tr_noop!("Autosave"), recovery_dir()), (tr_noop!("Logs"), log_dir()), (tr_noop!("Plug-ins"), plugins_dir()), (tr_noop!("Templates"), templates_dir()), (tr_noop!("Saved commands"), commands_dir())]; #[cfg(not(target_arch = "wasm32"))] v.push((tr_noop!("User guide"), Some(guide_dir()))); v @@ -554,6 +554,19 @@ pub fn templates_dir() -> Option { } } +/// Where saved commands live (ADR 0097): `Commands` in the settings folder, one small JSON file +/// each. `ANICRAFT_COMMANDS_DIR` points it elsewhere (tests, screenshots). None in a browser, +/// which has no folders to keep them in. +pub fn commands_dir() -> Option { + if WEB { + return None; + } + match std::env::var_os("ANICRAFT_COMMANDS_DIR").filter(|v| !v.is_empty()) { + Some(d) => Some(PathBuf::from(d)), + None => config_dir().map(|d| d.join("Commands")), // i18n-exempt: a folder name + } +} + /// Where installed plug-ins live: a `plugins` folder in the settings folder (ADR 0017). pub fn plugins_dir() -> Option { config_dir().map(|d| d.join("plugins")) @@ -851,6 +864,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { // Opening also imports .fla archives and .xfl packages. "file.open" => (tr_noop!("Documents"), &["anicraft", "fla", "xfl"]), "plugin.install" => (tr_noop!("WebAssembly plug-in"), &["wasm"]), + "macro.run" | "macro.import" => (tr_noop!("Saved command"), &["json"]), "brush.preset_export" | "brush.preset_import" => (tr_noop!("Brush set"), &["json"]), "filter.preset_export" | "filter.preset_import" => (tr_noop!("Filter preset file"), &["json"]), "swatch.export" => (tr_noop!("Swatch file"), &["json"]), @@ -861,7 +875,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { /// Commands that read a file the user picks (the others write one, or a folder of them). pub fn reads_file(cmd: &str) -> bool { - matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import") + matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "macro.run" | "macro.import") } /// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with diff --git a/src/plugin_export_ui.rs b/src/plugin_export_ui.rs index 97f8aa08..b1dc8f4c 100644 --- a/src/plugin_export_ui.rs +++ b/src/plugin_export_ui.rs @@ -172,7 +172,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) { let (mut go, mut replace, mut close) = (false, false, false); let running = e.running.is_some(); let at = ctx.content_rect().center() - egui::vec2(200.0, 180.0); - let shown = egui::Window::new(title.clone()).id(egui::Id::new("plugin_export")).open(&mut open).default_pos(at).default_width(400.0).resizable(false).collapsible(false).show(ctx, |ui| { + let shown = crate::windows::new(ctx, title.clone()).id(egui::Id::new("plugin_export")).open(&mut open).default_pos(at).default_width(400.0).resizable(false).collapsible(false).show(ctx, |ui| { let m = p.manifest(); let by = [m.author.as_str(), m.version.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" · "); ui.label(text(Type::Caption, if by.is_empty() { tr!("Plug-in").to_string() } else { tr!("Plug-in · {by}", by = by) })); diff --git a/src/plugins_ui.rs b/src/plugins_ui.rs index 0a29f62c..6735b4ff 100644 --- a/src/plugins_ui.rs +++ b/src/plugins_ui.rs @@ -141,6 +141,8 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui, cmds: &[CommandSpec], item: impl F for spec in cmds.iter().filter(|c| c.menu == "Commands") { item(app, ui, spec); } + // Saved commands last, as Animate lists them (ADR 0097). + crate::macros_ui::menu_items(app, ui); } fn hex_rgb(s: &str) -> [u8; 3] { @@ -286,7 +288,7 @@ fn manager(app: &mut App, ctx: &egui::Context) { let mut open = app.show_plugins; let mut action: Option<(&'static str, String)> = None; let title = tr!("Plug-ins"); - let shown = egui::Window::new(title).id(egui::Id::new("plugins_window")).open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| { + let shown = crate::windows::new(ctx, title).id(egui::Id::new("plugins_window")).open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| { let list: Vec> = app.s.plugins.list().cloned().collect(); if list.is_empty() { ui.label(text(Type::Label, tr!("No plug-ins installed yet. Plug-ins are WebAssembly (.wasm) files that add commands (generators, selection effects), export formats and eases."))); diff --git a/src/publish_panel.rs b/src/publish_panel.rs index 8be65d31..238202b2 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -287,7 +287,7 @@ fn settings_window(app: &mut App, ctx: &egui::Context) { } let mut open = true; let at = ctx.content_rect().center() - egui::vec2(330.0, 260.0); - let shown = egui::Window::new(tr!("Publish Settings")).id(egui::Id::new("publish_settings")).open(&mut open).default_pos(at).default_width(660.0).resizable(true).collapsible(false).show(ctx, |ui| settings(app, ui)); + let shown = crate::windows::new(ctx, tr!("Publish Settings")).id(egui::Id::new("publish_settings")).open(&mut open).default_pos(at).default_width(660.0).resizable(true).collapsible(false).show(ctx, |ui| settings(app, ui)); crate::a11y::name_title_bar(&shown, tr!("Publish Settings")); if !open { app.publish.open = false; @@ -695,7 +695,7 @@ fn progress_window(app: &mut App, ctx: &egui::Context) { let mut open = true; let title = if running { tr!("Publishing") } else { tr!("Publish report") }; let at = ctx.content_rect().center() - egui::vec2(220.0, 160.0); - let shown = egui::Window::new(title).id(egui::Id::new("publish_progress")).open(&mut open).default_pos(at).default_width(460.0).resizable(true).collapsible(false).show(ctx, |ui| { + let shown = crate::windows::new(ctx, title).id(egui::Id::new("publish_progress")).open(&mut open).default_pos(at).default_width(460.0).resizable(true).collapsible(false).show(ctx, |ui| { if let Some(job) = &app.publish.job { job_rows(ui, job); } else if let Some(r) = &app.publish.report { diff --git a/src/rich_edit.rs b/src/rich_edit.rs new file mode 100644 index 00000000..e9b1d881 --- /dev/null +++ b/src/rich_edit.rs @@ -0,0 +1,339 @@ +//! Styled text while typing on the stage (ADR 0085): the runs and paragraph styles of the text +//! being typed, kept as the text changes (what is typed continues the style before it), shown +//! in the editor with their colours, sizes, slant, underline and baseline shift; Properties +//! styles the selected characters (or what is typed next, at a caret); copying and pasting +//! inside AniCraft keeps styles, text from other apps comes in plain. +//! +//! Every style change on an existing block is one `text.edit` with the text, runs and +//! paragraphs, so it shows on the stage the same frame and undoes as one step. + +use crate::app::{App, TextEditing}; +use anicraft_engine::cmds_text::{CharPatch, ParaPatch}; +use anicraft_engine::doc::rich_text as rt; +use anicraft_engine::doc::{BaselineShift, CharStyle, ElementId, ParagraphStyle, Rgba, TextBlock, TextRun}; +use egui::text::{LayoutJob, TextFormat}; +use serde_json::{Value, json}; + +/// Styled text copied from the stage editor: pasted back as the same text, it keeps its runs. +#[derive(Clone, Debug, Default)] +pub struct StyledClip { + pub text: String, + pub runs: Vec, +} + +impl TextEditing { + /// Editing `block` (or new text in `style`, when there is none) with its top-left at `at`. + pub fn new(at: egui::Pos2, element: Option, block: Option<&TextBlock>, style: &anicraft_engine::cmds_text::TextStyle) -> TextEditing { + let (text, runs, paras) = match block { + Some(b) => (b.text.clone(), b.styled_runs(), b.paragraph_styles()), + None => { + let c = CharStyle { font: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, color: style.color, letter_spacing: style.letter_spacing, ..CharStyle::default() }; + (String::new(), vec![TextRun { chars: 0, style: c }], vec![ParagraphStyle { align: style.align, line_spacing: style.line_spacing, ..ParagraphStyle::default() }]) + } + }; + let n = text.chars().count() as u32; + TextEditing { at, element, original: text.clone(), last: text.clone(), text, runs, paras, sel: (n, n), pending: None, paste: None, focus: true } + } + + /// The selected characters, first to last. + pub fn range(&self) -> (u32, u32) { + (self.sel.0.min(self.sel.1), self.sel.0.max(self.sel.1)) + } + + /// Follows a change of the text: the runs and paragraphs move with it, and a paste of + /// styled text copied here takes its runs back. + pub fn sync(&mut self) { + if self.text == self.last { + return; + } + let (start, old_end, new_end) = rt::diff_chars(&self.last, &self.text); + let inserted: String = self.text.chars().skip(start as usize).take((new_end - start) as usize).collect(); + // A caret style picked before typing (Properties at a caret) styles what is typed. + let typed = match (self.pending.take(), self.paste.take()) { + (_, Some(clip)) if clip.text == inserted => clip.runs, + (Some(style), _) => vec![TextRun { chars: new_end - start, style }], + _ => vec![TextRun { chars: new_end - start, style: rt::style_at(&self.runs, start) }], + }; + self.runs = rt::replace_runs(&self.runs, start, old_end, typed); + self.paras = rt::edit_paragraphs(&self.paras, &self.last, start, old_end, &inserted); + self.last = self.text.clone(); + } + + /// What the selection shares (`None` attributes are mixed); at a caret, what typing gets. + pub fn summary(&self) -> rt::StyleSummary { + let (a, b) = self.range(); + match (&self.pending, a == b) { + (Some(p), true) => rt::StyleSummary::of(p), + _ => rt::summarize(&self.runs, a, b), + } + } + + /// Restyles the selection (at a caret: what is typed next there). + pub fn restyle(&mut self, patch: &CharPatch) { + let (a, b) = self.range(); + if a == b { + let mut s = self.pending.clone().unwrap_or_else(|| rt::style_at(&self.runs, a)); + patch.apply(&mut s); + self.pending = Some(s); + return; + } + self.runs = rt::restyle_runs(&self.runs, a, b, |s| patch.apply(s)); + } + + /// Sets the layout of the paragraphs the selection touches. + pub fn repara(&mut self, patch: &ParaPatch) { + let (a, b) = self.range(); + let range = rt::paragraphs_in(&self.text, a, b); + let n = rt::paragraph_count(&self.text); + let fill = self.paras.last().copied().unwrap_or_default(); + self.paras.resize(n, fill); + for (i, p) in self.paras.iter_mut().enumerate() { + if range.contains(&i) { + patch.apply(p); + } + } + } + + /// The `text.edit` params that set the block to what is being typed. + pub fn edit_params(&self) -> Value { + let runs: Vec = self.runs.iter().filter(|r| r.chars > 0).map(run_json).collect(); + let paras: Vec = self.paras.iter().map(para_json).collect(); + json!({"text": self.text, "runs": runs, "paragraphs": paras}) + } + + /// The styled text of the selection (for Copy and Cut). + pub fn clip(&self) -> Option { + let (a, b) = self.range(); + (a < b).then(|| StyledClip { text: self.text.chars().skip(a as usize).take((b - a) as usize).collect(), runs: rt::slice_runs(&self.runs, a, b) }) + } +} + +fn hex(c: Rgba) -> String { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b)) +} + +fn run_json(r: &TextRun) -> Value { + let s = &r.style; + json!({"chars": r.chars, "font": s.font, "size": s.size, "bold": s.bold, "italic": s.italic, "color": hex(s.color), "letter_spacing": s.letter_spacing, "shift": s.shift.key(), "underline": s.underline, "url": s.url}) +} + +fn para_json(p: &ParagraphStyle) -> Value { + let align = match p.align { + anicraft_engine::doc::TextAlign::Left => "left", + anicraft_engine::doc::TextAlign::Center => "center", + anicraft_engine::doc::TextAlign::Right => "right", + }; + json!({"align": align, "indent": p.indent, "left_margin": p.left_margin, "right_margin": p.right_margin, "line_spacing": p.line_spacing}) +} + +/// How the editor shows the text being typed: each run in its colour, size (at the stage's +/// zoom, within what the editor can show), slant, underline and baseline shift. The type is +/// the interface's (the stage itself shows the real faces). +pub fn layout_job(runs: &[TextRun], last: &str, text: &str, zoom: f32, wrap: f32) -> LayoutJob { + let mut job = LayoutJob { wrap: egui::text::TextWrapping { max_width: wrap, ..Default::default() }, ..LayoutJob::default() }; + // Typed this frame (before the runs follow it): laid out as typing will style it. + let runs = if last == text { + runs.to_vec() + } else { + let (start, old_end, new_end) = rt::diff_chars(last, text); + rt::type_into_runs(runs, start, old_end, new_end - start) + }; + let mut bytes = text.char_indices().map(|(b, _)| b).chain(std::iter::once(text.len())); + let mut at_byte = bytes.next().unwrap_or(0); + let total = text.chars().count() as u32; + let mut covered = 0u32; + for (i, r) in runs.iter().enumerate() { + let n = if i + 1 == runs.len() { total.saturating_sub(covered) } else { r.chars.min(total.saturating_sub(covered)) }; + if n == 0 { + continue; + } + let mut end_byte = at_byte; + for _ in 0..n { + end_byte = bytes.next().unwrap_or(text.len()); + } + let s = &r.style; + let small = s.shift != BaselineShift::Normal; + let size = s.size * zoom * if small { 0.6 } else { 1.0 }; + let mut f = TextFormat::simple(crate::theme::stage_text_run_font(size), crate::theme::stage_text_colour(s.color)); + f.italics = s.italic; + if s.underline || !s.url.is_empty() { + f.underline = egui::Stroke::new((size / 14.0).max(1.0), f.color); + } + f.valign = if s.shift == BaselineShift::Superscript { egui::Align::TOP } else { egui::Align::BOTTOM }; + if let Some(seg) = text.get(at_byte..end_byte) { + job.append(seg, 0.0, f); + } + at_byte = end_byte; + covered += n; + } + job +} + +/// Applies the editor's runs to the block on the stage (one undo step) when it exists, so the +/// change shows there now. +fn push(app: &mut App, label: &'static str) { + let Some(te) = app.text_edit.as_mut() else { return }; + te.focus = true; + let Some(id) = te.element else { return }; + if te.text.trim().is_empty() { + return; + } + let p = te.edit_params(); + te.original = te.text.clone(); + app.run("element.select", json!({"ids": [id.0]})); + crate::panels::live(app, label, "text.edit", p); +} + +/// Properties while typing on the stage: the selected characters' style (mixed values marked) +/// and the layout of the paragraphs they touch. +pub fn selection_rows(app: &mut App, ui: &mut egui::Ui) { + let Some(te) = app.text_edit.as_ref() else { return }; + let m = te.summary(); + let (a, b) = te.range(); + let para = { + let range = rt::paragraphs_in(&te.text, a, b); + let list: Vec = te.paras.iter().enumerate().filter(|(i, _)| range.contains(i)).map(|(_, p)| *p).collect(); + let first = list.first().copied().or(te.paras.last().copied()).unwrap_or_default(); + (first, list.iter().any(|p| p.align != first.align), list.iter().any(|p| p.indent != first.indent || p.left_margin != first.left_margin || p.right_margin != first.right_margin), list.iter().any(|p| p.line_spacing != first.line_spacing)) + }; + let first = rt::style_at(&te.runs, a); + let mut st = anicraft_engine::cmds_text::TextStyle { + font: m.font.clone().unwrap_or(first.font.clone()), + size: m.size.unwrap_or(first.size), + bold: m.bold.unwrap_or(false), + italic: m.italic.unwrap_or(false), + color: m.color.unwrap_or(first.color), + align: para.0.align, + letter_spacing: m.letter_spacing.unwrap_or(first.letter_spacing), + line_spacing: para.0.line_spacing, + }; + let mixed = crate::panels::TextMixed { font: m.font.is_none(), size: m.size.is_none(), color: m.color.is_none(), bold: m.bold.is_none(), italic: m.italic.is_none(), letter_spacing: m.letter_spacing.is_none(), align: para.1, line_spacing: para.3 }; + let mut extra = crate::panels::TextExtra { + shift: m.shift, + underline: m.underline, + url: m.url.clone(), + indent: para.0.indent, + left_margin: para.0.left_margin, + right_margin: para.0.right_margin, + layout_mixed: para.2, + }; + // Its own ids: the block's rows may show in the same panel. + let r = ui.push_id("text_selection_rows", |ui| { + let edit = crate::panels::text_style_rows(app, ui, &mut st, None, Some(&mixed)); + let more = crate::panels::text_more_rows(ui, &mut extra); + edit.or(more) + }); + app.text_props_rect = Some(r.response.rect); + let Some((label, p)) = r.inner else { return }; + let (cp, pp) = (CharPatch::parse(&p).unwrap_or_default(), ParaPatch::parse(&p).unwrap_or_default()); + if let Some(te) = app.text_edit.as_mut() { + te.restyle(&cp); + te.repara(&pp); + } + push(app, label); +} + +/// Before the editor sees this frame's input: Copy and Cut keep the selection's styles, and a +/// paste of exactly that text takes them back. +pub fn watch_clipboard(app: &mut App, ctx: &egui::Context, focused: bool) { + if !focused { + return; + } + let events = ctx.input(|i| i.events.clone()); + for e in events { + match e { + egui::Event::Copy | egui::Event::Cut => { + if let Some(clip) = app.text_edit.as_ref().and_then(TextEditing::clip) { + app.text_clip = Some(clip); + } + } + egui::Event::Paste(s) => { + let clip = app.text_clip.clone().filter(|c| c.text == s.replace("\r\n", "\n")); + if let Some(te) = app.text_edit.as_mut() { + te.paste = clip; + } + } + _ => {} + } + } +} + +/// A short title for the Properties section while typing. +pub fn title(te: &TextEditing) -> String { + let (a, b) = te.range(); + if a == b { tr!("Text: at the caret").to_string() } else { trn!("Text: {n} character selected", "Text: {n} characters selected", (b - a) as usize).to_string() } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn editing(text: &str) -> TextEditing { + let mut te = TextEditing::new(egui::Pos2::ZERO, None, None, &anicraft_engine::cmds_text::TextStyle::default()); + te.text = text.into(); + te.sync(); + te + } + + #[test] + fn typing_after_a_styled_word_continues_its_style() { + let mut te = editing("Hello world"); + te.sel = (0, 5); + te.restyle(&CharPatch { bold: Some(true), ..CharPatch::default() }); + te.text = "Hello! world".into(); + te.sync(); + assert_eq!(te.runs.iter().map(|r| (r.chars, r.style.bold)).collect::>(), vec![(6, true), (6, false)]); + // At a caret, a style picked first styles what is typed next. + te.sel = (12, 12); + te.restyle(&CharPatch { italic: Some(true), ..CharPatch::default() }); + assert_eq!(te.summary().italic, Some(true)); + te.text = "Hello! world?".into(); + te.sync(); + assert_eq!(te.runs.last().map(|r| (r.chars, r.style.italic)), Some((1, true))); + } + + #[test] + fn copy_and_paste_inside_keeps_styles_and_outside_text_is_plain() { + let mut te = editing("red blue"); + te.sel = (0, 3); + te.restyle(&CharPatch { color: Some(Rgba::hex(0xff0000)), ..CharPatch::default() }); + let clip = te.clip().unwrap(); + assert_eq!(clip.text, "red"); + // Pasted at the end: red again. + te.paste = Some(clip.clone()); + te.text = "red bluered".into(); + te.sync(); + assert_eq!(te.runs.last().map(|r| (r.chars, r.style.color)), Some((3, Rgba::hex(0xff0000)))); + // Other text (from another app): the style before it, plain. + te.paste = Some(clip); + te.text = "red bluered!!".into(); + te.sync(); + assert_eq!(te.runs.last().map(|r| (r.chars, r.style.color)), Some((5, Rgba::hex(0xff0000))), "continues the red before it"); + let mut te = editing("a b"); + te.paste = Some(StyledClip { text: "zz".into(), runs: vec![TextRun { chars: 2, style: CharStyle { bold: true, ..CharStyle::default() } }] }); + te.text = "a xyb".into(); + te.sync(); + assert!(te.runs.iter().all(|r| !r.style.bold), "a different text is plain"); + } + + #[test] + fn paragraphs_follow_line_breaks_and_selection_rows_mark_mixed() { + let mut te = editing("one\ntwo"); + te.sel = (0, 0); + te.repara(&ParaPatch { align: Some(anicraft_engine::doc::TextAlign::Center), ..ParaPatch::default() }); + te.text = "one\ntwo\nthree".into(); + te.sync(); + assert_eq!(te.paras.len(), 3); + assert_eq!(te.paras[0].align, anicraft_engine::doc::TextAlign::Center); + let p = te.edit_params(); + assert_eq!(p["paragraphs"].as_array().map(Vec::len), Some(3)); + te.sel = (0, 5); + te.restyle(&CharPatch { size: Some(50.0), ..CharPatch::default() }); + te.sel = (3, 9); + assert_eq!(te.summary().size, None, "mixed sizes"); + // The editor shows each run in its own format. + let job = layout_job(&te.runs, &te.last, &te.text, 1.0, 300.0); + assert!(job.sections.len() >= 2); + } +} diff --git a/src/stage.rs b/src/stage.rs index 3d5cbb11..7a832b5e 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -753,7 +753,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Text if !panning => { commit_text(app); if !open_text_at(app, sp, 3.0 / zoom.max(1e-3)) { - app.text_edit = Some(crate::app::TextEditing { at: sp, element: None, text: String::new(), original: String::new(), focus: true }); + app.text_edit = Some(crate::app::TextEditing::new(sp, None, None, &app.s.text_style)); } } Tool::Bone if !panning => crate::bone_tool::click(app, xf, p), @@ -1833,23 +1833,28 @@ mod pattern_tests { fn open_text_at(app: &mut App, sp: Pos2, tolerance: f32) -> bool { let Some((_, id)) = app.s.hit_test(to_v(sp), tolerance) else { return false }; let found = app.s.visible_elements().into_iter().find(|e| e.id == id).and_then(|e| match &e.kind { - anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(Vec2::ZERO), t.text.clone())), + anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(Vec2::ZERO), t.clone())), _ => None, }); - let Some((at, text)) = found else { return false }; + let Some((at, block)) = found else { return false }; app.run("element.select", json!({"ids": [id.0]})); - app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(id), original: text.clone(), text, focus: true }); + app.text_edit = Some(crate::app::TextEditing::new(pos2(at.x, at.y), Some(id), Some(&block), &app.s.text_style)); true } /// Commits the text being typed: new text is created, edited text replaced (one undo step -/// each); emptied text is deleted, and unchanged text commits nothing. +/// each), with its styled runs (ADR 0085); emptied text is deleted, and unchanged text commits +/// nothing. pub fn commit_text(app: &mut App) { - let Some(te) = app.text_edit.take() else { return }; + let Some(mut te) = app.text_edit.take() else { return }; + te.sync(); match te.element { None if te.text.trim().is_empty() => {} None => { - app.run("text.create", json!({"text": te.text, "x": te.at.x, "y": te.at.y})); + let mut p = te.edit_params(); + p["x"] = json!(te.at.x); + p["y"] = json!(te.at.y); + app.run("text.create", p); } Some(_) if te.text == te.original => {} Some(id) => { @@ -1857,35 +1862,69 @@ pub fn commit_text(app: &mut App) { if te.text.trim().is_empty() { app.run("edit.delete", json!({})); } else { - app.run("text.edit", json!({"text": te.text})); + app.run("text.edit", te.edit_params()); } } } } -/// The field text is typed in, over the stage at the text's top-left corner. Esc or a click -/// elsewhere finishes; Enter starts a new line. +/// The field text is typed in, over the stage at the text's top-left corner, each run shown in +/// its own colour, size and style (ADR 0085). Esc or a click elsewhere finishes (a click in +/// Properties' text styles keeps it open); Enter starts a new line. fn text_editor(app: &mut App, ui: &mut egui::Ui, stage_origin: Pos2, zoom: f32) { + let focused_id = egui::Id::new("stage_text_edit_field"); + let had_focus = ui.ctx().memory(|m| m.has_focus(focused_id)); + crate::rich_edit::watch_clipboard(app, ui.ctx(), had_focus); + let paper = crate::theme::stage_text_colour(anicraft_engine::doc::Rgba { a: 1.0, ..app.s.doc.stage.background }); + let held = app.text_props_rect.zip(ui.ctx().input(|i| i.pointer.interact_pos())).is_some_and(|(r, p)| r.contains(p)) || egui::Popup::is_any_open(ui.ctx()); + // As wide as the block being edited (at the zoom), so its lines break as they do. + let block_w = app.text_edit.as_ref().and_then(|te| te.element).and_then(|id| app.s.visible_elements().into_iter().find(|e| e.id == id)).and_then(|e| match &e.kind { + anicraft_engine::doc::ElementKind::Text(t) => Some(t.width.unwrap_or(t.box_width)), + _ => None, + }); let Some(te) = app.text_edit.as_mut() else { return }; let at = stage_origin + vec2(te.at.x * zoom, te.at.y * zoom); - let size = (app.s.text_style.size * zoom).clamp(12.0, 64.0); + let size = (rt_size(te) * zoom).clamp(12.0, 64.0); + let width = 260.0f32.max(size * 8.0).max(block_w.unwrap_or(0.0) * zoom + 8.0).min(4000.0); let mut done = false; + let (runs, last) = (te.runs.clone(), te.last.clone()); egui::Area::new(egui::Id::new("stage_text_edit")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - egui::Frame::new().fill(T.panel).stroke(Stroke::new(1.0, T.selection)).inner_margin(4.0).show(ui, |ui| { - let r = ui.add(egui::TextEdit::multiline(&mut te.text).font(crate::theme::stage_text_font(size)).desired_rows(1).desired_width(260.0f32.max(size * 8.0)).hint_text(tr!("Type text"))).named(tr!("Text on the stage")); + egui::Frame::new().fill(paper).stroke(Stroke::new(1.0, T.selection)).inner_margin(4.0).show(ui, |ui| { + let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap: f32| { + let job = crate::rich_edit::layout_job(&runs, &last, buf.as_str(), zoom, wrap); + ui.fonts_mut(|f| f.layout_job(job)) + }; + let r = ui + .add(egui::TextEdit::multiline(&mut te.text).id(focused_id).font(crate::theme::stage_text_font(size)).desired_rows(1).desired_width(width).background_color(paper).hint_text(tr!("Type text")).layouter(&mut layouter)) + .named(tr!("Text on the stage")); + if let Some(range) = egui::text_edit::TextEditState::load(ui.ctx(), r.id).and_then(|s| s.cursor.char_range()) { + te.sel = (range.secondary.index.0 as u32, range.primary.index.0 as u32); + } if te.focus { + // Back in the editor (after a style was picked): the selection as it was. + if let Some(mut state) = egui::text_edit::TextEditState::load(ui.ctx(), r.id) { + let (a, b) = te.sel; + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(a as usize), egui::text::CCursor::new(b as usize)))); + state.store(ui.ctx(), r.id); + } r.request_focus(); te.focus = false; - } else if r.lost_focus() { + } else if r.lost_focus() && !held { done = true; } }); }); + te.sync(); if done { commit_text(app); } } +/// The size the editor's caret line is shown at: the run at the caret's. +fn rt_size(te: &crate::app::TextEditing) -> f32 { + anicraft_engine::doc::rich_text::style_at(&te.runs, te.sel.1).size +} + // ----- free transform --------------------------------------------------------------------------- /// Screen-space handle size and the rotation zone just outside each corner. diff --git a/src/templates.rs b/src/templates.rs index 9f499d67..39f0d438 100644 --- a/src/templates.rs +++ b/src/templates.rs @@ -240,7 +240,7 @@ pub fn save_window(app: &mut App, ctx: &egui::Context) { d.picture = Some(picture_png(doc).and_then(|png| texture(ctx, "save-preview", &png))); } let (mut submit, mut cancel) = (false, false); - egui::Window::new(tr!("Save as Template")).id(egui::Id::new("save_template")).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| { + crate::windows::new(ctx, tr!("Save as Template")).id(egui::Id::new("save_template")).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| { ui.set_min_width(420.0); if let Some(Some(tex)) = &d.picture { let s = tex.size_vec2(); diff --git a/src/test_movie.rs b/src/test_movie.rs index 5d0cd30b..6f387bba 100644 --- a/src/test_movie.rs +++ b/src/test_movie.rs @@ -386,7 +386,7 @@ fn inside(app: &mut App, ctx: &egui::Context, why: crate::platform::Inside) -> A let default_h = default_w * sh / sw.max(1.0) + 190.0; let title = title(tm); let note = why.note().map(crate::i18n::t); - let win = egui::Window::new(title.clone()) + let win = crate::windows::new(ctx, title.clone()) .id(egui::Id::new("test_movie")) .open(&mut shown) .collapsible(false) diff --git a/src/theme.rs b/src/theme.rs index 429c9c22..50c89f0a 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -512,6 +512,18 @@ pub fn stage_text_font(size: f32) -> egui::FontId { egui::FontId::proportional(size.clamp(12.0, 64.0)) } +/// The editor's face for a run of stage text at `size` screen pixels (within what the editor +/// can show legibly). +pub fn stage_text_run_font(size: f32) -> egui::FontId { + egui::FontId::proportional(if size.is_finite() { size.clamp(6.0, 96.0) } else { 14.0 }) +} + +/// A run's own colour (document data) as the editor shows it, at least faintly visible. +pub fn stage_text_colour(c: anicraft_engine::doc::Rgba) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgba_unmultiplied(b(c.r), b(c.g), b(c.b), b(c.a.max(0.25))) +} + /// The typefaces embedded at build time (Inter, JetBrains Mono), for text on the stage. pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() diff --git a/src/updates.rs b/src/updates.rs index 1a85ec82..34c070f5 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -186,7 +186,7 @@ impl Updates { let mut open = true; let mut install = false; let mut again = false; - egui::Window::new(tr!("Check for Updates")) + crate::windows::new(ctx, tr!("Check for Updates")) .open(&mut open) .collapsible(false) .resizable(false) @@ -418,13 +418,10 @@ mod tests { let mut app = crate::app::App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); assert!(!app.s.is_dirty()); assert!(safe_to_install(&app)); - app.text_edit = Some(crate::app::TextEditing { - at: egui::Pos2::ZERO, - element: None, - text: "Uncommitted stage text".into(), - original: String::new(), - focus: false, - }); + let mut te = crate::app::TextEditing::new(egui::Pos2::ZERO, None, None, &app.s.text_style); + te.text = "Uncommitted stage text".into(); + te.focus = false; + app.text_edit = Some(te); assert!(!app.s.is_dirty(), "the edit has not reached Session yet"); assert!(!safe_to_install(&app), "restarting would discard the text buffer"); app.text_edit = None; diff --git a/src/windows.rs b/src/windows.rs new file mode 100644 index 00000000..8e299deb --- /dev/null +++ b/src/windows.rs @@ -0,0 +1,69 @@ +//! Floating windows: every `egui::Window` the shell opens comes from [`new`], which keeps it +//! inside the work area below the menu bar, so no dialog's title bar covers File, Edit, View +//! (a window dragged up stops under the bar; one placed or anchored over it is moved down). +//! `guidelines_tests` checks that no other code opens a window directly. + +/// Where the area below the menu bar is kept for this frame. +fn key() -> egui::Id { + egui::Id::new("anicraft_work_area") +} + +/// Records the work area: the window's content below the menu bar (`bar_bottom`). +pub fn set_work_area(ctx: &egui::Context, bar_bottom: f32) { + let mut r = ctx.content_rect(); + if bar_bottom.is_finite() { + r.min.y = bar_bottom.clamp(r.min.y, r.max.y); + } + ctx.data_mut(|d| d.insert_temp(key(), r)); +} + +/// The area floating windows stay in (the whole window before the menu bar has been laid out). +pub fn work_area(ctx: &egui::Context) -> egui::Rect { + ctx.data(|d| d.get_temp::(key())).unwrap_or_else(|| ctx.content_rect()) +} + +/// A floating window kept below the menu bar. +pub fn new(ctx: &egui::Context, title: impl Into) -> egui::Window<'static> { + egui::Window::new(title).constrain_to(work_area(ctx)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Runs one frame of a 800 × 600 window with a 24 px bar, a window asked to sit at the very + /// top, and returns where it was drawn. + fn frame(ctx: &egui::Context, at: egui::Pos2) -> egui::Rect { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }; + let mut shown = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx().clone(); + set_work_area(&ctx, 24.0); + if let Some(r) = new(&ctx, "Custom Ease").id(egui::Id::new("t")).current_pos(at).show(&ctx, |ui| { + ui.label("graph"); + }) { + shown = r.response.rect; + } + }); + out.textures_delta.clear(); + shown + } + + #[test] + fn windows_never_open_over_the_menu_bar() { + let ctx = egui::Context::default(); + for at in [egui::pos2(100.0, 0.0), egui::pos2(100.0, -50.0), egui::pos2(-20.0, 10.0)] { + let r = frame(&ctx, at); + let r = frame(&ctx, at).union(r); + assert!(r.min.y >= 24.0 - 0.5, "{at:?} → {r:?}"); + assert!(r.min.x >= -0.5); + } + // Lower down, a window stays where it was put. + let lower = egui::Context::default(); + frame(&lower, egui::pos2(100.0, 200.0)); + let r = frame(&lower, egui::pos2(100.0, 200.0)); + assert!((r.min.y - 200.0).abs() < 1.0, "{r:?}"); + // Before a bar was laid out, the whole window is the area. + assert_eq!(work_area(&egui::Context::default()), egui::Context::default().content_rect()); + } +} diff --git a/src/workspaces_window.rs b/src/workspaces_window.rs index 2ab21ed1..a81b3851 100644 --- a/src/workspaces_window.rs +++ b/src/workspaces_window.rs @@ -28,7 +28,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) { } let mut open = true; let title = tr!("Manage Workspaces"); - let shown = egui::Window::new(title).id(egui::Id::new("manage_workspaces")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + let shown = crate::windows::new(ctx, title).id(egui::Id::new("manage_workspaces")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { ui.set_min_width(380.0); let current = app.prefs.workspaces.current.clone(); for key in app.prefs.workspaces.keys() {