mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-21 10:01:55 +01:00
chore: merge main into m7/mixed-armatures
This commit is contained in:
commit
b5f3e5f0a8
97 files changed
+6156
-1054
No files matched your search
@@ -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.
|
||||
@@ -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`), <https://cldr.unicode.org>, 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, <https://www.w3.org/WAI/ARIA/apg/> (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`), <https://learn.microsoft.com/typography/opentype/spec/> | 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*, <https://specifications.freedesktop.org/>; 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, <https://flatpak.github.io/xdg-desktop-portal/> (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). |
|
||||
|
||||
@@ -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
|
||||
|
||||
Generated
+60
-5
@@ -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"
|
||||
|
||||
+4
-1
@@ -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 }
|
||||
|
||||
+16
-60
@@ -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<Vec<u8>> {
|
||||
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<u8>, 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<u8> {
|
||||
@@ -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<i16> = vec![0, 1, -1, 32_767, -32_768, 12_345, -54, 7];
|
||||
|
||||
+29
-1
@@ -30,6 +30,8 @@ USAGE:
|
||||
anicraft-cli formats lists every export format, plug-ins included (JSON)
|
||||
anicraft-cli commands
|
||||
anicraft-cli run <file|--sample> <script.json> [--save <out.anicraft>]
|
||||
a JSON array of {cmd, params}, or a saved command
|
||||
(one undo step; nothing changes if a step fails)
|
||||
anicraft-cli exec <file|--sample> <command.id> [<json-params>] [--save <out.anicraft>]
|
||||
anicraft-cli new --out <file.anicraft> [--width W] [--height H] [--fps F]
|
||||
anicraft-cli guide --out <folder> writes the user guide as HTML pages (open index.html)
|
||||
@@ -260,7 +262,16 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
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<Value> = 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<Value> = 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"));
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
+25
-11
@@ -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<Group>,
|
||||
/// 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<str>)>,
|
||||
}
|
||||
|
||||
/// 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<Path>, 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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<TextPath>,
|
||||
/// 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<TextRun>,
|
||||
/// One style per paragraph, when they differ (empty: all as above).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paragraphs: Vec<ParagraphStyle>,
|
||||
/// 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<TextFill>,
|
||||
#[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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -722,7 +722,7 @@ impl ScriptHost for Mono {
|
||||
}
|
||||
|
||||
fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc<Element> {
|
||||
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)) })
|
||||
}
|
||||
|
||||
|
||||
@@ -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<BaselineShift> {
|
||||
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<String> {
|
||||
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::<String>().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<u32>, Vec<Arc<Path>>)>);
|
||||
|
||||
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<TextRun> {
|
||||
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<ParagraphStyle> {
|
||||
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<TextRun>, paragraphs: Vec<ParagraphStyle>) {
|
||||
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<ParagraphStyle> = 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<Path>)> {
|
||||
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<u32> = 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<Arc<Path>> {
|
||||
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<TextRun>, n: u32) -> Vec<TextRun> {
|
||||
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<TextRun>, n: u32) -> Vec<TextRun> {
|
||||
let fallback = runs.first().map(|r| r.style.clone()).unwrap_or_default();
|
||||
let mut out: Vec<TextRun> = 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<TextRun> {
|
||||
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<TextRun>) -> Vec<TextRun> {
|
||||
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<TextRun> {
|
||||
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<TextRun> {
|
||||
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<ParagraphStyle> {
|
||||
let count = paragraph_count(old);
|
||||
let fill = paras.last().copied().unwrap_or_default();
|
||||
let full: Vec<ParagraphStyle> = (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<ParagraphStyle> = 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<char>, Vec<char>) = (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<String>,
|
||||
pub size: Option<f32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub color: Option<Rgba>,
|
||||
pub letter_spacing: Option<f32>,
|
||||
pub shift: Option<BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
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<T: PartialEq>(v: &mut Option<T>, 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<usize> {
|
||||
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;
|
||||
@@ -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<_>>(), 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::<u32>(), 5);
|
||||
// Too many runs are capped; lengths past the text are cut.
|
||||
let many: Vec<TextRun> = (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::<usize>(), 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<_>>(), 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");
|
||||
}
|
||||
+25
-39
@@ -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<Swatch>), 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::<u16>().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";
|
||||
|
||||
@@ -891,15 +891,17 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
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).
|
||||
|
||||
@@ -264,7 +264,7 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -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 `<folder>/<name>.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 `<folder>/.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<CommandSpec> {
|
||||
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 <folder>/<name>.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<Step>,
|
||||
}
|
||||
|
||||
impl Macro {
|
||||
/// The file's content.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let steps: Vec<Value> = 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<Macro> {
|
||||
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<PathBuf> {
|
||||
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<Macro> {
|
||||
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<String> {
|
||||
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<Saved>, Vec<(String, String)>) {
|
||||
let order: Vec<String> = 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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
command_path(&folder(p)?, str_req(p, "name")?)
|
||||
}
|
||||
|
||||
/// Where `macro.import` copies its file to.
|
||||
pub(crate) fn import_target(p: &Value) -> Result<PathBuf> {
|
||||
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<Macro> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let (found, problems) = saved_commands(&folder(p)?);
|
||||
let commands: Vec<Value> = found.iter().map(|c| json!({"name": c.name, "path": c.path.display().to_string(), "steps": c.steps})).collect();
|
||||
let problems: Vec<Value> = 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<Vec<&'static str>, 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>), String> {
|
||||
let dropped = check(cmd, params)?;
|
||||
let out: Map<String, Value> = 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<Step>, Vec<String>), 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>), String> {
|
||||
let cmds = usable(cmds)?;
|
||||
let mut dropped: Vec<String> = 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<String> {
|
||||
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<Value> {
|
||||
let done = s.history().undo_len();
|
||||
let steps: Vec<Value> = 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<Step>, Vec<Value>)> {
|
||||
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<String> = 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<Value> {
|
||||
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<Value> {
|
||||
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<PathBuf> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let path = existing(p)?;
|
||||
let dir = folder(p)?;
|
||||
let name = name_of(&path);
|
||||
vfs::remove_file(&path)?;
|
||||
let order: Vec<String> = 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<Value> {
|
||||
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<String> = 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}))
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -108,6 +108,9 @@ pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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<u64> {
|
||||
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<TempTrack> {
|
||||
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)
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// A name usable as a file or folder name on every system, or why not.
|
||||
fn clean_name(raw: &str, what: &str) -> Result<String> {
|
||||
pub(crate) fn clean_name(raw: &str, what: &str) -> Result<String> {
|
||||
let name = raw.trim();
|
||||
if name.is_empty() {
|
||||
return Err(EngineError::Param(format!("give the {what} a name")));
|
||||
|
||||
+540
-199
@@ -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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn align_param(p: &Value) -> Result<Option<TextAlign>> {
|
||||
Ok(match opt_str(p, "align")? {
|
||||
fn align_of(p: &Value, key: &str) -> Result<Option<TextAlign>> {
|
||||
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<f32>) -> Result<Option<f32>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The style in `p` over `base`.
|
||||
fn style_param(p: &Value, base: &TextStyle) -> Result<TextStyle> {
|
||||
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<Option<f32>> {
|
||||
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<f32> {
|
||||
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<f32>) -> Result<(TextBlock, Option<String>)> {
|
||||
/// 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<String>,
|
||||
pub size: Option<f32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub color: Option<Rgba>,
|
||||
pub letter_spacing: Option<f32>,
|
||||
pub shift: Option<BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
impl CharPatch {
|
||||
pub fn parse(p: &Value) -> Result<CharPatch> {
|
||||
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<TextAlign>,
|
||||
pub indent: Option<f32>,
|
||||
pub left_margin: Option<f32>,
|
||||
pub right_margin: Option<f32>,
|
||||
pub line_spacing: Option<f32>,
|
||||
}
|
||||
|
||||
impl ParaPatch {
|
||||
pub fn parse(p: &Value) -> Result<ParaPatch> {
|
||||
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<Option<Vec<TextRun>>> {
|
||||
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<Option<Vec<ParagraphStyle>>> {
|
||||
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::<Result<Vec<_>>>()
|
||||
.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<anicraft_text::Run>, Vec<anicraft_text::ParaStyle>, 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<String>) {
|
||||
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<String>, 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<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
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<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
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<String>)> {
|
||||
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<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
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<String>, 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<f32>) -> Result<(TextBlock, Option<String>, 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<String>, 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<String>, 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<String>, 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
// 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
@@ -479,65 +642,243 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<String>)> {
|
||||
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<Value> {
|
||||
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<ParagraphStyle> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> = 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::<Vec<_>>(),
|
||||
"start": start,
|
||||
"end": end,
|
||||
"selection": summary_json(&rt::summarize(&t.styled_runs(), start, end)),
|
||||
"paragraph": paragraph,
|
||||
}))
|
||||
}
|
||||
|
||||
fn fonts(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
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<Path> = 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<anicraft_doc::Shape> {
|
||||
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 }
|
||||
}
|
||||
@@ -116,6 +116,25 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
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)?;
|
||||
|
||||
@@ -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)) => {
|
||||
|
||||
@@ -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<Rgba>) -> Element {
|
||||
|
||||
@@ -92,9 +92,13 @@ pub fn load(path: &std::path::Path) -> Result<Document, EngineError> {
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Arc<[Recorded]>>,
|
||||
}
|
||||
|
||||
/// 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<Recorded>,
|
||||
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<Arc<[Recorded]>> {
|
||||
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<Recorded> {
|
||||
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<Item = &str> {
|
||||
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<Item = (&str, Option<&[Recorded]>)> {
|
||||
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
|
||||
|
||||
+77
-10
@@ -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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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::collections::HashMap<&'static str, CommandSpec>> = 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<Vec<anicraft_doc::FilterEntry>>,
|
||||
/// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture.
|
||||
pub(crate) envelope: Option<cmds_envelope::Envelope>,
|
||||
/// 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<Vec<Recorded>>,
|
||||
}
|
||||
|
||||
/// 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<Value> {
|
||||
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<Value> {
|
||||
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;
|
||||
|
||||
@@ -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<Value> {
|
||||
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<Vec<Recorded>>)> = 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::<Vec<_>>());
|
||||
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::<Vec<_>>(), ["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<bool> = 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<String> { 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<u8>> = 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");
|
||||
}
|
||||
@@ -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<LayerId> = 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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<TextBlock> {
|
||||
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<_>>(), 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::<usize>(), 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<_>>(), 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<_>>(), 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<_>>(), 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<_>>(), 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<Value> = (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::<u32>(), 12_000);
|
||||
let too_many: Vec<Value> = (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("<a href=\"https://example.org/?a=1&b=2\">"), "the linked word is a link");
|
||||
assert_eq!(svg.matches("</a>").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");
|
||||
}
|
||||
@@ -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::<Vec<_>>(), "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": ""}),
|
||||
|
||||
@@ -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<u64> {
|
||||
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<Writer> {
|
||||
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"));
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
+17
-17
@@ -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<DisplayItem> = (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);
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Value> = 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 } => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<anicraft_doc::TextField>) -> Arc<Element> {
|
||||
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<Vec<f32>> = (!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()
|
||||
});
|
||||
|
||||
+12
-11
@@ -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<DisplayItem>) -> 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:?}");
|
||||
|
||||
+93
-14
@@ -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<Value> = 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<f64> {
|
||||
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<f64> {
|
||||
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<f64> = 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<f64> {
|
||||
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::<Vec<_>>(), expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>());
|
||||
assert_eq!(actual.iter().map(|x| num(*x)).collect::<Vec<_>>(), expected.iter().map(|x| num(*x)).collect::<Vec<_>>());
|
||||
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<Value> =
|
||||
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();
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -79,8 +79,9 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
// Groups that fade as one become `<g opacity>` around their run of items.
|
||||
let chains = crate::group_chains(&dl.groups);
|
||||
let mut open: Vec<u32> = 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, "<a href=\"{}\">", attr_escape(url));
|
||||
}
|
||||
draw(item, &d, &clip, &mut body, &mut defs, &mut grad, &mut images);
|
||||
if link.is_some() {
|
||||
body.push_str("</a>");
|
||||
}
|
||||
}
|
||||
for _ in open {
|
||||
body.push_str("</g>");
|
||||
@@ -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("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"0 0 100 50\">"));
|
||||
assert!(svg.contains("<rect width=\"100\" height=\"50\" fill=\"#ffffff\"/>"), "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("<stop offset=\"1\" stop-color=\"#ffffff\" stop-opacity=\"0.25\"/>"));
|
||||
assert!(svg.contains("<clipPath id=\"c1\" clipPathUnits=\"userSpaceOnUse\" clip-path=\"url(#c0)\">"), "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("<path").count(), 1, "{svg}");
|
||||
assert!(svg.contains("<clipPath id=\"c0\" clipPathUnits=\"userSpaceOnUse\"></clipPath>"), "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("<g opacity=\"0.5\">") && svg.contains("<g opacity=\"0.25\">"), "{svg}");
|
||||
assert_eq!(svg.matches("<g ").count(), svg.matches("</g>").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
|
||||
}
|
||||
@@ -539,6 +539,7 @@ impl<'a> Builder<'a> {
|
||||
box_height: layout.height,
|
||||
field: None,
|
||||
on_path: None,
|
||||
..TextBlock::default()
|
||||
};
|
||||
Ok(Some((block, ascent)))
|
||||
}
|
||||
|
||||
+43
-205
@@ -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<PlacedGlyph>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// 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<Layout, TextError> {
|
||||
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<Layout> {
|
||||
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<u32>>)> = 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<Glyph> = 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<usize> = 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<PlacedGlyph> = 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<Vec<u32>>)], box_width: f32, align: Align) -> Vec<CaretLine> {
|
||||
let mut out: Vec<CaretLine> = 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<PathCmd>,
|
||||
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<PlacedGlyph> {
|
||||
(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);
|
||||
}
|
||||
|
||||
@@ -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<f32>,
|
||||
}
|
||||
|
||||
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<Arc<Path>>,
|
||||
/// 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<Layout, TextError> {
|
||||
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<usize> = Vec::with_capacity(runs.len());
|
||||
let mut families: Vec<String> = 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<char> = text.chars().collect();
|
||||
|
||||
// Paragraphs at line breaks.
|
||||
let mut paras: Vec<Para> = 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<usize> = 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<usize>> = 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<usize>> = 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<Vec<Shaped>> = (0..segs.len()).map(|_| Vec::new()).collect();
|
||||
let mut metrics: Vec<RunMetrics> = 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<Arc<Path>>> = 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<Shaped> = 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<Line> = 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<Shaped> = 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<usize> = 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<usize> = 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<f32> = 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<u32, usize> = HashMap::new();
|
||||
let mut placed: Vec<PlacedGlyph> = 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<u32, usize>| {
|
||||
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<CaretLine> {
|
||||
let mut out: Vec<CaretLine> = 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;
|
||||
@@ -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<f32>) -> 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<_>>(), vec![7, 3], "in the order paints first appear");
|
||||
let joined: Vec<PathCmd> = 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<_>>(), 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::<Vec<_>>(), l.glyphs.iter().map(|g| g.x).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// 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<f32> = 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<Run> = (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));
|
||||
}
|
||||
@@ -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
|
||||
+209
-284
@@ -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 (`<textRuns><DOMTextRun><characters>…</characters><textAttrs>
|
||||
//! <DOMTextAttrs face="Arial-BoldMT" size="24" fillColor="#FF0000" alignment="center"
|
||||
//! letterSpacing="1" lineSpacing="2"/>`). 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<craft_xfl::text::TextStyle<'_, X>>, 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<craft_xfl::text::TextStyle<'_, X>>, 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<f32>, 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<craft_xfl::text::TextStyle<'_, X>>, 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<TextRun>,
|
||||
paragraphs: Vec<ParagraphStyle>,
|
||||
/// Faces asked for that aren't installed (reported once the text is laid out).
|
||||
missing: Vec<String>,
|
||||
}
|
||||
|
||||
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<String, FaceMatch>, report: &mut Report) -> Vec<Placed> {
|
||||
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<RunStyle> = Vec::new();
|
||||
let mut lines: Vec<Line> = 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<String, FaceMatch>, 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<String> = 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<TextRun> = Vec::new();
|
||||
let mut para_of_run: Vec<ParagraphStyle> = 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<String> = 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<String, FaceMatch>, 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<usize> = 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<Placed> = 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<f32>) -> Result<anicraft_text::Layout, TextError> {
|
||||
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<anicraft_text::Run> = 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<anicraft_text::ParaStyle> = 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<String, FaceMatch>, report: &mut Report) -> Vec<Placed> {
|
||||
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<String, FaceMatch>,
|
||||
report: &mut Report,
|
||||
lines: &[Line],
|
||||
styles: &[RunStyle],
|
||||
) -> Option<Placed> {
|
||||
fn text_field(native: craft_xfl::text::TextField<'_, X>, fonts: &Fonts, report: &mut Report, styled: Styled) -> Option<Placed> {
|
||||
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::<String>()).collect::<Vec<_>>().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)) })
|
||||
}
|
||||
@@ -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#"<DOMStaticText autoExpand="true"><matrix><Matrix tx="10" ty="20"/></matrix><textRuns>{runs}</textRuns></DOMStaticText>"#);
|
||||
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<TextAlign> = 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#"<DOMStaticText><textRuns>{}{}</textRuns></DOMStaticText>"#, 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#"<DOMStaticText autoExpand="true"><textRuns>{}{}</textRuns></DOMStaticText>"#, 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::<Vec<_>>(), ["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");
|
||||
|
||||
+3
-37
@@ -96,43 +96,9 @@ fn flv(data: &[u8]) -> Option<Video> {
|
||||
/// then every block bottom row first, left to right, each a 16-bit size and zlib-compressed BGR
|
||||
/// pixels, bottom row first. A key frame has every block.
|
||||
fn screen_video(p: &[u8]) -> Option<Video> {
|
||||
let h0 = u16::from_be_bytes([*p.first()?, *p.get(1)?]);
|
||||
let h1 = u16::from_be_bytes([*p.get(2)?, *p.get(3)?]);
|
||||
let (bw, w) = ((usize::from(h0 >> 12) + 1) * 16, usize::from(h0 & 0x0fff));
|
||||
let (bh, h) = ((usize::from(h1 >> 12) + 1) * 16, usize::from(h1 & 0x0fff));
|
||||
if w == 0 || h == 0 || w > MAX_BITMAP_EDGE as usize || h > MAX_BITMAP_EDGE as usize {
|
||||
return None;
|
||||
}
|
||||
let mut rgba = vec![0u8; w * h * 4];
|
||||
let mut at = 4usize;
|
||||
// Block rows from the bottom of the picture.
|
||||
for by in 0..h.div_ceil(bh) {
|
||||
for bx in 0..w.div_ceil(bw) {
|
||||
let (x0, y0) = (bx * bw, by * bh);
|
||||
let (cw, ch) = (bw.min(w - x0), bh.min(h - y0));
|
||||
let size = usize::from(u16::from_be_bytes([*p.get(at)?, *p.get(at + 1)?]));
|
||||
let packed = p.get(at + 2..at + 2 + size)?;
|
||||
at += 2 + size;
|
||||
if size == 0 {
|
||||
// An unchanged block can't be in a key frame.
|
||||
return None;
|
||||
}
|
||||
let want = cw * ch * 3;
|
||||
let bgr = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(packed, want).ok()?;
|
||||
if bgr.len() != want {
|
||||
return None;
|
||||
}
|
||||
for (row, line) in bgr.chunks_exact(cw * 3).enumerate() {
|
||||
// Rows count up from the bottom; the bitmap's rows count down from the top.
|
||||
let y = h - 1 - (y0 + row);
|
||||
for (col, px) in line.as_chunks::<3>().0.iter().enumerate() {
|
||||
let i = (y * w + x0 + col) * 4;
|
||||
rgba.get_mut(i..i + 4)?.copy_from_slice(&[px[2], px[1], px[0], 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Video::Frame { width: w as u32, height: h as u32, rgba })
|
||||
let max_rgba_bytes = (MAX_BITMAP_EDGE as usize).checked_mul(MAX_BITMAP_EDGE as usize)?.checked_mul(4)?;
|
||||
let frame = craft_video::screen_video::decode_keyframe(p, MAX_BITMAP_EDGE, max_rgba_bytes)?;
|
||||
Some(Video::Frame { width: frame.width, height: frame.height, rgba: frame.rgba })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -444,7 +444,9 @@ fn text_fields_become_blocks_with_this_computers_fonts() {
|
||||
.iter()
|
||||
.filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.name.clone(), t.text.clone(), t.size, t.bold)) } else { None })
|
||||
.collect();
|
||||
let want = [("", "Corpus", 28.0, true), ("", "self-authored, line two", 12.0, false), ("", "A fixed-width field wraps its words onto lines.", 11.0, false), ("score", "Score 0042", 18.0, false), ("answer", "type here", 14.0, false)];
|
||||
// One block per field, its runs kept (ADR 0085): the title's style is the block's first.
|
||||
let want = [("", "Corpus
|
||||
self-authored, line two", 28.0, true), ("", "A fixed-width field wraps its words onto lines.", 11.0, false), ("score", "Score 0042", 18.0, false), ("answer", "type here", 14.0, false)];
|
||||
assert_eq!(blocks.iter().map(|(n, t, s, b)| (n.as_str(), t.as_str(), *s, *b)).collect::<Vec<_>>(), want);
|
||||
assert_eq!(report.runs.get("dynamic text fields"), Some(&1), "fields run in Test Movie (ADR 0066)");
|
||||
assert!(!report.skipped.contains_key("text fields (no fonts on this computer)"));
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# ADR 0085: Per-character and paragraph styles in text
|
||||
|
||||
* Status: accepted (2026-11-16), first slice built
|
||||
* Relates to: ADR 0012 (text), ADR 0014 (text from Animate documents), ADR 0066 (dynamic and
|
||||
input fields), ADR 0070 (text on a path), ADR 0004 (destructive actions), roadmap M5
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0012 gave a text block one style. Animate's static text mixes styles freely: a bold word, a
|
||||
coloured name, a superscript in "mc²", a centred title above left-aligned body text. Animate
|
||||
documents store this as `DOMTextRun`s, each with its own `DOMTextAttrs`, and our XFL import split
|
||||
such a field into one block per style, losing anything mixed within a line. The constraints of
|
||||
ADR 0012 still hold: rendering and every export use only stored outlines (no fonts at render
|
||||
time), `evaluate` stays pure, older files must open and save unchanged.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Runs and paragraphs on the block.** `TextBlock` gains `runs: Vec<TextRun>` (a character
|
||||
count and a `CharStyle`: font, size, bold, italic, colour, letter spacing, baseline shift,
|
||||
underline, link) and `paragraphs: Vec<ParagraphStyle>` (alignment, first-line indent, left
|
||||
and right margins, line spacing), both `#[serde(default, skip_serializing_if = "Vec::is_empty")]`.
|
||||
**Empty means "all in the block's own style"**, so every older file opens unchanged and a
|
||||
block whose characters share one style saves byte for byte as before (a test pins the JSON).
|
||||
When there are runs, the block's own style fields mirror the first run and first paragraph,
|
||||
so code that asks "the block's style" (the player laying out a script's text, Find, exports
|
||||
of fields) keeps working. `TextBlock::set_styles` is the one way to set them: it fits runs to
|
||||
the text, joins neighbours in one style, caps them at 10,000 (`MAX_TEXT_RUNS`; the rest takes
|
||||
the last style), sanitizes values, and drops runs and paragraphs that add nothing.
|
||||
2. **Run edits are pure functions** in `anicraft_doc::rich_text` (`type_into_runs`,
|
||||
`replace_runs`, `restyle_runs`, `slice_runs`, `edit_paragraphs`, `summarize`, `diff_chars`),
|
||||
shared by the engine, the shell and the tests. **Typing continues the style of the character
|
||||
before the caret** (the first character's at the start), as Animate and word processors do. A
|
||||
line break splits a paragraph into two with its style; joining keeps the first's. A change of
|
||||
text given as a whole (`text.edit {text}`, Find and Replace) is taken as one edit: the longest
|
||||
common start and end are kept and the middle replaced.
|
||||
3. **Layout per run** in `anicraft-text` (`Fonts::layout_rich`): each stretch of a paragraph in
|
||||
one run is shaped on its own with `harfrust` in its own face (faces read once per layout,
|
||||
glyph outlines cached per face, glyph and size), lines break greedily at spaces across runs,
|
||||
a line makes room for its tallest run, and paragraphs are aligned, indented and narrowed by
|
||||
their margins. **One run in one paragraph lays out exactly as before**: the old layout's
|
||||
outline, box, lines, carets and glyphs were compared bit for bit on 288 inputs (sizes,
|
||||
spacing, widths, alignments, line breaks, ligatures) before the old code was removed.
|
||||
Kerning across a run boundary is not applied (each run is shaped alone).
|
||||
4. **Superscript and subscript use the font's own OS/2 metrics** (`ySuperscriptYSize`,
|
||||
`ySuperscriptYOffset`, and the subscript pair, per the OpenType specification), falling back
|
||||
to 0.65 em raised 0.35 em (lowered 0.15 em) when a font leaves them out. The glyphs are drawn
|
||||
smaller and shifted; the line keeps the run's full-size height so a superscript doesn't push
|
||||
lines apart. Underlines use the font's `post` underline position and thickness.
|
||||
5. **Colour pieces without duplicating outlines.** The outline is still one path, now laid out
|
||||
as one piece per paint (colour and link) one after another; `fills: Vec<TextFill>` records each
|
||||
piece's colour, link and command count. `evaluate` emits one display item per piece; the
|
||||
pieces are cut from the outline once and cached in memory (never saved, invalidated on copy
|
||||
or when the outline changes), so a frame costs what it did. A single piece in the block's
|
||||
colour keeps no fills (files unchanged). Every renderer and export (CPU oracle, GPU stage,
|
||||
PNG, GIF, video, SVG, Lottie, HTML canvas, sprite sheets) therefore draws each colour with no
|
||||
change. Break Apart gives one shape per colour.
|
||||
6. **Links.** A run's `url` is kept (unsafe schemes — `javascript:`, `vbscript:`, `data:` — are
|
||||
refused by the commands and dropped on import). The display list carries a sparse
|
||||
`links: Vec<(item, url)>`; SVG export wraps those items in `<a href>`. We chose outlines with
|
||||
links over SVG `<text>`/`<tspan>` output: tspans would make the SVG depend on the viewer's
|
||||
fonts and break ADR 0012's "looks the same everywhere"; selectable SVG text, if wanted, will
|
||||
be an export option.
|
||||
7. **Fields and paths keep runs.** A dynamic or input field's authored text is laid out with its
|
||||
runs (ADR 0066 allows authored styles); the HTML page draws its pieces (`pp`). Text a script
|
||||
or viewer sets uses the field's first style; `htmlText` is later. Text on a path keeps its
|
||||
runs' faces, sizes, colours and shifts; underlines aren't drawn on a path yet.
|
||||
8. **Commands.** `text.style {start?, end?, …character keys}`, `text.paragraph {start?, end?,
|
||||
…paragraph keys}` (the paragraphs the range touches), `text.styles {start?, end?}` (runs,
|
||||
paragraphs, and what the range shares, a mixed value as `null`), and `runs`/`paragraphs` on
|
||||
`text.create` and `text.edit` (character keys on `text.edit` restyle every run, keeping the
|
||||
rest). All live in the `text` namespace, which plug-ins may already call. Each change is one
|
||||
undo step; the panic hunt covers hostile runs, ranges, sizes and links.
|
||||
9. **The shell.** While typing on the stage, the editor keeps the runs and paragraphs with the
|
||||
text and shows each run's colour, size (at the zoom), italic, underline and baseline shift in
|
||||
the interface font (egui can't show the document's faces; the stage, updated by each style
|
||||
change in the same frame, shows the real result). Properties gains a section named after the
|
||||
selection ("Text: 6 characters selected") with the character and paragraph rows; values the
|
||||
selection doesn't share show the first one's and say **mixed**; at a caret, a style picked
|
||||
applies to what is typed next. A click in that section keeps the editor open and its
|
||||
selection. Copy and Cut remember the selection's runs; a paste of exactly that text gets
|
||||
them back, anything else pastes plain in the style before it (the system clipboard keeps
|
||||
plain text, so other apps are unaffected).
|
||||
10. **XFL import** reads every `DOMTextRun` into one block per field: face (PostScript name to
|
||||
family, bold and italic), size, colour and alpha, letter spacing, `characterPosition` and
|
||||
`url` per run; `alignment`, `indent`, `leftMargin`, `rightMargin` and `lineSpacing` per
|
||||
paragraph from the run the paragraph starts in. Justified text is still drawn left-aligned
|
||||
and reported. The corpus test now expects one block for the two-style title field.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Text with mixed styles round-trips through `.anicraft`, XFL import and every export, edits
|
||||
stay live and undoable, and documents without mixed styles are unchanged on disk.
|
||||
* A block costs one display item per colour instead of one.
|
||||
* Fields from Animate show their authored styles; scripts still set text in one style.
|
||||
* Not yet: justified alignment, kerning across runs, underlines on a path, `htmlText`, links
|
||||
that click in Test Movie and the HTML page, SVG `<text>` output, the stage editor showing the
|
||||
real faces, bold and paragraph alignment while typing, and tab stops.
|
||||
@@ -0,0 +1,118 @@
|
||||
# ADR 0097: Command macros (saved commands)
|
||||
|
||||
* Status: accepted (2026-11-14)
|
||||
* Relates to: roadmap M6 (command macros), ADR 0001 (undo over persistent snapshots), ADR 0004
|
||||
(destructive actions), ADR 0017 (WebAssembly plug-ins and `plugin_may_call`), ADR 0065
|
||||
(templates: files in the settings folder the shell passes in), ADR 0073 (groups refuse
|
||||
timeline commands), ADR 0016 (auto-keying motion tweens)
|
||||
|
||||
## Context
|
||||
|
||||
Animate users repeat the same few edits all day (rotate, fade, nudge, add a keyframe, set an
|
||||
ease) and expect to keep them: in Animate's History panel they select steps and choose **Save As
|
||||
Command**; the command then appears at the end of the **Commands** menu, can get a keyboard
|
||||
shortcut, and **Manage Saved Commands** renames and deletes them. **Run Command…** runs a
|
||||
command file someone sent. Behaviour was learnt from Adobe's public help pages for the History
|
||||
panel and the Commands menu and by observation; no Adobe code, file format or asset was used
|
||||
(Animate stores JSFL scripts; ours are JSON lists of registry commands).
|
||||
|
||||
Everything in AniCraft is already a registry command, so a macro is naturally "these command ids
|
||||
with these params, in order". The questions were: where the steps come from, what a step that
|
||||
names this document's things (element and layer ids) means elsewhere, what a macro may call,
|
||||
how a run stays one undo step and transactional, where the files live, and how macros get
|
||||
shortcuts from a shortcut map whose actions are all known at build time.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **History records the commands of each step.** `history::Snapshot` gains
|
||||
`commands: Option<Arc<[Recorded]>>`, the `(id, params)` of every top-level mutating command
|
||||
that changed the document since the previous step: one for a plain edit, all of them for a
|
||||
gesture (a drag), the marquee's provisional cut and the edit that used it together. Undo and
|
||||
redo carry them with the label. A live preview's revert drops what it reverted; undo, redo,
|
||||
healing a cut and opening a document drop what wasn't recorded. Consecutive plain
|
||||
`element.translate {dx, dy}` add up into one, so a drag of 600 moves is one step. A step keeps
|
||||
at most 4096 commands and 1 MiB of params (`None` past that: "too many to keep"), and the
|
||||
bytes count against the undo budget. Nested commands (a plug-in's, a macro's) are not
|
||||
recorded on their own: `macro.run` records its steps (`Session::record_as`), so a run can be
|
||||
saved again with other steps; `plugin.run` records itself and therefore can't be kept.
|
||||
|
||||
2. **Steps are rewritten to act on the selection, or refused with the step named.** Save As
|
||||
Command never stores ids of this document's things. For each recorded param in `TARGETS`
|
||||
(`layer(s)`, `element(s)`, `id(s)`, `shape`, `path`, `symbol`): it is dropped when the
|
||||
command's params doc marks it optional (`key?`) and, but for layers, says its default is the
|
||||
selection; the step then acts on the selection or the active layer. Any other target, and any
|
||||
param in `FIXED` (`bitmap`, `sound`, `folder`, `bone`, `parent`, `items`, and a bone's
|
||||
`from`/`to`), refuses the step: "step 4 “Move Points” can't be kept: it works on particular
|
||||
objects of this document". The params docs are the contract the registry already keeps for
|
||||
every command (the guide's command reference is generated from them); a test pins the
|
||||
behaviour on representative commands. Selections and the playhead are not steps (selection
|
||||
commands don't change the document), so a macro runs on whatever is selected, as in Animate.
|
||||
|
||||
3. **A macro may call what a plug-in may, and never `macro.*`.** `macro_may_call` is
|
||||
`plugin_may_call` plus the `macro` namespace refused. So macros never open or write files,
|
||||
use the clipboard, undo, change preferences or run plug-ins or other macros (no recursion),
|
||||
and plug-ins may not call any `macro.*` command (reading files and running macros is outside
|
||||
the sandbox). The rule is checked when a file is read and again before each step runs.
|
||||
|
||||
4. **A run is one undo step and transactional.** `macro.run` is a mutating command whose steps
|
||||
run through `execute_nested` (checked and atomic, no history of their own). At the first
|
||||
failing step it returns "“Turn and Fade” stopped at step 3 of 3 (Taller row): … Nothing was
|
||||
changed." and `Session::execute` puts the document, selection and playhead back. The step is
|
||||
labelled with the macro's name. `execute_nested` now also refuses timeline commands inside an
|
||||
open group (as `execute` does, ADR 0073) and finishes each command's motion-tween auto-key on
|
||||
its own, so a step in a macro keys a tween exactly as the command alone does (plug-in runs
|
||||
benefit too).
|
||||
|
||||
5. **Files: one small JSON file per macro in the settings folder.** `Commands/<name>.json` =
|
||||
`{"format": "anicraft-command", "version": 1, "steps": [{"cmd", "params", "label"}]}`. The
|
||||
file's name is the macro's name (no name inside to go stale when a file is renamed or shared);
|
||||
a bare JSON array of `{cmd, params}` (an `anicraft-cli run` script) reads too, and `command`
|
||||
is accepted for `cmd` (the MCP spelling). Reading is bounded: 1 MiB, 1000 steps, known
|
||||
commands only, object params, labels cut to 200 characters without control characters; a
|
||||
newer version is refused with a clear message. The order of the Commands menu is
|
||||
`Commands/.order.json` (a dot name no macro can have); files not in it follow by name. Names
|
||||
follow the template rules (no path characters, no Windows device names). As with templates
|
||||
(ADR 0065) the shell passes the folder (`platform::commands_dir`, `ANICRAFT_COMMANDS_DIR`
|
||||
for tests); screenshot runs use a temporary folder; the browser build has none yet.
|
||||
|
||||
6. **Commands.** `macro.run {name + folder | path | steps}` (Commands › Run Command…, asks for a
|
||||
file), `macro.list {folder}` (Commands › Manage Saved Commands…), `macro.history` (every
|
||||
history step as Save As Command keeps it: `keep`, `why`, `rewritten`), `macro.save {folder,
|
||||
name, history | steps}`, `macro.rename`, `macro.move`, `macro.delete` and `macro.import`.
|
||||
Replacing a file asks first and deleting always does (ADR 0004: undo can't bring a file back),
|
||||
for every front end. Everything works headless: `anicraft-cli exec doc macro.run '{"path":
|
||||
…}'`, `anicraft-cli run doc macro.json` (it reads either format) and MCP's `anicraft_run`.
|
||||
|
||||
7. **Shortcuts through the existing map.** A macro is an action `macro:<name>` in the "Commands"
|
||||
group of Keyboard Shortcuts, bound, reset and checked for clashes like any other; Manage Saved
|
||||
Commands' **Shortcut…** opens the editor on it, already waiting for the keys. Actions are
|
||||
`&'static str` throughout the map and the editor, so macro names are interned once each
|
||||
(bounded at 4096 distinct names a run) rather than reworking the shortcut system for owned
|
||||
strings. Bindings live in the preferences under the action id and survive a start before the
|
||||
folder is read; a rename moves them, a delete drops them; a chord bound twice by a hand-edited
|
||||
file stays with the action listed first.
|
||||
|
||||
8. **Desktop flow.** In the History panel Ctrl+click picks steps and Shift+click a range (a plain
|
||||
click still travels); a step's context menu picks it or saves it. **Save As Command…** (the
|
||||
panel's footer, or the context menu) shows the picked steps with what was rewritten and why a
|
||||
step can't be kept, and asks for a name; Save is disabled until every step can be kept. Saved
|
||||
macros appear at the end of the Commands menu with their keys. Manage Saved Commands lists
|
||||
them with Run, ↑/↓ (reorder), Shortcut…, Rename…, Delete… and Add from File….
|
||||
|
||||
## Consequences
|
||||
|
||||
* Every undo step costs a few more bytes (its commands' JSON), counted in the undo budget.
|
||||
* A step whose params name document things the command can't do without (moving particular
|
||||
path points, painting bone weights, placing a particular Library item) can't be saved; the
|
||||
message says which step and why. Steps that ran as plug-ins can't be saved either.
|
||||
* The rewrite relies on params docs following the `key?` and "default: the selected …"
|
||||
conventions; a new command that names an element without saying so is refused, never
|
||||
replayed wrongly.
|
||||
* Interning keeps each macro name for the life of the process (bytes per name).
|
||||
|
||||
## Not yet
|
||||
|
||||
Replaying picked steps without saving them (Animate's Replay), a slider for travelling history
|
||||
separately from picking, macros in the browser build (no folder) and the command palette,
|
||||
editing a macro's steps or params in the app, recording selection changes as steps, and
|
||||
macros that ask for a value when they run.
|
||||
@@ -27,7 +27,7 @@ Animator and Designer, plus your own saved workspaces and Reset.
|
||||
| Movie Explorer (**Alt+F3**) | Same key; a tab next to the Library (**Window › Movie Explorer**). |
|
||||
| Output | The Output panel inside Test Movie, and **Window › Output**, which keeps the last run's lines. |
|
||||
| Align | The Align panel on the right, and **Modify › Align**. |
|
||||
| History | The History panel on the right. |
|
||||
| History | The History panel on the right. Ctrl+click steps, then Save As Command… ([saved commands](saved-commands.md)). |
|
||||
| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). |
|
||||
| Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. |
|
||||
| Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. |
|
||||
|
||||
+5
-4
@@ -34,13 +34,14 @@ the panels, tools and shortcuts you know to AniCraft's, and lists what works dif
|
||||
|
||||
13. [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md).
|
||||
14. [Plug-ins](plugins.md): add commands safely.
|
||||
15. [Working headless](working-headless.md): the command line and AI assistants, for pipelines.
|
||||
15. [Saved commands](saved-commands.md): keep steps from the History panel and run them again on any selection.
|
||||
16. [Working headless](working-headless.md): the command line and AI assistants, for pipelines.
|
||||
|
||||
## Help
|
||||
|
||||
16. [Using this guide](using-this-guide.md): searching it, and help for whatever you are working on (**F1**).
|
||||
17. [Troubleshooting and FAQ](troubleshooting-and-faq.md).
|
||||
18. [Coming from Animate](coming-from-animate.md).
|
||||
17. [Using this guide](using-this-guide.md): searching it, and help for whatever you are working on (**F1**).
|
||||
18. [Troubleshooting and FAQ](troubleshooting-and-faq.md).
|
||||
19. [Coming from Animate](coming-from-animate.md).
|
||||
|
||||
## Reference
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Command reference
|
||||
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 352 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 363 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
|
||||
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
|
||||
|
||||
@@ -249,6 +249,10 @@ This page is generated from the command registry, so it always matches the versi
|
||||
Parameters: `{} lists the installed plug-ins (the app shows them in a window)`
|
||||
- **Reload Plug-ins** `plugin.reload`
|
||||
Parameters: `{folder? (makes it the plug-ins folder first)} re-reads every .wasm in the plug-ins folder`
|
||||
- **Run Command…** `macro.run` · changes the document
|
||||
Parameters: `{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.*`
|
||||
- **Manage Saved Commands…** `macro.list`
|
||||
Parameters: `{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)`
|
||||
|
||||
## Control
|
||||
|
||||
@@ -678,9 +682,15 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Export Swatches** `swatch.export`
|
||||
Parameters: `{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}`
|
||||
- **New Text** `text.create` · changes the document
|
||||
Parameters: `{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?}`
|
||||
Parameters: `{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), width?, font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px), 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)`
|
||||
- **Edit Text** `text.edit` · changes the document
|
||||
Parameters: `{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`
|
||||
Parameters: `{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), font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none) (every character), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px) (every paragraph)} on the selected text`
|
||||
- **Text Character Style** `text.style` · changes the document
|
||||
Parameters: `{start?, end? (characters; default: all), font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none)} styles those characters of the selected text, splitting and joining its runs (ADR 0085)`
|
||||
- **Text Paragraph Style** `text.paragraph` · changes the document
|
||||
Parameters: `{start?, end? (characters; default: all), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px)} sets the layout of the paragraphs those characters touch in the selected text (ADR 0085)`
|
||||
- **Text Styles** `text.styles`
|
||||
Parameters: `{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)`
|
||||
- **Fonts** `text.fonts`
|
||||
Parameters: `{}`
|
||||
- **Text on Path** `text.path` · changes the document
|
||||
@@ -733,3 +743,15 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
Parameters: ``{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, the names it takes from other frames of its timeline (`uses`), and what it compiles to (`steps`, `program`); changes nothing``
|
||||
- **Set Script Class** `script.set_class` · changes the document
|
||||
Parameters: `{symbol?: id (default: the document), class: dotted class name ("" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run`
|
||||
- **List History Steps** `macro.history`
|
||||
Parameters: ``{} → {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``
|
||||
- **Save As Command…** `macro.save`
|
||||
Parameters: `{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 <folder>/<name>.json, last in the list`
|
||||
- **Rename Saved Command** `macro.rename`
|
||||
Parameters: `{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays`
|
||||
- **Delete Saved Command** `macro.delete`
|
||||
Parameters: `{folder, name, confirm}: deletes a saved command's file (cannot be undone)`
|
||||
- **Move Saved Command** `macro.move`
|
||||
Parameters: `{folder, name, index (its new place in the list, 0-based)}`
|
||||
- **Add Saved Command from File** `macro.import`
|
||||
Parameters: `{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`
|
||||
@@ -0,0 +1,80 @@
|
||||
# Saved commands
|
||||
|
||||
Do the same few edits over and over? Keep them as a **saved command**: pick the steps in the
|
||||
History panel, save them with a name, and run them again on any selection from the **Commands**
|
||||
menu or with a key of your own. A saved command runs as **one undo step**, so a single Ctrl+Z
|
||||
takes it all back. This works as Save As Command does in Animate.
|
||||
|
||||
## Saving steps as a command
|
||||
|
||||
1. Make the edits once on something selected (say, rotate it, fade it to 40 % and move it).
|
||||
2. In the **History** panel (Window › History), **Ctrl+click** each step you want to keep.
|
||||
**Shift+click** picks every step between the last one you picked and this one. A plain click
|
||||
still goes back to that step, as before. You can also right-click a step and choose
|
||||
**Pick for Save As Command**.
|
||||
3. Click **Save As Command…** at the bottom of the panel (or right-click a step and choose it
|
||||
there).
|
||||
4. Give it a name and click **Save**.
|
||||
|
||||
The dialog lists the picked steps in order. Some steps name a particular layer or object of this
|
||||
document; where the command can work on the selection (or the active layer) instead, that's what
|
||||
the saved command does, and the dialog says so ("acts on the selection"). A step that only makes
|
||||
sense in this document, such as moving particular path points, placing a particular Library
|
||||
item or using the clipboard, can't be kept: the dialog says which step and why, and **Save**
|
||||
stays off until you Ctrl+click that step to take it out of the picks.
|
||||
|
||||
Selecting things and moving the playhead aren't steps, so a saved command always works on what
|
||||
is selected when you run it.
|
||||
|
||||
## Running a saved command
|
||||
|
||||
Your saved commands are at the end of the **Commands** menu, with their keys. Choose one and it
|
||||
runs on the selection. If a step can't run (nothing is selected that it needs, say, or the layer
|
||||
is locked), the command stops there, **nothing is changed**, and the status line names the step
|
||||
that stopped it.
|
||||
|
||||
**Commands › Run Command…** runs a saved command file without adding it to your list, for
|
||||
example one a colleague sent you.
|
||||
|
||||
## Managing saved commands
|
||||
|
||||
**Commands › Manage Saved Commands…** lists your commands in their menu order. For each one:
|
||||
|
||||
* **Run** runs it on the selection.
|
||||
* **↑** and **↓** move it up or down the Commands menu.
|
||||
* **Shortcut…** opens Keyboard Shortcuts on it, waiting for the keys you press. You can also find
|
||||
it there yourself, under Commands. Keys you give a saved command follow it when you rename it.
|
||||
* **Rename…** renames it.
|
||||
* **Delete…** deletes it, after asking (undo can't bring a file back).
|
||||
|
||||
**Add from File…** copies a saved command file into your commands.
|
||||
|
||||
## Sharing saved commands
|
||||
|
||||
Each saved command is a small JSON file in the `Commands` folder of your settings folder
|
||||
(Preferences › About shows where). Send the file to share it; whoever receives it uses
|
||||
**Run Command…** or **Add from File…**. The file's name is the command's name.
|
||||
|
||||
Saved commands can do what [plug-ins](plugins.md) may do: change the document. They can't open
|
||||
or save files, use the clipboard, change your preferences, run plug-ins or run other saved
|
||||
commands, so a file from someone else can't do any of that either. Files that aren't saved
|
||||
commands, or that ask for something they may not do, are refused with the reason.
|
||||
|
||||
## On the command line and for AI assistants
|
||||
|
||||
The same commands work [headless](working-headless.md):
|
||||
|
||||
```sh
|
||||
anicraft-cli run scene.anicraft "Turn and Fade.json" --save out.anicraft
|
||||
anicraft-cli exec scene.anicraft macro.run '{"path": "Turn and Fade.json"}'
|
||||
```
|
||||
|
||||
`anicraft-cli run` takes either a saved command or a plain list of `{cmd, params}`. Assistants
|
||||
using the MCP server call `macro.run` through `anicraft_run`. `macro.history`, `macro.save`,
|
||||
`macro.list`, `macro.rename`, `macro.move`, `macro.delete` and `macro.import` are in the
|
||||
[command reference](reference/commands.md).
|
||||
|
||||
## What isn't there yet
|
||||
|
||||
Replaying picked steps without saving them, editing a saved command's steps in the app, saved
|
||||
commands that ask for a value when they run, and saved commands in the browser version.
|
||||
+38
-8
@@ -31,12 +31,40 @@ Animate.
|
||||
| **Style** | **B** for bold and **I** for italic, then **Left**, **Centre** or **Right** alignment. |
|
||||
| **Spacing** | **Letters** (letter spacing) and **Lines** (line spacing), in pixels. |
|
||||
| **Width** | Turn on **Wrap** to wrap lines at a fixed width, and set the width. With Wrap off, each paragraph stays on one line. |
|
||||
| **Position** | **Normal**, **Superscript** or **Subscript**, then **U** for underline. |
|
||||
| **Link** | A web address the characters link to in SVG exports. |
|
||||
| **Indent** | How far the first line of a paragraph starts in (negative hangs it out). |
|
||||
| **Margins** | Space kept clear at the left and right of each line, in pixels. |
|
||||
|
||||
Bold and italic use the matching face of the font (for example, its Bold or Italic file). If a
|
||||
font has no bold or italic face, AniCraft doesn't fake one.
|
||||
|
||||
A style applies to the whole text block. Different styles for single words in one block aren't
|
||||
there yet; use a separate block for each style.
|
||||
With the text selected (not being typed in), a change applies to the whole block. Where the
|
||||
characters differ, the row shows the first one's value and says **mixed**.
|
||||
|
||||
## Styling words and characters
|
||||
|
||||
One block can mix styles, as in Animate:
|
||||
|
||||
1. Click into the text with the **Text** tool (or double-click it).
|
||||
2. Select the characters: drag across them, or hold **Shift** with the arrow keys.
|
||||
3. Set their style in **Properties**: the section at the top is named after your selection, for
|
||||
example **Text: 6 characters selected**. Font, size, colour, bold, italic, letter spacing,
|
||||
superscript and subscript, underline and link all apply to just those characters, and the
|
||||
stage shows the change at once (each change is one undo step).
|
||||
|
||||
Things to know:
|
||||
|
||||
* **Typing continues the style before the caret.** Type after a red word and the new letters
|
||||
are red. To start a new style, set it in Properties with nothing selected, then type.
|
||||
* **Paragraph settings** (alignment, indent, margins and line spacing) apply to every paragraph
|
||||
your selection touches. Press **Enter** inside a paragraph and both halves keep its settings.
|
||||
* **Copy and paste keeps the styles inside AniCraft.** Text pasted from other apps comes in
|
||||
plain, in the style of the text before it.
|
||||
* While you type, the box over the stage shows the colours, sizes, italics, underlines and
|
||||
superscripts in AniCraft's interface font; the stage shows the real fonts and alignment.
|
||||
* **Superscript and subscript** use the size and offset the font itself suggests.
|
||||
* Text set by a script in a dynamic or input field uses the field's first style.
|
||||
|
||||
## Fonts on your computer
|
||||
|
||||
@@ -131,14 +159,15 @@ outlines like all text, so it looks the same on every computer.
|
||||
|
||||
To reshape the letters themselves, select the text and choose **Modify › Break Apart**
|
||||
(**Ctrl+B**). The text becomes an ordinary shape that you can edit with the Subselection tool,
|
||||
recolour and morph. It is no longer editable as text, so keep a copy if you might want to change
|
||||
the words.
|
||||
recolour and morph. Text in several colours becomes one shape per colour. It is no longer
|
||||
editable as text, so keep a copy if you might want to change the words.
|
||||
|
||||
## Text in exports
|
||||
|
||||
Because the letter shapes are saved with the document, text comes out exactly as you see it on
|
||||
the stage in every picture export: PNG, PNG sequences, GIF, animated PNG and WebP, video, sprite
|
||||
sheets, SVG and Lottie. Fields show their authored text, box and border there.
|
||||
sheets, SVG and Lottie. Fields show their authored text, box and border there. Each colour in a
|
||||
block is drawn in its colour, and in SVG, characters with a link are a link.
|
||||
|
||||
In the **HTML canvas** export, the movie plays in a web browser:
|
||||
|
||||
@@ -158,9 +187,10 @@ See [Exporting and Publish](exporting-and-publish.md) for every format.
|
||||
## Text in Animate files
|
||||
|
||||
When you open an Animate document, its text comes across as text you can edit, with its font,
|
||||
size, colour, bold and italic, alignment, spacing, position and wrapping. Dynamic and input
|
||||
fields come across as fields, with their names, boxes, borders and line types. A block whose
|
||||
lines use different styles becomes one block per style, stacked as before. Fonts that aren't on
|
||||
size, colour, bold and italic, superscript and subscript, links, alignment, indents, margins,
|
||||
spacing, position and wrapping. Each Animate text block stays one block, with every run's style
|
||||
kept. Dynamic and input fields come across as fields, with their names, boxes, borders and line
|
||||
types. Fonts that aren't on
|
||||
your computer use the default font, and the status bar names them. See
|
||||
[Opening Animate files](opening-animate-files.md).
|
||||
|
||||
|
||||
@@ -301,6 +301,10 @@ drag is always a single step. The **History** panel at the bottom of the dock li
|
||||
by name. Click any step to jump back to it, and click a later (dimmed) one to go forward
|
||||
again.
|
||||
|
||||
To keep steps you repeat, **Ctrl+click** them in the History panel and choose **Save As
|
||||
Command…**: they come back at the end of the Commands menu, to run on any selection as one step.
|
||||
See [Saved commands](saved-commands.md).
|
||||
|
||||
Undo history is kept in memory while the document is open. It isn't saved with the file.
|
||||
|
||||
## Right-click menus
|
||||
|
||||
@@ -43,6 +43,11 @@ with every release, and `anicraft_commands` lets it find what it needs. Frames i
|
||||
0-based, as everywhere in the engine (the CLI's own `--frame` flags are 1-based, as in the
|
||||
timeline).
|
||||
|
||||
Saved commands (ADR 0097) run through `anicraft_run` too: `macro.run` with `{"path": …}` (a
|
||||
saved command's file) or `{"steps": [{"cmd", "params"}]}` runs the steps as one undo step, and
|
||||
unlike `anicraft_run_script` a failing step leaves the document as it was. `macro.history` and
|
||||
`macro.save` turn the session's undo steps into a saved command.
|
||||
|
||||
## Safety
|
||||
|
||||
* Everything runs through the engine's commands, so params are checked and every edit can be
|
||||
|
||||
@@ -44,6 +44,12 @@ anicraft-cli exec --sample plugin.run '{"id":"org.anicraft.star-field","params":
|
||||
--plugins examples/plugins/dist --save stars.anicraft
|
||||
```
|
||||
|
||||
## Saved commands share the rule
|
||||
|
||||
A saved command (ADR 0097, History › Save As Command) may call exactly the commands a plug-in
|
||||
may (`plugin_may_call`), and no `macro.*` command. Plug-ins may not call any `macro.*` command
|
||||
either, so the two can never call each other.
|
||||
|
||||
## The sandbox
|
||||
|
||||
The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssembly interpreter
|
||||
|
||||
+7
-3
@@ -6,6 +6,10 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
|
||||
## Honest status (2026-11-09, v0.1.0 early alpha)
|
||||
|
||||
Streaming WAV headers and PCM sample blocks now delegate to `craft_audio::wav_stream`;
|
||||
AniCraft retains mixing, frame-range limits, temporary-file cleanup and VFS writes.
|
||||
This integration depends on craft-libs #1962 and still requires hosted parity validation.
|
||||
|
||||
| Dimension | Status |
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
@@ -38,8 +42,8 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text); ~~per-character and paragraph styles~~ ✅ first slice (ADR 0085: styled runs (font, size, bold, italic, colour, letter spacing, superscript/subscript by the font's OS/2 metrics, underline, link) set on the selected characters while typing, mixed values in Properties, paragraph alignment, indent, margins and line spacing, runs shaped one by one and wrapped across, one fill per colour in every export, SVG links, XFL `DOMTextRun`s kept in one block, `text.style`/`text.paragraph`/`text.styles`; not yet: justified text, runs on a path's underlines, `htmlText` in fields, links that click in Test Movie and the HTML page, SVG `<text>`/`<tspan>` output, the editor showing the real faces and alignment); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); ~~command macros~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette). **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: reshaping at a posed frame); ~~mixed armatures: symbol instances and shapes in one armature~~ ✅ (ADR 0098: bones inside a shape and bones that move instances or whole shapes in one armature, several skinned shapes, chains across the kinds with the Bone tool, one pose for IK, tweens, springs and translation, file format version 4 only for documents that use it; not yet: joining two armatures, joining a whole shape from a shape's bone by dragging, XFL import of armatures); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); ~~AppImage desktop integration, portable mode, store readiness checks~~ ✅ (ADR 0094); next: store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline), ~~search and context help~~ ✅ (ADR 0096: a prebuilt index and an offline search page with the same ranking as `anicraft-cli guide search`; F1, Help › Help for This and each panel menu open the guide at the section for the dialog, panel or tool, through a map checked against the guide's headings; F1 moves from the shortcut editor, which keeps Ctrl+Alt+Shift+K); next: translated guides, a print edition (PDF through the browser; a native PDF proposed in ADR 0096), help for single fields; ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groLine truncated
|
||||
|
||||
@@ -60,7 +64,7 @@ titled with its milestone.
|
||||
| M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 |
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~command macros~~ ✅ first slice (ADR 0097); next: growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~mixed armatures (instances and shapes together)~~ ✅ (ADR 0098), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~portable mode and AppImage desktop integration~~ ✅ (ADR 0094), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~guide search and context help~~ ✅ (ADR 0096); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
|
||||
+1
-1
@@ -443,7 +443,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// Every panel in front where it docks, and floating (ADR 0075); the other workspaces.
|
||||
|
||||
+2
-2
@@ -137,7 +137,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
fn grid_window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.aids_dialogs.grid else { return };
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Edit Grid")).id(egui::Id::new("edit_grid")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Edit Grid")).id(egui::Id::new("edit_grid")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Colour"), |ui| {
|
||||
crate::colour::button_alpha(ui, &mut d.color).named(tr!("Grid colour"));
|
||||
@@ -171,7 +171,7 @@ pub fn accept_grid(app: &mut App) {
|
||||
fn guides_window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.aids_dialogs.guides else { return };
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Edit Guides")).id(egui::Id::new("edit_guides")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Edit Guides")).id(egui::Id::new("edit_guides")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(420.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Colour"), |ui| {
|
||||
crate::colour::button_alpha(ui, &mut d.color).named(tr!("Guide colour"));
|
||||
|
||||
+122
-10
@@ -168,9 +168,21 @@ pub struct TextEditing {
|
||||
/// The text element being edited, or `None` for new text.
|
||||
pub element: Option<anicraft_engine::doc::ElementId>,
|
||||
pub text: String,
|
||||
/// The text when editing started (unchanged text commits nothing).
|
||||
/// The text when editing started, or when its styles were last applied (unchanged text
|
||||
/// commits nothing).
|
||||
pub original: String,
|
||||
/// Focus the field on its first frame.
|
||||
/// The text as the runs last saw it (a change since is followed by [`TextEditing::sync`]).
|
||||
pub last: String,
|
||||
/// Its styled runs and one style per paragraph (ADR 0085).
|
||||
pub runs: Vec<anicraft_engine::doc::TextRun>,
|
||||
pub paras: Vec<anicraft_engine::doc::ParagraphStyle>,
|
||||
/// The selected characters (anchor, caret), as the editor last reported them.
|
||||
pub sel: (u32, u32),
|
||||
/// A style picked at a caret, for what is typed there next.
|
||||
pub pending: Option<anicraft_engine::doc::CharStyle>,
|
||||
/// Styled text being pasted this frame (copied from this editor).
|
||||
pub paste: Option<crate::rich_edit::StyledClip>,
|
||||
/// Focus the field on its next frame.
|
||||
pub focus: bool,
|
||||
}
|
||||
|
||||
@@ -390,6 +402,11 @@ pub struct App {
|
||||
pub library: crate::library::LibraryView,
|
||||
/// Text being typed on the stage.
|
||||
pub text_edit: Option<TextEditing>,
|
||||
/// Styled text last copied from the stage editor (ADR 0085).
|
||||
pub text_clip: Option<crate::rich_edit::StyledClip>,
|
||||
/// Where Properties showed the styles of the text being typed (last frame): a click there
|
||||
/// keeps the editor open.
|
||||
pub text_props_rect: Option<egui::Rect>,
|
||||
/// Attach to Path is waiting for a click on a shape (ADR 0070): the text to set along it.
|
||||
pub path_pick: Option<anicraft_engine::doc::ElementId>,
|
||||
/// Font families on this computer, listed once on first need.
|
||||
@@ -584,6 +601,8 @@ pub struct App {
|
||||
pub thumbs: crate::recent::Thumbs,
|
||||
/// Templates: their pictures, the user's list and the Save as Template dialog (ADR 0065).
|
||||
pub templates: crate::templates::Templates,
|
||||
/// Saved commands (ADR 0097): the folder's list, the History panel's picks, their windows.
|
||||
pub macros: crate::macros_ui::Macros,
|
||||
}
|
||||
|
||||
/// How often (seconds) the system's contrast and light or dark setting are asked again (ADR 0064).
|
||||
@@ -700,6 +719,8 @@ impl App {
|
||||
library_sel,
|
||||
library: Default::default(),
|
||||
text_edit: None,
|
||||
text_clip: None,
|
||||
text_props_rect: None,
|
||||
path_pick: None,
|
||||
font_families: None,
|
||||
polystar: PolyStarOptions::default(),
|
||||
@@ -804,6 +825,7 @@ impl App {
|
||||
drop: Default::default(),
|
||||
thumbs: Default::default(),
|
||||
templates: Default::default(),
|
||||
macros: Default::default(),
|
||||
};
|
||||
app.apply_prefs(ctx);
|
||||
app.decode_sounds();
|
||||
@@ -812,6 +834,7 @@ impl App {
|
||||
app.status_err(e);
|
||||
}
|
||||
crate::plugins_ui::load_at_start(&mut app);
|
||||
crate::macros_ui::rescan(&mut app);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::desktop_ui::at_start(&mut app);
|
||||
app
|
||||
@@ -908,8 +931,7 @@ impl App {
|
||||
ctx.set_zoom_factor(self.prefs.ui_scale);
|
||||
theme::apply_palette(ctx, self.prefs.palette(self.system_look));
|
||||
crate::onion::refresh_colors(self);
|
||||
self.keymap = keymap::Keymap::new(&self.prefs.shortcuts);
|
||||
self.shortcuts = self.keymap.table();
|
||||
self.refresh_keymap();
|
||||
let wants_system = [&self.prefs.ui_font, &self.prefs.data_font].iter().any(|f| matches!(f, prefs::FontChoice::System(_)));
|
||||
if wants_system && self.system_fonts.is_none() {
|
||||
self.scan_system_fonts();
|
||||
@@ -992,6 +1014,12 @@ impl App {
|
||||
|
||||
/// Changes preferences: applies them live and saves them.
|
||||
/// Writes the preferences as they are (a setting changed in place, such as the volume).
|
||||
/// The shortcut map again, from the preferences and the saved commands listed (ADR 0097).
|
||||
pub fn refresh_keymap(&mut self) {
|
||||
self.keymap = keymap::Keymap::new(&self.prefs.shortcuts);
|
||||
self.shortcuts = self.keymap.table();
|
||||
}
|
||||
|
||||
pub fn save_prefs(&mut self) {
|
||||
if self.shot.is_none()
|
||||
&& let Err(e) = self.prefs.save()
|
||||
@@ -1173,6 +1201,39 @@ impl App {
|
||||
}
|
||||
Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), ..Default::default() }),
|
||||
Some("shortcuts") => self.show_shortcuts = true,
|
||||
Some("savecommand") | Some("managecommands") => {
|
||||
// Saved commands (ADR 0097): three edits on the sample's selection, picked in the
|
||||
// History panel with Save As Command open; or a few saved commands, managed.
|
||||
self.tool = Tool::Select;
|
||||
self.run("edit.select_all", json!({}));
|
||||
self.run("modify.rotate_cw", json!({}));
|
||||
self.run("element.set_color_effect", json!({"style": "alpha", "alpha": 60}));
|
||||
self.run("element.translate", json!({"dx": 24, "dy": -12}));
|
||||
if !self.panel_visible(crate::dock::Panel::History) {
|
||||
self.toggle_panel(crate::dock::Panel::History);
|
||||
}
|
||||
let n = self.s.history_len();
|
||||
for i in n.saturating_sub(3)..n {
|
||||
crate::macros_ui::pick(self, i, true, false);
|
||||
}
|
||||
if which == Some("savecommand") {
|
||||
crate::macros_ui::open_save(self);
|
||||
if let Some(d) = self.macros.save.as_mut() {
|
||||
d.name = "Turn, Fade and Nudge".into(); // i18n-exempt: a sample name a user would type
|
||||
}
|
||||
} else if let Some(folder) = crate::macros_ui::folder(self) {
|
||||
let f = folder.display().to_string();
|
||||
// i18n-exempt: sample names a user would type
|
||||
for (name, steps) in [("Turn, Fade and Nudge", json!([n.saturating_sub(3), n.saturating_sub(2), n.saturating_sub(1)])), ("Quarter Turn", json!([n.saturating_sub(3)])), ("Fade to 60 %", json!([n.saturating_sub(2)]))] {
|
||||
let _ = self.s.execute("macro.save", &json!({"folder": f, "name": name, "history": steps, "confirm": true}));
|
||||
}
|
||||
crate::macros_ui::clear_picks(self);
|
||||
// i18n-exempt: a sample name
|
||||
let id = crate::keymap::macro_id("Quarter Turn");
|
||||
self.prefs.shortcuts.insert(id, vec!["Ctrl+Alt+R".into()]);
|
||||
crate::macros_ui::open_manage(self);
|
||||
}
|
||||
}
|
||||
Some("lastscene") => {
|
||||
let last = self.s.doc.scenes.len().saturating_sub(1);
|
||||
self.run("scene.select", json!({"scene": last}));
|
||||
@@ -1682,6 +1743,31 @@ impl App {
|
||||
crate::layer_props::open(self, Some(anicraft_engine::doc::LayerId(m)));
|
||||
}
|
||||
}
|
||||
Some("richtext") => {
|
||||
// Styled text (ADR 0085): a title with bold, coloured and superscript runs and a
|
||||
// centred paragraph, open for typing with a word selected, its style in
|
||||
// Properties.
|
||||
self.perform("file.new", json!({"width": 640, "height": 400}));
|
||||
// i18n-exempt: document content
|
||||
let made = self.run("text.create", json!({"text": "Energy E = mc2\nStyled runs in one block", "x": 60, "y": 90, "size": 44, "color": "#264653", "width": 520}));
|
||||
if let Some(id) = made.and_then(|v| v["element"].as_u64()) {
|
||||
self.run("text.style", json!({"start": 0, "end": 6, "bold": true, "color": "#e76f51"}));
|
||||
self.run("text.style", json!({"start": 13, "end": 14, "shift": "superscript"}));
|
||||
self.run("text.style", json!({"start": 15, "end": 39, "size": 26, "italic": true, "color": "#2a9d8f"}));
|
||||
self.run("text.style", json!({"start": 22, "end": 26, "underline": true, "url": "https://example.org"}));
|
||||
self.run("text.paragraph", json!({"start": 15, "end": 39, "align": "center"}));
|
||||
let block = self.s.visible_elements().into_iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind {
|
||||
anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(anicraft_engine::geom::Vec2::ZERO), t.clone())),
|
||||
_ => None,
|
||||
});
|
||||
if let Some((at, t)) = block {
|
||||
self.tool = Tool::Text;
|
||||
let mut te = TextEditing::new(egui::pos2(at.x, at.y), Some(anicraft_engine::doc::ElementId(id)), Some(&t), &self.s.text_style);
|
||||
te.sel = (0, 6);
|
||||
self.text_edit = Some(te);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(which @ ("textfields" | "testtext")) => {
|
||||
// Dynamic and input text fields (ADR 0066): a score a script sets, a name field
|
||||
// and a multiline notes field. `textfields` selects the name field for its
|
||||
@@ -2728,7 +2814,14 @@ impl App {
|
||||
|
||||
/// The single entry point for user-initiated commands: asks first when the engine says the
|
||||
/// command needs confirmation (ADR 0004), otherwise runs it.
|
||||
pub fn request(&mut self, id: &str, params: Value) {
|
||||
pub fn request(&mut self, id: &str, mut params: Value) {
|
||||
// A saved command from a file goes into the user's commands folder (ADR 0097).
|
||||
if id == "macro.import"
|
||||
&& params.get("folder").is_none()
|
||||
&& let (Some(o), Some(f)) = (params.as_object_mut(), crate::macros_ui::folder(self))
|
||||
{
|
||||
o.insert("folder".into(), json!(f.display().to_string()));
|
||||
}
|
||||
if let Some(c) = self.s.confirmation(id, ¶ms)
|
||||
&& (c.irreversible || !self.skip_confirm.contains(id))
|
||||
{
|
||||
@@ -2933,6 +3026,7 @@ impl App {
|
||||
});
|
||||
}
|
||||
"plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, v),
|
||||
id if id.starts_with("macro.") => crate::macros_ui::done(self, id, v),
|
||||
"timeline.remove_frame" => {
|
||||
let n = v["removed"].as_u64().unwrap_or(1);
|
||||
self.status_ok(if n == 1 { tr!("Removed frame — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Removed {n} frame — {undo} to undo", "Removed {n} frames — {undo} to undo", n, undo = self.undo_key()) });
|
||||
@@ -3021,6 +3115,16 @@ impl App {
|
||||
self.show_plugins = true;
|
||||
return;
|
||||
}
|
||||
if id == "macro.list" {
|
||||
// Commands › Manage Saved Commands (ADR 0097; headless, the command lists them).
|
||||
crate::macros_ui::open_manage(self);
|
||||
return;
|
||||
}
|
||||
if id == "macro.save" {
|
||||
// Save As Command, for the steps picked in the History panel.
|
||||
crate::macros_ui::open_save(self);
|
||||
return;
|
||||
}
|
||||
if id == "layer.set_properties" {
|
||||
// Modify › Timeline › Layer Properties: the dialog for the active layer.
|
||||
crate::layer_props::open(self, None);
|
||||
@@ -3079,6 +3183,9 @@ impl App {
|
||||
"file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())),
|
||||
"file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())),
|
||||
"plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())),
|
||||
// Saved commands (ADR 0097): run a file, or copy one into your commands.
|
||||
"macro.run" => Some((tr_noop!("Run a saved command (a .json file)"), "path", "command.json".to_string())),
|
||||
"macro.import" => Some((tr_noop!("Add a saved command (a .json file)"), "path", "command.json".to_string())),
|
||||
// A brush set (ADR 0068): your brushes as a small JSON file.
|
||||
"brush.preset_export" => Some((tr_noop!("Export your brushes (a brush set file)"), "path", "brushes.json".to_string())),
|
||||
"brush.preset_import" => Some((tr_noop!("Import brushes (a brush set file)"), "path", "brushes.json".to_string())),
|
||||
@@ -3091,7 +3198,7 @@ impl App {
|
||||
_ => None,
|
||||
};
|
||||
if let Some((title, key, text)) = prompt {
|
||||
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import"));
|
||||
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import"));
|
||||
if is_file && platform::WEB && platform::reads_file(id) {
|
||||
// The browser's file picker (ADR 0036). The file arrives on a later frame
|
||||
// (`open_picked`); a save or export asks for the download's name below.
|
||||
@@ -3426,6 +3533,8 @@ impl App {
|
||||
"view.brush_smaller" => crate::brushtool::resize(self, false),
|
||||
"view.brush_larger" => crate::brushtool::resize(self, true),
|
||||
id if id.starts_with("tool.") => tool = keymap::tool_for(id).or(tool),
|
||||
// A saved command's own key (ADR 0097).
|
||||
id if keymap::macro_name(id).is_some() => crate::macros_ui::run_saved(self, keymap::macro_name(id).unwrap_or("")),
|
||||
_ => self.invoke(id),
|
||||
}
|
||||
}
|
||||
@@ -3513,7 +3622,7 @@ impl App {
|
||||
let mut submit = false;
|
||||
let mut cancel = false;
|
||||
let title = crate::i18n::t(p.title);
|
||||
egui::Window::new(title).id(egui::Id::new(("prompt", p.title))).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, title).id(egui::Id::new(("prompt", p.title))).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(360.0);
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut p.text).desired_width(f32::INFINITY)).named(title);
|
||||
if p.focus {
|
||||
@@ -3550,7 +3659,7 @@ impl App {
|
||||
|
||||
fn about_window(&mut self, ctx: &egui::Context) {
|
||||
let mut open = self.show_about;
|
||||
let shown = egui::Window::new(tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
ui.add(egui::Image::new((app_mark(ctx).id(), egui::vec2(64.0, 64.0))));
|
||||
ui.heading("AniCraft");
|
||||
ui.label(tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(RELEASE_STAGE)));
|
||||
@@ -3582,7 +3691,7 @@ impl App {
|
||||
(tr!("Screenshots"), root.join("shots")),
|
||||
];
|
||||
let mut opened: Option<Result<(), String>> = None;
|
||||
let shown = egui::Window::new(tr!("Project Files")).id(egui::Id::new("files_window")).open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, tr!("Project Files")).id(egui::Id::new("files_window")).open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| {
|
||||
ui.label(theme::text(theme::Type::Label, tr!("Where AniCraft's documents and files are on this computer")));
|
||||
ui.add_space(4.0);
|
||||
egui::Grid::new("files").num_columns(3).spacing([10.0, 6.0]).striped(true).show(ui, |ui| {
|
||||
@@ -3827,7 +3936,9 @@ impl App {
|
||||
|
||||
let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2));
|
||||
crate::drop::begin_frame(self);
|
||||
egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui));
|
||||
let menu = egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui));
|
||||
// Floating windows stay below the menu bar (crate::windows).
|
||||
crate::windows::set_work_area(&ctx, menu.response.rect.max.y);
|
||||
if self.start.is_some() {
|
||||
// The start screen takes the workspace's place (ADR 0059); the menus stay.
|
||||
egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui));
|
||||
@@ -3864,6 +3975,7 @@ impl App {
|
||||
crate::plugin_export_ui::show(self, &ctx);
|
||||
crate::dock_float::floating(self, &ctx);
|
||||
crate::workspaces_window::show(self, &ctx);
|
||||
crate::macros_ui::show(self, &ctx);
|
||||
crate::find_panel::show(self, &ctx);
|
||||
crate::brush_panel::show(self, &ctx);
|
||||
crate::publish_panel::show(self, &ctx);
|
||||
|
||||
+1
-1
@@ -360,7 +360,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
let confirm = app.recovery.confirm_discard.clone();
|
||||
let btn = egui::vec2(96.0, crate::theme::TARGET + 4.0);
|
||||
let title = tr!("Recover unsaved work");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("recover_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -127,7 +127,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let at = ctx.content_rect().right_top() + vec2(-620.0, 90.0);
|
||||
let shown = egui::Window::new(tr!("Brush Library")).id(egui::Id::new("brush_library")).open(&mut open).default_pos(at).default_width(300.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
let shown = crate::windows::new(ctx, tr!("Brush Library")).id(egui::Id::new("brush_library")).open(&mut open).default_pos(at).default_width(300.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
a11y::name_title_bar(&shown, tr!("Brush Library"));
|
||||
app.brush_lib.open &= open;
|
||||
}
|
||||
|
||||
+10
-1
@@ -79,12 +79,14 @@ pub enum Dialog {
|
||||
Recover,
|
||||
Updates,
|
||||
ManageWorkspaces,
|
||||
SaveAsCommand,
|
||||
ManageSavedCommands,
|
||||
Palette,
|
||||
CloseUnsaved,
|
||||
}
|
||||
|
||||
impl Dialog {
|
||||
pub const ALL: [Dialog; 25] = [
|
||||
pub const ALL: [Dialog; 27] = [
|
||||
Dialog::Preferences,
|
||||
Dialog::Shortcuts,
|
||||
Dialog::Licenses,
|
||||
@@ -108,6 +110,8 @@ impl Dialog {
|
||||
Dialog::Recover,
|
||||
Dialog::Updates,
|
||||
Dialog::ManageWorkspaces,
|
||||
Dialog::SaveAsCommand,
|
||||
Dialog::ManageSavedCommands,
|
||||
Dialog::Palette,
|
||||
Dialog::CloseUnsaved,
|
||||
];
|
||||
@@ -136,6 +140,8 @@ impl Dialog {
|
||||
Dialog::SoundEnvelope => "envelope_editor",
|
||||
Dialog::Recover => "recover_window",
|
||||
Dialog::ManageWorkspaces => "manage_workspaces",
|
||||
Dialog::SaveAsCommand => "save_as_command",
|
||||
Dialog::ManageSavedCommands => "manage_saved_commands",
|
||||
Dialog::Updates | Dialog::PluginSettings | Dialog::Palette | Dialog::CloseUnsaved => return None,
|
||||
})
|
||||
}
|
||||
@@ -165,6 +171,8 @@ impl Dialog {
|
||||
Dialog::Recover => "getting-started.md#autosave-and-crash-recovery",
|
||||
Dialog::Updates => "getting-started.md#install-anicraft",
|
||||
Dialog::ManageWorkspaces => "workspace.md#workspaces",
|
||||
Dialog::SaveAsCommand => "saved-commands.md#saving-steps-as-a-command",
|
||||
Dialog::ManageSavedCommands => "saved-commands.md#managing-saved-commands",
|
||||
Dialog::Palette => "workspace.md#the-command-palette",
|
||||
Dialog::CloseUnsaved => "getting-started.md#save-your-work",
|
||||
}
|
||||
@@ -202,6 +210,7 @@ pub const COMMAND_TOPICS: &[(&str, &str)] = &[
|
||||
("instance.", "symbols-and-library.md#instance-properties"),
|
||||
("layer.", "timeline.md#layers"),
|
||||
("library.", "symbols-and-library.md#the-library-panel"),
|
||||
("macro.", "saved-commands.md#saving-steps-as-a-command"),
|
||||
("modify.", "drawing.md#transforming-artwork"),
|
||||
("modify.convert_to_symbol", "symbols-and-library.md#making-a-symbol"),
|
||||
("motion.", "tweens.md#motion-tweens"),
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
folders.sort_by_key(|(_, p)| p.to_lowercase());
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
let title = tr!("Convert to Symbol");
|
||||
egui::Window::new(title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Symbol name"));
|
||||
|
||||
+17
-3
@@ -390,7 +390,7 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
|
||||
let mut about_act: Option<crate::desktop_ui::Act> = None;
|
||||
let to_about = std::mem::take(&mut app.prefs_to_about);
|
||||
let title = if crate::platform::OS == crate::platform::Os::Mac { tr!("Settings") } else { tr!("Preferences") };
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
// An id of its own: the window keeps its place when the language changes.
|
||||
.id(egui::Id::new("prefs_window"))
|
||||
.open(&mut open)
|
||||
@@ -697,7 +697,7 @@ fn licenses(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let title = tr!("Licenses & Notices");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("licenses_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
@@ -850,6 +850,20 @@ fn take_key_press(ctx: &egui::Context) -> Option<(egui::Modifiers, Key)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the shortcut editor filtered to `filter` and waiting for a new key for `id` (Manage
|
||||
/// Saved Commands' Shortcut…, ADR 0097).
|
||||
pub(crate) fn shortcuts_for(app: &mut App, ctx: &egui::Context, filter: &str, id: &'static str) {
|
||||
let state_id = egui::Id::new("shortcut_editor");
|
||||
let mut st: SheetState = ctx.data_mut(|d| d.get_temp(state_id).unwrap_or_default());
|
||||
st.filter = filter.to_string();
|
||||
st.notice = None;
|
||||
st.steal = None;
|
||||
ctx.data_mut(|d| d.insert_temp(state_id, st));
|
||||
app.show_shortcuts = true;
|
||||
let replace = (!app.keymap.keys(id).is_empty()).then_some(0);
|
||||
app.key_capture = Some(KeyCapture { id, replace });
|
||||
}
|
||||
|
||||
fn shortcut_sheet(app: &mut App, ctx: &egui::Context) {
|
||||
if !app.show_shortcuts {
|
||||
app.key_capture = None;
|
||||
@@ -890,7 +904,7 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) {
|
||||
let capture = app.key_capture;
|
||||
let changed = app.prefs.shortcuts.len();
|
||||
let title = tr!("Keyboard Shortcuts");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("shortcuts_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ fn inside(app: &mut App, ctx: &egui::Context, f: &Float, layout: &Layout, acts:
|
||||
let title = crate::i18n::t(p.label());
|
||||
let mut open = true;
|
||||
let size = vec2(f.size[0], f.size[1]);
|
||||
let mut w = egui::Window::new(title).id(id).open(&mut open).collapsible(false).resizable(true).default_size(size).min_size([crate::dock::MIN_FLOAT, 120.0]);
|
||||
let mut w = crate::windows::new(ctx, title).id(id).open(&mut open).collapsible(false).resizable(true).default_size(size).min_size([crate::dock::MIN_FLOAT, 120.0]);
|
||||
let at = f.at.map_or_else(|| ctx.content_rect().center() - size * 0.5, |a| pos2(a[0], a[1]));
|
||||
w = if app.dock_view.placed.insert(f.id) { w.current_pos(at) } else { w.default_pos(at) };
|
||||
let shown = w.show(ctx, |ui| {
|
||||
|
||||
+1
-1
@@ -304,7 +304,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(ease) = ease_now(app, &ed) else { return };
|
||||
let mut open = true;
|
||||
let title = tr!("Custom Ease");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("ease_editor"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(t) = target(app, &ed) else { return };
|
||||
let mut open = true;
|
||||
let title = tr!("Edit Envelope — {name}", name = t.sound.name);
|
||||
let shown = egui::Window::new(title.clone())
|
||||
let shown = crate::windows::new(ctx, title.clone())
|
||||
.id(egui::Id::new("envelope_editor"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -243,7 +243,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = app.find.open;
|
||||
let at = ctx.content_rect().right_top() + vec2(-720.0, 110.0);
|
||||
let shown = egui::Window::new(tr!("Find and Replace")).id(egui::Id::new("find_replace")).open(&mut open).default_pos(at).default_width(400.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
let shown = crate::windows::new(ctx, tr!("Find and Replace")).id(egui::Id::new("find_replace")).open(&mut open).default_pos(at).default_width(400.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
a11y::name_title_bar(&shown, tr!("Find and Replace"));
|
||||
app.find.open = open;
|
||||
}
|
||||
|
||||
+33
-1
@@ -1,6 +1,8 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 31] = [
|
||||
const SOURCES: [(&str, &str); 33] = [
|
||||
("rich_edit.rs", include_str!("rich_edit.rs")),
|
||||
("windows.rs", include_str!("windows.rs")),
|
||||
("ease_editor.rs", include_str!("ease_editor.rs")),
|
||||
("colour.rs", include_str!("colour.rs")),
|
||||
("drop.rs", include_str!("drop.rs")),
|
||||
@@ -196,3 +198,33 @@ fn data_roles_are_monospace_and_prose_roles_are_not() {
|
||||
assert_eq!(font(t).family, FontFamily::Proportional, "{t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every floating window comes from `crate::windows::new`, which keeps it below the menu bar
|
||||
/// (a dialog's title bar must never cover File, Edit, View).
|
||||
#[test]
|
||||
fn floating_windows_stay_below_the_menu_bar() {
|
||||
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
||||
for e in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
walk(&p, out);
|
||||
} else if p.extension().is_some_and(|x| x == "rs") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
|
||||
assert!(files.len() > 40);
|
||||
let opened = ["egui::Window::new(", concat!("Window", "::new(")];
|
||||
for f in files {
|
||||
let name = f.file_name().unwrap().to_string_lossy().to_string();
|
||||
if name == "windows.rs" || name.ends_with("tests.rs") {
|
||||
continue;
|
||||
}
|
||||
let src = std::fs::read_to_string(&f).unwrap();
|
||||
for o in opened {
|
||||
assert!(!src.contains(o), "{name} opens a window with {o}; use crate::windows::new (kept below the menu bar)");
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
-6
@@ -10,7 +10,8 @@
|
||||
use crate::app::{Tool, VIEW_SHORTCUTS};
|
||||
use anicraft_engine::{SHORTCUT_ALIASES, commands};
|
||||
use egui::{Key, Modifiers};
|
||||
use std::collections::BTreeMap;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Keys handled before the shortcut map, which the editor will not assign, and what for
|
||||
/// (English: translated where it is shown).
|
||||
@@ -94,8 +95,56 @@ fn view_label(id: &str) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a saved command's action id (ADR 0097): `macro:<its name>`.
|
||||
pub const MACRO_PREFIX: &str = "macro:";
|
||||
|
||||
/// Most distinct saved command names the map ever binds in one run (see [`intern`]).
|
||||
const MAX_INTERNED: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The saved commands that can carry a shortcut, as `(action id, name)`, in their order.
|
||||
static MACROS: RefCell<Vec<(&'static str, &'static str)>> = const { RefCell::new(Vec::new()) };
|
||||
static INTERNED: RefCell<BTreeSet<&'static str>> = const { RefCell::new(BTreeSet::new()) };
|
||||
}
|
||||
|
||||
/// `s` for the life of the program, each distinct string kept once. An action's id and label
|
||||
/// are `&'static str` everywhere the map is used; saved commands are the only actions named at
|
||||
/// run time, and a run meets a handful of their names, so keeping each one is the simple
|
||||
/// choice. Past [`MAX_INTERNED`] names a new one can't carry a shortcut until the next start.
|
||||
fn intern(s: &str) -> Option<&'static str> {
|
||||
INTERNED.with(|set| {
|
||||
let mut set = set.borrow_mut();
|
||||
if let Some(kept) = set.get(s) {
|
||||
return Some(*kept);
|
||||
}
|
||||
if set.len() >= MAX_INTERNED {
|
||||
return None;
|
||||
}
|
||||
let kept: &'static str = Box::leak(s.to_string().into_boxed_str());
|
||||
set.insert(kept);
|
||||
Some(kept)
|
||||
})
|
||||
}
|
||||
|
||||
/// A saved command's action id.
|
||||
pub fn macro_id(name: &str) -> String {
|
||||
format!("{MACRO_PREFIX}{name}")
|
||||
}
|
||||
|
||||
/// The saved command an action id names.
|
||||
pub fn macro_name(id: &str) -> Option<&str> {
|
||||
id.strip_prefix(MACRO_PREFIX)
|
||||
}
|
||||
|
||||
/// The saved commands, in their order, as actions that can carry a shortcut (Manage Saved
|
||||
/// Commands sets them whenever the list changes; rebuild the [`Keymap`] after).
|
||||
pub fn set_macros<'a>(names: impl IntoIterator<Item = &'a str>) {
|
||||
let list: Vec<(&'static str, &'static str)> = names.into_iter().filter_map(|n| Some((intern(¯o_id(n))?, intern(n)?))).collect();
|
||||
MACROS.with(|m| *m.borrow_mut() = list);
|
||||
}
|
||||
|
||||
/// Every action that can carry a shortcut: the menu commands, any command with a default key,
|
||||
/// the tools and the view keys.
|
||||
/// the tools, the view keys and the saved commands.
|
||||
pub fn actions() -> Vec<Action> {
|
||||
let mut v: Vec<Action> = commands()
|
||||
.into_iter()
|
||||
@@ -120,6 +169,7 @@ pub fn actions() -> Vec<Action> {
|
||||
group: tr_noop!("View"),
|
||||
defaults: VIEW_SHORTCUTS.iter().filter(|(_, i)| *i == id).map(|(k, _)| *k).collect(),
|
||||
}));
|
||||
MACROS.with(|m| v.extend(m.borrow().iter().map(|&(id, label)| Action { id, label, group: tr_noop!("Commands"), defaults: Vec::new() })));
|
||||
v
|
||||
}
|
||||
|
||||
@@ -192,11 +242,17 @@ pub struct Keymap {
|
||||
impl Keymap {
|
||||
pub fn new(overrides: &BTreeMap<String, Vec<String>>) -> Keymap {
|
||||
let actions = actions();
|
||||
// A chord bound twice (a saved command's key in a hand-edited preferences file) stays
|
||||
// with the action listed first.
|
||||
let mut taken: BTreeSet<String> = BTreeSet::new();
|
||||
let keys = actions
|
||||
.iter()
|
||||
.map(|a| match overrides.get(a.id) {
|
||||
Some(user) => user.iter().filter_map(|k| normalize(k)).collect(),
|
||||
None => a.defaults.iter().filter_map(|k| normalize(k)).collect(),
|
||||
.map(|a| {
|
||||
let ks: Vec<String> = match overrides.get(a.id) {
|
||||
Some(user) => user.iter().filter_map(|k| normalize(k)).collect(),
|
||||
None => a.defaults.iter().filter_map(|k| normalize(k)).collect(),
|
||||
};
|
||||
ks.into_iter().filter(|k| taken.insert(k.clone())).collect()
|
||||
})
|
||||
.collect();
|
||||
Keymap { actions, keys }
|
||||
@@ -326,7 +382,9 @@ pub fn sanitize(overrides: BTreeMap<String, Vec<String>>) -> BTreeMap<String, Ve
|
||||
let known = actions();
|
||||
let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
for (id, keys) in overrides.into_iter().take(1_000) {
|
||||
if !known.iter().any(|a| a.id == id) {
|
||||
// A saved command's keys are kept while it isn't listed yet (they bind once it is).
|
||||
let saved = macro_name(&id).is_some_and(|n| !n.is_empty() && n.chars().count() <= 64);
|
||||
if !saved && !known.iter().any(|a| a.id == id) {
|
||||
continue;
|
||||
}
|
||||
let mut clean: Vec<String> = Vec::new();
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
};
|
||||
let fixed = matches!(kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature);
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(420.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Name"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Layer name"));
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Saved commands in the desktop app (ADR 0097): Save As Command from the steps picked in the
|
||||
//! History panel, the saved commands at the end of the Commands menu with their shortcuts, Run
|
||||
//! Command… for a file, and Commands › Manage Saved Commands (run, rename, reorder, shortcut,
|
||||
//! delete, add from a file). The `macro.*` commands do the work; the files live in the settings
|
||||
//! folder (`platform::commands_dir`).
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::keymap;
|
||||
use crate::theme::{T, Type, text};
|
||||
use anicraft_engine::cmds_macro::{self, Saved};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// What the window keeps for saved commands between frames (view state, not saved).
|
||||
#[derive(Default)]
|
||||
pub struct Macros {
|
||||
/// The saved commands, as last read from the folder, in their order.
|
||||
pub list: Vec<Saved>,
|
||||
/// Files in the folder that aren't saved commands, with why.
|
||||
pub problems: Vec<(String, String)>,
|
||||
/// History steps picked for Save As Command (as `macro.history` numbers them).
|
||||
pub picked: BTreeSet<usize>,
|
||||
/// The step picked last (the anchor of a Shift+click range).
|
||||
anchor: Option<usize>,
|
||||
/// The history the picks belong to: (steps freed, steps listed).
|
||||
picked_for: (usize, usize),
|
||||
/// The Save As Command dialog, while it is open.
|
||||
pub save: Option<SaveDialog>,
|
||||
/// Commands › Manage Saved Commands.
|
||||
pub manage: Manage,
|
||||
/// Tests: this app's own folder. Test apps have none otherwise, so tests running side by
|
||||
/// side never see each other's saved commands.
|
||||
#[cfg(test)]
|
||||
pub(crate) test_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// A picked step as Save As Command keeps it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StepView {
|
||||
pub index: usize,
|
||||
pub label: String,
|
||||
/// Why it can't be kept (`None`: it can).
|
||||
pub refused: Option<String>,
|
||||
/// What was rewritten so it replays elsewhere ("acts on the selection").
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// The Save As Command dialog.
|
||||
pub struct SaveDialog {
|
||||
pub name: String,
|
||||
pub steps: Vec<StepView>,
|
||||
focus: bool,
|
||||
}
|
||||
|
||||
/// The Manage Saved Commands window.
|
||||
#[derive(Default)]
|
||||
pub struct Manage {
|
||||
pub open: bool,
|
||||
/// The command being renamed and the name typed so far.
|
||||
pub(crate) renaming: Option<(String, String)>,
|
||||
focus: bool,
|
||||
}
|
||||
|
||||
/// The folder the saved commands are in. Screenshot runs never touch the real one: they use a
|
||||
/// temporary folder (unless `ANICRAFT_COMMANDS_DIR` names one). None in a browser.
|
||||
pub fn folder(app: &App) -> Option<PathBuf> {
|
||||
#[cfg(test)]
|
||||
return app.macros.test_folder.clone();
|
||||
#[cfg_attr(test, allow(unreachable_code))]
|
||||
if app.shot.is_some() && std::env::var_os("ANICRAFT_COMMANDS_DIR").is_none() && !crate::platform::WEB {
|
||||
return Some(std::env::temp_dir().join(format!("anicraft-commands-shot-{}", std::process::id())));
|
||||
}
|
||||
crate::platform::commands_dir()
|
||||
}
|
||||
|
||||
fn folder_str(app: &App) -> Option<String> {
|
||||
folder(app).map(|f| f.display().to_string())
|
||||
}
|
||||
|
||||
/// Reads the folder again, and lets the shortcut map bind what is in it.
|
||||
pub fn rescan(app: &mut App) {
|
||||
let (list, problems) = folder(app).map(|f| cmds_macro::saved_commands(&f)).unwrap_or_default();
|
||||
app.macros.list = list;
|
||||
app.macros.problems = problems;
|
||||
keymap::set_macros(app.macros.list.iter().map(|c| c.name.as_str()));
|
||||
app.refresh_keymap();
|
||||
}
|
||||
|
||||
/// Runs the saved command called `name` (from the menu, a shortcut or the Manage window).
|
||||
pub fn run_saved(app: &mut App, name: &str) {
|
||||
let Some(folder) = folder_str(app) else { return };
|
||||
app.playing = false;
|
||||
app.request("macro.run", json!({"folder": folder, "name": name}));
|
||||
}
|
||||
|
||||
/// Whether the steps picked so far still belong to this history; if not, they are let go.
|
||||
fn sync_picks(app: &mut App) {
|
||||
let h = app.s.history();
|
||||
let now = (h.evicted, h.undo_len() + h.redo_len());
|
||||
let was = app.macros.picked_for;
|
||||
// New steps keep the numbers of the old ones; a freed step or a dropped redo moves them.
|
||||
if now.0 != was.0 || now.1 < was.1 {
|
||||
app.macros.picked.clear();
|
||||
app.macros.anchor = None;
|
||||
}
|
||||
app.macros.picked_for = now;
|
||||
}
|
||||
|
||||
/// Picks history step `i` for Save As Command: Ctrl toggles it, Shift picks the range from the
|
||||
/// step picked last.
|
||||
pub fn pick(app: &mut App, i: usize, toggle: bool, range: bool) {
|
||||
sync_picks(app);
|
||||
let m = &mut app.macros;
|
||||
match (range, m.anchor) {
|
||||
(true, Some(a)) => {
|
||||
m.picked.extend(a.min(i)..=a.max(i));
|
||||
}
|
||||
_ if toggle && m.picked.contains(&i) => {
|
||||
m.picked.remove(&i);
|
||||
}
|
||||
_ => {
|
||||
m.picked.insert(i);
|
||||
}
|
||||
}
|
||||
m.anchor = Some(i);
|
||||
}
|
||||
|
||||
/// The picked steps, in order (after letting go of picks the history no longer has).
|
||||
pub fn picked(app: &mut App) -> Vec<usize> {
|
||||
sync_picks(app);
|
||||
app.macros.picked.iter().copied().collect()
|
||||
}
|
||||
|
||||
pub fn clear_picks(app: &mut App) {
|
||||
app.macros.picked.clear();
|
||||
app.macros.anchor = None;
|
||||
}
|
||||
|
||||
/// Opens Save As Command for the picked steps.
|
||||
pub fn open_save(app: &mut App) {
|
||||
if folder(app).is_none() {
|
||||
app.status_err(tr!("Saved commands are kept in a folder on your computer: save them in the desktop app."));
|
||||
return;
|
||||
}
|
||||
let picked = picked(app);
|
||||
if picked.is_empty() {
|
||||
app.status_err(tr!("Pick the steps to save first: Ctrl+click them in the History panel (Shift+click picks a range)."));
|
||||
return;
|
||||
}
|
||||
let listed = app.s.execute("macro.history", &json!({})).unwrap_or(Value::Null);
|
||||
let rows = listed["steps"].as_array().cloned().unwrap_or_default();
|
||||
let steps: Vec<StepView> = picked
|
||||
.iter()
|
||||
.filter_map(|&i| rows.get(i))
|
||||
.map(|r| StepView {
|
||||
index: r["index"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0),
|
||||
label: r["label"].as_str().unwrap_or("").to_string(),
|
||||
refused: r["why"].as_str().map(str::to_string),
|
||||
note: r["rewritten"].as_str().map(str::to_string),
|
||||
})
|
||||
.collect();
|
||||
let n = app.macros.list.len() + 1;
|
||||
app.macros.save = Some(SaveDialog { name: tr!("Command {n}", n = n), steps, focus: true });
|
||||
}
|
||||
|
||||
/// A step's undo label in the interface language (the engine's English is the key).
|
||||
fn step_label(label: &str) -> String {
|
||||
crate::i18n::t_dyn(label).into_owned()
|
||||
}
|
||||
|
||||
fn save_window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.macros.save else { return };
|
||||
let mut open = true;
|
||||
let mut save = false;
|
||||
let mut cancel = false;
|
||||
let title = tr!("Save As Command");
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("save_as_command")).open(&mut open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center()).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Label, tr!("Name")));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(280.0)).named(tr!("Saved command name"));
|
||||
if d.focus {
|
||||
r.request_focus();
|
||||
d.focus = false;
|
||||
}
|
||||
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
save = true;
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(text(Type::Label, trn!("{n} step, run in order as one undo step:", "{n} steps, run in order as one undo step:", d.steps.len())));
|
||||
egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| {
|
||||
for st in &d.steps {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Data, (st.index + 1).to_string()).color(T.text_dim));
|
||||
ui.label(text(Type::Body, step_label(&st.label)));
|
||||
match (&st.refused, &st.note) {
|
||||
(Some(why), _) => {
|
||||
ui.label(text(Type::Caption, tr!("can't be kept: {why}", why = crate::i18n::t_dyn(why))).color(T.error));
|
||||
}
|
||||
(None, Some(note)) => {
|
||||
ui.label(text(Type::Caption, crate::i18n::t_dyn(note)).color(T.text_dim));
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let refused = d.steps.iter().filter(|s| s.refused.is_some()).count();
|
||||
ui.add_space(4.0);
|
||||
if refused > 0 {
|
||||
ui.label(text(Type::Caption, trn!("Take the {n} step that can't be kept out of the picks (Ctrl+click it) to save the others.", "Take the {n} steps that can't be kept out of the picks (Ctrl+click them) to save the others.", refused)).color(T.error));
|
||||
} else {
|
||||
ui.label(text(Type::Caption, tr!("It runs on whatever is selected when you choose it in the Commands menu.")));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
let ok = refused == 0 && !d.name.trim().is_empty();
|
||||
if ui.add_enabled(ok, egui::Button::new(tr!("Save"))).clicked() {
|
||||
save = true;
|
||||
}
|
||||
if ui.button(tr!("Cancel")).clicked() {
|
||||
cancel = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
a11y::name_title_bar(&shown, title);
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
cancel = true;
|
||||
}
|
||||
if !open || cancel {
|
||||
app.macros.save = None;
|
||||
return;
|
||||
}
|
||||
let ready = app.macros.save.as_ref().filter(|d| save && !d.name.trim().is_empty() && d.steps.iter().all(|s| s.refused.is_none()));
|
||||
if let Some(d) = ready {
|
||||
let history: Vec<usize> = d.steps.iter().map(|s| s.index).collect();
|
||||
let name = d.name.trim().to_string();
|
||||
if let Some(folder) = folder_str(app) {
|
||||
app.request("macro.save", json!({"folder": folder, "name": name, "history": history}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved commands at the end of the Commands menu, as Animate lists them.
|
||||
pub fn menu_items(app: &mut App, ui: &mut egui::Ui) {
|
||||
if folder(app).is_none() {
|
||||
return;
|
||||
}
|
||||
ui.separator();
|
||||
if app.macros.list.is_empty() {
|
||||
ui.label(text(Type::Caption, tr!("No saved commands yet: pick steps in the History panel and Save As Command")));
|
||||
return;
|
||||
}
|
||||
let names: Vec<String> = app.macros.list.iter().map(|c| c.name.clone()).collect();
|
||||
for name in names {
|
||||
let key = crate::platform::shortcut_label(app.keymap.primary(&keymap::macro_id(&name)).unwrap_or(""));
|
||||
if ui.add(egui::Button::new(name.as_str()).shortcut_text(text(Type::Key, key))).clicked() {
|
||||
ui.input_mut(|i| {
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Enter);
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Space);
|
||||
});
|
||||
ui.close();
|
||||
run_saved(app, &name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands › Manage Saved Commands…
|
||||
pub fn open_manage(app: &mut App) {
|
||||
rescan(app);
|
||||
app.macros.manage = Manage { open: true, ..Manage::default() };
|
||||
}
|
||||
|
||||
/// Opens the shortcut editor on the saved command `name`, already waiting for its keys.
|
||||
fn assign_shortcut(app: &mut App, ctx: &egui::Context, name: &str) {
|
||||
let id = keymap::macro_id(name);
|
||||
let Some(action) = app.keymap.actions.iter().find(|a| a.id == id).map(|a| a.id) else { return };
|
||||
crate::dialogs::shortcuts_for(app, ctx, name, action);
|
||||
}
|
||||
|
||||
enum Act {
|
||||
Run(String),
|
||||
Move(String, usize),
|
||||
Rename(String, String),
|
||||
Delete(String),
|
||||
Shortcut(String),
|
||||
}
|
||||
|
||||
fn manage_window(app: &mut App, ctx: &egui::Context) {
|
||||
if !app.macros.manage.open {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = folder(app) else {
|
||||
app.macros.manage.open = false;
|
||||
return;
|
||||
};
|
||||
let mut open = true;
|
||||
let mut acts: Vec<Act> = Vec::new();
|
||||
let title = tr!("Manage Saved Commands");
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("manage_saved_commands")).open(&mut open).collapsible(false).resizable(false).default_width(760.0).show(ctx, |ui| {
|
||||
ui.set_min_width(720.0);
|
||||
let list = app.macros.list.clone();
|
||||
if list.is_empty() {
|
||||
ui.label(text(Type::Label, tr!("No saved commands yet. Pick steps in the History panel (Ctrl+click), then Save As Command: they run again on the selection as one undo step.")));
|
||||
}
|
||||
let n = list.len();
|
||||
for (i, c) in list.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(crate::theme::TARGET);
|
||||
let mut renaming = app.macros.manage.renaming.take();
|
||||
if let Some((k, typed)) = &mut renaming
|
||||
&& *k == c.name
|
||||
{
|
||||
let r = ui.add(egui::TextEdit::singleline(typed).desired_width(220.0)).named(&tr!("New name for “{name}”", name = c.name));
|
||||
if app.macros.manage.focus {
|
||||
r.request_focus();
|
||||
app.macros.manage.focus = false;
|
||||
}
|
||||
let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
if ui.button(tr!("Rename")).clicked() || enter {
|
||||
acts.push(Act::Rename(c.name.clone(), typed.trim().to_string()));
|
||||
} else if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
renaming = None;
|
||||
}
|
||||
app.macros.manage.renaming = renaming;
|
||||
return;
|
||||
}
|
||||
app.macros.manage.renaming = renaming;
|
||||
// Fixed columns, so the buttons line up row under row.
|
||||
let cell = |ui: &mut egui::Ui, w: f32, add: &mut dyn FnMut(&mut egui::Ui)| {
|
||||
ui.allocate_ui_with_layout(egui::vec2(w, crate::theme::TARGET), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_width(w);
|
||||
add(ui);
|
||||
});
|
||||
};
|
||||
cell(ui, 210.0, &mut |ui| {
|
||||
ui.add(egui::Label::new(text(Type::Body, &c.name)).truncate());
|
||||
});
|
||||
cell(ui, 64.0, &mut |ui| {
|
||||
ui.label(text(Type::DataSmall, trn!("{n} step", "{n} steps", c.steps)).color(T.text_dim));
|
||||
});
|
||||
let key = app.keymap.primary(&keymap::macro_id(&c.name)).map(crate::platform::shortcut_label).unwrap_or_default();
|
||||
cell(ui, 96.0, &mut |ui| {
|
||||
ui.add(egui::Label::new(text(Type::Key, key.as_str()).color(T.text_dim)).truncate());
|
||||
});
|
||||
if ui.button(tr!("Run")).named(&tr!("Run “{name}”", name = c.name)).on_hover_text(tr!("Run it on the selection (one undo step)")).clicked() {
|
||||
acts.push(Act::Run(c.name.clone()));
|
||||
}
|
||||
let gap = crate::theme::TARGET + 4.0;
|
||||
if i > 0 {
|
||||
if crate::timeline::icon_button(ui, &tr!("Move “{name}” up", name = c.name), None, crate::icons::Icon::ChevronUp).clicked() {
|
||||
acts.push(Act::Move(c.name.clone(), i - 1));
|
||||
}
|
||||
} else {
|
||||
ui.allocate_exact_size(egui::vec2(gap, crate::theme::TARGET), egui::Sense::hover());
|
||||
}
|
||||
if i + 1 < n {
|
||||
if crate::timeline::icon_button(ui, &tr!("Move “{name}” down", name = c.name), None, crate::icons::Icon::ChevronDown).clicked() {
|
||||
acts.push(Act::Move(c.name.clone(), i + 1));
|
||||
}
|
||||
} else {
|
||||
ui.allocate_exact_size(egui::vec2(gap, crate::theme::TARGET), egui::Sense::hover());
|
||||
}
|
||||
if ui.button(tr!("Shortcut…")).named(&tr!("Shortcut for “{name}”", name = c.name)).on_hover_text(tr!("Give it a key in Keyboard Shortcuts")).clicked() {
|
||||
acts.push(Act::Shortcut(c.name.clone()));
|
||||
}
|
||||
if ui.button(tr!("Rename…")).named(&tr!("Rename “{name}”", name = c.name)).clicked() {
|
||||
app.macros.manage.renaming = Some((c.name.clone(), c.name.clone()));
|
||||
app.macros.manage.focus = true;
|
||||
}
|
||||
if ui.button(tr!("Delete…")).named(&tr!("Delete “{name}”", name = c.name)).on_hover_text(tr!("Delete this saved command's file (asks first)")).clicked() {
|
||||
acts.push(Act::Delete(c.name.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
for (file, why) in &app.macros.problems {
|
||||
ui.label(text(Type::Caption, tr!("{file} isn't a saved command: {why}", file = file, why = crate::i18n::t_dyn(why))).color(T.error));
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr!("Add from File…")).on_hover_text(tr!("Copy a saved command someone shared into your commands")).clicked() {
|
||||
app.invoke("macro.import");
|
||||
}
|
||||
ui.label(text(Type::Path, dir.display().to_string()).color(T.text_faint));
|
||||
});
|
||||
ui.label(text(Type::Caption, tr!("Saved commands are small JSON files: share one by sending it; Commands › Run Command… runs a file without adding it.")));
|
||||
});
|
||||
a11y::name_title_bar(&shown, title);
|
||||
let folder = dir.display().to_string();
|
||||
for act in acts {
|
||||
match act {
|
||||
Act::Run(name) => run_saved(app, &name),
|
||||
Act::Move(name, index) => app.request("macro.move", json!({"folder": folder, "name": name, "index": index})),
|
||||
Act::Rename(name, to) => app.request("macro.rename", json!({"folder": folder, "name": name, "to": to})),
|
||||
Act::Delete(name) => app.request("macro.delete", json!({"folder": folder, "name": name})),
|
||||
Act::Shortcut(name) => assign_shortcut(app, ctx, &name),
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
app.macros.manage = Manage::default();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
save_window(app, ctx);
|
||||
manage_window(app, ctx);
|
||||
}
|
||||
|
||||
/// Moves (or with `to` None, drops) the shortcut keys kept for the saved command `from`.
|
||||
fn move_shortcut(app: &mut App, from: &str, to: Option<&str>) {
|
||||
let Some(keys) = app.prefs.shortcuts.remove(&keymap::macro_id(from)) else { return };
|
||||
if let Some(to) = to {
|
||||
app.prefs.shortcuts.insert(keymap::macro_id(to), keys);
|
||||
}
|
||||
app.save_prefs();
|
||||
}
|
||||
|
||||
/// After a `macro.*` command ran: the list again, the status line, and a renamed or deleted
|
||||
/// command's shortcut following it.
|
||||
pub fn done(app: &mut App, id: &str, v: &Value) {
|
||||
let name = v["name"].as_str().unwrap_or("").to_string();
|
||||
match id {
|
||||
"macro.run" => {
|
||||
let n = v["steps"].as_u64().unwrap_or(0);
|
||||
app.status_ok(trn!("Ran “{name}” ({n} step) — {undo} to undo", "Ran “{name}” ({n} steps) — {undo} to undo", n, name = name, undo = app.undo_key()));
|
||||
return;
|
||||
}
|
||||
"macro.save" => {
|
||||
app.macros.save = None;
|
||||
clear_picks(app);
|
||||
app.status_ok(tr!("Saved “{name}”: find it at the end of the Commands menu", name = name));
|
||||
}
|
||||
"macro.rename" => {
|
||||
app.macros.manage.renaming = None;
|
||||
if let Some(from) = v["from"].as_str() {
|
||||
move_shortcut(app, from, Some(&name));
|
||||
}
|
||||
}
|
||||
"macro.delete" => {
|
||||
let gone = v["deleted"].as_str().unwrap_or("").to_string();
|
||||
move_shortcut(app, &gone, None);
|
||||
app.status_ok(tr!("Deleted “{name}”", name = gone));
|
||||
}
|
||||
"macro.import" => app.status_ok(tr!("Added “{name}” to your commands", name = name)),
|
||||
_ => {}
|
||||
}
|
||||
rescan(app);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Saved commands in the desktop app (ADR 0097): picking steps in the History panel, Save As
|
||||
//! Command, a saved command's shortcut running it, and a rename or delete taking its keys
|
||||
//! along.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::keymap;
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::sample;
|
||||
use serde_json::json;
|
||||
|
||||
/// A test app: a screenshot path, so the saved commands live in a temporary folder.
|
||||
fn app(ctx: &egui::Context) -> App {
|
||||
App::with_context(ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png")))
|
||||
}
|
||||
|
||||
fn frame(ctx: &egui::Context, app: &mut App, events: Vec<egui::Event>) {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), events, ..Default::default() };
|
||||
ctx.run_ui(raw, |ui| app.frame(ui)).textures_delta.clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picked_steps_save_as_a_command_and_its_shortcut_runs_it() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app(&ctx);
|
||||
// A folder of its own.
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-macros-ui-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
app.macros.test_folder = Some(dir);
|
||||
app.run("edit.select_all", json!({}));
|
||||
app.run("modify.rotate_cw", json!({}));
|
||||
app.run("element.set_color_effect", json!({"style": "alpha", "alpha": 50}));
|
||||
let n = app.s.history_len();
|
||||
// Ctrl+click the two steps; a plain pick of a third, then Ctrl+click takes it out again.
|
||||
crate::macros_ui::pick(&mut app, n - 2, true, false);
|
||||
crate::macros_ui::pick(&mut app, n - 1, true, false);
|
||||
assert_eq!(crate::macros_ui::picked(&mut app), [n - 2, n - 1]);
|
||||
crate::macros_ui::open_save(&mut app);
|
||||
let d = app.macros.save.as_mut().expect("the dialog");
|
||||
assert_eq!(d.steps.len(), 2);
|
||||
assert!(d.steps.iter().all(|s| s.refused.is_none()));
|
||||
d.name = "Spin and Fade".into();
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
let folder = crate::macros_ui::folder(&app).expect("a folder").display().to_string();
|
||||
app.request("macro.save", json!({"folder": folder, "name": "Spin and Fade", "history": [n - 2, n - 1]}));
|
||||
assert!(app.macros.save.is_none(), "saved, the dialog closes");
|
||||
assert!(crate::macros_ui::picked(&mut app).is_empty());
|
||||
assert_eq!(app.macros.list.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Spin and Fade"]);
|
||||
|
||||
// A key of its own, through the shortcut map.
|
||||
let id = keymap::macro_id("Spin and Fade");
|
||||
app.prefs.shortcuts = keymap::assign(&app.prefs.shortcuts, &id, None, "Ctrl+Alt+R", false).expect("a free key");
|
||||
app.refresh_keymap();
|
||||
assert!(app.shortcuts.iter().any(|(_, k, a)| *k == egui::Key::R && *a == id));
|
||||
let steps = app.s.history_len();
|
||||
let before = app.s.selected_elements().first().map(|(_, e)| e.transform);
|
||||
// (The dialog's name field gives the keyboard back once it is gone.)
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
}
|
||||
let key = egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND | egui::Modifiers::ALT };
|
||||
frame(&ctx, &mut app, vec![key]);
|
||||
assert_eq!(app.s.history_len(), steps + 1, "the key ran it as one step");
|
||||
assert_eq!(app.s.undo_label(), Some("Spin and Fade"));
|
||||
assert_ne!(app.s.selected_elements().first().map(|(_, e)| e.transform), before);
|
||||
|
||||
// A rename takes its key along; a delete (confirmed) drops it.
|
||||
app.request("macro.rename", json!({"folder": folder, "name": "Spin and Fade", "to": "Twirl"}));
|
||||
assert_eq!(app.keymap.keys(&keymap::macro_id("Twirl")), ["Ctrl+Alt+R"]);
|
||||
assert!(!app.prefs.shortcuts.contains_key(&id));
|
||||
app.request("macro.delete", json!({"folder": folder, "name": "Twirl"}));
|
||||
assert!(app.confirm.is_some(), "deleting a file asks first");
|
||||
app.confirm = None;
|
||||
app.perform("macro.delete", json!({"folder": folder, "name": "Twirl", "confirm": true}));
|
||||
assert!(app.macros.list.is_empty());
|
||||
assert!(app.prefs.shortcuts.keys().all(|k| keymap::macro_name(k).is_none()));
|
||||
|
||||
// The windows and the menu draw, and their buttons work (same folder: this test owns it).
|
||||
app.open_panel(Some("managecommands"));
|
||||
assert!(app.macros.manage.open);
|
||||
assert_eq!(app.macros.list.len(), 3, "the sample commands");
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
}
|
||||
let cmds = anicraft_engine::commands();
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::menus::menu_contents(&mut app, ui, "Commands", &cmds));
|
||||
out.textures_delta.clear();
|
||||
// Reorder and rename through the same requests the buttons make.
|
||||
let first = app.macros.list[0].name.clone();
|
||||
app.request("macro.move", json!({"folder": folder, "name": first, "index": 2}));
|
||||
assert_eq!(app.macros.list[2].name, first);
|
||||
app.macros.manage.renaming = Some((first.clone(), "Renamed".into()));
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
crate::macros_ui::run_saved(&mut app, "Quarter Turn");
|
||||
assert_eq!(app.s.undo_label(), Some("Quarter Turn"));
|
||||
// A file shared from elsewhere comes in through Add from File (the folder is filled in).
|
||||
let shared = std::env::temp_dir().join(format!("anicraft-shared-{}.json", std::process::id()));
|
||||
std::fs::write(&shared, r#"[{"cmd": "modify.rotate_ccw"}]"#).unwrap();
|
||||
app.request("macro.import", json!({"path": shared.display().to_string()}));
|
||||
assert!(app.macros.list.iter().any(|c| c.name.starts_with("anicraft-shared")));
|
||||
let _ = std::fs::remove_file(&shared);
|
||||
app.macros.manage.open = false;
|
||||
// History with steps picked, and Save As Command over it.
|
||||
app.open_panel(Some("savecommand"));
|
||||
assert!(app.macros.save.is_some());
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
}
|
||||
crate::macros_ui::clear_picks(&mut app);
|
||||
crate::macros_ui::open_save(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_step_that_cant_be_kept_is_named_in_the_dialog() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app(&ctx);
|
||||
app.macros.test_folder = Some(std::env::temp_dir().join(format!("anicraft-macros-ui-refused-{}", std::process::id())));
|
||||
app.run("edit.select_all", json!({}));
|
||||
app.run("edit.copy", json!({}));
|
||||
app.run("edit.paste", json!({}));
|
||||
let n = app.s.history_len();
|
||||
crate::macros_ui::pick(&mut app, n - 1, false, false);
|
||||
crate::macros_ui::open_save(&mut app);
|
||||
let d = app.macros.save.as_ref().expect("the dialog");
|
||||
assert!(d.steps[0].refused.as_deref().is_some_and(|w| w.contains("clipboard")), "{:?}", d.steps);
|
||||
// The dialog draws, and Save stays off.
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
assert!(app.macros.save.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_commands_take_shortcuts_like_any_action() {
|
||||
keymap::set_macros(["Spin"]);
|
||||
let none = std::collections::BTreeMap::new();
|
||||
let o = keymap::assign(&none, "macro:Spin", None, "Ctrl+Alt+R", false).expect("free");
|
||||
let m = keymap::Keymap::new(&o);
|
||||
assert_eq!(m.owner("Ctrl+Alt+R").map(|a| a.id), Some("macro:Spin"));
|
||||
assert!(matches!(keymap::assign(&o, "macro:Spin", None, "Ctrl+Z", false), Err(keymap::Refusal::Taken { id: "edit.undo", .. })));
|
||||
// Kept while the folder hasn't been read yet, bound once it is.
|
||||
keymap::set_macros([]);
|
||||
let kept = keymap::sanitize(o.clone());
|
||||
assert!(kept.contains_key("macro:Spin"));
|
||||
assert!(keymap::Keymap::new(&kept).keys("macro:Spin").is_empty());
|
||||
// A clash from a hand-edited file stays with the action listed first.
|
||||
keymap::set_macros(["Spin"]);
|
||||
let bad = std::collections::BTreeMap::from([("macro:Spin".to_string(), vec!["Ctrl+Z".to_string()])]);
|
||||
let m = keymap::Keymap::new(&bad);
|
||||
assert_eq!(m.owner("Ctrl+Z").map(|a| a.id), Some("edit.undo"));
|
||||
assert!(m.keys("macro:Spin").is_empty());
|
||||
}
|
||||
+6
-1
@@ -72,9 +72,13 @@ mod plugin_export_ui;
|
||||
mod plugin_fixture_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod macros_ui_tests;
|
||||
mod macros_ui;
|
||||
mod plugins_ui;
|
||||
mod prefs;
|
||||
mod recent;
|
||||
mod rich_edit;
|
||||
mod rulers;
|
||||
mod scale_grid;
|
||||
mod shape_envelope;
|
||||
@@ -92,6 +96,7 @@ mod timeline;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
mod widthtool;
|
||||
mod windows;
|
||||
mod workspaces_window;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -267,7 +272,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|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 <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|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\
|
||||
|
||||
+184
-14
@@ -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<usize> = crate::macros_ui::picked(app).into_iter().collect();
|
||||
let hist = app.s.history();
|
||||
let past: Vec<String> = hist.undo_labels().map(str::to_string).collect();
|
||||
let future: Vec<String> = 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<anicraft_engine::
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, sel));
|
||||
}
|
||||
|
||||
/// Which of the text style rows' values differ across the characters (or paragraphs) they show
|
||||
/// (ADR 0085): those rows show the first one's and say "mixed".
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct TextMixed {
|
||||
pub font: bool,
|
||||
pub size: bool,
|
||||
pub color: bool,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub letter_spacing: bool,
|
||||
pub align: bool,
|
||||
pub line_spacing: bool,
|
||||
}
|
||||
|
||||
/// "mixed" after a text row whose characters differ.
|
||||
fn mixed_chars(ui: &mut egui::Ui, differs: bool) {
|
||||
if differs {
|
||||
ui.label(text(Type::Caption, tr!("mixed")).color(T.text_faint)).on_hover_text(tr!("The characters differ here; it shows the first one's. A change applies to all of them"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a text's character and paragraph style (ADR 0085): baseline shift, underline,
|
||||
/// link, indent and margins. `None` values are mixed.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TextExtra {
|
||||
pub shift: Option<anicraft_engine::doc::BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
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<f32>>) -> 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<f32>>, 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;
|
||||
|
||||
+16
-2
@@ -397,7 +397,7 @@ pub fn places() -> Vec<(&'static str, Option<PathBuf>)> {
|
||||
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<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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
|
||||
|
||||
@@ -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::<Vec<_>>().join(" · ");
|
||||
ui.label(text(Type::Caption, if by.is_empty() { tr!("Plug-in").to_string() } else { tr!("Plug-in · {by}", by = by) }));
|
||||
|
||||
+3
-1
@@ -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<Arc<Plugin>> = 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.")));
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<TextRun>,
|
||||
}
|
||||
|
||||
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<ElementId>, 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<Value> = self.runs.iter().filter(|r| r.chars > 0).map(run_json).collect();
|
||||
let paras: Vec<Value> = 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<StyledClip> {
|
||||
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<ParagraphStyle> = 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<_>>(), 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);
|
||||
}
|
||||
}
|
||||
+53
-14
@@ -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.
|
||||
|
||||
+1
-1
@@ -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();
|
||||
|
||||
+1
-1
@@ -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)
|
||||
|
||||
@@ -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<std::sync::Arc<[u8]>> {
|
||||
[craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect()
|
||||
|
||||
+5
-8
@@ -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;
|
||||
|
||||
@@ -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::<egui::Rect>(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::WidgetText>) -> 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());
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user